Change Letters to numbers (ints) in python - python

This might be python 101, but I am having a hard time changing letters into a valid integer.
The put what I am trying to do simply
char >> [ ] >> int
I created a case statement to give me a number depending on certain characters, so what I tried doing was
def char_to_int(sometext):
return {
'Z':1,
'Y':17,
'X':8,
'w':4,
}.get(sometext, '')
Which converts the letter into a number, but when I try using that number into any argument that takes ints it doesn't work.
I've tried
text_number = int(sometext)
But I get the message TypeError: int() argument must be a string or a number, not 'function'
So from there I returned the type of sometext using
print(type(sometext))
And the return type is a function.
So my question is, is there a better way to convert letters into numbers, or a better way to setup my switch/def statement
Heres the full code where its call
if sometext:
for i in range ( 0, len(sometext)):
char_to_int(sometext[i])
I've managed to get it working, ultimately what I changed was the default of the definition, I now set the definition to a variable before instead of calling it in another function, and I recoded the section I was using it.
Originally my definition looked liked this
def char_to_int(sometext):
return {
...
}.get(sometext, '')
But I changed the default to 0, so now it looks like
def char_to_int(sometext):
return {
...
}.get(sometext, 0)
The old code that called the definition looked
if sometext:
for i in range ( 0, len(sometext)):
C_T_I = int(char_to_int(sometext[i]))
I changed it to this.
if sometext:
for i in range ( 0, len(sometext)):
C_T_I = char_to_int(sometext[i])
TEXTNUM = int(C_T_I)
Hopefully this clarifies the changes. Thanks for everyone's assistance.

in the python console:
>>> type({ 'Z':1, 'Y':17, 'X':8, 'w':4, }.get('X', ''))
<class 'int'>
so as cdarke suggested, you should look at how you are calling the function.

Related

python s=input().count What does input().count function do in python?

