how to reverse a string number in python with for loop - python

I am trying to reverse a string number from right to wrong with odd index I have done from left to right but can you some one help how to do it from right to left
for i in range(0, len(number), 2):
print(number[i])
something like
for i in range (-len(length), len(length), -2)
let's say a number 1234567
i want to print 7,5,3,1.

num = '123456789'
for i in num[::-1][::2]:
print(i)
Output -
9
7
5
3
1

You can use the slice notation [start:end:increment] to do
value = "123456789"
for v in value[::-2]:
print(v)
To have
9
7
5
3
1

number = "1234567"
for i in range (len(number)-1,-1,-2):
print (number[i])
output:
7
5
3
1
is that what you want?

Suppose your string is:
number = "123456789"
then,
for i in range(0, len(number), 2):
print(number[len(number) - i - 1])

Update: Now I think I understood correctly:
number = "1234567"
for i in range(len(number), 0, -2):
print(number[i-1])

Related

Why is it giving runtime error on codeforces for python?

So I am very new to code and have learnt the basics of python. I am testing out my skills on codeforces by first solving some of their easier problems. I am trying to do 158A on codeforces. I think I have got it because it passed a few tests I assigned. So, I tried submitting it and it told me something about a runtime error. I don't really know what it is so I would like it if someone could tell me what it is and how to fix it in my code. Here is the link to the problem: https://codeforces.com/problemset/problem/158/A
n = int(input())
k = int(input())
b = []
for i in range(n):
a = int(input())
b.append(a)
c = 0
for i in b:
if i >= b[k]:
c = c+1
else:
pass
print(c)
The input you are given is "8 5" and "10 9 8 7 7 7 5 5". That doesn't mean you are given "8" and "5" as two different inputs. It means you have a very long string that contains numbers separated by spaces. You should turn these into a list.
a = input()
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
a should equal "8 5". We then turn the string into a list using a.split(" "). This will produce ["8", "5"].
In the problem 158A the expected input are:
1. Two numbers (int) separated by a single space, where 1 ≤ k ≤ n ≤ 50
2. n space-separated integers, where ai ≥ ai + 1
There is also a condition: Scores MUST be positive (score>0) so you can advance
This is all you need, I tested it and I got the expected output everytime
a = input("Input n and k: ")
n = int(a.split(" ")[0])
k = int(a.split(" ")[1])
b = input("Input n scores: ")
willAdvance = 0
scores = b.split()
print(scores)
for element in scores:
if int(element) >= int(scores[k-1]) and int(scores[k-1]) > 0:
willAdvance += 1
print(willAdvance)
TEST
Input:
8 5
10 9 8 7 7 7 5 5
Output:
6
Input:
4 6
0 0 0 0
Output:
0

Python list output

Quiz on Tutorials Point list the following question?
https://www.tutorialspoint.com/python/python_online_quiz.htm
Q 9 - What is the output of L[-2] if L = [1,2,3]?
A - 1
B - 2
C - 3
D - None of the above.
Answer : A Explanation 1, Negative: count from the right.
They are saying the answer is 1, but when I run the following in idle I get output of 2
L = [1,2,3]
print (L[-2])
output 2
is this a error on tutorial point or is it error in idle ?
My python version is 2.7
The Quiz should be wrong.
L[-1] refers to the last element of the list, 1. Therefore, L[-2] should refer to 2.
Assuming L = [1,2,3], we know that their elements positions are:
number 1 = position 0
number 2 = position 1
number 3 = position 2
So L[-2] is equal to 2, because:
Counting Forward:
L[0] = number 1
L[1] = number 2
L[2] = number 3
Counting Backward:
L[-1] = number 3
L[-2] = number 2
L[-3] = number 1
So... I think your quiz answer is wrong. The correct answer for L[-2] is the alternative B-2.

Taking user input of 2-D array in a given format

I have a 2-D 6x6 array, A.
I want its values to be input by the user in the following format or example:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
where the 0's indicate the places where the user would write their values.
This is my code. It returns an error in split().
def arr_input(x):
for i in range(6):
for j in range(6):
n = int(input().split(' '))
if n>=-9 and n<=9:
x[i][j] = n
print "\n"
I don't want input in a single line. Please help!
EDIT 1
The code I needed was already provided :D. Nevertheless, I learned something new and helpful. Here is the existing code to do the task I wanted:
arr = []
for arr_i in xrange(6):
arr_temp = map(int,raw_input().strip().split(' '))
arr.append(arr_temp)
First of all, you are using input() which returns int when you enter numbers in terminal. You should use raw_input() and get it line by line.
Second, you are trying to convert a list to integer, you should loop through the list values, convert and insert on the resulting list.
Fixed code:
def arr_input(x):
for i in range(6):
num_list = raw_input().split(' ')
for j, str_num in enumerate(num_list):
n = int(str_num)
if n >= -9 and n <= 9:
x[i][j] = n
print "\n"
Here, I used enumerate() to loop though the number list by getting its index each iteration.
There's an inconsistency in how you're treating the input. In python 2.7, the input() function is designed to read one, and only one, argument from stdin.
I'm not exactly sure which way you're trying to read the input in. The nested for loop suggests that you're trying to read the values in one by one, but the split suggests that you're doing it line by line. To cover all bases, I'll explain both cases. At least one of them will be relevant.
Case 1:
Let's say you've been inputting the values one by one, i.e.
1
4
9
4
...
In this case, what's happening is that the input() function is automatically parsing the inputs as integers, and when you try running split() on an integer there's a type error. Python is expecting a string and you're providing an int. That's going to break. There's an easy solution--this can be fixed by simply replacing that line with
n = input()
Case 2: Let's say you're inputing the numbers line by line, as strings. By this, I mean something like:
"1 3 4 5 7 9"
"4 1 8 2 5 1"
...
What's occurring here is that int(...) is trying to cast a list of strings into an integer. That will clearly break the code. A possible solution would be to restructure the code by gett rid of the inner for loop. Something like this should work:
def arr_input(arr):
for i in range(6):
s = input()
nums_s = s.split(' ')
nums = [int(x) for x in nums_s]
arr.append(nums)
print "\n"
return arr
# Usage
a = []
print(a)
a = arr_input(a)
print(a)
Give this one-liner a try:
def arr_input(N=6):
print 'Enter %d by %d array, one row per line (elements separated by blanks)' % (N, N)
return [[n if abs(n)<=9 else 0 for n in map(int, raw_input().split())] for i in range(N)]
The following interactive session demonstrates its usage:
>>> A = arr_input(3)
Enter 3 by 3 array, one row per line (elements separated by blanks)
1 2 -3
4 5 -6
8 9 10
>>> A
[[1, 2, -3], [4, 5, -6], [8, 9, 0]]

