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
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
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
I am total newbie in python who is practising right now with little 'algorithms'.
So here is my exercise:
N-number integers are given (user have to input). The task is to find out if this sequence is one in which the same numbers are in pairs, but there is one other number between the same numbers.
For example, for a sequence of 11 numbers 3 3 5 10 10 1 12 12 3 6 6, the answer is "yes" and for the sequence 2 2 3 15 15 4 4 8 4 4 1 the answer is "no".
Here's what I tried. But this gypsy-code is not working well:
n = int(input())
right_sequence = True
for i in range(n):
current = int(input())
if i > 0:
if current == previous:
if previous != current:
right_sequence = True
else:
right_sequence = False
previous = current
if right_sequence == True:
print('Yes')
else:
print('No')
I tried to use your own code as much as possible.
Basically the number of inputs should be at least 5. (The shortest correct answer would be in this format : A A B A A which has 5 input.
If we replace the i's with their remainder to 3. (i.e i % 3) Then the indexes for 8 input values would be:
0 1 2 0 1 2 0 1 ...
For which a correct answer would look like bellow:
A A B A A B A A ...
A correct list (The one that outputs "Yes") is the one that:
all the 0 indexes are different from their previous value (Except the first 0 which deosn't have previous value)
all the 1 indexes are equal to their previous value
all the 2 indexes are different from their previous value
The list ends with a 1 index
These 4 points are summarized into 4 if conditions in the bellow code. (The ones that have the value 'k' which carries the remainder of i'th to 3)
n = int(input())
right_sequence = True
k = 0
if n < 5:
right_sequence = False
for i in range(n):
current = int(input())
if i > 0:
k = i % 3
if k == 0:
if current == previous:
right_sequence = False # Print (No)
if k == 1:
if current != previous:
right_sequence = False # Print (No)
if k == 2:
if current == previous:
right_sequence = False # Print (No)
previous = current
if k != 1:
print('No')
elif right_sequence == True:
print('Yes')
elif right_sequence == False:
print('No')
You could slices and zip:
def f(l):
all(a == b != c for a, b, c in zip(x[::3], x[1::3], x[2::3]))
f([3, 3, 5, 10, 10, 1, 12, 12, 3, 6, 6])
# True
f([2, 2, 3, 15, 15, 4, 4, 8, 4, 4, 1])
# False
This will work only if the sequence starts with a pair and you might have to check special cases at the end, but it should hint in the right direction.
I have solved the issue the following way:
x = [2, 2, 3, 15, 15, 4, 4, 8, 4, 4, 1]
y = [3, 3, 5, 10, 10, 1, 12, 12, 6, 6]
def check_order(x):
for i in range(len(x)):
only_equal_in_row = True # all previous checked j index elements were equal to i
for j in range(i+1, len(x)):
if x[i] == x[j]:
if only_equal_in_row is False: # check if there was j not equal to i elements before
return False
else:
only_equal_in_row = False # found j element not equal to i
return True
if __name__ == "__main__":
print(check_order(x))
print(check_order(y))
Edit: Without functions due to OP request:
x = [2, 2, 3, 15, 15, 4, 4, 8, 4, 4, 1]
is_right = True
stop = False # need to stop outer for loop
for i in range(len(x)):
if stop:
break
only_equal_in_row = True # all previous checked j index elements were equal to i
for j in range(i+1, len(x)):
if x[i] == x[j]:
if only_equal_in_row is False: # check if there was j not equal to i elements before
is_right = False
stop = True
break
else:
only_equal_in_row = False # found j element not equal to i
print(is_right)
SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.
summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14
This is the problem. I have been trying to solve this using list slicing but have been unable to. Note: 9 can only be trailing 6, not before 6.
Here’s what my logic is- I found out the index of 6 and assigned it to a variable and I found the variable of 9 and assigned a variable to it too. The other two conditions are satisfied but the condition with 9 doesn’t get satisfied no matter what I try.
Here is some code from my side. Please excuse my bad programming skills.
def summer_69(arr):
if 6 not in arr:
return sum(arr)
elif 6 and 9 in arr:
i = arr.index(6)
y = arr.index(9)
sxy = sum(arr[i:y])
return sum(arr) - sxy
else:
i = arr.index(6)
return sum(arr[:i])
For an array [4, 5, 6, 7, 8, 9] I am getting the output 18.
Done without slicing.
def summer_69(l):
sign, count = False, 0
for num in l:
if num == 6:
sign = True
if not sign:
count += num
if num == 9:
sign = False
return count
my solution is:
def sum67(nums):
add = True
sum1 =0
for i in range(len(nums)):
if add:
if nums[i] == 6:
add = False
else:
sum1 += nums[i]
else:
if nums[i] == 7:
add= True
return sum1