Convert list of integers to a single integer : ValueError - string

I am trying to convert a list of integers in Python into a single integer say for example [1,2,3,4] to 1234(integer). In my function, I am using following piece of code:
L = [1,2,3,4]
b = int(''.join(map(str, L)))
return b
The compiler throws a ValueError. Why so? How to rectify this issue?

You can do this like this also if that cause problems:
L = [1,2,3,4]
maxR = len(L) -1
res = 0
for n in L:
res += n * 10 ** maxR
maxR -= 1
print(res)
1234

another solution would be
L = [1,2,3,4]
digitsCounter = 1
def digits(num):
global digitsCounter
num *= digitsCounter
digitsCounter *= 10
return num
sum(map(digits, L[::-1]))
the digits() is a non pure function that takes a number and places it on place value depending on the iteration calling digits on each iteration
1. digits(4) = 4 1st iteration
2. digits(4) = 40 2nd iteration
3. digits(4) = 400 3rd iteration
when we sum up the array returned by map from the inverted list L[::-1] we get 1234 since every digit in the array is hoisted to it place value
if we choose not no invert L array to L[::-1] then we would need our digits function to do more to figure out the place value of each number in the list so we use this to take adv of language features

Related

I don't know why the correct answer isn't coming up

I'm novice programmer.
I want the smallest of the input values ​​to be output, but I don't know what's wrong.
Input example :
10
10 4 2 3 6 6 7 9 8 5
Output example :
2
n = int(input())
a = input().split()
min=a[0]
for i in range(n) :
if a[i] < min :
min = a[i]
print(min)
what is the problem? please help me
Your code should work (and it does for me).
Nevertheless, min is a reserved Python word. Taking that into consideration, I also recommend the following changes for it to be more idiomatic:
a = input().split()
min_num = a[0]
for element in a:
if element < min :
min = element
print(min)
Variables can be either number or strings. For example "2" is different from 2.
The function split returns an array of strings. You would need to convert each to a number if you want to do number comparison, like:
n = int(input())
a = input().split()
min=int(a[0])
for i in range(n) :
if int(a[i]) < min :
min = int(a[i])
print(min)
Note: you already did that for n (first line in original code), but you did not do the same when you access a.
So, min is actually a python built-in, which would be very useful in this scenario. Also, you are not making the input values in a into integers, so we can do that too:
n = int(input())
a = list(map(int, input().split()))
print(min(a))
We use map to turn all the values from the split list into integers, then turn the map object back into a list. Then, using min, we can find the smallest number very easily, without a for loop.
I think you should convert each element to integers before comparing them.
a = [int(i) for i in input().split()]
Your code should work, but it will compare strings against strings instead of integers against integers.

