Below is the code(I know below code is wrong syntax just sharing for understanding requirement) I am using to test multiple for loop.
server = ['1']
start = 2
end = 4
for x in range(start, end + 1) and for y in serverip:
print x
print y
Requirement.
for loop iterations must not cross server list length or range .
Input 1
start = 2
end = 4
server list length = 1 that is server = ['1']
expected output 1:
print
x = 2
y = 1
Input 2
start = 2
end = 4
server list length = 2 that is server = ['1','2']
expected output 2:
print
x = 2
y = 1
x = 3
y = 2
Input 3
start = 1
end = 1
server list length = 2 that is server = ['1','2']
expected output 3:
print
x = 1
y = 1
Please help.
The easiest way is to use the built-in zip function suggested in the comments. zip creates a list, or an iterator in python 3, with the iterators “zipped” together. Until one of the iterators runs out.
server = ['1']
start = 2
end = 4
for x, y in zip(range(start, end + 1), server):
print x
print y
Output:
2
1
https://docs.python.org/2/library/functions.html#zip :
This function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables. The
returned list is truncated in length to the length of the shortest
argument sequence.
Related
making a function that recieves numbers separated by spaces and adds the first element to the rest, the ouput should be a list of numbers if the first element is a number
i'm trying to remove all non numeric elements of list b
examples- input: 1 2 3 4
output: [3, 4, 5] (2+1, 3+1, 4+1)
input: 1 2 b 4
output: [3, 5] (2+1,b is purged, 4+1)
input: a 1 2 3
output: Sucessor invalido
linha = input()
a = linha.split()
b = [x for x in (a[1:]) if type(x)==int]
b = [eval(x) for x in b]
c = eval(a[0])
d = []
d.append(c)
f = d*len(b)
def soma():
if type(c)!= int: return print("Sucessor invalido")
else: return list(map(lambda x, y: x + y, b, f))
g = soma()
g
> this condition always returns an empty list
if type(x)==int
sorry if im not clear, i started learning recently
Two things:
The results of input are always strings. When you split the string, you end up with more strings. So even if that string is '7', it is the string 7, not the integer 7.
If you want to check if an object is of a type, use isinstance(x,int) rather than type(x)==int.
To accomplish what it looks like you are doing, I dunno if you can get it with list comprehension, since you probably want a try:...except:... block, like this.
linha = input()
a = linha.split()
b = [] #empty list
for x in a[1:]: # confusing thing you are doing here, also... you want to skip the first element?
try:
x_int = int(x)
b.append(x_int)
except ValueError:
pass
...
You need to convert the numbers separated by lines to integers, after checking that they are valid numberic values like this:
b = [int(x) for x in (a[1:]) if x.isnumeric()]
this is because your input will be a string by default, and split() will be just a list of strings
Your input is string, you need to cast it to int and then do calculation to append it to a new list.
The function should check for the index 0 first using str.islpha() method. If it's an alphabet, return invalid input.
Use try except when iterating the input list. If some element can't be cast to int it will continue to the next index.
def soma(linha):
if linha[0].isalpha():
return f"Sucessor invalido"
result = []
for i in range(len(linha) - 1):
try:
result.append(int(linha[0]) + int(linha[i+1]))
except ValueError:
continue
return result
linha = input().split()
print(soma(linha))
Output:
1 2 3 4
[3, 4, 5]
1 2 b 4
[3, 5]
a 1 2 3
Sucessor invalido
I want to write this for loop in a more elaborative and in a efficient way...is there a way to do that
for index in indices:
x = seq[lowerIndex:(index+1)] #lower index is set to 0 so it will take the first broken string and also the last string
digests.append(x) #it will add the pieces here in to a given list format
print("length: "+ str(len(x)) + " range: " + str(lowerIndex + 1) + "-" + str(index+1)) #This will print the length of each piece and how long each piece is.
print(x) #this will print the piece or fragments
lowerIndex = index + 1 # this refers to the piece after the first piece
You can try:
# new indices contains the beginning index of all segments
indices = [i+1 for i in indices]
indices.insert(0, 0)
for from, to in zip(indices, indices[1:]): # pair 2 consecutive indices
x = seq[from:to]
digest.append(x)
print(f'length: {to-from} range: {from+1} - {to}') # use string format
print(x)
For example:
>>> seq = 'abcdefghijk'
>>> indices = [0, 3, 5, 6, 9]
---------- (result)
length: 3 range: 1 - 3
abc
length: 2 range 4 - 5
de
length: 1 range 6 - 6
f
length: 3 range 7 - 9
ghi
The input for the code is supposed to be something like
10
1 0 1 0 1 0
and the output is supposed to be the absolute value difference of the number of 1s and 0s. The code works when I enter just the 2nd line but when I enter the first line the array is only [1, 0] so the output doesn't work either. How can I make it so both lines are registered?
array = input()
array = array.replace(" ","")
array = [int(x) for x in str(array)]
one = (array.count(1))
zero = (array.count(0))
output = zero - one
if output < 0:
#output = output * -1
print(output)
You want to take 2 lines of input from the user. But input always only reads 1 line. However, you may make 2 calls to input, one for each line, then join the two lines. E.g.
array = input() # line 1
array += input() # line 2
The rest of your code could be written as follows:
array = array.replace(" ","")
array = [int(x) for x in array]
one = array.count(1)
zero = array.count(0)
output = zero - one
print(output)
I have an object x
print(x)
1
1
2
print(type(x).__name__)
int
int
int
How do I extract only the first 1 from it. If I try x[0], I get the following message
TypeError: 'int' object is not subscriptable
I found a lot of questions about the error but none of the solutions worked for me.
Here is the stdin from where x was read
3
1 2 3
1 3 2
2 1 3
Here is how it was read
q = int(input().strip())
for a0 in range(q):
x,y,z = input().strip().split(' ')
x,y,z = [int(x),int(y),int(z)]
Typically you store them in a container (for example a list) during the loop in case you want to access them later on.
For example:
q = int(input().strip())
res = []
for a0 in range(q):
x,y,z = input().strip().split(' ')
res.append([int(x),int(y),int(z)])
print(res) # all x, y and z
or to access specific elements:
print(res[0][0]) # first x
print(res[1][0]) # second x
print(res[0][1]) # first y
Very new to python so please excuse!
question is...to make an output look like
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
I am using user input for the limit and the number of copies ( in this example 5 and 3), so I have done this;
limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))
def output(limit):
for i in range(copies):
for x in range(limit):
print (x + 1, end=" ")
output(limit)
However the answer shows up as 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5. I know it's because of the end=" " but not sure how to get around it! Any help appreciated
Print new line explicitly for every loop:
def output(copies, limit):
for i in range(copies):
for x in range(limit):
print (x + 1, end=" ")
print() # <----
# print() # Add this if you want an empty line
output(copies, limit)
You got the part with the ranges correctly, but there's one thing you missed, you can specify a starting number:
v0 = range(1, limit + 1)
In order to convert a number to a string, use the str() function:
v1 = (str(x) for x in v0)
In order to put a space between adjacent numbers, use the string's join() memberfunction:
v2 = ' '.join(v1)
Then, you could either add the linebreaks yourself:
v3 = (v2 + '\n') * copies
print(v3, end='')
Alternatively in this form:
v3 = '\n'.join(v2 for i in range(copies))
print(v3)
Or you just print the same line multiple times in a plain loop:
for i in range(copies):
print(v2)
BTW: Note that v0 and v1 are generators, so joining them into a string v2 will change their internal state, so you can't simply repeat that and get the same results.
Just a little modification to your code:
def output(limit):
for i in range(copies):
for x in range(limit):
print(x + 1, end=' ')
print()
limit = int(input("Select upper limit"))
copies = int(input("Select number of copies"))
def output(limit):
for i in range(copies):
if (i!=0):
print()
print()
for x in range(limit):
print (x + 1, end="")
output(limit)