In the code I've written, there's a variable called SignA. Depending upon this value the loop needs to repeat a certain amount of times. In the case of this example lets say SignA is 3 and hence the inner contents needs to loop three times.
Here's the code:
if (signA > 0):
count = 0
for iterate in range(signA):
count=count + 1
#ws.Cells(row_origin, column_origin).Value = "Created " + str(signA) + " Sign A signs"
# The index pertains to the index location of the element in the list
# the 'n' represents the actual name of the header attribute
#for test in range(signA):
repeated = 0
for index, n in enumerate(header):
rowDictionary[n] = row[index+3]
ws.Cells(row_origin, column_origin).Value = rowDictionary[n]
column_origin += 1
print("The value of signa is: " + str(signA))
repeated+=1
print("Loop has repeated {} times".format(str(repeated)))
print("count (this increments to the sign num value): " + str(count))
#print("The row_origin is: " + str(row_origin) + " and the column_origin is: " + str(column_origin))
#row_origin = row_origin + 1
#resetRowDictionaryionary()
print("Ending row loop now. This is printed once the whole sign num loops are done")
I require the inner loop of line "for index, n in enumerate(header):" to repeat 3 times, however it appears to only repeat once and then not print anything at all.
Can someone please take a look at my code.
Thanks!
Related
I I've finally found how to make a RLE algorithm by watching a tutorial but This tutorial didn' t explain something in that code I didn't get why we write j = i instead of j = 0 (Knowing that I = 0) it's the same no ?
I didn't get why i = j + 1 either. Why i = j + 1 At the end of the function ? Why not simply i += 1 but if we want to repeat a loop in a loop then we do j + 1 ?
Did the first while loop is supposed to repeat the second while loop until the string is finished ?
And finally why encoded_message is repeated two times ? instead of one. We return encoded_message so that's it ? We can simply do print(encode(text)) instead of
"print('The encoded message is the output ',encoded_message)" (when we put encode(text) into encoded_message)
I know i'm asking a lot of questions but I just can't memorize the code without understanding it, it would be totally useless and unproductive
def encode(message):
encoded_message = ""
i = 0
while(i<len(message)):
count = 1
ch = message[i]
j = i # ???
while(j<len(message)-1): # GET IT -----------------------------------------------------------
if message[j] == message[j+1]: # if the previous and next characters are the same
count = count + 1 # we increase count variable
j += 1 # we increase j position
# GET IT ----------------------------------------------------------------------------
else:
break
encoded_message = encoded_message + str(count) + ch # "" + count converted to string + character (ch)
i = j + 1 # ???
return encoded_message
text = input('enter your charcter chain...')
encoded_message = encode(text)
print('The encoded message is the output ',encoded_message)
When I replaced j = i by j = 0 nothing is displayed in the terminal
see : no result
There is an outer loop and an inner loop. The outer loop with the variable i starts iterating over the message. The inner loop uses the variable j and starts at the current position of i.
That is: when i=0 then j=0. But when i=5 (for example) then j=5 also.
The inner loops task is to check whether 2 or more identical characters follow one another. If they do i is increased accordingly at the end of the inner loop. So that each letter of the message is only looked at once.
That is why j should not be set to a constant value. Setting it to j=0 would cause the inner loop to start at the beginning of the message at every iteration.
I added two simple print() statements to your code to clarify:
def encode(message):
encoded_message = ""
i = 0
while(i<len(message)):
print(f'outer loop: i={i}')
count = 1
ch = message[i]
j = i
while(j<len(message)-1):
print(f'\tinner loop: j={j}')
if message[j] == message[j+1]: # if the previous and next characters are the same
count = count + 1 # we increase count variable
j += 1 # we increase j position
else:
break
encoded_message = encoded_message + str(count) + ch # "" + count converted to string + character (ch)
i = j + 1
return encoded_message
text = 'Hello World'
encoded_message = encode(text)
print('The encoded message is the output ', encoded_message)
(Please note: I do not know the RLE algorithm but just looked at your code.)
I have a 2d list [1,2,3,4],[4,3,3,1],[3,2,1,1],[2,2,2,1] and I want to print it out to match the following format.
0123
XXXXXXXX
0*1234*0
1*4331*1
2*3211*2
3*2221*3
XXXXXXXX
0123
It should not be hard coded and the length of the list = n so this list n=4 but if list n=5 there would be 5 digits per row and the number on the sides would go 0,1,2,3,4.
So far all I have is:
for row in board:
for column in row:
print(column, end="")
print("")
Which only outputs the list as:
1234
4331
3211
2221
please help me add all the special stuff.
so I find a solution for what you want to do however I think it can be improved a lot (not program quite a lot in python), but I'll leave it here anyways :)
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
for x in range(len(board)+4):
print("X", end="")
print()
for num,row in enumerate(board):
print(f"{num}*", end="")
for column in row:
print(column, end="")
print(f"*{num}", end="")
print("")
for x in range(len(board)+4):
print("X", end="")
print()
print(" ", end="")
for x in range(len(board)):
print(x, end="")
print()
Well for the first line you pretty much print 2 spaces, followed by all the digits between 0 and the number of columns in your board. You can use the "range" function for this. Then you must print the correct amount of 'X'. The correct amount is number of columns + 4, I think you can see why.
You should keep a counter starting from 0. For each row you print, you must print the string value of the counter, followed by an asterisk(*), followed by your row, followed by an asterisk(*) and finally followed by the same counter value. You must increment the counter by one for each row.
The last 2 rows are the same as top 2.
I do not want to share my code because this is such a simple problem, I think solving it on your own will help you in the long run.
Probably an unpopular opinion, but I think these kinds of problems are really fun.
This solution formats the contents correctly, even if you change the number of rows, and even the number of items in each row.
def draw_board(board):
# determining the number of elements in a row,
# this is used for printing the X's
# and printing the spaced ranges (i.e. " 0123 ")
n = len(board[0])
# calculating the total width of the board,
# + 4 is because of the "0*...*0" situation
width = n + 4
# calculating margin of the spaced ranges
# (i.e. calculating how much space on each side)
margin = int(n / 2)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
# printing the XXXX
print("X" * width)
# printing the row index number,
# with the *,
# along with the numbers in the row,
# followed by the * and the row number
for row in range(len(board)):
print(str(row) + "*" + "".join(str(elem) for elem in board[row]) + "*" + str(row))
# printing the XXXX
print("X" * width)
# printing the spaced ranges using the margin
print(" " * margin + "".join(str(num) for num in list(range(n))) + " " * margin)
b = [
[1,2,3,4],
[4,3,3,1],
[3,2,1,1],
[2,2,2,1]
]
draw_board(b)
# OUTPUT:
# 0123
# XXXXXXXX
# 0*1234*0
# 1*4331*1
# 2*3211*2
# 3*2221*3
# XXXXXXXX
# 0123
Edited to remove my own tests and to reflect given problem.
I'm a beginner in coding and in Python too. Right now I'm working on a Vigenère cipher.
I've gotten far enough to encrypt the message using a key. I added comments on each section of code for reference. Here is my code. My question is below the code.
# Ask user for message
print('type a message.')
message = input()
# print a white line for neatness
print()
# ask user for a key
print('give your key')
key = input()
# create a range with the length of the message
ran = range(len(message))
# Iterate though the range and therefor show all the letters
for i in ran:
# get current letters for this iteration
currentLetter = message[i]
currentKeyLetter = key[i % len(key)]
# Get corresponding numbers
numberLetter = ord(currentLetter)
numberKeyLetter = ord(currentKeyLetter)
# Add two letters
sumTwoLetters = numberLetter + numberKeyLetter
# Get the number of the encrypted letter
newNumberLetter = sumTwoLetters % 128
# Get the encrypted number based on number
newLetter = chr(newNumberLetter)
# print out the result
printText = currentLetter + "(" + str(numberLetter) + ") + "
printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = "
printText += newLetter + "(" + str(newNumberLetter) + ")"
print(printText)
The code asks for the user's input for the message and key. The ran variable creates a range with the length of the message.
After that, the for loop encrypts the message with the key using ord and chr
The encrypted letter is stored in the variable newLetter
the user can see what the program has done with printText
However, my question is: How can I make the encrypted text appear on a single string. I tried to do it in a loop. I failed miserably (so much so that I don't want to show it)
Does anyone have any suggestions on how to make the encrypted message appear in a single line of text?
You can gather the results in a list and then join() them all into a single string at the end after the for loop. See the comments for the changes.
...
results = [] # ADDED.
# Iterate though the range and therefor show all the letters
for i in ran:
# get current letters for this iteration
currentLetter = message[i]
currentKeyLetter = key[i % len(key)]
# Get corresponding numbers
numberLetter = ord(currentLetter)
numberKeyLetter = ord(currentKeyLetter)
# Add two letters
sumTwoLetters = numberLetter + numberKeyLetter
# Get the number of the encrypted letter
newNumberLetter = sumTwoLetters % 128
# Get the encrypted number based on number
newLetter = chr(newNumberLetter)
# print out the result
printText = currentLetter + "(" + str(numberLetter) + ") + "
printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = "
printText += newLetter + "(" + str(newNumberLetter) + ")"
results.append(printText) # PUT IN results LIST INSTEAD OF PRINTING.
print(''.join(results)) # ADDED.
There are two easy ways. Either (1) build the string inside the loop and print it outside the loop, or (2) print each character as you move through the loop but without newlines, plus one newline after the loop.
Try one of those approaches and if you need more help, add a comment. You'll learn more by trying it yourself!
We are reading lines from a file which contain integers. There are an indeterminate amount of lines being read. We must split each integer into the digits of the integer and then add the digits together and create another file which writes in both the integer and the sum of the digits for each integer.
The professor said to use an event-controlled loop, but didn't specify beyond that. We are only permitted to use while loops, not for loops.
I can't figure out how to put code in here so that I can show what I have tested so far just to get reacquainted with the splitting of a certain amount of digits in an integer.
Edit to add:
myFile = open("cpFileIOhw_digitSum.txt", "r")
numbers = 1
numberOfLines = 3
digitList = []
while(numbers <= numberOfLines):
firstNum = int(myFile.readline())
while (firstNum != 0):
lastDigit = firstNum % 10
digitList.append(lastDigit)
firstNum = firstNum / 10
firstDigit = firstNum
digitList.append(firstDigit)
digitSum = sum(digitList)
print digitList
print digitSum
numbers += 1
myFile.close()
^Here is what I have so far but now my problem is I need each integer's digits stored in a different list. And this is an undetermined amount of integers being read from the file. The numbers used for the count and to end the loop are simply examples.
LASTEST UPDATE to my code: Pretty much all I need to know now is how to let the while loop know that there are no more lines left in the txt file.
myFile = open("cpFileIOhw_digitSum.txt", "r")
myNewFile = open("cpFileIOhw_output.txt", "w")
total = 0
fullInteger =
while(fullInteger != 0):
fullInteger = int(myFile.readline())
firstNum = fullInteger
while (firstNum != 0):
lastDigit = firstNum % 10
total = total + lastDigit
firstNum = firstNum / 10
firstDigit = firstNum
total = total + firstDigit
myNewFile.write(str(fullInteger) + "-" + str(total))
print " " + str(fullInteger) + "-" + str(total)
total = 0
myFile.close()
myNewFile.close()
Well, there are two ways to approach this:
cast the integer to a string and iterate through each character, casting each back to an int (best done with a for loop)
repeatedly get the dividend and modulo of dividing the integer by 10; repeat until the dividend is 0 (best done with a while loop).
And these are the math operators you need:
mod = 123 % 10 # 3
div = 123 // 10 # 12
Casting the integers to strings shouldn't be necessary. Since you're reading the integers in from a text file, you'll start with strings.
You'll need an outer while loop to handle reading the lines from the file. Since you're forbidden to use for loops, I would use my_file.readline(), and you'll know you're done reading the file when it returns an empty string.
Nested inside that loop, you'll need one to handle pulling apart the digits. Although-- did your professor require two loops? I thought that your question said that before it was edited, but now it doesn't. If it's not required, I would just use a list comprehension.
Try this for splitting into digits:
num = 123456
s = str(num)
summary = 0
counter = 0
while (counter < len(s)):
summary += int(s[counter])
counter += 1
print s + ', ' + str(summary)
Result:
C:\Users\Joe\Desktop>split.py
123456, 21
C:\Users\Joe\Desktop>
Try the following...
total = lambda s: str(sum(int(d) for d in s))
with open('u3.txt','r') as infile, open('u4.txt','w') as outfile:
line = '.' # anything other than '' will do
while line != '':
line = infile.readline()
number = line.strip('\n').strip()
if line != '':
outfile.write(number + ' ' + total(number) + '\n')
# or use ',' instead of ' 'to produce a CSV text file
places=["Jack", "John", "Sochi"]
place = places[0]
while places != "Sochi" and count < len(places):
if ' ' in place:
multi_word += 1
count += 1
place = places[count]
I basically want the program to check how many cities till Sochi, by adding one for each element of the list. Then when it reaches Sochi it stops adding 1 to the list then it do nothing when it reaches Sochi. The program adds one for every element of the list. Then it checks if their is a space in any of the elements of the list and if so adds one but only if that element of the list comes from Sochi. What is wrong with this program?
Also what does this line do..{count < len(places)}
The main error I see is that you need to check if place != "Sochi", instead of using places. Assuming you initialize count=0, this will give you the output you desire:
places = ["Jack", "John", "Sochi"]
place = places[count]
while place != "Sochi" and count < len(places):
if ' ' in place:
multi_word += 1
count += 1
place = places[count]
print 'Number of cities before Sochi:', count
The clause count < len(places) makes sure that you don't try access indices in places beyond the length of the list, which would return an IndexError.
places = ["Jack", "John", "Sochi"]
count=0
multi_word=0
place = places[count]
while place != "Sochi" and count < len(places):
if ' ' in place:
multi_word += 1
count += 1
place = places[count]
print ('Number of cities before Sochi:', count)
Here is the fixed code