I saw this code on the internet:
s=input().count
print( max( (s('6')+s('9')+1)//2, max([s(i) for i in "01234578"])))
but I don't get what this line does :
s=input().count
I thought this function was to count how many letters are in the word. So I tried to print the s, but I got this error:
<built-in method count of str object at 0x7f4f8b859148>
what does input().count function do and what situation will it be used?
s=input().count is a function which you can call.
You could write
input().count('6')
to count how many times you get 6 in the input.
Or,
s('6')
is now a shorthand for this.
s = input().count
Basically you are binding the count method to s so when you call s like s(i), it converts the code to input().count(i) internally.
Let me give you a simple example:
p = print
p("hello world")
# hello world

Avoiding the mistake of comparing number and string

We've all made this kind of mistake in python:
if ( number < string ):
python silently accepts this and just gives incorrect output.
Thank goodness python 3 finally warns us. But in some cases python 2.7 is needed. Is there any way in python 2.7 to guard against this mistake other than "just be careful" (which we all know doesn't work 100% of the time)?
You could explicitly convert both numbers to int. The string will get converted, and the number won't be effected (it's already an int). So this saves you the need to start remembering what type of value the number holds:
a = 11
b = "2"
print a > b # prints False, which isn't what you intended
print int(a) > int(b) # prints True
EDIT:
As noted in the comments, you cannot assume a number is an integer. However, applying the same train of though with the proper function - float should work just fine:
a = 11
b = "2"
print a > b # prints False, which isn't what you intended
print float(a) > float(b) # prints True
If you really, really want to be 100% sure that comparing strings and ints is impossible, you can overload the __builtin__.int (and __builtin__.float, etc. as necessary) method to disallow comparing ints (and floats, etc) with strings. It would look like this:
import __builtin__
class no_str_cmp_int(int):
def __lt__(self,other):
if type(other) is str:
raise TypeError
return super.__lt__(other)
def __gt__(self,other):
if type(other) is str:
raise TypeError
return super.__gt__(other)
# implement __gte__, __lte__ and others as necessary
# replace the builtin int method to disallow string comparisons
__builtin__.int = no_str_cmp_int
x = int(10)
Then, if you attempted to do something like this, you'd receive this error:
>>> print x < '15'
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
print x < '15'
File "tmp.py", line 7, in __lt__
raise TypeError
TypeError
There is a major caveat to this approach, though. It only replaces the int function, so every time you created an int, you'd have to pass it through the function, as I do in the declaration of x above. Literals will continue to be the original int type, and as far as I am aware there is no way to change this. However, if you properly create these objects, they will continue to work with the 100% assurance you desire.
Just convert the string or any data type to float first.
When two data types are same, then only we can compare them.
Suppose,
a = "10"
b= 9.3
c=9
We want to add a,b,c.. So,
So, the correct way to add these three is to convert them to same data type and then add.
a = float(a)
b = float(b)
c = float(c)
print a+b+c
You can check if each variable is an int like this :
if ( isinstance(number, int) and isinstance(string, int) ):
if (number < string):
Do something
else:
Do something else
else :
print "NaN"
*Edit:
To check for a float too the code should be :
if ( isinstance(number, (int,float )) and isinstance(string, (int,float) ) ):

writing odd number in a list python

This is a part of my homework assignment and im close to the final answer but not quite yet. I need to write a function that writes the odd number between position 1 and 5 in a list.
I make something like that:
-in a file domain I write the condition for odd number:
def oddNumber(x):
"""
this instruction help us to write the odd numbers from the positions specificated
input: x-number
output:-True if the number is odd
-False otherwise
"""
if x % 2==1:
return True
else:
return False
-then the tests:
def testOdd_Number():
testOdd_Number=[0,1,2,3,4,5,6,7,8]
oddNumber(testOdd_Number,0,6)
assert (testOdd_Number==[1,3,5])
oddNumber(testOdd_Number,0,3)
assert (testOdd_Number==[3])
-and in the other file named userinterface I write this:
elif(cmd.startswith("odd from ", "")):
try:
cmd=cmd.replace("odd from ", "")
cmd=cmd.replace("to ", "")
i=int(cmd[:cmd.find(" ")])
j=int(cmd[cmd.find(" "):])
if (i>=len(NumberList) or i>j or j>=len(NumberList) or i<0 or j<0):
print("Invalid value(s).")
else:
for m in range(i-1,j):
if oddNumber(NumberList[m]):
print (NumberList[m])
except:
print("Error!")
-when I run the entire project(I have more requirements but the others one are good), and write odd from [pos] to [pos] it says me
Traceback (most recent call last):
File "C:\Users\Adina\My Documents\LiClipse Workspace\P1\userinterface.py", line 94, in <module>
run()
File "C:\Users\Adina\My Documents\LiClipse Workspace\P1\userinterface.py", line 77, in run
elif(cmd.startswith("odd from ", "")):
TypeError: slice indices must be integers or None or have an __index__ method
I've forgotten to say that I have a also a function main() where I print the requirements.Where am I wrong?
Python's string startswith method, described here:
https://docs.python.org/2/library/stdtypes.html
states that arguments are
some_string.startswith(prefix, beginning, end) #where beginning and end are optional integers
and You have provided prefix and empty string ( cmd.startswith("odd from ", "") )
Some things I noticed:
1) you can shorten your oddNumber function to
def oddNumber(x):
return x%2
2) in your tests, you rebind the functions name testOdd_Number to some list, then pass that around to your oddNumber function. is that the same function described above? Then it won't work, as this function expects a single integer to be passed.
Using the same name to refer to two different things is discouraged.
Actually, I have no idea what your testcode does or should do. Are you passing a list and expect oddNumber to modify it in place?
3) your custom command parser looks... odd, and fragile. Maybe invest in a real parser?
You should decouple command parsing and actual computation.
As brainovergrow pointed out, there is also your error, since .startswith does not accept a string as second argument.
Some general hints:
You can use list(range(9)) instead of hardcoding [0,1,2,3,4,5,6,7,8]
You can use filter to filter the odd numbers of a given list:>>> list(filter(oddNumber, range(9))) yields [1, 3, 5, 7].
You can also use list comprehensions: [x for x in range(9) if x%2] yields the same.
you might find any() and all() useful. Take a look at them.
Your naming scheme is neighter consistent nor pythonic. Read PEP8 for a style guide.

