for loop through an array to display its contents [duplicate] - python

This question already has answers here:
Why does range(start, end) not include end? [duplicate]
(11 answers)
Closed 4 years ago.
The program calculates the multiplication table from 0 to 12 for the number the user has entered.
I am trying to display the contents of the array with the results in it by for looping through it. However, it only displays the tables from 0 to 11, but not the 12th one, even if the 12th data is there.
Here is what I came up with:
def multiplicationTable():
nb = int(input("Please enter a number between 1 and 12 : \n"))
table = array('i')
for i in range(0,12):
table.append(i * nb)
for i in range(len(table)):
print(str(nb) + "x" + str(i) + " = " + str(table[i]))
The output looks like this:
4x0 = 0
4x1 = 4
4x2 = 8
4x3 = 12
4x4 = 16
4x5 = 20
4x6 = 24
4x7 = 28
4x8 = 32
4x9 = 36
4x10 = 40
4x11 = 44
What could be causing that ? Coming from VB and C# so I may be mistaking the i as an index, while it is a value from the array, but I really don't see how I could be fixing this.
Thank you !

The range() function is non-inclusive of the upper bound. So when you're saying range(0,12), you're only going to get [0,11]. If you want [0,12], you have to do range(0,13). Note that range(0,13) is equivalent to range(13) because the default lower-bound is 0.
See the documentation.

Related

How can I get the sum of the outputs of an equation from a for loop? [duplicate]

This question already has answers here:
How can i sum the value in list with for loop in python?
(3 answers)
Closed 1 year ago.
I know how I can get the sum of the numbers themselves in a range, but if I had an equation written in a for-loop such as the following:
for t in range(0,6):
velocity = (.2*(t**2)) + 3
How could I get Python to add all the outputs of the equation together?
Just add the value of velocity obtained in every iteration as below:
velocity = 0
for t in range(0,6):
velocity += (.2*(t**2)) + 3
print (velocity)
Output:
29.0
Just add the result of the formula to a variable defined outside the for loop
sum_velocity = 0
for t in range(0,6):
sum_velocity += (.2*(t**2)) + 3

String indexing within loop only returns two values [duplicate]

This question already has answers here:
How to find all occurrences of a substring?
(32 answers)
Closed 4 years ago.
I am trying to iterate over a string and find all of the occurrences of a certain substring, like so:
contant = "old men old men old men"
def this (l,n):
while n < 20:
m = contant[l:].index("o")
l = m + 3
n += 1
print(m,l)
this(0,1)
Which will only return the nnumbers 0 3 and 5 8 over and over again, instead of iterating through the entire string.
Try this
value = "old men old men old men"
location = -1
# Loop while true.
while True:
# Advance location by 1.
location = value.find("o", location + 1)
# Break if not found.
if location == -1: break
# Display result.
print(location)
output
0
8
16

