Python doesn't show anything - python

It's my first Python program and my first excercise is that I just need to swap places in a tuple:
stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"),
("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")]
Is the tuple, and I need to swap Frans with Eefje (those are just names) and then swap the second tuple.
I read the whole data structure tutorial off Python and I thought I could do this like this:
#!/path/to/python
stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"),
("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")]
def switchplace(x):
stamboom[x], stamboom[x + 1] = stamboom[x + 1], stamboom[x]
return stamboom
map(switchplace, range(0, len(stamboom)))
It doens't give syntax errors but it doesn't show anything.

To show something you have to print it.
Change the last line to:
print map(switchplace,range(0,len(stamboom)))

That was very complicated code for a simple task. Check out something called list comprehension.
Change the code to:
stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"),
("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")]
stamboom = [(item[1], item[0]) for item in stamboom]
print stamboom
Update
I saw your solution in the comment. I don't know if there are more premisses to the excersise that I'm not aware of. But I would probably do this instead:
def switchplace(x):
return x[1], x[0]
stamboom = [("Frans","Eefje"),("Klaar","Eefje"),("Eefje","Mattho"), ("Eefje","Salammbo"),("Gustave","Mattho"),("Gustave","Salammbo")]
print map(switchplace, stamboom)
The iterable argument to map don't have to be a numeric range. It could be the list itself. But maybe I missed something and you already got it :)

Tuples are immutable in Python:
http://docs.python.org/reference/datamodel.html

Related

How can I get the sum of all list[1] inside of list of lists items using python 3?

