I tried writing a Python program to accept a list of integers starting with 0 and ending with 20 from the user. Each integer of the said list either differs from the previous one by two or is four times the previous one. Return true or false
Can someone correct the condition which I have written
lst = []
n = int(input("Enter the no of elements in the list :"))
for i in range (0,n):
elem = int(input("Enter the elements between 0 and 20 : "))
lst.append(elem)
if elem >= 0 and elem <=20:
print(lst)
for i in elem:
if (i+1) >= 2(i) or 4(i+1) == i:
print(True)
else:
print(False)
You can use zip to pair up items with their successors. This will let you compare them and check your condition using any() or all() depending on your requirement:
if any(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # at least one number pair meets the criteria
else:
print(False)
or
if all(abs(a-b)==2 or a*4==b for a,b in zip(lst,lst[1:]):
print(True) # all numbers meets the criteria
else:
print(False)
arr_len = int(input("Input a length for list: "))
nums = [0] * arr_len
res = [False] * arr_len
for i in range(len(nums)):
num = -1
while not(num >= 0 and num <= 20):
num = input("Enter the elements between 0 and 20 : ")
num = nums[i] = int(num)
if num >= 0 and num <= 20:
print('appended')
else:
print('that number is not between 0 and 20')
for i in range(1, len(res)):
num = nums[i]
prev_num = nums[i-1]
if abs(num-prev_num) == 2 or prev_num == 4*num:
res[i] = True
for i in range(len(nums)):
print('i is: ', i, 'nums[i], ', nums[i],
', is allowed in array: ', res[i])
res = dict(zip(nums, res))
print(res)
I am trying to get the lowest number that is divisible by all the numbers from 1 to 20.
The problem is in i%j == 0. It's giving me this error:
ZeroDivisionError: integer division or modulo by zero
even though I tried the same thing with a variable and a constant and it passes:
i % 2 == 0
My code:
i = 20
while True:
k = 0
for j in range(21):
if i % j == 0:
k += 1
if k == 21:
break
i+= 1
print(i)
Your current approach won't work for the time constraint - it'll just take too long to complete.
Try this code first and figure out what's the trick to save computing time.
primes = [2,3,5,7,11,13,17,19]
prod = 1
for p in primes:
n = 2
prod *= p
while (p**n < 21):
prod *= p
n += 1
print(prod) # 232_792_560
If you insist on using the for-loops to solve it. Here it's another alternative way:
i = 1
for k in (range(1, 21)):
if i % k > 0:
for j in range(1, 21):
if (i*j) % k == 0:
#print(i, j, k) # for debug only
i *= j
break
print(f' loop-way: {i} ') # 232792560
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()3
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
print(max(c))
This code works. However, I want to define a function to automatically calculating the max product from the 5th line in the code shown below.
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product = max(c)
return Product
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
MaxPairwiseProduct(n,a,c)
I re-write the function but it does not work. It reveals "IndentationError: expected an indented block"
# python3
result = 0
def max_pairwise_product_fast(n, numbers):
max_index1 = -1
for i in range(n):
if max_index1 == -1 or numbers[i] > numbers[max_index1]:
max_index1 = i
max_index2 = -1
for i in range(n):
if i != max_index1 and (max_index2 == -1 or numbers[i] > numbers[max_index2]):
max_index2 = i
return numbers[max_index1] * numbers[max_index2]
if __name__ == '__main__':
n = int(input())
a = [int(x) for x in input().split()]
assert (len(a) == n)
print(max_pairwise_product_fast(n, a))
# Uses python3
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product1 = max(c)
return Product1
def MaxPairwiseProductFast(n,a):
max_index1 = -1
for i in range(0,n):
if a[i] > a[max_index1]:
max_index1 = i
else:
continue
#the value of the other index should be different compared to the #first, else it will assume the same indices for both the max
max_index2 = -2
for j in range(0,n):
if a[j] > a[max_index2] and a[j] != a[max_index1]:
max_index2 = j
else:
continue
Product2 = a[max_index1]*a[max_index2]
return Product2
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
print('The max value by regular algorithm:', MaxPairwiseProduct(n,a,c))
print('The max value by faster algorithm:', MaxPairwiseProductFast(n,a))
This code contains the second algorithm to calculate the max value.
def MaxPairwiseProduct(n,a,c):
for i in range(0,n):
for j in range (1,n):
if a[i] != a[j]:
m = a[i]*a[j]
c.append(m)
else:
continue
Product = max(c)
return Product
n = int(input("Enter the number of elements in the array (2-200,000):"))
a = [int(x) for x in input("Enter all numbers of the sequence with only non-negative intergers not exceeding 100,000:").split()]
c = list()
print(MaxPairwiseProduct(n,a,c))
My stupid solution to the maximum pairwise product.
n = int(input()) #
nums = input().strip().split()
nums = [ int(i) for i in nums ]
firstmax, secondmax = sorted(set(nums))[-2:]
print(firstmax*secondmax)
To do the stress testing: you can use this code here. It works when I did an assignment.
#Stress test
from random import randint
def max_prod_stress(N,M):
while True:
n = randint(2,N)
A = [None]*n
for i in range(n):
A[i] = randint(0,M)
print(A)
result1 = max_prod_naive(A)
result2 = max_prod_fast(A)
if result1==result2:
print('OK')
else:
print('Wrong answer:',result1,result2)
return
max_prod_stress(5,100)
The Question:
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
My Code:
def sum13(nums):
l = len(nums)
tot = 0
if l==0:
return 0
for x in range(l):
if nums[x]!=13:
if nums[x-1]!=13:
tot+=nums[x]
return tot
Where It's Failing:
sum13([1, 2, 2, 1, 13]) should → 6, but my code is outputting 5
sum13([1, 2, 13, 2, 1, 13]) should → 4, but my code is outputting 3
Here is the solution:
def sum13(nums):
if len(nums) == 0:
return 0
for i in range(0, len(nums)):
if nums[i] == 13:
nums[i] = 0
if i+1 < len(nums):
nums[i+1] = 0
return sum(nums)
enumerate() can give the index, then it can be done using a generator expression in sum(). The extra 0 added to the end of the list makes it work for nums[i-1] when i = 0.
def sum13(nums):
nums += [0]
return sum(n for i, n in enumerate(nums) if n != 13 and nums[i-1] != 13)
Your problem is when x is zero. x - 1 will be -1 so it will get the last element of your list (13). To fix it, don't test x - 1 if x is zero:
if x == 0 or nums[x-1] != 13:
In Python, when you pass a negative index to a list it accesses its elements backwards, so:
>>> x = [1,2,3,4,5]
>>> x[-1]
5
>>> x[-2]
4
You could avoid the bug by using next() function instead of error-prone indexes:
def exclude13(iterable):
it = iter(iterable)
for x in it:
if x == 13: # don't yield 13
next(it) # skip number immediately after 13
else:
yield x
print(sum(exclude13([1, 2, 2, 1, 13]))) # -> 6
print(sum(exclude13([1, 2, 13, 2, 1, 13]))) # -> 4
def sum13(nums):
count = 0
while count < len(nums):
if nums[count] == 13:
del nums[count:count+2]
continue
count += 1
return sum(nums)
def sum13(nums):
count = 0
sum = 0
for i in range(len(nums)):
if nums[i] == 13 or sum == 1 :
nums[i]= 0
sum = sum + 1
count = count + nums[i]
if sum == 2:
sum = 0
if nums == []:
return 0
return coun
def sum13(nums):
if len(nums)==0:
return 0
sum=0
for i in range(1,len(nums)):
if nums[i]==13 or nums[i-1]==13:
sum = sum
else:
sum += nums[i]
if nums[0]==13:
return sum
else:
return sum + nums[0]
Start the loop form 1 and add back the first number (if it's not 13) at the end.
Make a copy of the list so that the original doesn't change, remove instances of the number 13 and the number immediately following, then sum the resulting list:
def sum13(nums):
nums = nums[:]
while 13 in nums:
i = nums.index(13)
del nums[i:i+2]
return sum(nums)
This is similar to the top answer for this problem:
looking for a more elegant solution to this
Another way to look at it:
def sum13(nums):
sub = 0
for i in range(len(nums)):
if nums[i] == 13 :
sub+=nums[i]
if i+1<len(nums) and nums[i+1]!=13:
sub+=nums[i+1]
return sum(nums)-sub
def sum13(nums):
sum = 0
len_n = len(nums)
k = 0
while k < len_n:
if nums[k] == 13:
k += 2
else:
sum += nums[k]
k += 1
return sum
sum of list except when item=13 will not be counted and item+1 also be not counted
def sum13(nums):
if len(nums)==0:
return 0
if nums[-1]==13:
nums[-1]=0
for i in range(len(nums)-1):
if nums[i]==13:
nums[i]=0
nums[i+1]=0
return sum(nums)
def sum13(nums):
result = 0
i = 0
while i < len(nums):
if nums[i] == 13:
i += 2
continue
else:
result += nums[i]
i += 1
return result
You're excluding numbers that come immediately before a 13 when you should be excluding numbers that come immediately after.
I would suggest to use a recursive solution. Note that while index of a list can be out of range the slicing gives an empty list and not an error, e.g. if a = [1,1,2] then a[3] would give an error while a[3:] gives the empty list [].
def sum13(nums):
if len(nums) == 0:
return 0
sum = sum13(nums[1:])
if nums[0] != 13:
return sum + nums[0]
if nums[0] == 13:
return sum13(nums[2:])
I solved the problem in the following fashion. It is brute force, but it does work:
def sum13(nums):
count = 0
if len(nums) == 0:
return 0
for ans in range(len(nums)):
if nums[ans] == 13 and ans < len(nums)-1:
nums[ans] = 0
nums[ans+1] = 0
elif nums[ans] == 13 and ans == len(nums)-1:
nums[ans] = 0
else:
count += nums[ans]
return count
def sum13(nums):
nums2 = []
if 13 in nums:
for i in range(len(nums)-1): # the -1 is needed to avoid out of range.
if nums[i] != 13: nums2.append(nums[i])
else:
nums[i] = 0
nums[i+1] = 0
return sum(nums2)
return sum(nums)
I created a separate list and appended the figures i wanted into that list.
i did this through a for loops by going through every element and appending that figure if it did not equal 13.
when it did eventually equal the number 13 i would then change that number by setting it to zero (nums[i] = 0). Then I also need to set the next number to it at Zero by indexing (nums[i+1] = 0). so they are then discounted from the sum of the list.
this is not a perfect solution but it is a working one.
This is an approach that i have taken,this works as well
nums = [1, 2, 2, 1, 13,2,1,2,3,13,4,5]
counter = 0
temp = []
for i in range(len(nums)):
if nums[i] == 13:
if (i+1) != len(nums) and nums[i+1] != 13:
temp.append(nums[i+1])
continue
elif (i+1) == len(nums):
continue
else:
counter = counter + nums[i]
temp_total = sum(temp)
count_total = counter - temp_total
print(count_total)
When x=0 in nums[x-1] it conflicts, because it results as nums[0-1] if it is 13 then it may not add so check nums[0] at last.
def sum13(nums):
co=0
if len(nums)<=0:
return co
for a in range(1,len(nums)):
if nums[a]==13:
continue
elif nums[a-1]==13:
continue
else:
co=co+nums[a]
if nums[0]!=13:
co+=nums[0]
return co
This is my solution for this exercise!!!!
def sum13(nums):
total = 0
for i in range(len(nums)):
if (nums[i] == 13 or nums[i-1] == 13 and i != 0):
total = total
else:
total += nums[i]
return total
def sum13(nums):
sum=0
ind13=[]
for num in nums:
if num==13:
num=0
ind13=nums.index(13)
ind13next=ind13+1
nums[ind13]=0
if nums[ind13] !=nums[-1]:
nums[ind13next]=0
sum=sum+num
else:
sum=sum+num
return sum
def sum13(nums):
summed=0
flag=True
index_13=0
for index, num in enumerate(nums):
if num==13:
index_13=index
flag=False
if flag==True:
summed=summed+num
if index_13+1<= len(nums)-1 and num==nums[index_13+1]:
flag=True
return summed
def sum13(nums):
li=[]
if nums[-1]==13:
li.append(13)
for i in range(len(nums)-1):
if nums[i]==13:
li.append(nums[i])
li.append(nums[i+1])
n=sum(nums)
return (n-sum(li))
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.
def sum13(nums):
nums += [0]
add=sum(j for i, j in enumerate(nums) if j != 13 and nums[i-1] != 13)
return add
def sum13(nums):
sum=0
count=0
for i in range(len(nums)):
if nums[i]!=13:
count=count-1
if count<=0:
sum=sum+nums[i]
else:
count=2
return sum
The way I think about the problem lends me to loop over the list - except for the last element. Then if a value is 13, the next element becomes 0. From there - I reload the list - and replace ALL 13 with 0. In the end I simply sum the values of the list.
def sum13(nums):
for i,x in enumerate(range(len(nums)-1)):
if (nums[x]==13):
nums[i+1]=0
nums=nums
for i,x in enumerate(nums):
if x==13: #if the element is equal to 13
nums[i]=0
return sum(nums)
This should work as well. Basically it's a double continue statement. You assign pairs of index and value for each iteration with enumerate(). If a number is == 13 --> continue, the next iterated item should qualify for the elif statement, which also continues for items preceded by a 13. Elif runs only for items at indices >= 1 (so there is no issue with going out of range at [0]).
def sum13(nums):
if nums ==[]:
return 0
sum = 0
for index, val in enumerate(nums):
if nums[index] == 13:
continue
elif nums[index-1] == 13 and index > 0:
continue
else:
sum += val
return sum
def sum13(nums):
total = sum(nums)
for i in range (len(nums)):
if nums[i]==13:
total = total - nums[i]
if (i+1) < len(nums) and nums[i+1]!=13: #Using !=13 because 13 will already
total = total-nums[i+1] #be detected from previous if
return total
def sum13(nums):
if len(nums) == 0:
return 0
total = 0
for i in range(len(nums)):
if nums[i] == 13 and (len(nums)-1)>i:
nums[i+1]=0
total = total
elif nums[i]==13:
total = total
else:
total = total +nums[i]
return total
here another solution :
def sum13(nums):
for i in range (len(nums)) :
if nums[i] == 13 :
nums[i] = 0
if i+1 < len(nums) and nums[i+1] != 13 :
nums[i+1] = 0
return sum(nums)
This is how I have tried:)
sum = 0
for i in range(len(a)):
if a[i] == 13:
if i+1 < len(a):
a[i], a[i+1] = 0, 0
else:
a[i] = 0
else:
sum += a[i]
return sum