How would I Create a second attack input in a battleship adviser without using a bunch of if statements? [closed]

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
After changing my code to what R.Sharp has suggested everything works completely fine but I still can't find a tutorial or anything on how I could create the second attack
Rank= input("What is your rank?")
Name= input("What is your name " + Rank + "?")
grid= input("What would you like the length of your grid to be " + Rank + " " + Name + "?")
Attack1=input("Where do you want to attack first " + Rank + " " + Name + "?\n" +"(Please print with capital letters)")
grid= int(grid)
#Removing the Number from the Letter
RemoveNum = Attack1[0].upper()
#Removing the letter from the coordinates
RemoveLetter = Attack1[1].upper()
RemoveLett=int(RemoveLetter)
row = "1 2 3 4 5 6 7 8 9 10".split()
col = "A B C D E F G H I J".split()
x=col.index(RemoveNum)
y=row.index(RemoveLetter)
possibles=[] # blank list to store suggestions in
if x > 0 :
possibles.append(col[x-1] + row[y]) # left
if x < grid-1:
possibles.append(col[x+1] + row[y]) # right
if y > 0 :
possibles.append(col[x] + row[y-1]) # up
if y < grid-1:
possibles.append(col[x] + row[y+1]) # down
# Construct string of all possibles except the last
poss_list = ','.join(possibles[:len(possibles)-1])
if possibles > grid:
pass
#Printing First Suggestions
print("You could try {0:s} and {1:s}".format(poss_list,possibles[-1]))
OKay - this really isn't an answer, but I wanted to put in some code snippets and use more characters than a comment would allow.
I would recommend re-thinking your approach.
You say you want to be able to vary the grid size, but then your function As() is explicitly hard-wired to a row length of 5.
step one - try to decompose the problem into an engine, or engines, which work on generic assumptions you can have about the data, And a set of data.
For example, to allow for grids up to 10 by 10, define 2 lists of indices :
row = "1 2 3 4 5 6 7 8 9 10".split()
col = "A B C D E F G H I J".split()
Now, google for a way to get the position in the col list, of the letter that was input or read this : How to get the position of a character in Python?
I'm going to refer to this as x
Convert the row value you extracted to an int as before and subtract one as in python lists the first index is zero.
I'm going to refer to this value as y
So if I had input 'D7' x would be 3 and y would be 6.
x=3
y=6
Because the grid is regular you know that the 4 locations around the one you've been given as (x,y) are :
Left = (col[x-1] + row[y])
Right = (col[x+1] + row[y])
Up = (col[x] + row[y-1])
Down = (col[x] + row[y+1])
So to get the 4 points round the one indicated all you need to do is :
print("you could try {0:s}, {1:s}, {2:s} and {3:s}".format(Left, Right, Up, Down))
which gives :
you could try C7, E7, D6 and D8
What you need to consider now is how to handle when your indices go outside your grid. i.e. what to do if x or y are zero, or 9 and how to restructure the output text accordingly.
build the calculation of Up, Down, Right and Left into a function, along with appropriate checking of the indices and then you're ready to handle more complicated advice based on the size of the vessel you're trying to hit and eventually storing known hit locations so you don't advise shooting somewhere that's been hit before.
I hope that helps.
==> Based on your edited question - does this help :
Rank= input("What is your rank?")
Name= input("What is your name " + Rank + "?")
grid= input("What would you like the length of your grid to be " + Rank + " " + Name + "?")
Attack1=input("Where do you want to attack first "
+ Rank + " " + Name + "?\n" +
"(Please print with capital letters)")
#Removing the Number from the Letter
RemoveNum = Attack1[0].upper()
#Removing the letter from the coordinates
RemoveLetter = Attack1[1].upper()
row = "1 2 3 4 5 6 7 8 9 10".split()
col = "A B C D E F G H I J".split()
x=col.index(RemoveNum)
y=row.index(RemoveLetter)
possibles=[] # blank list to store suggestions in
if x > 0 :
possibles.append(col[x-1] + row[y]) # left
if x < grid-1:
possibles.append(col[x+1] + row[y]) # right
if y > 0 :
possibles.append(col[x] + row[y-1]) # up
if y < grid-1:
possibles.append(col[x] + row[y+1]) # down
# Construct string of all possibles except the last
poss_list = ','.join(possibles[:len(possibles)-1])
#Printing First Suggestions
print("You could try {0:s} and {1:s}".format(poss_list,possibles[-1]))

Python - User Input For Arithmetic Progression [duplicate]

