I have written a code which finds unique elements from the list of integers.
def Distinct(arr, n):
for i in range(0, n):
d = 0
for j in range(0, i):
if (arr[i] == arr[j]):
d = 1
break
if (d == 0):
print(arr[i], end=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
print(Distinct(arr, n))
if my given input array is [1,2,2,3,4] where n = 5 i get the output as 1,2,3,4,None but i want the output to be 1,2,3,4
can anyone tell how to fix this ?
Your function Distinct has no return statement so it will always return None. When you call print(Distinct(arr, n)) this is printing the None that is returned. You can simply remove the print() like so:
Distinct(arr, n)
To remove the last comma you can't print a comma on the first iteration, then print the commas before the items. This is because you don't know which item will be the last one.
if d == 0 and i == 0:
print(arr[i], end='')
elif d == 0:
print("," + arr[i], end='')
Try something like this:
def Distinct(arr, n):
lst = []
for i in range(0, n):
for j in range(0, i):
if (arr[i] == arr[j]):
lst.append(arr[i])
break
print(*lst, sep=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
Distinct(arr, n)
So first you compute all the numbers, and only at the end you print them
Related
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)
So if I get input number "n" and what I want to do is print 1~n like this. If n = 10
1
23
456
78910
and my code is this
x = int(input())
n=1
for i in range(1, x+1):
sum = (n+1)*n // 2
print(i , end = ' ')
if(sum == i):
print()
n+=1
I solved this question with my TA but is there a way to solve using multiple for statements other than this one? I don't want to use sum = (n+1)*n // 2 this part because my TA actually made this part without explanation.
I guess this is what you were thinking about:
x = int(input())
n = 1
for i in range(1, x+1):
for j in range(1, i):
if n <= x:
print(n, end=' ')
n += 1
print()
if n >= x:
break
If you're worried about needlessly looping too often on j for very large x, you could change:
if n <= x:
print(n, end=' ')
else:
break
of course you can do the summation using another for loop
sum = 0
for j in range(1,n+1):
sum += j
you cold also do sum = sum(range(n+1)), but (n + 1) * n // 2 is the best way of getting the summation of n
This is linear search code but it is not working can anyone help me out!!
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
x = raw_input('Enter the numbers into the array: ')
data.append(x)
print(data)
def lSearch(data, s):
for j in range(len(data)):
if data[j] == s:
return j
return -1
s = int(input('Enter the element do you want to search: '))
result = lSearch(data, s)
if result == -1:
print("The Element is not found")
else:
print("The element is an array at index %d",result)
s is an integer, but your list will be full of strings since you append x to it.
x = raw_input('Enter the numbers into the array: ')
See here x is a string. You have not converted this to an int (unlike at other places)
If this is actually Python 3 and not Python 2 (as it says in your tags), then you should be using input() not raw_input() (raw_input doesn't actually exist in Python 3). input() will return a string in Python 3 (unlike in python2, where it might return an integer).
thanks to everyone.Now , my code is running by a simple change raw_input to input().
data = []
n = int(input('Enter how many elements you want: '))
for i in range(0, n):
x = input('Enter the numbers into the array: ')
data.append(x)
k = sorted(data)
print(k)
def lSearch(k, s):
for j in range(len(k)):
if k[j] == s:
return j
return -1
s = int(input('Enter the element do you want to search: '))
result = lSearch(k, s)
if result == -1:
print("The Element is not found")
else:
print("The element is an array at index %d",result)
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)
I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.