Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
The following code snippet takes two numbers from the user. Each number is made from digits 0 or 1. The program should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0.
This was my approach to solving the problem which gives me the desired output:
s1 = input()
s2 = input()
s = ''
for i in range(len(s1)):
if s1[i] != s2[i]:
s += '1'
else:
s += '0'
print(s)
This one-line approach is producing the same output, and I am just curious to know how it is doing so but couldn't figure it out. So here I am on Stackoverflow.
i=input;print(''.join('01'[a!=b]for a,b in zip(i(),i())))
Explained step by step:
i=input - storing the function in i to be called later
zip(i(),i()) - if the user entered 1010 and 1101, this would return [(1, 1), (0, 1), (1, 0), (0, 1)] - the elements of both strings paired up
for a,b in - a and b are the pair from the zip (in the example they are first set to a=1 and b=1, then a=0 and b=1, etc.)
'01'[a!=b] - a!=b will return a boolean - either True or False. True = 1 and False = 0 so you can use this for indexing. Basically this says if a!=b: '1', if a==b: '0'
''.join - finally, join all the '0's and '1's together to make one string and print
If you really want to make it a oneliner, remove the semicolon and do it like this:
print(''.join('01'[a!=b] for a, b in zip(input(), input())))
Python will ask the user for two input strings
zip creates an iterable with tuples, so "hi" and "ho" will become [(h,h), (i,o)]
in the list comprehension, you've got a string '01' that can be indexed with either 0 or 1
that is what your expression [a!=b] does, it evaluates to either True (1) or False (0)
because you loop over all tuples, this happens for every character in your input strings
finally, ''.join concatenates all elements in your list, and this gets printed
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I am fairly new to programming and I try to create the above mentioned sequence.
this problem is about having a strict length of elements which always progresses, this progression is inside the list by moving on the indexes. this strict length shifts from a set of indexes to the next one once all the indexes inside the strict length (not passing it's limits) are finished being scanned, and they are scanned in a format of "one after the other".
after all of that we come to the root of the problem:
once the strict length moves to another set, it starts from the last index that was previously, inside of the strict length but in the previous strict length.
the output of the root problem is the title of this post. I don't know how to solve the root problem.
this problem, involves "k" as an exponent of the strict length.
this is the script:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
the output I got is:
1,2,3,3,4,5,5,6,7,7,8,9,9,10
and I don't know why I got such output, it doesn't seem logical.
As I can understand what you are looking for is to print the even numbers twice.
You can do the following without using a for loop by this way.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while (n<10):
if(int(strarr[n])%2 == 0):
print(strarr[n])
print(strarr[n])
elif(int(strarr[n])%2 != 0):
print(strarr[n])
n = n+1
The reason why your code gives that output is because,
for the 1st iteration it would print 1, 2, 3
2nd iteration it would print out 3 again as there is another print(stararr[n]) outside the for loop. That's the reason why you are getting the output you are getting.
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = 0
while True:
for i in range(k):
print(strarr[n])
n = n+1
print(strarr[n])
The error that I think you're seeing has to do with the order that you print your output and update the index n. In the current, buggy code, you're printing first, then updating the value. This means that the second print outside of the inner loop prints using the next value of n, not the one you just used in the inner loop. The same index gets used a second time in the first pass of the inner loop the next time, but that's not the value you wanted to see repeated.
The solution to this issue is pretty simple. Rather than updating after you print, update before. You'll need to adjust the starting value of n, but that's no problem:
strarr = ["1","2","3","4","5","6","7","8","9","10"]
k = 2
n = -1 # change starting index
while True:
for i in range(k):
n = n+1 # and reorder the lines in the inner loop
print(strarr[n])
print(strarr[n])
That said, the two loop thing is a lot more awkward than anything I'd really recommend. If you just want to repeat the odd-indexed values in the loop, you can do that much more simply:
for index in range(len(strarr)):
print(strarr[index])
if index % 2 == 1:
print(strarr[index])
Or you can avoid directly needing to index at all, using enumerate to get the index and value of each element in the for statement itself. This is probably a more "Pythonic" way to solve the problem.
for index, value in enumerate(strarr):
print(value)
if index % 2 == 1:
print(value)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I got stuck by finding out how to build a recursive function
that sums the elements in a list form a specific starting point
to the end of the list.
for example when list a[1,2,3,4,5,6,7,8,9,10] and starting point is Index 5
I want to get the sum of 6+7+8+9+10.
For me it is quite difficult to understand the whole concept of recursive functions. Maybe you can help me to get a step further understanding the concept.
Many thanks in advance
Define a function that normally computes the sum recursively.
To compute sum of a subsequence of a list, use list slicing.
def recsum(num_list):
if len(num_list) == 0:
return 0
return num_list[0] + recsum(num_list[1:])
a = [1,2,3,4,5]
recsum(a)
>>> 15
# It means 1+2+3+4+5
recsum(a[1:])
>>> 14
# It means 2+3+4+5
recsum(a[2:4])
>>> 7
# It means 3+4
It's difficult to describe a recursive function in short. Please read the comments carefully.
my_recursive_function will take the list and the index from which I want to calculate the sum
If the index==list_length then I already traversed the list so in this case I shall return 0.
If I have not completed traversing the list then I shall take the value of that index call my_recursive_function again from the next index. This is where recursion starts.
Then return the sum of current index and value of next indices.
For recursion we should place the recursion braking condition at the first portion of the function.Otherwise it may run infinitely.
def my_recursive_sum(my_list, index):
list_length = len(my_list)
if index == list_length: # If i am next to the last element then return 0 and I won't go next and I shall go back
return 0
return my_list[index] + my_recursive_sum(my_list, index + 1) # value of current index+value of next indices.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = my_recursive_sum(a, 3)
print(result)
this is how I interpreted the code delivered by Taohidul Islam:
might be right?
recursion
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
n=int(input())
def palindrome(x):
m=str(x)
l=len(m)
if l==1 or l==2 or l==3:
return True
if l>3:
for i in m:
for j in range (0,10):
k=m.replace(str(i),str(j))
if k==k[::-1]:
return True
else:
return False
def almost(n):
count=0
for x in range (10,n):
if str(x)!=str(x)[::-1] and palindrome(x):
count+=1
return count
print (almost(n))
Here's my code so far. It's not working for all cases where the input has more than 3 digits. For instance, it won't let me input numbers with more than 5 digits in the terminal. It just goes to a new line so I have to open a new tab. I tried to input 1000000 and it didn't yield an output. It should've given me 43,011. The code has to give a number of integers that are NOT palindromes but would be if your just change one digit like 14351, if you change 4 to 5 it'd be a palindrome. So the input might be something like 23 and the output would be 11 (since the numbers less than 23 that would be palindromes if you change one digit are 10,12,13,14,15,16,17,18,19,20,21). The one-digit numbers are excluded since they are already palindromes. Thank!
Instead of replacing digits and testing if it's a palindrome, check if you've already seen a location that differs between the left and right side. If more than one digit differs, you can't make it a palindrome by just changing one digit.
Since we're comparing the left side against the right side, we only need to iterate half the string (to l/2). And since we're dealing with integers here, we'll end up stopping before the middle digit if there's an odd number of digits.
def palindrome(x):
m = str(x)
l = len(m)
if m == m[::-1]:
return False
if l < 4:
return True
already_wrong = False
for i in range(0, l/2):
# -1 since the index is 0 based and l is one larger than the last index
if m[i] != m[l-i-1]:
# more than one digit differs? (i.e. we've already been here?)
if already_wrong:
return False
already_wrong = True
return True
print(palindrome(14456))
print(palindrome(15556))
print(palindrome(14351))
print(palindrome(166666))
print(palindrome(131666))
outputs
False
True
True
True
False
You just need to work out if only 2 digits are out of sequence between the string and the string in reverse - then it follows you can swap one digit to make a palindrome... This also excludes single digits and palindromes themselves (as 0 digits will be different), eg:
def is_almost_palindrome(n):
s = str(n)
if sum(a != b for a, b in zip(s, reversed(s))) == 2:
return True
return False
Then you get your count as:
almost_palindromes = sum(is_almost_palindrome(n) for n in range(1000000))
# 43011
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list of integers for example: [30,21,32,32,41,20,21,32,21,20]
I have a variable of X, X has a value within the range of the list.
How can I find the sum of all the elements in the list to the number of X.
For example if x was 4 I would want: 30+21+32+32
Another way to go is to use the takewhile function from itertools:
>>> import itertools
>>> sum(itertools.takewhile(lambda x: x<5, range(10)))
10
In your case:
>>> l = [1,2,3,4,5,6,7,8,9]
>>> x = 5
>>> sum(itertools.takewhile(lambda i: i < x, l))
10
if you want till the 5th element, maybe use enumerate and zip:
>>> sum(zip(*(itertools.takewhile(lambda i: i[0]<x-1, enumerate(l))))[1])
10
If you're a beginner, you should learn that the common way to carry out a task is to define a function
A function needs a name and usually needs one or more arguments, in this example sum_until is the name and l and n are the arguments.
Following the definition, there is some code that does the task for generical values of l and n. Eventually the function returns the result of the computation, here the statement return sum.
Note the commented # return sum at the end of the function definition. You should try to control what to do in exceptional cases, here what we want to do when n is not found into l. One option is to return the sum of all the numbers in l, another one is to return a value that is impossible for a summation, and the second one is exactly my choice.
def sum_until(l,n):
"returns the sum of the numbers in l that occur before the appearance of n"
sum = 0:
for num in l:
if num == n:
return sum
sum = sum + num
# return sum
return None
Now, we have to use the function. This is achieved calling the function, that is you call its name and tell it on which actual values you need to operate the sum:
print(sum_until([2,4,6,8,5,10,12], 5))
print(sum_until([2,4,6,8,5,10,12], 3))
Output
20
None
If you want to sum the x first elements:
>>> l = [1,2,3,4,5,6,7,8,9]
>>> x = 5
>>> result = sum(l[:x])
>>> result
15
My answer may be not efficient, but I it is very straightforward.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a list and I want to return the first number that out of order,
this is what I've written. and it's not working..
a=input("enter list")
out_of_order(a)
def out_of_order(list):
foundit=0
for i in list:
while foundit==0:
if (i+1 < i):
print(i)
foundit=1
if (foundit==0)
print("none")
for the list [4,8,9,10,2,12,16] It should return 2
You are confusing list items and indices. As it stands, you are testing for:
if i+1 < i:
which will never, ever be True - whatever value i takes, i+1 will be one louder larger.
I think what you were trying to do is compare adjacent items by index:
for i in range(len(lst)):
if lst[i+1] < lst[i]:
(note that you shouldn't use list as your own variable name), but:
this will give you problems if you reach the end of the list (where lst[i+1] will cause an IndexError, so you have to either try or alter the range appropriately); and
it is not generally considered Pythonic to use len(range(...)).
Instead, the best way is to compare pairs of elements:
def out_of_order(lst):
for a, b in zip(lst, lst[1:]):
if b < a:
print(b)
break
else:
print("none")
You also make a few other mistakes:
As #timgeb points out, your input will be strings not integers;
You have a SyntaxError (missing colon, incorrect indentation) at the end; and
You are using an integer as a flag, when Python has perfectly serviceable booleans True and False.
First of all, you are getting a string from input, not a list. You could get a list of numbers from the input like this:
inputstr = input('enter comma separated integers! ')
inputlist = inputstr.split(',')
inputnums = [int(x) for x in inputlist]
Another thing is that you should not use list as a variable name, because that's already used for the builtin list. Now, assuming that your a is a proper list, you want to compare one element of the list with the next element:
def out_of_order(lst):
for i in range(len(lst) - 1):
if lst[i+1] < lst[i]:
print(i+1,lst[i+1])
break
Demo:
enter comma separated integers! 100,101,102,100,101,102
3 100 # output of out_of_order(inputnums)
for i in list:
This iterates through the list by letting i be each element. Naturally, i+1 is never less than i.
I haven't used python in a while, but I believe that when you use 'i' it is referring to a number from the list. For your example in the first iteration i would be 4, in the second i would be 8, and so on. Calling i+1 doesn't return the next number in the sequence, it just adds one to it. When you're saying
if (i+1 < i)
in the first iteration you're pretty much saying if ((4+1) < 4), which is never true.
a=input("enter list")
out_of_order(a)
def out_of_order(list):
foundit=0
for i in range(len(list)):
while foundit==0:
if i < len(list)-1:
if (list[i+1] < list[i]):
print(list[i+1])
foundit=1
else
break;
if (foundit==0):
print("none")