This question already has answers here:
accepting multiple user inputs separated by a space in python and append them to a list
(4 answers)
Closed 7 years ago.
I am trying to create a function that calculates the sum of an artithmetic sequence. I know how to set up the mathematical calculations but I don't know how to take input from the user to actually perform them.
How can I take user input (like below) such that the three ints on each line are read as A, B, N, with A being the first value
of the sequence, B being the step size and N the number of steps.
8 1 60
19 16 69
17 4 48
What should come next?
def arithmetic_progression():
a = raw_input('enter the numbers: ')
with raw_input you generally get a string
>> a = raw_input('enter the numbers')
you enter the numbers 8 1 60, so a will be a string '8 1 60'. Then you can split the string into the 3 substrings
>> b = a.split()
This will return you a list ['8', '1', '60']. Out of this you can get your numbers
>> A = int(b[0])
>> B = int(b[1])
>> N = int(b[2])
To read multiple lines you could add a function similar to this
def readlines():
out = raw_input('enter the numbers\n')
a = 'dummy'
while(len(a)>0):
a = raw_input()
out += '\n' + a
return out
This function would read any input and write it to the out string until you have one empty line. To get the numbers out of the string just do again the same as for a single line.
Sum to n terms of AP is: Sn = (n/2) [ 2a + (n-1)d ]
def arithmetic_progression():
inp = raw_input('enter the numbers: ').split(' ')
if not len(inp) == 3: # in case of invalid input
return arithmetic_progression() # prompt user to enter numbers again
a = float(inp[0])
d = float(inp[1])
n = float(inp[2])
s = ( (2 * a) + ((n - 1) * d) ) * (n / 2)
print('Sum to n terms of given AP is: ' + str(s))
arithmetic_progression()

Split array by rows

I have a very basic problem.I have wrote a code which open a .txt file which contain a numbers 1 2 3 4 5 6 7 8 9.Then it square all of it and write to other file.
Right now I want to add to this code procedure which split all of this numbers in rows and rewrite,like this:
1 4 9
16 25 36
49 64 81
My code already:
n=[]
dane = open("num.txt", "r")
for i in dane:
i = i.replace('\n','')
for j in i.split(' '):
j = int(j)
j = j**2
n.append(j)
nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()
The code you have written works fine expect for the writing part. For which you need to change the last three lines of code as
nowy = open("newnum.txt","w")
for i in range(0,len(n),3):
nowy.write("{} {} {}\n".format(n[i],n[i+1],n[i+2]))
nowy.close()
The for loop can be explained as,
loop through the list n that you have generated 3 at a time by using the third argument to the range function which is called step.
write out the values three at a time into the file, terminated by the newline character
The output after changing the lines of code is as expected
1 4 9
16 25 36
49 64 81
Ref:
format
range
As a complement to #Bhargav's answer, according to the doc "[a] possible idiom for clustering a data series into n-length groups [is] using zip(*[iter(s)]*n)"
You can use the star to unpack a list/tuple as arguments to format function call too.
All this will lead to a more Pythonic (or, rather crypto-Pythonic ?) version of the writing part:
with open("newnum.txt","w") as nowy:
for sublist in zip(*[iter(n)]*3):
nowy.write("{} {} {}\n".format(*sublist))
Please note the use of a context manager (with statement) to ensure proper closing of the file in all cases when exiting from the block. As other changes would be subject to discussion, that later is a must -- and you should definitively take the habit of using it
(BTW, have you noticed you never closed the dane file? A simple mistake that would have been avoided by the use of a context manager to manage that resource...)
You can try this:
strNew = ''
dane = open("num.txt", "r")
row = 0
for i in dane:
i = i.replace('\n','')
for j in i.split(' '):
row += 1
j = int(j)
j = j**2
if (row % 3) == 0:
strNew += str(j)+'\n'
else:
strNew += str(j) + ' ' # it can be ' ' or '\t'
nowy = open("newnum.txt","w")
nowy.write(strNew)
nowy.close()
The result is:
1 4 9
16 25 36
49 64 81
n=[]
dane = open("num.txt", "r")
for i in dane:
i = i.replace('\n','')
for j in i.split(' '):
j = int(j)
j = j**2
# new code added
# why str(j)? Because array in Python can only have one type of element such as string, int, etc. as opposed to tuple that can have multiple type in itself. I appended string because I wanna append \n at the end of each step(in outer loop I mean)
n.append(str(j))
# new code added
n.append("\n")
nowy = open("newnum.txt","w")
nowy.write(str(n))
nowy.close()

Categories

Resources