I was trying to sum the digits for every element in the list and print the sum of every element at once but my code below only gives me 6 6 6. My desired output is 6 1 2.
#pythonCode#
my_list = [15, 10, 20]
sum = 0
m = ""
for i in range(0, 3):
while m != 0:
rem= my_list[i] % 10
m = my_list[i] //10
my_list[i] = m
sum = sum + rem
print(sum)
You could do this using map to apply a lambda function - if I understand the desired output correctly:
>>> my_list = [15, 10, 20]
>>> list(map(lambda x: sum(int(s) for s in str(x)), my_list))
[6, 1, 2]
Written out in full, this is roughly equivalent to:
my_list = [15, 10, 20]
for integer in my_list:
total = 0
for digit in str(integer):
total += int(digit)
print(f"The sum of {integer} is {total}")
Output:
The sum of 15 is 6
The sum of 10 is 1
The sum of 20 is 2
Related
Is it possible to print integers in one line inside the brackets? I would like my output to look like this:
[0 1 1 2 3 5 8 13 21 34]
But due to the way I wrote my code I can add brackets at the end of the list 0 1 1 2 3 5 8 13 21 34[] but not start and end.
My code:
n = int(input("Input a number to create Fibonacci sequence: "))
def fibo(n):
if n <=0:
print("Incorrect input")
return []
if n == 1:
return [0]
a,b = 0,1
for i in range(0,n):
print(a , end = " ",)
#assign a=b and b=a+b to get the sequence
a,b=b,a+b
print()
fibo(n)
The output format you are looking for is the one you get when you print a list.
You can use recursion to progressively build th eresulting list:
def fibo(n,a=0,b=1): return [a]+fibo(n-1,b,a+b) if n else [a]
print(fibo(10)) # fibonacci up to index 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
It can also be done iteratively
n = 10 # first 10 fibonacci numbers
fibo = [0,1]
while len(fibo) < n: fibo.append(sum(fibo[-2:]))
print(fibo[:n])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
How can I search for the three maximum elements of a list and replace it at same index with its result when divided by 2.
Please what am I doing wrong:
input is: 2 5 8 19 1 15 7 20 11
output should be : 2 5 8 9.5 1 7.5 7 10 11
Index out of range is the result displayed
def numberInput(line):
lineInput = [int(i) for i in line.split()]
min1 = min(lineInput)
for j in range(len(lineInput)):
if lineInput[j]>min1 and lineInput[j] > lineInput[j+1]:
max1 = lineInput[j]/float(2)
else:
max1 = lineInput[j]/float(2)
lineInput[j] = max1
lineInput[j] = max1
return(lineInput)
number = '2 5 8 19 1 15 7 20 11'
print(numberInput(number))
If the order of list isn't important, you can simply sort the list in descending order and then replace the first 3 elements as
a = [2, 5, 8, 19, 1, 15, 7, 20, 11]
a.sort(reverse = True)
a[0] = a[0] / 2
a[1] = a[1] / 2
a[2] = a[2] / 2
Output
[10.0, 9.5, 7.5, 11, 8, 7, 5, 2, 1]
If the order is important,
import heapq
largest = heapq.nlargest(3, a)
for i in range(len(a)):
if a[i] in largest:
a[i] = a[i] / 2
Output
[2, 5, 8, 9.5, 1, 7.5, 7, 10.0, 11]
heapq.nlargest() is a function of heapq which can give you n largest numbers from a list. Since lists in Python do not have a replace function, the list had to be traversed once, and then replaced manually. Hope this resolves your issue.
Why wouldn't you just walk through the list once (it maybe a bit longer code, but definitely efficient)
def numberInput(line):
lineInput = [int(i) for i in line.split()]
n = len(lineInput)
if n <= 3:
return [i / 2 for i in lineInput]
max_pairs = [(lineInput[i], i) for i in range(3)] # keep track of 3 max's and their indices
max_pairs.sort(key = lambda x: -x) # sort in descending order
for i in range(3, n):
if lineInput[i] >= max_pairs[0][0]: # greater than the largest element
max_pairs = [(lineInput[i], i)] + max_pairs[:2]
elif lineInput[i] >= max_pairs[1][0]: # greater than second element
max_pairs = [max_pairs[0], (lineInput[i], i), max_pairs[1]]
elif lineInput[i] >= max_pairs[2][0]: # greater than third element
max_pairs = max_pairs[:2] + [(lineInput[i], i)]
for pair in max_pairs:
lineInput[pair[1]] = lineInput[pair[0]] / 2
return lineInput
Explanation: max_pairs is a set of three tuples, containing the maximum three elements and their indices
Note: I think the above is easiest to understand, but you can do it in a loop if you don't like all those ifs
For an array of numbers, I must use list comprehension to find elements that:
Are divisible by 6
Their position is also divisible by 6
For example if the input is:
6 12 8 9 1 18
The output should be:
18
Here's what I have already done.
print(list(map(int, input().split()))[5::6])
I don't know how to find numbers that are divisible by 6.
That's how you can do it:
[el for idx, el in enumerate(lst) if idx % 6 == 0 and el % 6 == 0]
Note that typically indexes start from 0 and so the correct answer is 6, not 18. If you want to index from 1 then tweak the above:
[el for idx, el in enumerate(lst, 1) if idx % 6 == 0 and el % 6 == 0]
If I understand your question correctly, this code is for you:
lst = [6, 12, 8, 9, 1, 18]
[n for i,n in enumerate(lst,1) if not n%6 if not i%6]
# output: [18]
or, if you use input():
[n for i,n in enumerate(map(int, input().split()), 1) if not n%6 if not i%6]
You could use % (mod) to get number which can be divided by 6. In short:
# my_list is your input list
[x for x in my_list[5::6] if x % 6 == 0]
Index of 18 will be 5 because list index starts from 0.
Try this code :
lst = [6,12,8,9,1,18,24]
print(" ".join([str(num) for num in lst if num %6 ==0 and lst.index(num)%6 == 0]))
It will return 6 and 24.
Can you try the following:
Let's assume that your original list is original_list
new_list = [original_list[i] for i in range(len(original_list)) if i % 6 == 0 and original_list[I] % 6 == 0]
l = [6, 10, 8, 9, 1, 18, 12]
x = [l[i] for i in range(len(l)) if l[i] % 6 == 0 and i % 6 == 0]
print(x)
op: 6 and 12
This should work:
lst = [6,12,8,9,1,18]
answer = [num for num in lst if num %6 ==0 and lst.index(num)%6 == 0]
Output: 6
Note: The answer is not 18 because the index of 18 is 5 as indexing is zero based in python. Therefore only the first number meets both criteria
This question already has answers here:
What is the most efficient way of finding all the factors of a number in Python?
(29 answers)
Closed 9 years ago.
This is the code I have right now. I can't get it to return the right results for the question.
def problem(n):
myList = [1,n]
for i in range(1,n):
result = int(n ** .5)
new = n/result
i = i + 1
myList.append(new)
return myList
Factors of n are all numbers that divide into n evenly. So i is a factor of n if n % i == 0.
You need to do is perform this test for each number from 1 to n, and if that condition is true append that number to your list.
If you have issues as you start to write this code, update your question with what you tried.
Note that the above approach is not the most efficient way to find factors, but it seems to me like this is just an exercise for a beginning programmer so a naive approach is expected.
There are a few problems with your code. First of all you do not need to increment i as your for loop already does that. Secondly, using some basic math principles you only need to go through a range of numbers up to the square root of your passed in number. I will leave the second part for you to play and experiment with.
def problem(n):
myList = []
for i in range(1, n+1):
if n % i == 0:
myList.append(i)
return myList
For a more advanced approach you can try list comprehensions which are very powerful but are usually better for smaller data sets.
def problem(n):
return [x for x in range(1, n+1) if n % x == 0]
You only need to iterate from 1 to n ** 0.5 + 1, and your factors will be all i's, and n/i's you pick up along the way.
For example: factors of 10:
We only need to iterate from 1 to 4
i = 1 => 10 % 1 == 0, so factors: i = 1, 10 / i = 10
i = 2 => 10 % 2 == 0, so factors: i = 2, 10 / i = 5
i = 3 => 10 % 3 != 0, no factors
We don't need to go any further, the answer is 1, 2, 5, 10.
def problem(n):
myList = []
for i in xrange(1, int(n ** 0.5 + 1)):
if n % i == 0:
if (i != n/i):
myList.append(i)
myList.append(n / i)
else:
myList.append(i)
return myList
Result:
>>> problem(10)
[1, 10, 2, 5]
>>> problem(12)
[1, 12, 2, 6, 3, 4]
>>> problem(77)
[1, 77, 7, 11]
>>> problem(4)
[1, 4, 2]
>>> problem(64)
[1, 64, 2, 32, 4, 16, 8]
>>> len(problem(10 ** 12))
169
use a list comprehension:
In [4]: num=120
In [5]: [x for x in range(2,int(num/2)+1) if num%x==0]
Out[5]: [2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60]
In [6]: num=121
In [7]: [x for x in range(2,int(num/2)+1) if num%x==0]
Out[7]: [11]
say I have a string n = '22' and another number a = 4 so that n is a str and a is an int. I would like to create a group of lists like:
list1 = [22, 12, 2] #decreasing n by 10, the last item must be single digit, positive or 0
list2 = [22, 11, 0] #decreasing n by 11, last item must be single digit, positive or 0
list3 = [22, 21, 20] #decreasing n by 1, last item must have last digit 0
list4 = [22, 13] #decreasing n by 9, last item must be single digit. if last item is == a, remove from list
list5 = [22, 32] #increasing n by 10, last item must have first digit as a - 1
list6 = [22, 33] #increasing n by 11, last item must have first digit as a - 1
list7 = [22, 23] #increasing n by 1, last item must have last digit a - 1
list8 = [22, 31] #increasing n by 9, last item must have first digit a - 1
I am struggling on how to start this. Maybe you can give me an idea of how to approach this problem?
By the way if a condition cannot be satisfied, then only n will be on that list. say n = '20', a = 4:
list3 = [20]
Also this is for a school project, for indexes in a list which has list items. I can't think of a better way to approach the problem.
This should get you started:
def lbuild( start, inc, test ):
rslt = [start]
while not test(start,inc):
start += inc
rslt.append( start )
return rslt
n = '22'
a = 4
nval = int(n)
print lbuild( nval, -10, lambda(x,y): (x<10 and x>=0) )
print lbuild( nval, 1, lambda(x,y): x%10 == a-1 )