Refer to a basic atoi in C:
int myAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and update result
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
Which translates into the Python:
def atoi(s):
rtr=0
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return rtr
Test it:
>>> atoi('123456789')
123456789
If you want to accommodate an optional sign and whitespace the way that int does:
def atoi(s):
rtr, sign=0, 1
s=s.strip()
if s[0] in '+-':
sc, s=s[0], s[1:]
if sc=='-':
sign=-1
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return sign*rtr
Now add exceptions and you are there!
Answer from dawg on Stack OverflowRefer to a basic atoi in C:
int myAtoi(char *str)
{
int res = 0; // Initialize result
// Iterate through all characters of input string and update result
for (int i = 0; str[i] != '\0'; ++i)
res = res*10 + str[i] - '0';
// return result.
return res;
}
Which translates into the Python:
def atoi(s):
rtr=0
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return rtr
Test it:
>>> atoi('123456789')
123456789
If you want to accommodate an optional sign and whitespace the way that int does:
def atoi(s):
rtr, sign=0, 1
s=s.strip()
if s[0] in '+-':
sc, s=s[0], s[1:]
if sc=='-':
sign=-1
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return sign*rtr
Now add exceptions and you are there!
This is really inefficient but:
>>> zero = ord("0")
>>> s = "1234"
>>> sum([x * 10**i for i, x in enumerate(map(lambda x: x - zero, map(ord, s))[::-1])])
1234
This is slightly better:
>>>> sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])])
1234
>>> atoi = lambda s: sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])])
>>> atoi("1234")
1234
Videos
I want to convert a sting of a single number, for example ['14'] into just 14. I tried all kinds of replace functions to separate just the number, but they all end up as an error. Any help is greatly appreciated!
Doctstrings
The docstring:
"""
Convert numeric string to number withoutusing python's built in functions.
"""
Should be at the top of the inside of the function.
(Also withoutusing should be without using.)
Global Variables
Global variables are typically a bad design practice. Move these:
dec_places = {6:100000, 5:10000, 4:1000, 3:100, 2:10, 1:1}
char_digit = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
Inside the function.
Function naming
str2int should be renamed to str_to_int.
Better algorithm
dec_places is unneeded and limits your algorithm significantly.
I would enumerate over the reversed of your string:
for ind, char in enumerate(reversed(num_str)):
number += char_digit[char] * 10**(ind + 1)
enumerate takes an iterable and creates tuples of (0, el1), (1, el2) ....
We reverse the string and then multiply each character by the appropriate power of 10. This allows you to go beyond the 6th power.
Alternatively, you can keep an iter value that counts up from 1. I'll leave this as an exercise. It might be faster than using reversed. You should not need a dictionary though.
You should avoid using iter as a variable name, since it happens to be the name of a built-in function. It's confusing to other Python programmers who have to read your code, and could produce a failure if you ever want to call the standard iter() function.
In any case, you don't want to have a clumsy loop that is based on char and also maintains iter. You certainly don't want an algorithm that puts an upper bound on the numbers you can handle. The standard algorithm goes like this:
CHAR_DIGIT = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
def str2int(num_str):
"""
Convert numeric string to number without using Python's built in functions.
"""
number = 0
for char in num_str:
number = 10 * number + CHAR_DIGIT[char]
return number
my_input = int(my_input)
There is no shorter way than using the int function (as you mention)
Maybe you were hoping for something like my_number = my_input.to_int. But it is not currently possible to do it natively. And funny enough, if you want to extract the integer part from a float-like string, you have to convert to float first, and then to int. Or else you get ValueError: invalid literal for int().
The robust way:
my_input = int(float(my_input))
For example:
>>> nb = "88.8"
>>> int(nb)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '88.8'
>>> int(float(nb))
88
here is the code:
integer = 170
string = 'sadsad'
print(integer+int(string))
ps thx
Hello Everyone,
I was wondering if it's possible to get the input of a string from the user and convert it into an integer later on. I'm asking this as the code I'm working on requires a string input from the user of what service they'd like. I later had to add up the totals of the services and wondered if once the choice was selected or inputted then if it would become a number that later adds up to the total cost if multiple services are inputted.
This is a long code that works:
def string_to_int(s):
rtr=0
for c in s:
rtr=rtr*10 + ord(c) - ord('0')
return rtr
print(string_to_int("12445"))
output:
12445
I found this at https://www.geeksforgeeks.org/how-to-convert-string-to-integer-in-python/
# User-defined function to
# convert a string into integer
def string_to_int(input_string):
output_int = 0
# Check if the number contains
# any minus sign or not,
# i.e. is it a negative number or not.
# If it contains in the first
# position in a minus sign,
# we start our conversion
# from the second position which
# contains numbers.
if input_string[0] == '-' :
starting_idx = 1
check_negative = True
else:
starting_idx = 0
check_negative = False
for i in range(starting_idx, len(input_string)):
# calculate the place value for
# the respective digit
place_value = 10**(len(input_string) - (i+1))
# calculate digit value
# ord() function gives Ascii value
digit_value = ord(input_string[i]) - ord('0')
# calculating the final integer value
output_int += place_value * digit_value
# if check_negative is true
# then final integer value
# is multiplied by -1
if check_negative :
return -1 * output_int
else:
return output_int
# Driver code
if __name__ == "__main__" :
string = "554"
# function call
x = string_to_int(string)
# Show the Data type
print(type(x))
string = "123"
# Show the Data type
print(type(string_to_int(string)))
string = "-123"
# Show the Data type
print(type(string_to_int(string)))
The "purest" I can think of:
>>> a = "546"
>>> result = 0
>>> for digit in a:
result *= 10
for d in '0123456789':
result += digit > d
>>> result
546
Or using @Ajax1234's dictionary idea if that's allowed:
>>> a = "546"
>>> value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
>>> result = 0
>>> for digit in a:
result = 10 * result + value[digit]
>>> result
546
You can keep a dictionary that stores the string and integer values of a numeric key, and then iterate over the string. While iterating over the string, you can use enumerate to keep track of the index and then raise 10 to that power minus 1 and then multiply by the corresponding key from the dictionary:
a = "546"
length = 0
for i in a:
length += 1
d = {'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
count = 0
counter = 0
for i in a:
count += (10**(length-counter-1)*d[i])
counter += 1
print(count)
Output:
546
Okay, so I had a crash course in Python a looooong time ago, and that's all the prior experience I have with it. I'm starting to dabble in it again, playing around with it to make a text-based game.
In this game, you have stats - Speed, Health, etc etc. Each of these is a number (an int).
I am trying to define a function names statdisplay() so that when I call on it, it prints out your stats. So, if you have a Speed of 1, and the max Speed you can increase that stat to is 5, one of the printed lines would be:
Speed: 1 / 5
This was my ORIGINAL code:
print("\nHealth: " + healthstat + " / " + maxhealth)
print("\nHunger: " + hungerstat + " / " + maxhunger)
print("\nStalking Skill: " + stalkingstat + " / 5")
print("\nHunting Skill: " + huntingstat + " / 5")
print("\nSpeed: " + speedstat + " / 5")
print("\nStrength: " + speedstat + " / 5")But then I got the following error:
TypeError: can only concatenate str (not "int") to str
So I mentally facepalmed myself and looked up how to convert an int to a string, and I keep reading that you can use the str() function (I know there are other ways, but I'm taking baby steps here trying to jog my memory on how everything works before I go doing everything by what's deemed "most appropriate").
This is my NEW code with that in mind:
print("\nHealth: " + str(healthstat) + " / " + maxhealth)
print("\nHunger: " + str(hungerstat) + " / " + maxhunger)
print("\nStalking Skill: " + str(stalkingstat) + " / 5")
print("\nHunting Skill: " + str(huntingstat) + " / 5")
print("\nSpeed: " + str(speedstat) + " / 5")
print("\nStrength: " + str(speedstat) + " / 5")...and yet I am still getting the following error:
TypeError: can only concatenate str (not "int") to str
I can't seem to figure out what's wrong. I do not have the str() function defined as anything else. str() also doesn't seem to come from any special libraries that I'd need to import, but maybe I'm wrong there (I tried to look it up)... the only import I currently have is "import random".
My only other thought is that maybe it's a Google Colab thing, as that's where I'm currently running my code since this wasn't anything serious and I tend to go between two different computers.
Any help would be much appreciated!
Edit: accidentally had the new code in both code boxes.