I don't know why the correct answer isn't coming up - python-3.x

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.

Related

I need the code to stop after break and it should not print max(b)

Rahul was learning about numbers in list. He came across one word ground of a number.
A ground of a number is defined as the number which is just smaller or equal to the number given to you.Hence he started solving some assignments related to it. He got struck in some questions. Your task is to help him.
O(n) time complexity
O(n) Auxilary space
Input Description:
First line contains two numbers ‘n’ denoting number of integers and ‘k’ whose ground is to be check. Next line contains n space separated numbers.
Output Description:
Print the index of val.Print -1 if equal or near exqual number
Sample Input :
7 3
1 2 3 4 5 6 7
Sample Output :
2
`
n,k = 7,3
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
print(max(b))
`
I've found a solution, you can pour in if you've any different views
n,k = 7,12
a= [1,2,3,4,5,6,7]
b=[]
for i in range(n):
if k==a[i]:
print(i)
break
elif a[i]<k:
b.append(i)
else:
print(max(b))
From what I understand, these are the conditions to your question,
If can find number, print the number and break
If cannot find number, get the last index IF it's less than value k
Firstly, it's unsafe to manually input the length of iteration for your list, do it like this:
k = 3
a= [1,7,2,2,5,1,7]
finalindex = 0
for i, val in enumerate(a):
if val==k:
finalindex = i #+1 to index because loop will end prematurely
break
elif val>=k:
continue
finalindex = i #skip this if value not more or equal to k
print(finalindex) #this will either be the index of value found OR if not found,
#it will be the latest index which value lesser than k
Basically, you don't need to print twice. because it's mutually exclusive. Either you find the value, print the index or if you don't find it you print the latest index that is lesser than K. You don't need max() because the index only increases, and the latest index would already be your max value.
Another thing that I notice, if you use your else statement like in your answer, if you have two elements in your list that are larger than value K, you will be printing max() twice. It's redundant
else:
print(max(b))

How can i optimise my code and make it readable?

The task is:
User enters a number, you take 1 number from the left, one from the right and sum it. Then you take the rest of this number and sum every digit in it. then you get two answers. You have to sort them from biggest to lowest and make them into a one solid number. I solved it, but i don't like how it looks like. i mean the task is pretty simple but my code looks like trash. Maybe i should use some more built-in functions and libraries. If so, could you please advise me some? Thank you
a = int(input())
b = [int(i) for i in str(a)]
closesum = 0
d = []
e = ""
farsum = b[0] + b[-1]
print(farsum)
b.pop(0)
b.pop(-1)
print(b)
for i in b:
closesum += i
print(closesum)
d.append(int(closesum))
d.append(int(farsum))
print(d)
for i in sorted(d, reverse = True):
e += str(i)
print(int(e))
input()
You can use reduce
from functools import reduce
a = [0,1,2,3,4,5,6,7,8,9]
print(reduce(lambda x, y: x + y, a))
# 45
and you can just pass in a shortened list instead of poping elements: b[1:-1]
The first two lines:
str_input = input() # input will always read strings
num_list = [int(i) for i in str_input]
the for loop at the end is useless and there is no need to sort only 2 elements. You can just use a simple if..else condition to print what you want.
You don't need a loop to sum a slice of a list. You can also use join to concatenate a list of strings without looping. This implementation converts to string before sorting (the result would be the same). You could convert to string after sorting using map(str,...)
farsum = b[0] + b[-1]
closesum = sum(b[1:-2])
"".join(sorted((str(farsum),str(closesum)),reverse=True))

how do I call an element in a list?

a= int(input())
# I input 12345
b = a
list(map(int, b))
print (list[0]*2+list[3]*1)
#can't seem to get 6 as my answer
how do I attain my answer? I can't seem to call the elements in the list. Thank you for your help.
Since you're treating the input as individual digits, you should avoid converting the input to an integer as a whole, but map the individual digits to integers as a sequence of characters:
a= input()
b = list(map(int, a))
print(b[0] * 2 + b[3] * 1)
There are several reasons why your code won't work, including your use of the map function, the fact that you do not assign the result to a variable and the use of list (which is a keyword in Python).
However, consider this code snippet which calculates your desired output:
a = int(input('Enter a number: '))
b = [int(digit) for digit in str(a)]
res = 2 * b[0] + b[3]
print(res)
Basically you have to transform your integer into a string to be able to iterate over it. Afterwards you create your list of digits out of it and can do your calculations.
Generally speaking, you should learn the basics of Python properly. A good starting point would be the official documentation (LINK).

Convert list of integers to a single integer : ValueError

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

I'm stuck on finding how many odd digits are in a number for python

So we have to write a function in python to count how many digits of a non-negative integer are odd numbers.
def odd_dig(n):
ans = 0
for i in range(n):
if i in range(n) %2 == 1:
ans += 1
elif n[i]==0:
return None
I don't know python, but for a solution, why not something like the following?
while n > 0 do these two things:
add (n%2) to your count
divide n by 10
because n is defined as non-negative we should be fine with this.
You're using range(n) which creates a list from 1 to n. So when you do range(5), in your for loop, you're iterating over 1,2,3,4,5 instead of the actual digits of n.
If you want to find the number of digits you can do something like len(str(n)) which finds the length of the string form of n.
After that, make sure you're using the right operators on the right variables (string operators on strings, list operators on lists, etc...).

Resources