I need to create a program that will take a integer, (e.g. 4586), and return the number with the digits in descending order (e.g. 8654).
num = 4586
num1 = num #num1 is a string
descendingNumber = []
for i in num1:
for j in i:
if i < j:
descendingNumber.append(i)
else:
descendingNumber.insert(1,i)
What am I doing wrong?
That insertion process doesn't look quite right. You can accomplish this in one line using built-ins.
First, we get the individual digits by using str(), and then sort them using sorted(). This gives us a list of digits, so we then use ''.join() to turn it back into a string. Finally, we cast the result back into an integer to get our desired output.:
int(''.join(sorted(str(num), reverse=True)))
This outputs:
8654
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I want to cast elements in a list (string to integer)
Can't find what my mistake is. I just get strings.
Some other post answers suggest list comprehensions, but, being a newbie, I prefer understanding why this more basic approach doesn't work, before learning list comprehensions.
Thanks for your help.
(Using Python 3)
I tried:
while True:
userInput=input("Write space-separated numbers: ")
listNumbers=userInput.split()
for i in listNumbers:
int(i)
print(type(listNumbers[0]))
Also tried:
for i in listNumbers:
i=int(i)
I expect the type(listNumbers[0]) or whatever index number to return integer
but the output is still a string.
You must do:
for i in range(0, len(listNumbers)):
listNumbers[i] = int(listNumbers[i])
or:
for idx, val in enumerate(listNumbers):
listNumbers[idx] = value
This can be shortened using:
listNumbers = [int(x) for x in listNumbers]
When doing:
for i in listNumbers):
i = int(i)
i is only a reference to the elements so you can't change the original value of the list.
When doing:
for i in listNumbers:
int(i)
You don't store the result of int(i).
The problem comes from the fact that you do not store the integer in the loop !
Do :
mylist = []
for i in listNumbers:
mylist.append(int(i))
The best solution is
listNumbers = list(map(int, listNumbers))
int(i) does not convert the element i in the list to an integer, you would need to explicitly assign int(i) back to the element in the list for that to happen
while True:
userInput=input("Write space-separated numbers: ")
listNumbers=userInput.split()
#Iterate over the list and get index and element of list
for idx, i in enumerate(listNumbers):
#Cast string to int and assign back to list
listNumbers[idx] = int(i)
#Get the type
print(type(listNumbers[0]))
The output will be
Write space-separated numbers: 1 3 5
<class 'int'>
you need to actually save your modified value back into the list
for i,val in enumerate(my_list):
my_list[i] = int(val)
but as mentioned its much better to just use a list comprehension
new_list = [int(val) for val in my_list]
Your first variant doesn't do anything, because the cast value is just thrown away.
Your second variant does assign the value to i, but that doesn't change the value that is stored in the list.
I suggest using a list comprehension instead:
while True:
userInput=input("Write space-separated numbers: ")
listNumbers=[int(i) for i in userInput.split()]
print(type(listNumbers[0]))
So i'm studying recursion and have to write some codes using no loops
For a part of my code I want to check if I can sum up a subset of a list to a specific number, and if so return the indexes of those numbers on the list.
For example, if the list is [5,40,20,20,20] and i send it with the number 60, i want my output to be [1,2] since 40+20=60.
In case I can't get to the number, the output should be an empty list.
I started with
def find_sum(num,lst,i,sub_lst_sum,index_lst):
if num == sub_lst_sum:
return index_lst
if i == len(sum): ## finished going over the list without getting to the sum
return []
if sub_lst_sum+lst[i] > num:
return find_sum(num,lst,i+1,sub_lst_sum,index_lst)
return ?..
index_lst = find_sum(60,[5,40,20,20,20],0,0,[])
num is the number i want to sum up to,
lst is the list of numbers
the last return should go over both the option that I count the current number in the list and not counting it.. (otherwise in the example it will take the five and there will be no solution).
I'm not sure how to do this..
Here's a hint. Perhaps the simplest way to go about it is to consider the following inductive reasoning to guide your recursion.
If
index_list = find_sum(num,lst,i+1)
Then
index_list = find_sum(num,lst,i)
That is, if a list of indices can be use to construct a sum num using elements from position i+1 onwards, then it is also a solution when using elements from position i onwards. That much should be clear. The second piece of inductive reasoning is,
If
index_list = find_sum(num-lst[i],lst,i+1)
Then
[i]+index_list = find_sum(num,lst,i)
That is, if a list of indices can be used to return a sum num-lst[i] using elements from position i+1 onwards, then you can use it to build a list of indices whose respective elements sum is num by appending i.
These two bits of inductive reasoning can be translated into two recursive calls to solve the problem. Also the first one I wrote should be used for the second recursive call and not the first (question: why?).
Also you might want to rethink using empty list for the base case where there is no solution. That can work, but your returning as a solution a list that is not a solution. In python I think None would be a the standard idiomatic choice (but you might want to double check that with someone more well-versed in python than me).
Fill in the blanks
def find_sum(num,lst,i):
if num == 0 :
return []
elif i == len(lst) :
return None
else :
ixs = find_sum(???,lst,i+1)
if ixs != None :
return ???
else :
return find_sum(???,lst,i+1)
I'm new to programming and have a Python-question!
What I want to do is:
Let the user type in a number (for ex 4512)
Sort this number, starting with the biggest digit (5421)
Sort the same number but starting with the smallest digit (1245)
Subtract the two numbers (5421-1245)
Print out the result
Here is what I have tried:
print("type in a number")
number = (input())
start_small = "".join(sorted(number))
start_big = "".join(sorted(number, reverse=True))
subtraction = ((start_big)-(start_small))
print(subtraction)
I'm getting the error
TypeError: unsupported operand type(s) for -: 'str' and 'str'
You forgot to convert the numbers to integers before doing arithmetic with them. Change the line where you do the subtraction to
subtraction = int(start_big) - int(start_small)
Try this
number = input('Please enter a number')
number = sorted(number, reverse=True)
number = ''.join(number)
print(int(number) - int(number[::-1]))
number[::-1] reverses the string, it's a feature of python called slicing, generally the syntax of a slice is
[start:stop:step] so leaving the first two arguments empty and filling -1 as the last, tells us to step through the list by negative 1, which starts from the last element, to the second to the last element whose index is -2 till it gets to the end of the string
iterables can also be sliced so this technique will work on tuples and lists
There are several answers on this question that explain more about slicing Explain Python's slice notation
Try:
print("type in a number")
number = input()
start_small = "".join(sorted(str(number)))
start_big = "".join(sorted(str(number), reverse=True))
subtraction = int(start_big)-int(start_small)
print(subtraction)
Using python 2.7. You have to use str() and int()
We can use abs if we are not sure about which one is large value
num = ''.join(sorted(input()))
res = abs(int(num) - int(num[::-1]))
print(res)
gives
32
9
I have a list like this, named x (which I have already split):
['16','bob','2440', '34']
I want to write a code that checks to see if any of the numbers are negative. The code I tried does not work. This is what I have tried:
for num in x:
if num < 0:
print ("Negative number")
Your list contains only strings. So you should cast them to floats (or integers, whatever you need) first:
a = ['"16','bob','2440', '-2', '34"']
for x in a:
try:
if float (x) < 0: print ('negative')
except: continue
EDIT: I changes int to float as OP is asking for numbers and not exclusively integers.
You need to turn your numbers into integers first; use a predicate function to try to do this:
def negative(string):
try:
return int(string.strip('"')) < 0
except ValueError:
return False
The predicate function here also removes quotes; your input list looks like it was not cleaned up properly and you may want to do so first before testing for negative values.
Then use that to test for negative values:
negative_values = [v for v in a if negative(v)]
or test if there are any negative values:
if any(negative(v) for v in a):
print "No negative values please!"
How about checking for - sign in the beginning of an item and for the rest of an item to consist of digits? One-liner:
>>> a = ["-1", "aa", "3"]
>>> any(s.startswith('-') and s[1:].isdigit() for s in a)
True
Using any, because you've said that you want to write a code that checks to see if any of the numbers are negative.
Note: if there can be negative floats, then just replace s[1:] with s[1:].replace(".", "").
Hope that helps.
First, you need to understand that neither '"16' nor '2440' are numbers - they are strings.
Secondly, you need to figure out what you want to do with '"16' - it doesn't represent a number, but I assume you want it to. You could alter these strings, but you should probably just use an appropriate method of splitting in the first place.
That said, you can do this:
x = ['"16','bob','2440', '34"']
def int_is_negative(s)
try:
return int(s) < 0
except ValueError:
return False
is_negative_num = [int_is_negative(s) for s in x]
I want to know how can I add these numbers in Python by using a loop? Thanks
num=input("Enter your number: ")
ansAdd= int(str(num)[7])+int(str(num)[5])+int(str(num)[3])+int(str(num)[1])
print....
you want to do it using a loop, here you go:
ansAdd = 0
for x in [7,5,3,1]:
ansAdd += int(str(num)[x])
However, using list comprehension is more pythonic
>>> s = '01234567'
>>> sum(map(int, s[1::2]))
16
Here is how it works:
s[1::2] takes a slice of the string starting at index 1 to the end of the string stepping by 2. For more information on slices see the Strings section of the Python Tutorial.
map takes a function and an iterable (strings are iterable) and applies the function to each item, returning a list of the results. Here we use map to convert each string-digit to an int.
sum takes an iterable and sums it.
If you want to do this without the sum and map builtins, without slices, and with an explicit for-loop:
>>> s = '01234567'
>>> total = 0
>>> for i in range(1, len(s), 2):
... total += int(s[i])
...
>>> total
16
>>> num=input()
12345678
>>> sum(map(int,num[:8][1::2]))
20
here num[:8][1::2] returns only the numbers required for sum(), num[:8] makes sure only the elemnets up to index 7 are used in calculation and [1::2] returns 1,3,5,7
>>> num[:8][1::2]
>>> '2468'
It seems you want to sum odd-numbered digits from user input. To do it with a loop:
num_str = raw_input("Enter your number: ")
ansAdd = 0
for digit in num_str[1::2]:
ansAdd += int(digit)
(The syntax [1::2] is python's string slicing -- three numbers separated by : that indicates start index, stop index and step. An omitted value tells python to grab as much as it can.)
There's a better way to do this without using a traditional loop:
num_str = raw_input("Enter your number: ")
ansAdd = sum(int(digit) for digit in num_str[1::2])
In python 2, input executes the entered text as python code and returns the result, which is why you had to turn the integer back into a string using str.
It is considered a security risk to use input in python 2, since the user of your script can enter any valid python code, and it will be executed, no questions asked. In python 3 raw_input has been renamed to input, and the old input was removed (use eval(input()) instead).