How do I get the alias of a function call?

The problem I'm having is I don't know how to get the alias of a function call.
what the code works on is for tracking the text:
"struct(...)"
in the code:
x = struct(...)
when calling:
x()
How the IDE works is 'x = struct(...)' only defines an area in a call-tree which creates an indent in the tree, it doesn't actually do anything in the file data.
When you call 'x()' is when the file data is highlighted with the color of 'color = hash("struct(...)")'.
So I need to get the alias 'x' so I can track the call in the code...
I can't exactly help anyone reproduce this as the code for doing so is rather large...
but I just need ideas as I can't seem to find any decent examples on Google.
I'm looking for cases such as:
the obvious:
x = struct(...)
the not so obvious:
p,x,t = 0, struct(...), True
the highly irrelevant:
p,x,t = (
0,
struct(...),
True )
all resulting in a call to x()
I'm using tokenize to get the call-name of struct(), and I have the entire code stored in 'self.codeeditor.data'...
How do I use "struct" to get "x"??
EDIT:
I could mention that x would be in instance of a dynamically created _SUB_STRUCT class returned by struct().
I don't think tokenize will really work here; you'd be better off working on the level of syntax trees using ast and looking for Assign nodes.
For example:
>>> [n.targets[0].id for n in ast.walk(ast.parse("x = struct()"))
if isinstance(n, ast.Assign)
and isinstance(n.value, ast.Call)
and n.value.func.id == 'struct']
['x']
You should be able to use a dict to get the functionality you desire:
# Relates a label to a function
function_maps = {'a':str, 'b':int, 'c':print}
# Will print 'Hello World!'
function_maps['c']('Hello World!')
# Lets look for the `int` function
for key, value in function_maps.items():
if value == int:
print('The alias for `int` is: {}'.format(key))
Without seeing more of your code, this is the way I would suggest doing it.

'str' object is not applicable

I have the following little function written in Python:
def encode(str):
out = ""
for i in str:
ret += str(ord(i.upper()) - 64)
return ret
Basically, what I want to do is get the number of the letter in the alphabat and concatenate it to the 'out' string. With this code I get a traceback at line 4: 'str' object is not applicable.
Could someone please explain me why it throws this error and how I can fix this? (Sorry if this was already asked once, I couldn't find it, probably also because I'm pretty new to Python and programming)
Never name your variable on the pre-defined built-in name.
In your code, str is not a built-in function. It's the variable you have used as parameter in your function.
Another problem is, you have declared out variable, and using ret which will give you error. Change out = "" to ret = "".
Don't call your variable str, you're shadowing the built-in function.
Also, you need to fix the naming of out/ret.
I personally would write this function as follows:
def encode(s):
return ''.join(str(ord(c.upper()) - 64) for c in s)
(I don't really follow what the str(ord(...)) is meant to be doing, so I've just copied it from your code.)
As the others have said, do not use str as a variable.
I suspect this is what you want though:
def encode(s):
return "".join(chr(ord(c.upper()) - 64) for c in s)
This is equivalent to:
def encode(s):
out = ""
for c in s:
ret += chr(ord(c.upper()) - 64)
return ret
You were looking for the chr() function, which converts a numerical ASCII/Unicode value into a 1-character string. Running str() would convert 5 to "5".
Also on a stylistic note, it's customary to do for c in s when iterating over a string, and for i in x when iterating over a sequence of integers.

Categories

Resources