Python

Discussion on other languages at the COJ. This is the place to clear your doubts about these languages, and to share with the community the new things you learn about them.
User avatar
Phantom
Posts: 58
Joined: Thu Nov 17, 2011 11:21 am
Location: Cuba
Gender: None specified

Python

Postby Phantom » Mon Dec 05, 2011 11:18 am

If you have any doubt about python, you can make me a question. ;)



User avatar
Robbin
Posts: 38
Joined: Mon Nov 21, 2011 11:42 am
Location: Santiago de Cuba
Gender: None specified

Re: Python

Postby Robbin » Mon May 07, 2012 7:19 pm

Well, I need to know how to read a matrix :geek:

User avatar
Phantom
Posts: 58
Joined: Thu Nov 17, 2011 11:21 am
Location: Cuba
Gender: None specified

Re: Python

Postby Phantom » Mon May 07, 2012 9:03 pm

You have to see the matrix in Python as an array of array.
You know how read an array. For this reason, you can do this:

cant = input() #imagine they tell you first the number of rows
matrix = [[int(i) for i in raw_input().split()] for i in range(cant)] #in just a line of code :D

As well, you can write:

matrix = [map(int, raw_input().split()) for i in range(cant)] #in just a line of code too :D

That is assuming that you want to cast to <int>, but you can cast to the type you want
Mmmmm... interesting eh??
Now...
What's the diference between map(int, raw_input().split()) and [int(i) for i in raw_input().split()] for create a list???
You haven't to believe me... but some birds tell me that the function map is more slow because the another way is implemented in C and... bla bla bla
The choice is yours.

Ah!! I forgot something important...
Now you know you can create a list in this manner:
lista = [i for i in sequence]
or
lista = map(typeToCast, sequence)
or
lista = [i for i in sequence if condition(i)] equivalent to: lista = filter(conditionFunc, sequence)
or
lista = list() equivalent to: lista = [] #empty list
or
lista = list(sequence)

But in the same way you can create an tuple, that is like a list, but is more simple and you can't change the values in the tuple.
Now you know you can create a tuple in this manner:
tup = (i for i in sequence)
or
tup = (i for i in sequence if condition(i)) equivalent to: tup = filter(conditionFunc, sequence) #if the sequence is a tuple or string
or
tup = tuple() equivalent to: tup = () #empty tuple
or
tup = tuple(sequence)

Beautifull, really??
I love it!!!

User avatar
Robbin
Posts: 38
Joined: Mon Nov 21, 2011 11:42 am
Location: Santiago de Cuba
Gender: None specified

Re: Python

Postby Robbin » Tue May 08, 2012 7:07 pm

That's cool, man!
Yes, I was thinking to make an array of arrays, after your previous lesson of arrays,
but I was thinking so slowly.. It seems that's my problem in python..

Now:

How do I work with a "map"?
and:
How do I use the words "sequence" and "condition"?
I never saw it before

However, that's cool

User avatar
Phantom
Posts: 58
Joined: Thu Nov 17, 2011 11:21 am
Location: Cuba
Gender: None specified

Re: Python

Postby Phantom » Tue May 08, 2012 8:45 pm

:lol: Sorry if I didn´t explained very well.
----I´ll answer first the second question(How do I use the words "sequence" and "condition"?)
1.1)When I say "sequence" I refer to that :) , to any collection, for example:
sequence = 1,2,3,4,5,6 equivalent to: sequence = (1,2,3,4,5,6)
sequence = [1,2,3,4,5,6]
sequence = iter(collection) #collection in this case is a variable

But... When I say "sequence", I also refer to something more powerfull than that :twisted: look it:
if you have the method:

def Iterator(val):
----pos = 0
----while pos < val:
---------yield pos
---------pos+=1

You can do something like this:
pepe = [False for i in Iterator(50)]

And now you have an boolean array of 50 elements :P :twisted: but... you also can do this:
pepe = [False] * 50
or
pepe = [False] * 30 + [False] * 20
And now you also have an boolean array :mrgreen: I love it!!

Robbin, you said something in where I'm in disagreement. You said:
...but I was thinking so slowly.. It seems that's my problem in python..


The other languages do the same like Python, but in in Python you see it, in other languages, no.
In C#, for example, you create an array in the following mode:
int[] array = new int[50];
What do you thing C# did behind???

I forget something important in the previous lesson. You can do a list or tuple or dictionary in Python of anything:
pepe = True, 1, "pepe is my friend", dict(), [1,2,3], {"pepe": 5}

1.2)When I say "condition" I refer to that :) , to any condition, for example:
pepe = [i for i in "10101010101" if i != '1']
Now pepe have the value:
['0', '0', '0', '0', '0']
In this case <i != "1"> is a condition

----Answering now the first question(How do I work with a "map"?)
The map function is a method that many scripts languages have. Python is one of them.
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

Example1:
addition = map(sum, [2,6,4], [3,8,4])
Addition now have the following value:
[5, 14, 8]

Example2:
map(len, ("Pepe", "Alexander", "my 2 friends"))
It return:
[4, 9, 12]

That's cool too, eh??? ;)

User avatar
Robbin
Posts: 38
Joined: Mon Nov 21, 2011 11:42 am
Location: Santiago de Cuba
Gender: None specified

Re: Python

Postby Robbin » Sat May 12, 2012 2:28 am

Ok..
I see there are too many things that I don't know, eh? :)