Iterate through 2 Python list and get all x to y combinations [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 2 years ago.
I have the following two lists:
x = [1,2]
y = [4,5,6]
I want to iterate x by z.
I have a variable called code set to NONE and another variable called value also set to NONE. Here is the output I am aiming for:
1st iteration, code = 1 and value = 4
2nd iteration, code = 1 and value = 5
3rd iteration, code = 1 and value = 6
4th iteration, code = 2 and value = 4
5th iteration, code = 2 and value = 5
6th iteration, code = 2 and value = 6
Here is what I have tried:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
for x_ids, y_ids in zip(x, y):
code = x_ids
value = y_ids
print("c", code)
print("v", value)
output:
c 1
v 4
c 2
v 5
Can anyone suggest how to get the output described above?
This is one way to achieve what you're looking for:
x = [1, 2]
y = [4, 5, 6]
code = None
value = None
iter_count = 0
for x_ids in x:
code = x_ids
for y_ids in y:
iter_count += 1
value = y_ids
print('{} iteration, code = {} and value = {}'.format(iter_count, code, value))
#print(str(iter_count) + ' iteration, code = ' + str(code) + 'and value = ' + str(value))
Like discussed in the comments, this code iterates through all elements of y for every element in x. In your original code, you were iterating through both lists all at ones, using zip. Since you want to print the number of iteration too, there is a new variable, iter_count, that counts and stores those.
The code has two print statements, they print the same messages. The commented out one concatenates strings, and numbers converted to strings. The uncommented one may be less intuitive but it is often more useful and cleaner. It's worth looking at it, you can find an introduction here.
Last thing, if you need that too - to print numbers in 1st, 2nd etc. format you can use some of these approaches.

Python how to calculate average of range list?

Could somebody tell me what I am doing wrong?
I am gotting error Vidurkis = sum(B)/len(B)
TypeError: 'int' object is not callable
A = int(input('Betkoks skaicius'))
if A == 0:
print('Ačiū')
if A <= 10 and A>=-10:
if A<0:
print('Neigiamas vienženklis')
if A>0:
print('Teigiamas vienženklis')
else:
print('| {:^20} |'.format('Autorius: '))
for r in range(10,A,1):
Vidurkis = sum(r)/len(r)
print(Vidurkis)
after
sum = 0
sum is no longer the built-in sum function! You would have to rename that variable. The real error is, however, that you are applying functions that take iterables as arguments to integers (Your loop variable B is an int while sum and len would expect a list or similar). The following would suffice:
r = range(10, A, 1) # == range(10, A)
Vidurkis = sum(r)/len(r) # only works for A > 10, otherwise ZeroDivisionError

find the first occurrence of a number greater than k in a sorted array

For the given sorted list,the program should return the index of the number in the list which is greater than the number which is given as input.
Now when i run code and check if it is working i am getting 2 outputs. One is the value and other output is None.
If say i gave a input of 3 for the below code.The expected output is index of 20 i.e., 1 instead i am getting 1 followed by None.
If i give any value that is greater than the one present in the list i am getting correct output i.e., "The entered number is greater than the numbers in the list"
num_to_find = int(input("Enter the number to be found"))
a=[2,20,30]
def occur1(a,num_to_find):
j = i = 0
while j==0:
if a[len(a)-1] > num_to_find:
if num_to_find < a[i]:
j=1
print(i)
break
else:
i = i + 1
else:
ret_state = "The entered number is greater than the numbers in the list"
return ret_state
print(occur1(a,num_to_find))
This code is difficult to reason about due to extra variables, poor variable names (j is typically used as an index, not a bool flag), usage of break, nested conditionals and side effect. It's also inefficient because it needs to visit each element in the list in the worst case scenario and fails to take advantage of the sorted nature of the list to the fullest. However, it appears working.
Your first misunderstanding is likely that print(i) is printing the index of the next largest element rather than the element itself. In your example call of occur1([2, 20, 30], 3)), 1 is where 20 lives in the array.
Secondly, once the found element is printed, the function returns None after it breaks from the loop, and print dutifully prints None. Hopefully this explains your output--you can use return a[i] in place of break to fix your immediate problem and meet your expectations.
Having said that, Python has a builtin module for this: bisect. Here's an example:
from bisect import bisect_right
a = [1, 2, 5, 6, 8, 9, 15]
index_of_next_largest = bisect_right(a, 6)
print(a[index_of_next_largest]) # => 8
If the next number greater than k is out of bounds, you can try/except that or use a conditional to report the failure as you see fit. This function takes advantage of the fact that the list is sorted using a binary search algorithm, which cuts the search space in half on every step. The time complexity is O(log(n)), which is very fast.
If you do wish to stick with a linear algorithm similar to your solution, you can simplify your logic to:
def occur1(a, num_to_find):
for n in a:
if n > num_to_find:
return n
# test it...
a = [2, 5, 10]
for i in range(11):
print(i, " -> ", occur1(a, i))
Output:
0 -> 2
1 -> 2
2 -> 5
3 -> 5
4 -> 5
5 -> 10
6 -> 10
7 -> 10
8 -> 10
9 -> 10
10 -> None
Or, if you want the index of the next largest number:
def occur1(a, num_to_find):
for i, n in enumerate(a):
if n > num_to_find:
return i
But I want to stress that the binary search is, by every measure, far superior to the linear search. For a list of a billion elements, the binary search will make about 20 comparisons in the worst case where the linear version will make a billion comparisons. The only reason not to use it is if the list can't be guaranteed to be pre-sorted, which isn't the case here.
To make this more concrete, you can play with this program (but use the builtin module in practice):
import random
def bisect_right(a, target, lo=0, hi=None, cmps=0):
if hi is None:
hi = len(a)
mid = (hi - lo) // 2 + lo
cmps += 1
if lo <= hi and mid < len(a):
if a[mid] < target:
return bisect_right(a, target, mid + 1, hi, cmps)
elif a[mid] > target:
return bisect_right(a, target, lo, mid - 1, cmps)
else:
return cmps, mid + 1
return cmps, mid + 1
def linear_search(a, target, cmps=0):
for i, n in enumerate(a):
cmps += 1
if n > target:
return cmps, i
return cmps, i
if __name__ == "__main__":
random.seed(42)
trials = 10**3
list_size = 10**4
binary_search_cmps = 0
linear_search_cmps = 0
for n in range(trials):
test_list = sorted([random.randint(0, list_size) for _ in range(list_size)])
test_target = random.randint(0, list_size)
res = bisect_right(test_list, test_target)[0]
binary_search_cmps += res
linear_search_cmps += linear_search(test_list, test_target)[0]
binary_search_avg = binary_search_cmps / trials
linear_search_avg = linear_search_cmps / trials
s = "%s search made %d comparisons across \n%d searches on random lists of %d elements\n(found the element in an average of %d comparisons\nper search)\n"
print(s % ("binary", binary_search_cmps, trials, list_size, binary_search_avg))
print(s % ("linear", linear_search_cmps, trials, list_size, linear_search_avg))
Output:
binary search made 12820 comparisons across
1000 searches on random lists of 10000 elements
(found the element in an average of 12 comparisons
per search)
linear search made 5013525 comparisons across
1000 searches on random lists of 10000 elements
(found the element in an average of 5013 comparisons
per search)
The more elements you add, the worse the situation looks for the linear search.
I would do something along the lines of:
num_to_find = int(input("Enter the number to be found"))
a=[2,20,30]
def occur1(a, num_to_find):
for i in a:
if not i <= num_to_find:
return a.index(i)
return "The entered number is greater than the numbers in the list"
print(occur1(a, num_to_find))
Which gives the output of 1 (when inputting 3).
The reason yours gives you 2 outputs, is because you have 2 print statements inside your code.