Taking an input of any length of number and splitting them one character each

I'm a few weeks into learning python and I am trying to write a script that takes an input of any length of numbers and splits them in one-character lengths. like this:
input:
123456
output:
1 2 3 4 5 6
I need to do this without using strings, and preferably using divmod...
something like this:
s = int(input("enter numbers you want to split:"))
while s > 0:
s, remainder = divmod(s, 10)
I'm not sure how to get the spacing right.
Thank you for the help.
As your priority is to use divmod, you can do it like this:
lst=[]
while s>0:
s, remainder = divmod(s, 10)
lst.append(remainder)
for i in reversed(lst):
print i,
Output:
enter numbers you want to split:123456
1 2 3 4 5 6
You can use join() to achieve that. Cast to string if your are using python 2.*
s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)
In case, you are in need of integers, just do it.
intDigitlist=map(int,digitlist)
What about the following using the remainder:
s = 123456
output = []
while s > 0:
s, r = divmod(s, 10)
output.append(r)
fmt='{:<12d}'*len(output)
print fmt.format(*output[::-1])
Output:
1 2 3 4 5 6
This also uses some other useful Python stuff: the list of digits can be reversed (output[::-1]) and formatted into 12-character fields, with the digit aligned on the left ({:<12d}).
Try it with mod:
while x > 0:
x = input
y = x % 10
//add y to list of numbers
x = (int) x / 10
e.g. if x is 123:
123 % 10 is 3 -> you save 3.
the Integer value of 123 / 10 is 12.
Then 12 % 10 is 2 -> you save 2
Int of 12 / 10 is 1.
1 % 10 = 1 -> you save 1
Now you have all numbers. You can invert the list after that to have it like you want.
You can iterate over Python string amd use String.join() to get result:
>>>' '.join(str(input("Enter numbers you want to split: ")))
Enter numbers you want to split: 12345
1 2 3 4 5

Nested Loops to create a pattern

How could I use Nested Loops to create the following pattern?
111111
11111
1111
111
11
1
So far i have this and i seem to be stuck.
def main():
stars = "******"
for x in range (1,7):
print(stars)
for y in range (1,1):
stars = stars.replace("*"," ")
main()
You need to replace just 1 star in the inner loop:
stars = "******"
for x in range(6):
stars = stars.replace("*","1")
print(stars)
for y in range(1): # need range(1) to loop exactly once
stars = stars.replace("1","",1)
Output:
111111
11111
1111
111
11
1
If you actually want stars:
stars = "******"
for x in range(6):
print(stars)
for y in range(1):
stars = stars.replace("*","",1)
Output:
******
*****
****
***
**
*
The last arg to str.replace is count where only the first count occurrences are replaced. So each time we only replace a single character.
If you have to uses the stars variable and replace then the code above will work, if you just need nested loops and to create the pattern, you can loop down from 5 and use end="" printing once in the inner loop:
for x in range(5, -1, -1):
print("1" * x, end="")
for y in range(1):
print("1")
Again the same output:
111111
11111
1111
111
11
1
def main(symbol, number):
for x in reversed(range(number)):
s = ""
for y in range(x+1):
s += symbol
print s
main("1", 6)
You can give arguments one symbol (Example - '1','*') and number (Example - '5 for *****' to start with)
You are replacing all the stars in the string with the replace method, meaning you would online print one line of start. You could use the substring method for a better result.
Check answer of Padraic Cunningham with Nested Loop.
Without Nested Loop:
Create Count list by range method and reverse method of list.
Iterate list and print 1 multiple of count.
code:
counters = range(1, 7)
counters.reverse()
for i in counters:
print "1"*i
Output:
111111
11111
1111
111
11
1
Since you're requesting a nested loop, I guess this is just a training exercise and it is not important how efficient it is.
Therefore let me propose a solution with a 'proper' inner loop and without reversed ranges:
def triangle(x, c='1'):
for i in range(x):
line = ''
for _ in range(i, x):
line += c
print(line)
You can get the same output using a simple approach, as Python supports * operator on Strings which returns a string with repeated occurrences.
character = "1" #You can change it to "*"
for i in range(6, 0, -1):
print character*i
Output:
111111
11111
1111
111
11
1

Categories

Resources