I am trying to get the sum of x in this type of list: myList=[[y,x],[y,x],[y,x]
Here is my code I have been trying:
myLists = [['0.9999', '2423.99000000'], ['0.9998', '900.00000000'], ['0.9997', '4741.23000000'], ['0.9995', '6516.16000000'], ['0.9991', '10.01000000'], ['0.9990', '9800.00000000']]
if chckList(myLists):
floatList = []
listLength = len(acceptibleBids)
acceptibleBids0 = list(map(float, acceptibleBids[0]))
acceptibleBids1 = list(map(float, acceptibleBids[1]))
floatList.append(acceptibleBids0)
floatList.append(acceptibleBids1)
sumAmounts = sum(amount[1] for amount in floatList)
print(sumAmounts)
print(acceptibleBids)
I have run into many problems, but my current problem are listed below:
1. This list is the way I receive it, so the fact that they are all strings I have been trying to change them to floats so that I can the the sum(myList[1]) of each list inside myList.
2. The list ranges from 1 to 100
You can use list comprehension:
total = sum([float(x[1]) for x in myLists])
print(total) # 24391.39
This should do:
sum = 0
for pair in myLists:
sum+= float(pair[1])
#of course, if there is something that can't
#be a float there, it'll raise an error, so
#do make all the checks you need to make
I'm unsure where acceptibleBids comes from in that code, but I'll assume it is a copy of myList, or something similar to it. The problem with your code is that acceptibleBids[0] is just ['0.9999', '2423.99000000']. Similarly, acceptibleBids[1] is just ['0.9998', '900.00000000']. So when end up with acceptibleBids0 as [[0.9999, 2423.99000000]] and acceptibleBids1 is similarly wrong. Then this makes floatList not be what you wanted it to be.
Edit: list comprehension works too, but I kinda like this way of looking at it. Either way, with list comprehension this would be sum_floats = sum(float([pair[1]) for pair in myLists]).
The following will do:
>>> sum([float(x[0]) for x in myLists])
5.997

Function Definition: Matching Area Codes to Phone Numbers

If I want to define a function called match_numbers, which would match the area code from one list to the phone number of another list, how should I fix my code? For example:
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
would give me
(666)313-2534
(332)123-3332
My code is:
def phone (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print(results[x])
The problem with this code is, however:
It gives me the outputs in brackets, whereas I want it to print
the output line by line like shown above, and
it won't work with the parantheses in the 2nd list (for example
(666)543-2322 must be converted as 666-543-2322 for the list to
work.
Now, there are better/faster approaches to do what you are trying to do, but let us focus on fixing your code.
The first issue you have is how you are slicing your string. Remember that you start at index 0. So if you do:
x[0:3]
What you are actually getting is something like this from your string:
(12
Instead of your intended:
123
So, knowing that indexes start at 0, what you actually want to do is slice your string as such:
x[1:4]
Finally, your line here:
results[x[0:3]].append(x)
There are two problems here.
First, as mentioned above, you are still trying to slice the wrong parts of your string, so fix that.
Second, since you are trying to make a key value pair, what that above line is actually doing is making a key value pair where the value is a list. I don't think you want to do that. You want to do something like:
{'123': '(123)5556666'}
So, you don't want to use the append in this case. What you want to do is assign the string directly as the value for that key. You can do that as such:
results[x[1:4]] = x
Finally, another problem that was noticed, is in what you are doing here:
results.setdefault(x[1:4], [])
Based on the above explanation on how you want to store a string as your value in your dictionary instead of a list, so you don't need to be doing this. Therefore, you should simply be removing that line, it does not serve any purpose for what you are trying to do. You have already initialized your dictionary as results = {}
When you put it all together, your code will look like this:
def match_phone(nlist, nlist1):
results = {}
for x in nlist1:
results[x[1:4]] = x
for x in nlist:
if x in results:
print(results[x])
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
And will provide the following output:
(666)313-2534
(332)123-3332
If all the phone numbers will be in the format (ddd)ddd-dddd you can use
for number in (num for num in nlist1 if num[1:4] in nlist):
print(number)
You could use some better variable names than nlist and nlist1, in my view.
def match_phone(area_codes, numbers):
area_codes = set(area_codes)
for num in numbers:
if num in area_codes:
print num
You could do something like this:
phone_numbers = ['(443)241-1254', '(666)313-2534', '(332)123-3332']
area_codes = ['666', '332']
numbers = filter(lambda number: number[1:4] in area_codes, phone_numbers)
for number in numbers:
print(number)
Another similar way to do this without using a filter could be something like this:
for number in phone_numbers:
if number[1:4] in area_codes:
print(number)
Output in either case would be:
(666)313-2534
(332)123-3332
No one with regex solution! This may be an option too.
import re
def my_formatter(l1,l2):
mydic = {re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(2):re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(4) for i in l2}
for i in l1:
print "({0}){1}".format(str(i),str(mydic.get(i)))
my_formatter(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
It prints-
(666)313-2534
(332)123-3332

Reversing string in python using def

Can anyone help me with the assignment - I have to reverse a string by using def. I am not allowed to use approaches like [::-1] or .reversed...
The following function works, but prints vertically:
def ex1(name):
for x in range(len(name)-1,-1,-1):
print(name[x])
k
r
o
Y
w
e
N
how do I put the letters back into horizontal order?? Anyone? Thanks!
You can use str.join and a list comprehension like so:
>>> def ex1(name):
... return "".join([name[x] for x in range(len(name)-1,-1,-1)])
...
>>> print(ex1('abcd'))
dcba
>>>
Also, notice that I made the function return the string instead of print it. If your teachers want you to use def for this job, then they probably want that too. If not, then you can always replace return with print if you want.
You were very close:
def ex1(name):
reverseName=""
for x in range(len(name)-1,-1,-1):
reverseName+=name[x]
print reverseName
The print statement prints a newline character (a line break) after each line, this is why you get your characters in vertical. The solution is not to print the character in each loop, but to collect them in a string and print the final string at once at the end.
Note that there are more efficient ways of doing this (see the other answers), but it might be the most straightforward way and the closest one to what you have already done.
Here is another way that you can reverse a string.
def ex1(name):
length = len(name)
return "".join([name[length-x-1] for x in range(0, length)])
print ex1("hello world")
name=input("Whats your name ?")
def reversemyname(name):
x=name[::-1]
return x
reversedname=reversemyname(name)
print(reversedname)
print(name[x]), # <= add that comma
if you want the output like this kroy wen then try this:
sys.stdout.write(name[x])
remember to import sys

How list every item of dir(object)?

In Python, to find all attributes, there is:
dir(object)
object.__dict__.keys()
But what i want is to list what is in the second branch, not only the first branch, it's kind of a recursive operation?
How to do that?
it's like
dir(dir(x) for x in dir(math))
tried this and still get the same result duplicated:
>>> for i in dir(math):
... for j in i:
... print dir(j)
and all results are the methods of str
Update: it seems that the dir() commande returns a list of str, here is a simple hack; I tried to exclude the reserved names to see if i go further, but the result was only str
[i for i in dir(math) if i[0]!="_"]
[type(i) for i in dir(math) if i[0]!="_"]
Thank you again :)
object.__dict__.keys() # Just keys
object.__dict__.values() # Just values
object.__dict__.items() # Key-value pairs
Edit wait! I think I misunderstood. You want to list an object's properties, and those properties' properties and so on and so forth? Try something like this:
def discover(object):
for key in dir(object):
value = getattr(object, key)
print key, value
discover(value)
It's pretty crude, but that's the recursion I think you're looking for. Note that you will have to stop it manually at some point. There's no turtles at the bottom, it goes on and on.

How to convert a tuple to a string in Python?

After a MySQL select statement, I am left with the following:
set([('1#a.com',), ('2#b.net',), ('3#c.com',), ('4#d.com',), ('5#e.com',), ('6#f.net',), ('7#h.net',), ('8#g.com',)])
What I would like to have is a
emaillist = "\n".join(queryresult)
to in the end, have a string:
1#a.com
2#b.net
3#c.com
etc
What would be the proper way to convert this nested tuple into string?
As long as you're sure you have just one element per tuple:
'\n'.join(elem[0] for elem in queryresult)
A list comprehension along the lines of
[item[0] for item in queryresult]
should help. eg,
emaillist = "\n".join([item[0] for item in queryresult])
.. this makes strong assumptions about the type and structure of queryresult, however.
edit
A generator expression is even better at doing this:
emaillist = "\n".join(item[0] for item in queryresult)
thanks to #delnan for this update
Try this and see
>>> something=set([('1#a.com',), ('2#b.net',), ('3#c.com',), ('4#d.com',), ('5#e.com',), ('6#f.net',), ('7#h.net',), ('8#g.com',)])
>>> print '\n'.join(''.join(s) for s in something)
6#f.net
7#h.net
2#b.net
1#a.com
8#g.com
5#e.com
4#d.com
3#c.com
Note, join can only work on strings, but the items of the set are tuples. To make the join work, you have to iterate over the set to convert each item as string. Finally once done you can join them in the way your heart desires
On a side note. A circumbendibus way of doing it :-)
>>> print "\n".join(re.findall("\'(.*?)\'",pprint.pformat(something)))
1#a.com
2#b.net
3#c.com
4#d.com
5#e.com
6#f.net
7#h.net
8#g.com
new = '\n'.join(x[0] for x in old)

Categories