Python 3.x: Trying to compare current element with previous and next (without built-in functions)

I'm trying to write code that adds to a count if the current list element is greater than both the previous list element and the next list element. So, for example, in a list: [1, 3, 5, 7, 2]... 1 and 2 are not evaluated because they only have one number to the side. So 3 is the first to be compared and 3 is not greater than 1 and 5, 5 is not greater than 3 and 7, and 7 is greater than 5 and 2 so count = 1.
This is for homework so I can't use built-in functions. List is of random length and may contain positive and negative numbers.
I tried two variations...
In this version, the i value never goes up. Why is this? How do I get it to go to the next number?
a = [int(i) for i in input().split()]
b = a[0]
count = 0
for i in a[1:]:
for j in a[2:]:
if i > j and i > b:
count +=1
b = i
print(count)
In the second version, I get Index Error: list index out of range. How can I fix such an error?
a = [int(i) for i in input().split()]
prev = nxt = 0
b = a[1]
count = 0
for i in range(1, len(a)):
prev = a[i-1]
nxt = a[i+1]
if b > prev and b > nxt:
count +=1
prev = b
b = nxt
print(count)
Thank you for any help. I would like to know where I'm going wrong.
In the code you have written you are trying to access the index which is not on the list.You are trying to access the next element for the last element in the list, which is not there!
Just change the for loop range
for i in range(1,len(a)-1)
Here is the code I have written:
count = 0
for i in range(1,len(a)-1):
if a[i+1] < a[i] > a[i-1] :
count += 1
You can check without the first and last:
my_list = my_list[1:-1]
res=0
for ndx,el in enumerate(my_list):
if my_list[ndx-1] > el and my_list[ndx+1] > el:
res+=el

Resources