How do you convert a string to an integer in Python - python

"""
A trimorphic number is a number whose cube ends in the number itself.
For example:
Input: 4
Output: true (4^3 is 64, which ends in 4)
Input: 24
Output: true (24^3 = 13824)
Input: 249
Output: true (249^3 = 15438249)
Write a program to check if the user input is a trimorphic number or not.
"""
num = int(input("Enter a number:"))
print(num)
num_cube = pow(num, 3)
str(num_cube)
print(num_cube[len(num_cube) - 1:] == num)
I tried running the code and I got a TypeError at line 22 (the last line) even though I converted the variable num_cube to a string in order to slice it. Why does it not work?

You should use the endswith function to check whether the last "n" characters in the cube are equal to the string representation of the number you are passed.
You could thus do:
print(str(num_cube).endswith(num))
The way you have currently implemented it, you are "hard coding" the expected length of the number read from the stdin and are thus assuming it to always be of length 1.
To correct your code, you would do the following:
>>> num = "24"
>>> num_cube = str(pow(int(num), 3))
>>> num_cube[len(num_cube) - len(num):] == num
True
>>> num_cube[-len(num):] == num # negative indexing
True

str(num_cube) is not assigned, so you are converting it but still using num_cube which is an int, hence the TypeError. Also, you need to compare it to another string, not to to num which is another integer:
print(str(num_cube)[-3:] == str(num))

Related

Loops through a whole list

I have a pretty simple function where the user is asked to input a list of numbers, then a second input for a second number. If any single number in the first argument is larger than the second argument, then it will return True, and if none of the numbers in the first argument in larger, it should return false. Seems simple enough but I'm struggling to get it to loop through the entire list before it returns the boolean value. A new problem I'm having throws up an error and says I'm trying to compare int's to lists with the > operator.
def num_gt(list_num, single_num):
#breakpoint()
for i in list_num :
if i > single_num :
return True
else:
return False
list_num = (input("Please enter list numbers: "))
single_num = (input("Please enter single number: "))
list_num = list(map(int, list_num))
single_num = list(map(int, single_num))
Not sure where I'm goinging wrong here. The inputs get converted to lists of integers, and stepping through it shows its return lists as it should. Any help appreciated
You need to not cast your single num to a list as it is a single value.
Remove the line.
single_num = list(map(int, single_num))
And replace with:
single_num = int(single_num)
Your function is also slightly wrong as it will only check one value then always return. It should instead check all the values and only if all of them are smaller then return false.
def num_gt(list_num, single_num):
#breakpoint()
for i in list_num :
if i > single_num :
return True
return False
Now your function will check all the values and then if none of them return True, it will return False at the end.

How to make a code that detects repeating digits in a number python?

I want a simple code that can detect if number contains a repeated digit or not.
In python
without counter method.
For example,
if I enter 1234555
it sends a message that tells me invalid input
def isUnique(number):
numberSet = set(list(number))
if len(number) == len(numberSet):
return True
else:
return False
change the number to string first
str_number= str(number)
return len(str_number)==len(set(str_number))
Your code assumes that the number is provided as a string (you can't convert an int variable to list). Try:
def isUnique(num):
number = str(num) # convert provided num to string
numberSet = set(number)
return len(number) == len(numberSet)

python string and integer comparison

I want to print all the numbers until the given user input using while loop. Example:Enter:5 ==> 1 2 3 4 5 But the below program loops for ever.
user = str(input("Enter : "))
i = 1
while i < user:
print(i)
i = i + 1
ummm while i < int(user):?
Try this instead:
try:
user = int(raw_input('Enter: ')) # Cannot compare a string with an integer.
except ValueError:
print('Input should be an integer!')
i = 1
while True:
i += 1
if i > user:
break
print(i)
Note: In your code, even if we were to explicitly declare the input as an integer it would still not quite work the way you want it to. This is because in your code the while loop stops once i is equal to user (as the condition is while less than... and will thus not print out the final value, user. I therefore modified it so it breaks at the point where i is greater than user, meaning that the last printed value will be equal to user.
Example previous output where user = 5:
1
2
3
4
And with the new code:
1
2
3
4
5
It is however better to use a for loop here, if you are not set on using a while loop:
for i in range(1, user+1):
print(i)
input in Python 2.x will try to evaluate what the user enters, it is equivalent to
user = eval(raw_input(...))
In this case, you are explicitly converting whatever is supplied to a string (with str()). In Python 2.x, strings always compare larger than numbers, so i < user is always True.
It is wiser to use raw_input and convert to int. You can also simplify your code with a for loop:
user = int(raw_input("Enter : "))
for i in range(user):
print(i)
You are comparing an int to a str and that is why you are getting an infinite loop. You should compare the same type of variables
user = int(input("Enter: "))
should work

Why do I appear to have an infinite loop?

This is part of a tutorial. My goal was to take an input from user and then increment it while a condition is true.
inputNum = raw_input("What is max number?")
def incrementF(greatest):
i = 0
numbers = []
while i < greatest:
print "At the top of the list numbers is %d" % i
numbers.append(i)
i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers:"
for num in numbers:
print num
incrementF(inputNum)
When I run the script and type anything in for inputNum, rather than a few lines of output, I appear to run into an infinite loop.
For example, is the raw input prompt gave 10, I'd have expected to see something like:
At the top of the list numbers is 0,
Numbers now: 0,
0
At the top of the list numbers is 1,
Numbers now: 1,
1
I've read over my script several times and cannot see. I suspect it could have something to do with indenting? But I'm not sure.
As quoted in the docs for raw_input:
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that.
So, greatest will be a string because you used raw_input to get it.
Furthermore, in Python 2.x, strings are always evaluated as being greater than integers*:
>>> 1 < 'a'
True
>>> 100000000000 < 'a'
True
>>>
This means that the condition of your while-loop will always evaluate to True because greatest will always be evaluated as being greater than i. Thus, you get an infinite loop.
You can fix this problem simply by making greatest an integer like i:
inputNum = int(raw_input("What is max number?"))
*Note: If you would like some more information on this, see How does Python compare string and int?

Create an array and store in a different function

This program creates an array in main and prompts the user to enter 5 integers and stores them in a array in a different function. It then creates a function that accepts the array and returns a true if the array contains only odd numbers or false if it does not. Print a message indicating the results being either the array contains both odd and even numbers or the array contains only odd numbers.
I keep getting TypeError:Unsupported operand types for /: 'list' and 'int'.
def main():
integer = 5
intArray = [0] * integer
for index in range(integer):
intArray[index] = int(input("Enter integers:"))
print(intArray)
fibArray(integer)
containsOnlyOdds(intArray)
return intArray
def fibArray(num):
fibArray = [0] * num
for index in range(num):
print(num)
def containsOnlyOdds(notEven):
average = (notEven / 2) % 2
for odd in range(average):
if notEven %2 != 0:
print('This array contains only odd numbers')
else:
print('This array contains odd and even numbers')
main()
Even without seeing your indentation, I can give you a simple way to check for all odds:
def check_list(lst):
for num in lst:
if num % 2 == 0:
return False
return True
The check_list() function takes a list argument and checks if each number in the list is divisible by 2. If a number is, clearly it is even and the function returns False. This is efficient because as soon as it finds an even number, it exits, rather than searching the entire list.
Now that you fixed your formatting:
It appears that you are trying to divide a list by a factor of 2 in your containsOnlyOdds function. It is not possible to divide a list, you need to set up a loop to loop through each index of the list, and then check if each number is divisible by 2 or not.

Categories