I am out of trial and error again Lists
Seymore4Head
Seymore4Head at Hotmail.invalid
Thu Oct 23 09:53:48 EDT 2014
On Thu, 23 Oct 2014 00:10:28 -0700, Larry Hudson <orgnut at yahoo.com>
wrote:
>On 10/22/2014 03:30 PM, Seymore4Head wrote:
>> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head
>> <Seymore4Head at Hotmail.invalid> wrote:
>>
>> One more question.
>> if y in str(range(10)
>> Why doesn't that work.
>> I commented it out and just did it "long hand"
>>
>> def nametonumber(name):
>> lst=[]
>> nx=[]
>> for x in (name):
>> lst.append(x)
>> for y in (lst):
>> #if y in str(range(10)):
>> if y in "1234567890":
>> nx.append(y)
>> if y in " -()":
>> nx.append(y)
>> if y in "abc":
>> nx.append("2")
>> if y in "def":
>> nx.append("3")
>> if y in "ghi":
>> nx.append("4")
>> if y in "jkl":
>> nx.append("5")
>> if y in "mno":
>> nx.append("6")
>> if y in "pqrs":
>> nx.append("7")
>> if y in "tuv":
>> nx.append("8")
>> if y in "wxyz":
>> nx.append("9")
>> number="".join(str(e) for e in nx)
>> return (number)
>> a="1-800-getcharter"
>> print (nametonumber(a))#1800 438 2427 837
>> a="1-800-leo laporte"
>> print (nametonumber(a))
>> a="1 800 callaprogrammer"
>> print (nametonumber(a))
>>
>I know you are trying to explore lists here, but I found myself somewhat intrigued with the
>problem itself, so I wrote a different version. This version does not use lists but only
>strings. I'm just presenting it as-is to let you try to follow the logic, but if you ask, I'll
>explain it in detail. It turns your long sequence of if's essentially into a single line --
>unfortunately 's' and 'z' have to be handled as special-cases, which turns that single line into
>a six-line if/elif/else set. You might consider this line 'tricky', but I'll just say it's just
>looking at the problem from a different viewpoint. BTW, this version accepts upper-case as well
>as lower-case. isdigit() and isalpha() are standard string methods.
>
>#------ Code ----------
>def name2number(name):
> nstr = '' # Phone-number string to return
> codes = 'abcdefghijklmnopqrtuvwxy' # Note missing s and z
>
> for ch in name:
> if ch in " -()":
> nstr += ch
> elif ch.isdigit():
> nstr += ch
> elif ch.isalpha():
> ch = ch.lower()
> # S and Z are special cases
> if ch == 's':
> nstr += '7'
> elif ch == 'z':
> nstr += '9'
> else:
> nstr += str(codes.index(ch) // 3 + 2)
> return nstr
>#------- End of Code ---------
>
>A possible variation would be to make nstr a list instead of a string, and use .append() instead
>of the +=, and finally return the string by using join() on the list. Also, the if and first
>elif in the for could be combined: if ch in " -()" or ch.isdigit():
>
> -=- Larry -=-
Sure I will have a look at it. I am always open on better ways to do
something.
Thanks
More information about the Python-list
mailing list