I'm an absolute beginner and have read many related topics but I just can't get my mind around it.
I try to create a function which iterates through the string s exactly "n" times.
s="hello"
n=2
If I simply type in
s[::n]
it does work, however, if I try to express this in a function everything goes haywire.
My function looks like this:
def printEvery(s,n):
for n in range(len(s)):
print(s[::n])
ValueError: slice step cannot be zero
I really don't get why it doesn't work in a function as in my head it only makes sense this way. I'd deeply appreciate any help.
E: Sorry for the format and thank you for the edit khelwood!
def printEvery(s,n):
for x in range(1, len(s) + 1):
print(s[::n])
printEvery("Hello", 2)
Not quite sure why you would ever need this though
As I already mentioned in the comment, range starts at 0, so you cannot slice a string to return every zero-th element.
Another problem with your function is, that the parameter "n" is immediately overwritten by the for loop, so no matter with what second argument you call printEvery, it will always print the same text. This is equivalent:
def printEvery(text):
for stepsize in range(1, len(text)):
print(text[::stepsize])
def printEvery(text):
for i in range(len(text)+1,1,-1):
print (text[::i])
Every for loop starts at 0
Range's instruction is
range([start], stop[, step])
in which it indicates that where should the number start, then when should it stop and how many steps should it undergo.
In this case, it starts at 11, as I wrote len(text)+1 and I supposed len(text) is 10. I told Python to stop when it reachs 1, and each time it is -1 each time so if you replace
print (text[::i])
#replace this line to this:
print i
This would be printed:
11
10
9
8
7
6
5
4
3
2
1
I hope it works for you. I am not really good at English so sorry for my bad English :)
Related
Link to question: https://www.spoj.com/UTPEST22/problems/UTP_Q2/
From what I understand, the question is divided into 2 parts:
Input
The first input is an integer that limits the number of time the user can provide a set of integers.
From the second line onwards, the user provides the sequence of integers up until the specified limit.
The set of integers are arranged in ascending order, separated only by a space each.
Output
For each sequence of integers, the integers in it are looped over. Only those that are even are printed as outputs horizontally.
from sys import stdin
for x in range(1, 1+ int(input())):
# number of cases, number of times the user is allowed to provide input
for line in stdin:
num_list = line.split()
# remove the space in between the integers
num = [eval(i) for i in num_list]
# change the list of numbers into integers each
for numbers in range(num[0], num[-1] + 1):
# the first integer is the lower bound
# the second the upper bound
if numbers % 2 == 0:
# modulo operation to check whether are the integers fully divisible
print(numbers, end = ' ')
# print only the even numbers, horizantally
Can anyone please provide some insights on how to make changes to my code, specifically the loop. I felt so messed up with it. Screenshot of the result.
Any help will be appreciated.
You can use restructure the code into the following steps:
Read each case. You can use the input function here. A list comprehension can be used to read each line, split it into the lower and upper bound and then convert these to integers.
Process each case. Use the lower and upper bounds to display the even numbers in that range.
Using loops: Here is an example solution that is similar to your attempt:
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
for val in range(case[0], case[1] + 1):
if val % 2 == 0:
print(val, end=' ')
print()
This will produce the following desired output:
4 6 8 10 12 14 16 18 20
2 4 6 8 10 12 14 16
-4 -2 0 2 4 6
100 102 104 106 108
Simplify using unpacking: You can simplify this further by unpacking range. You can learn more about unpacking here.
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
lower = case[0] if case[0] % 2 == 0 else case[0]
print(*range(lower, case[1] + 1, 2))
Simplify using bit-wise operators: You can simplify this further using the bit-wise & operator. You can learn more about this operator here.
n = int(input())
cases = []
for case in range(n):
cases.append([int(x) for x in input().split()])
for case in cases:
print(*range(case[0] + (case[0] & 1), case[1] + 1, 2))
So first of obviously ask user to input the range however many times they specified, you can just split the input and then just get the first and second item of that list that split will return, by using tuple unpacking, then append to the ranges list the range user inputted but as a Python range object so that you can later easier iterate over it.
After everything's inputted, iterate over that ranges list and then over each range and only print out the even numbers, then call print again to move to a new line in console and done.
ranges = []
for _ in range(int(input())):
start, end = input().split()
ranges.append(range(int(start), int(end) + 1))
for r in ranges:
for number in r:
if number % 2 == 0:
print(number, end="")
print()
Here's my solution:
n = int(input())
my_list = []
for i in range(n):
new_line = input().split()
new_line = [int(x) for x in new_line]
my_list.append(new_line)
for i in my_list:
new_string = ""
for j in range(i[0], i[1]+1):
if (not(j % 2)): new_string += f"{j} "
print(new_string)
Read the first value from stdin using input(). Convert to an integer and create a for loop based on that value.
Read a line from stdin using input(). Assumption is that there will be two whitespace delimited tokens per line each of which represents an integer.
Which gives us:
N = int(input()) # number of inputs
for _ in range(N):
line = input()
lo, hi = map(int, line.split())
print(*range(lo+(lo&1), hi+1, 2))
There are a few issues here but I'm guessing this is what's happening: you run the code, you enter the first two lines of input (4, followed by 3 20) and the code doesn't print anything so you press Enter again and then you get the results printed, but you also get the error.
Here is what's actually happening:
You enter the input and the program prints everything as you expect but, you can't see it. Because for some reason when you use sys.stdin then print without a new line, stdout does not flush. I found this similar issue with this (Doing print("Enter text: ", end="") sys.stdin.readline() does not work properly in Python-3).
Then when you hit Enter again, you're basically sending your program a new input line which contains nothing (equivalent to string of ""). Then you try to split that string which is fine (it will just give you an empty list) and then try to get the first element of that list by calling num[0] but there are no elements in the list so it raises the error you see.
So you can fix that issue by changing your print statement to print(numbers, end = ' ', flush=True). This will force Python to show you what you have printed in terminal. If you still try to Enter and send more empty lines, however, you will still get the same error. You can fix that by putting an if inside your for loop and check if line == "" then do nothing.
There is still an issue with your program though. You are not printing new lines after each line of output. You print all of the numbers then you should go to the newline and print the answer for the next line of input. That can be fixed by putting a print() outside the for loop for numbers in range(num[0], num[-1] + 1):.
That brings us to the more important part of this answer: how could you have figured this out by yourself? Here's how:
Put logs in your code. This is especially important when solving this type of problems on SPOJ, Codeforces, etc. So when your program is doing that weird thing, the first thing you should do is to print your variables before the line of the error to see what their value is. That would probably give you a clue. Equally important: when your program didn't show you your output and you pressed Enter again out of confusion, you should've gotten curious about why it didn't print it. Because according to your program logic it should have; so there already was a problem there.
And finally some side notes:
I wouldn't use eval like that. What you want there is int not eval and it's just by accident that it's working in the same way.
We usually put comments above the line not below.
Since it appears you're doing competitive programming, I would suggest using input() and print() instead of stdin and stdout to avoid the confusions like this one.
SPOJ and other competitive programming websites read your stdout completely independent of the output. That means, if you forget to put that empty print() statement and don't print new lines, your program would look fine in your terminal because you would press Enter before giving the next input line but in reality, you are sending the new line to the stdin and SPOJ will only read stdout section, which does not have a new line. I would suggest actually submitting this code without the new line to see what I mean, then add the new line.
In my opinion, the variable numbers does not have a good name in your code. numbers imply a list of values but it's only holding one number.
Your first if does not need to start from 1 and go to the number does it? It only needs to iterate that many times so you may as well save yourself some code and write range(int(input())).
In the same for loop, you don't really care about the value of variable x - it's just a counter. A standard practice in these situations is that you put _ as your variable. That will imply that the value of this variable doesn't really matter, it's just a counter. So it would look like this: for _ in range(int(input())).
I know some of these are really extra to what you asked for, but I figured you're learning programming and trying to compete in contests so thought give some more suggestions. I hope it helped.
Steps for simple solution
# taking input (number of rows) inside outer loop
# l = lower limit, u = upper limit, taking from user, then converting into integer using map function
# applying logic for even number
# finally printing the even number in single line
for j in range(int(input())):
l, u = map(int, input('lower limit , upper limit').split())
for i in range(l, u+1):
if i%2 == 0: # logic for even number
print(i, end=' ')
I am a novice programmer and I feel that I have very fundamental misunderstandings which I am trying to identify. In this question, I am going to be working out my logic to a coding challenge in order to help you identify the misconceptions I am experiencing. The context of this question is the Hackerrank Interview Kit problem "Left Rotation". https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays&h_r=next-challenge&h_v=zen
It says the following in regards to the input format:
The first line contains two space-separated integers n and d, the size of a and the number of left rotations.
The second line contains space-separated integers, each an a[i].
Then it gives an example input:
5 4
1 2 3 4 5
My approach to this problem:
What I want is to create 2 loops. One loop to repeat the following process d times, (ie. 4 times), and a nested loop that goes through the whole second input string (1 2 3 4 5), and does the following:
sets the value of the first index (ie: 1) of the second input string (ie: 1 2 3 4 5) to a variable called temp. (I was thinking the line of code that does this would look something like this: temp = a[1]. But is this correct syntactically? Can i do this? Because will python recognize 1 2 3 4 5 as an array automatically, or do I have to convert this second input line from a string to an array, first?)
Next, for every index of the second input line EXCEPT for the last, change the value of that index to equal the value of the next index in the sequence. So, a[1] = 2, a[2] = 3, a[3] = 4, and a[4] = 5. My logic is that at the end of this step, the line should now be this: 2 3 4 5 5. (I was thinking the line of code that does this would look something like this:
for i in len(a-1):
i = [i + 1].
(Is this correct syntactically? I feel like there is something wrong with this line, but I am not sure what it is.)
Set the last index of the array to the temp value. (I was thinking the line of code that does this would be the following: a[n] = temp. Again, unsure about my syntax. By my logic, I would imagine that the input line now looks like this: 2 3 4 5 1. (Also, how does python know what n: is? I understand that the first input line is in the format n,d, but how does python know what those variables stand for? How do I tell it?)
This process happens d times. So the final result to return once the loop finishes would be the rotated array, which would be: 5 1 2 3 4. But I am even confused on how to write the line for the return statement.
With this logic in mind, here is my code:
def rotLeft(a, d):
i = 0
newArr = []
for i in range (d):
temp = a[1]
for i in len(a-1):
i = [i + 1]
a[n] = temp
a = newArr
return newArr
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
d = int(first_multiple_input[1])
a = list(map(int, input().rstrip().split()))
result = rotLeft(a, d)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
I am getting a runtime error, which I know can be caused by a number of things.
Overall, I am wondering if someone can help me identify any places where I am going wrong in my syntax or logic. I think one of my main points of confusion is the relationship between the input strings and the values being passed into the function. Any contributions are severely appreciated. Thank you.
When you find yourself stuck it's never a bad idea to step back and go to the basics.
I suggest starting your problem by writing down a few of the possible cases on paper and trying to spot patterns, before you write ANY code.
Write your code in iterations, starting with something very simple and slowly work towards your end goal.
Loop through the existing array, adding it's elements to the newlist at the original elements index plus the shift amount, then apply modulus of the length of the original list to have it 'wrap' around.
Here's a helpful link if you aren't sure how modulus works
def rotLeft(a, d):
new_list = []
for i in range(len(a)):
new_list.append(a[(i+d) % len(a)]);
return new_list
There's a number of syntax errors, but HackerRank likely wouldn't accept an approach where you'd perform one left rotation at a time. (The input size is too big for your algorithm to handle in a small amount of time. If you're just starting to program, don't worry too much about what this means; Ewan Brown is right that correctness is infinitely more important than efficiency. This is solely meant to serve as an explanation to motivate why I'm giving a different approach as opposed to debugging the one you've laid out.)
Instead, what you should do is create a new array that rotates an element by d (since you know the offset in advance). This is faster: in essence, you'd be performing the left rotation for each element all at once, rather than over many steps.
def rotLeft(a, d):
result = [0] * len(a)
for index, element in enumerate(a):
result[((index - d) + len(a)) % len(a)] = element
return result
Ewan Brown nailed it. For completeness, I'll add an even more concise implementation using itertools:
from itertools import cycle, islice
def rotLeft(a, d):
return islice(cycle(a), d, len(a)+d)
cycle is a functional and abstract way to express the idea of "wrapping around" a collection.
This is a loop in PYTHON 3.X.
for i in range(2, 2):
print(i)
The result that I got after running this program was a blank console.
What type of output we get from this loop.
The range of numbers returned are integers from start to stop. ( the first param being start, and second being stop when 2 are given)
It includes the start int, but not the stop int.
hence, range(2,2) contains no numbers in between.
range(2,4) returns 2,3 but not 4.
Documentation here.
The reason you're getting blank output is because what the range() function does.
The first argument in the range() function tells the function which number to iterate to.
So, if this was your code:
for i in range(2):
print(i)
Then your output would be:
0
1
It starts from 0 and prints two numbers, because of the two.
However, the second parameter in your code tells it what to count by. For example, you added a 2 for the second parameter. This tells the program to skip count by 2, and since you have only 2 output in the first place, the program doesn't print anything
Read up on range in python 3.
Hopefully this helps!
I am currently a beginner in Python. This is my problem: First, the program asks that you input a number.
For example, if I put 1, I get 1 out. If i put 2, i get 12 out. If I put 3, I get 123. If I put 4, I get 1234. That is the gist of this set of problem. However, I developed a mathematical equation that works if I put it through a loop:
if __name__ == '__main__': # ignore this part
n = int(input())
s = 1
while s > n:
z = s*10**(n-s)
s += 1
answer = z
if s == n:
print(z)
When I tried to run this code, I got nothing, even though I added print at the end. What is it that I am doing wrong here? For anyone answering the problem, introduce any concepts that you know that may help me; I want to learn it.
Please enlighten me. Don't exactly give me the answer....but try to lead me in the right direction. If I made a mistake in the code (which I am 100% sure I did), please explain to me what's wrong.
It's because your while loop condition is backwards. It never enters the loop because s is not bigger than n. It should be while s < n
Use a for loop using range() as in
for i in range(1, n+1):
where n is the input so that the numbers from 1 till n can be obtained.
Now use a print() to print the value of i during each iteration.
print() by default will add a newline at the end. To avoid this, use end argument like
print(var, end='')
Once you are familiar with this, you can also use list comprehension and join() to get the output with a single statement like
print( ''.join([str(i) for i in range(1, n+1)]) )
Take the input as you've done using input() and int() although you might want to include exception handling in case the input is not an integer.
See Error handling using integers as input.
Here is the solution:
Using string
a = int(input())
# taking the input from the user
res=''
# using empty string easy to append
for i in range(1,a+1):
# taking the range from 1 (as user haven't said he want 0, go up to
# a+1 number (because range function work inclusively and will iterate over
# a-1 number, but we also need a in final output ))
res+=str(i)
# ^ appending the value of I to the string variable so for watch iteration
# number come append to it.
# Example : 1-> 12-> 123-> 1234-> 12345-> 123456-> 1234567-> 12345678-> 123456789
# so after each iteration number added to it ,in example i have taken a=9
sol = int(res) #converting the res value(string) to int value (as we desire)
print(sol)
In one line, the solution is
a=int(input())
res=int(''.join([str(i) for i in range(1,a+1)]))
Try this,
n = int(input('Please enter an integer'))
s = 1
do:
print(s)
s+=1
while s == n
this works.
(Simple and Short)
I have to write a program to print the numbers 1 to 50, but with 5 numbers in a row, like:
1,2,3,4,5
6,7,8,9,10
like that till 50 without using lists
for i in range(2,51):
if i%5==0:
print i
this is giving me 5,10,15,20
Please help me
A few hints:
The first parameter for the range() function is incorrect. It must be 1 not 2. The start index included, the ending one is excluded. This is btw a very good practice to avoid bugs.
With the modulo operator you found a way of detecting every 5 values; you could use this to print a line when that happens. You then would be left with having to find a way to not output a line when you output one value at at time; look in the python documentation for way to make the print() function do this. (attention, things have changed in the area of print with Python 3.0, but you seem to be using a 2.x version given your example)
An alternative approach is to use the 3rd argument of the range() function, to step though the sequence, in increments of 5). Such a range would give you 1, 6, 11, 16 etc. in sequence, and you can use this number as the first of each line, and simple addition for the following ones.
You can start almost like you did (except you need to start from 1 - that 2 is really weird!-):
for i in range(1,51):
if i % 5 == 0:
print i
but then you need to segue into an else clause for that if, because you do want to print something even when i is not a multiple of 5 -- just something different from the simple print i you're already doing when i is a multiple of 5...:
else:
print i, ',',
As other answers already said, the trailing comma means "no newline yet"!-) ((It's plainer and more sensible in Python 3.whatever, but you're clearly using Python 2.something, and in those versions this is what you need to do)).
I've never used Python, but this should be close if not right.
for i in range(1,51):
print i;
print ",";
if (i%5==0)
{ print "\n";}
Also, remember that using print will cause a new line to start. Unless as noted above a comma is used afterwards.
You can collect values using a string for printing out later.
Some Hints
To print 1 to 50, you need to pass n+1 for eg, 1 to 51 in range function, its (i=1;i<51,i++) in C alike syntax
print comma if you want between every digits
to print line break for every 5, you can just use current if i%5==0: but print blank line, instead of i
To concatenate num + string "," you can use `i` or str(i) , you can do like `i` +","
If you dont need comma in the end, you could do like i%5 print "," else print "\n" =>
(i%5 and "," or "\n")
print i will print i line by line, and print i, will print in the same line
just my 2 cents
for i in range(1,51):
if i%5 == 0:
print i
else:
print i, ",",
(there used to be python code here)
EDIT: My apologies, didn't realize this was homework. I reeeally need to check tags before answering. Here's an explanation of what needs to happen.
Obviously you know that you're trying to output consecutive numbers from 1 to 50, so you'll need a counter. You've figured out that it'll require a range() call, but it needs to be from 1 to 51, not from 2 to 50.
The reason the range() call needs to be from 1 to 51 is this: it will start the variable i at 1, then check to see if it has reached its goal (51) before looping. If the goal is reached (meaning if i == 51) it will quit the loop without executing the loop's code. So rather than go from 1 to 50, you go from 1 to 51 so that we don't skip the 50th iteration.
Next, you're going to want to have the numbers appear on-screen. But using python's print command prints each number on a new line! That's obviously not what you want. So you're going to have to create a buffer string to append each number to until you're ready to print the line. You can call it 'output' or whatever.
Personally, I like to clear the buffer BEFORE the for loop just to be sure no residual memory traces find their way into the output. Call me paranoid. So I write output = "" on a line before the loop.
Now you've got a buffer string, all you need to do is follow a logical flow:
Add i to the buffer output.
If i is a multiple of 5, print the buffer output and reset it back to an empty string. (We do this so that we can start the buffer for the next line.)
If i is NOT a multiple of 5, add a comma to the output buffer, so that the next number added will be after the comma.
Continue our loop.
These steps should be pretty simple to figure out. Step 2 you've already seen before... To check if a number is a multiple of another number, simply use %. If A % B == 0 then A is a multiple of B.
This should be a pretty straightforward explanation for how to solve this problem. Hope it helps.
And sorry for ruining your learning experience by posting the answer! Now you'll understand why the answer works.
for i in range(1,51):
if i%5 != 0:
print str(i)+',' , # trailing comma means no \n
else:
print i
this code will give you the required output.
#python
for i in range(1,51):
if i%5 == 0:
print (i)#this will give \n at the end
else:
print (i,end=",")#this will print the numbers with coma at the end
you can put 'end="" ' to print without a space
for space 'end=" "'
In one statement, you can unpack a generator expression withing print and utilise the sep argument. The benefit of this solution is there's no need for explicit if / else conditional logic.
k, n = 5, 50
print(*(','.join(map(str, range(i, i+k))) for i in range(1, n+1, k)), sep='\n')
# 1,2,3,4,5
# 6,7,8,9,10
# 11,12,13,14,15
# 16,17,18,19,20
# 21,22,23,24,25
# 26,27,28,29,30
# 31,32,33,34,35
# 36,37,38,39,40
# 41,42,43,44,45
# 46,47,48,49,50