Unexpected error While adding string in print() functuon - python-3.6

I have a simple function fact() to print factorial of a number which is to input at runtime.
Everything works fine ata this code given below.
# Find factorial of a number...
def fact():
number = int(input('Please enter a number: '))
tmp = 1
while number > 0:
tmp *= number
number -= 1
print(tmp)
ask = input('Do you want to try again... [y/n]: ')
if ('y' or 'Y') in ask:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()
But if I add some string in first print() function I get syntax error for the line "ask = input...". Here is the code below.
# Find factorial of a number...
def fact():
number = int(input('Please enter a number: '))
tmp = 1
while number > 0:
tmp *= number
number -= 1
print("Factorial of %d is %d" %(number, tmp)
ask = input('Do you want to try again... [y/n]: ')
if ('y' or 'Y') in ask:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()
I have one last problem. My program asks me if I want to try again. If I type y and enter, in works as it should be. But if I type Y, it exicute else statement.
I am using python3.6.4rc1 in Debian.

this should work!
def fact():
number = int(input("Please enter a number: "))
tmp = 1
while number > 0:
tmp *= number
number -= 1
print("Factorial of %d is %d" %(number, tmp))
ask = input("Do you want to try again... [y/n]: ")
if ask in ['y','Y']:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()

I had to preserve value of number variable as it will become 0 at end of loop. Otherwise my program will print Modulas of 0 is 'some_number. Now I have the correct code...
def fact():
number = int(input("Please enter a number: "))
preserve_number = number
tmp = 1
while number > 0:
tmp *= number
number -= 1
print("Factorial of %d is %d" %(preserve_number, tmp))
ask = input("Do you want to try again... [y/n]: ")
if ask in ['y','Y']:
fact()
else:
print('Thank you for using my tool. Good bye')
fact()

Related

When running code in R was given an error that there was a missing value where true/false needed and I can't fix it

I am new to using R and have minimal amount of Python experience. I am sure this is an easy fix but I am just not seeing it. I was given a code to run a Fibonacci sequence to 100 and I copy and pasted it, but I am getting the following error code: Error in if (numterms <= 0) { : missing value where TRUE/FALSE needed. I know this has to do with the if/else clause but I am not seeing the problem.
I have run through the code a couple different ways but it has not helped. And the person to assist is not available during the weekend. Any help would be appreciated.
# take the max number input from the user
numterms = as.integer(readline(prompt="What is your max number? "))
# first two items
num1 = 0
num2 = 1
counter = 2
# check if the number of terms is valid
if(numterms <= 0) {
print("Please enter an integer above zero")
} else {
if(numterms == 1) {
print("The Fibonacci sequence:")
print(num1)
} else {
print("The Fibonacci sequence:")
print(num1)
print(num2)
while(counter < numterms) {
numth = num1 + num2
print(numth)
# update values
num1 = num2
num2 = numth
counter = counter + 1
}
}
}
If you just execute the code numterms is not correctly defined. It is normally defined by a user input: The function readline reads the numbers the user types in the command line. If you just execute this line you can properly define numterms.
If you execute all the code at once numterms is set to NA which cannot be compared to 0 in the numterms <= 0 clause. In this case numterms <= 0 is also NA which is not a logical value and can therefore not be evaluated by if. This ultimately causes your error.
The solution would be to just run the first line of your code and enter the number and only after you entered the number to execute the rest of the code.
Alternatively you can define your code as a function:
printFibonacci <- function(){
numterms = as.integer(readline(prompt="What is your max number? "))
if(is.na(numterms)){
numterms <- 4
}
# first two items
num1 = 0
num2 = 1
counter = 2
# check if the number of terms is valid
if(numterms <= 0) {
print("Please enter an integer above zero")
} else {
if(numterms == 1) {
print("The Fibonacci sequence:")
print(num1)
} else {
print("The Fibonacci sequence:")
print(num1)
print(num2)
while(counter < numterms) {
numth = num1 + num2
print(numth)
# update values
num1 = num2
num2 = numth
counter = counter + 1
}
}
}
}
And then just call your function with printFibonacci(). In this case the prompt and answer of the readline function gets executed first and numterms can be defined by the user before the rest of the code is executed.

Python 3.6 user-defined board size win check with 2 variables

I have somewhat a general question for more experienced programmers. I'm somewhat new to programming, but still enjoy it quite a bit. I've been working with Python, and decided to try to program a tic tac toe game, but with variable board size that can be decided by the user (all the way up to a 26x26 board). Here's what I've got so far:
print("""Welcome to tic tac toe!
You will begin by determining who goes first;
Player 2 will decide on the board size, from 3 to 26.
Depending on the size of the board, you will have to
get a certain amount of your symbol (X/O) in a row to win.
To place symbols on the board, input their coordinates;
letter first, then number (e.g. a2, g10, or f18).
That's it for the rules. Good luck!\n""")
while True:
ready = input("Are you ready? When you are, input 'yes'.")
if ready.lower() == 'yes': break
def printboard(n, board):
print() #print board in ranks of n length; n given later
boardbyrnk = [board[ind:ind+n] for ind in range(0,n**2,n)]
for rank in range(n):
rn = f"{n-rank:02d}" #pads with a 0 if rank number < 10
print(f"{rn}|{'|'.join(boardbyrnk[rank])}|") #with rank#'s
print(" ",end="") #files at bottom of board
for file in range(97,n+97): print(" "+chr(file), end="")
print()
def sqindex(prompt, n, board, syms): #takes input & returns index
#ss is a list/array of all possible square names
ss = [chr(r+97)+str(f+1) for r in range(n) for f in range(n)]
while True: #all bugs will cause input to be taken for same turn
sq = input(prompt)
if not(sq in ss): print("Square doesn't exist!"); continue
#the index is found by multiplying rank and adding file #'s
index = n*(n-int(sq[1:])) + ord(sq[0])-97
if board[index] in syms: #ensure it contains ' '
print("The square must be empty!"); continue
return index
def checkwin(n, w, board, sm): #TODO
#check rows, columns and diagonals in terms of n and w;
#presumably return True if each case is met
return False
ps = ["Player 1", "Player 2"]; syms = ['X', 'O']
#determines number of symbols in a row needed to win later on
c = {3:[3,3],4:[4,6],5:[7,13],6:[14,18],7:[19,24],8:[25,26]}
goagain = True
while goagain:
#decide on board size
while True:
try: n=int(input(f"\n{ps[1]}, how long is the board side? "))
except ValueError: print("Has to be an integer!"); continue
if not(2<n<27): print("Has to be from 3 to 26."); continue
break
board = (n**2)*" " #can be rewritten around a square's index
for num in c:
if c[num][0] <= n <= c[num][1]: w = num; break
print(f"You'll have to get {w} symbols in a row to win.")
for tn in range(n**2): #tn%2 = 0 or 1, determining turn order
printboard(n, board)
pt = ps[tn%2]
sm = syms[tn%2]
prompt = f"{pt}, where do you place your {sm}? "
idx = sqindex(prompt, n, board, syms)
#the index found in the function is used to split the board string
board = board[:idx] + sm + board[idx+1:]
if checkwin(n, w, board, sm):
printboard(n, board); print('\n' + pt + ' wins!!\n\n')
break
if board.count(" ") == 0:
printboard(n, board); print("\nIt's a draw!")
while True: #replay y/n; board size can be redetermined
rstorq = input("Will you play again? Input 'yes' or 'no': ")
if rstorq in ['yes', 'no']:
if rstorq == 'no': goagain = False
break
else: print("Please only input lowercase 'yes' or 'no'.")
print("Thanks for playing!")
So my question to those who know what they're doing is how they would recommend determining whether the current player has won (obviously I have to check in terms of w for all cases, but how to program it well?). It's the only part of the program that doesn't work yet. Thanks!
You can get the size of the board from the board variable (assuming a square board).
def winning_line(line, symbol):
return all(cell == symbol for cell in line)
def diag(board):
return (board[i][i] for i in range(len(board)))
def checkwin(board, symbol):
if any(winning_line(row, symbol) for row in board):
return True
transpose = list(zip(*board))
if any(winning_line(column, symbol) for column in transpose):
return True
return any(winning_line(diag(layout), symbol) for layout in (board, transpose))
zip(*board) is a nice way to get the transpose of your board. If you imagine your original board list as a list of rows, the transpose will be a list of columns.

Python 3.4 help - using slicing to replace characters in a string

Say I have a string.
"poop"
I want to change "poop" to "peep".
In fact, I also want all of the o's in poop to change to e's for any word I put in.
Here's my attempt to do the above.
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
for i in range (len(y)):
if y[i] == "o":
y = y[:i] + "e"
print (y)
main()
As you can see, when you run it, it doesn't amount to what I want. Here is my expected output.
Enter a word.
>>> brother
brether
Something like this. I need to do it using slicing. I just don't know how.
Please keep your answer simple, since I'm somewhat new to Python. Thanks!
This uses slicing (but keep in mind that slicing is not the best way to do it):
def f(s):
for x in range(len(s)):
if s[x] == 'o':
s = s[:x]+'e'+s[x+1:]
return s
Strings in python are non-mutable, which means that you can't just swap out letters in a string, you would need to create a whole new string and concatenate letters on one-by-one
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = ''
for i in range(len(y)):
if y[i] == "o":
output = output + 'e'
else:
output = output + y[i]
print(output)
main()
I'll help you this once, but you should know that stack overflow is not a homework help site. You should be figuring these things out on your own to get the full educational experience.
EDIT
Using slicing, I suppose you could do:
def getword():
x = (input("Please enter a word."))
return x
def main():
y = getword()
output = '' # String variable to hold the output string. Starts empty
slice_start = 0 # Keeps track of what we have already added to the output. Starts at 0
for i in range(len(y) - 1): # Scan through all but the last character
if y[i] == "o": # If character is 'o'
output = output + y[slice_start:i] + 'e' # then add all the previous characters to the output string, and an e character to replace the o
slice_start = i + 1 # Increment the index to start the slice at to be the letter immediately after the 'o'
output = output + y[slice_start:-1] # Add the rest of the characters to output string from the last occurrence of an 'o' to the end of the string
if y[-1] == 'o': # We still haven't checked the last character, so check if its an 'o'
output = output + 'e' # If it is, add an 'e' instead to output
else:
output = output + y[-1] # Otherwise just add the character as-is
print(output)
main()
Comments should explain what is going on. I'm not sure if this is the most efficient or best way to do it (which really shouldn't matter, since slicing is a terribly inefficient way to do this anyways), just the first thing I hacked together that uses slicing.
EDIT Yeah... Ourous's solution is much more elegant
Can slicing even be used in this situation??
The only probable solution I think would work, as MirekE stated, is y.replace("o","e").

Longest substring in alphabetical order [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 8 years ago.
Improve this question
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print
Longest substring in alphabetical order is: abc
Here you go edx student i've been helped to finish the code :
from itertools import count
def long_sub(input_string):
maxsubstr = input_string[0:0] # empty slice (to accept subclasses of str)
for start in range(len(input_string)): # O(n)
for end in count(start + len(maxsubstr) + 1): # O(m)
substr = input_string[start:end] # O(m)
if len(substr) != (end - start): # found duplicates or EOS
break
if sorted(substr) == list(substr):
maxsubstr = substr
return maxsubstr
sub = (long_sub(s))
print "Longest substring in alphabetical order is: %s" %sub
These are all assuming you have a string (s) and are needing to find the longest substring in alphabetical order.
Option A
test = s[0] # seed with first letter in string s
best = '' # empty var for keeping track of longest sequence
for n in range(1, len(s)): # have s[0] so compare to s[1]
if len(test) > len(best):
best = test
if s[n] >= s[n-1]:
test = test + s[n] # add s[1] to s[0] if greater or equal
else: # if not, do one of these options
test = s[n]
print "Longest substring in alphabetical order is:", best
Option B
maxSub, currentSub, previousChar = '', '', ''
for char in s:
if char >= previousChar:
currentSub = currentSub + char
if len(currentSub) > len(maxSub):
maxSub = currentSub
else: currentSub = char
previousChar = char
print maxSub
Option C
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]: current.append(character)
else:
matches.append(current)
current = [character]
print "".join(max(matches, key=len))
Option D
def longest_ascending(s):
matches = []
current = [s[0]]
for index, character in enumerate(s[1:]):
if character >= s[index]:
current.append(character)
else:
matches.append(current)
current = [character]
matches.append(current)
return "".join(max(matches, key=len))
print(longest_ascending(s))
The following code solves the problem using the reduce method:
solution = ''
def check(substr, char):
global solution
last_char = substr[-1]
substr = (substr + char) if char >= last_char else char
if len(substr) > len(solution):
solution = substr
return substr
def get_largest(s):
global solution
solution = ''
reduce(check, list(s))
return solution

scapy hexdump()

i wonder which hexdump() scapy uses, since i would like to modify it, but i simply cant find anything.
what i DO find is:
def hexdump(self, lfilter=None):
for i in range(len(self.res)):
p = self._elt2pkt(self.res[i])
if lfilter is not None and not lfilter(p):
continue
print "%s %s %s" % (conf.color_theme.id(i,"%04i"),
p.sprintf("%.time%"),
self._elt2sum(self.res[i]))
hexdump(p)
but that simply is an alternative for pkt.hexdump(), which does a pkt.summary() with a following hexdump(pkt)
could anyone tell me where to find the hexdump(pkt) sourcecode?
what i want to have is the hex'ed packet, almost like str(pkt[0]) (where i can check byte by byte via str(pkt[0])[0] ), but with nothing else than hexvalues, just like displayed in hexdump(pkt).
maybe you guys could help me out with this one :)
found it, so, to answer my own question, it is located in utils.py
def hexdump(x):
x=str(x)
l = len(x)
i = 0
while i < l:
print "%04x " % i,
for j in range(16):
if i+j < l:
print "%02X" % ord(x[i+j]),
else:
print " ",
if j%16 == 7:
print "",
print " ",
print sane_color(x[i:i+16])
i += 16

Resources