seriously: I asked you because I had neves seen those words

but you have a mine of information about python..
is there any book or documentation you can suggest me?


Another question:

What can you tell me about the classes?
I have a little about it, but, I don't understand it well
:P

User avatar
Phantom
Posts: 58
Joined: Thu Nov 17, 2011 11:21 am
Location: Cuba
Gender: None specified

Re: Python

Postby Phantom » Sun May 13, 2012 3:52 am

Yes, I have some goods books and tutorials. If you want, give me your email, and I'll send you some documentation.
The classes in Python is very simple, but... previously I want you know somethings.
In Python are specials methods that give to the class an especific property. For example, if you want your class be comparable, you just have to implement the method __cmp__, other special method(and very important) is __init__ that is the constructor of the class.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:
x = MyClass()

Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). For example,

>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

For the other comparissions, you only must define the next methods:
__lt__(self, b) #<
__le__(self, b) #<=
__eq__(self, b) #==
__ne__(self, b) #!=
__ge__(self, b) #>=
__gt__(self, b) #>

In Python 2.(...) in the instance methods, you always most put the "self" variable in the definition, that it been the "this" in C++, Java, C#, etc.
If you want an static method, you most decorate the method with the decorator @staticmethod:
A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C:
---@staticmethod
---def f(arg1, arg2, ...): ...

What?? Where are the propertys?? Ah!! Here!!

property( [fget[, fset[, fdel[, doc]]]])
Return a property attribute for new-style classes (classes that derive from object).
fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x:

class C(object):
---def __init__(self): self._x = None
---def getx(self): return self._x
---def setx(self, value): self._x = value
---def delx(self): del self._x
---x = property(getx, setx, delx, "I'm the 'x' property.")

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget's docstring (if it exists). This makes it possible to create read-only properties easily using property() as a decorator:

class Parrot(object):
---def __init__(self):
-------self._voltage = 100000

---@property
---def voltage(self):
-------"""Get the current voltage."""
-------return self._voltage

turns the voltage() method into a ``getter'' for a read-only attribute with the same name.

If you wanna convert your class in string... easy, you only define the method __str__, for example:

class Dog:
-----def __init__(self, name, length):
---------self.Name, self.Len = name, length
-----def __str__(self):
---------return "Doggy Name: %s, Length: %d" % (self.Name, self.Len)

doggy = Dog('Zuqui', 23)
print doggy

It print:
Doggy Name: Zuqui, Length: 23

Uffff!!! I'm exhausted!!! That all today...
You can make me more questions... I'm happy you are interested. I seen you had resolved some problems in Python.
For this reason, I'll give you a bonus:
Do you know how make a swap in Python between a value A and a value B??
In C++ it been(assuming A and B are intergers):

int temp = A;
A = B;
B = temp;

3 lines for this... shit!!!!
In Pyhton it is:

A, B = B, A

Just a line!!! :mrgreen: My love for Python increase by day....
Another plus... you can do the problems "A+B", "Harder A+B", "Powers of Two", ...,(just for mention some of them) in just a line in Python!!

User avatar
Robbin
Posts: 38
Joined: Mon Nov 21, 2011 11:42 am
Location: Santiago de Cuba
Gender: None specified

Re: Python

Postby Robbin » Mon May 14, 2012 1:26 am

In a single line?
OK, I'll try to make that, later, I guess..

Yes , I try to make some programs in python, I learn C++ in school, but I like python..
I have seen that a, b=b, a that is one of the reasons for I like python, and all that dinamic things, you can use variables without declaring anything, etcetera(I don't know how to write etcetera in English)

Now: I've seen some things about the classes in python, but you can put a lot of things there without saying anything..
For example:
In C++ you say:
class "name"
{
...
public:
name();
...
};
right?

But, in python I saw tis:
class name(object):
#this class ...

And that's all, your class is ready for all you may want
If you want your class to have any attribute, I don't remember that rigth now, but I saw you can add it in every moment..

Well, my e-mail is:
robin.cabeza@csd.uo.edu.cu
if you can, please send me something you considere util..
(you should treat that it doesn't occupy more than three megabytes, ok? that's the limit for another provinces)

User avatar
Robbin
Posts: 38
Joined: Mon Nov 21, 2011 11:42 am
Location: Santiago de Cuba
Gender: None specified

Re: Python

Postby Robbin » Thu May 17, 2012 1:29 am

hey:

I got another question:
how can I read an entire string on a cicle? :?:

if I put:

for i in range(range):
a=raw_input()

it doesn't work
help me

User avatar
Phantom
Posts: 58
Joined: Thu Nov 17, 2011 11:21 am
Location: Cuba
Gender: None specified

Re: Python

Postby Phantom » Thu May 17, 2012 9:42 pm

First: you wrote well "etcetera", in english is in this manner (without tilde).

Second:
Yes, as you said. You can also add attributes to a class after it created. For example:

class Friend:pass

pepe = Friend()
pepe.Name = "Pepe"
pepe.Salute = lambda: "Hello, people!!"

Now pepe have the "property" -Name- and the function -Salute- :)
You also can do this:

setattr(pepe,"Name","Pepe")
setattr(pepe,"Salute",lambda: "Hello, people!!")

:twisted: Powerfull!! With me you always will learn something new :D


Return to “Other languages”

Who is online

Users browsing this forum: No registered users and 1 guest