itertools.cycle(['eng', 'rus']).__next__ not works properly - python

Ayo, guys
Im started to learn python 2 days ago and started with simple Translator
My problem is:
I wanted to write "#" to the console, my values change, but I don't know how to achieve that "Toggle" effect, when when writing "#" is chekcing if language number 1 is enabled and I change it to language number 2 and vice versa, if Language number 2 is enabled then switch to Language number 1
I found a solution on the Internet by:
var = itertools.cycle(['1', '2']).__next__
However, I can't get langtoggle to give me values one by one
At the moment, I'm stuck on this moment, which gives me value number 2 and does not want to change it to value 1
Please tell me what am I doing wrong?
Thank you :)
import itertools
langtoggle = itertools.cycle(['eng', 'rus']).__next__
engstroke = 'ENGLISH > RUSSIAN'
russtroke = 'RUSSIAN > ENGLISH'
lstroke = engstroke
while True:
print (lstroke)
word = input('Введите слово: ')
if word == '#':
while True:
langtoggle()
if langtoggle() == 'eng':
lstroke = engstroke
if langtoggle() == 'rus':
lstroke = russtroke
break
to be honest, I need a solution what let me change to 1,2,3 and more values by same action so thats why I dont want to use boolean value for that problem
Also, I notice that "var()" cycling to next value even if im just checking this var in "if var() = 1"
that looks strange, but I dont understand a huge things in coding right now, so..

In your while block you're calling langtoggle() three times. Change this to be called only once.
Something like this:
import itertools
langtoggle = itertools.cycle(['eng', 'rus']).__next__
engstroke = 'ENGLISH > RUSSIAN'
russtroke = 'RUSSIAN > ENGLISH'
lstroke = eng
while True:
print (lstroke)
word = input('Введите слово: ')
if word == '#':
while True:
toggled = langtoggle()
if toggled == 'eng':
lstroke = engstroke
if toggled == 'rus':
lstroke = russtroke
break
This is your code but modified by setting toggled to the result of the first call to langtoggle(). Then the tests are looking at the value of toggled instead of separate calls they were making previously.

Related

trying to simplify some boolean statements in python

I'm "newish" to python programming. I'm trying my best to make my code look nice and function well. I'm using Pycharm as my IDE. I'm doing something for myself. I play tabletop RPG's and I'm attempting to create a character creator for a game I play. I have everything working well, but Pycharm is telling me that "Expression can be simplified" and "PEP 8: E712 comparison to True should be 'if cond is not True:' or 'if not cond:'"
Here is the code in question:
fname = False
while fname != True:
new_character.firstName = input('What would you like your first name to be?\n').capitalize()
if 1 >= len(new_character.firstName) or len(new_character.firstName) > 20:
print('Name does not meet length requirements. Please try again.')
if new_character.firstName.isalpha() != True:
print('Please do not use numbers or special characters in your name. Please try again.')
if (1 < len(new_character.firstName) < 20) and (new_character.firstName.isalpha() == True):
fname = True
Pycharm is telling me that my "while fname != True:" is the part that can be simplified as well as the "if new_character.firstName.isalpha() != True:".
I've tried googling a solution for what I'm doing, but most of them are for something kinda like what I'm asking, but never with the != True portion. I've even reached out to one of my friends that's a python programmer, but I haven't heard back yet.
Again, I want to state that as it is now, the code works correctly the way it is written, I'm just wanting to understand if there is a way to make the code look cleaner/neater or do the same function and be simplified somehow.
Any pointers on how to potentially simplify those lines of code and maintain the functionality would be greatly appreciated.
Here's one way you could rewrite this code to make it easier to read, and more efficient:
# Loop until the user provides a good input
while True:
# Set a temp variable, don't constantly reassign to the new_character.firstName attribute
name = input('What would you like your first name to be?\n').capitalize()
# If the name isn't between 2 and 20 characters, start the loop over at the beginning
if not (1 < len(name) <= 20):
print('Name does not meet length requirements. Please try again.')
continue
# If the name contains anything other than letters, start the loop over at the beginning
if not name.isalpha():
print('Please do not use numbers or special characters in your name. Please try again.')
continue
# You can only reach this break if the name "passed" the two checks above
break
# Finally, assign the character name
new_character.firstName = name
One thing you could do to simplify further is to check both conditions at the same time, and print a more helpful error message that re-states the requirements explicitly:
NAME_ERROR_MESSAGE = """
Invalid name '{name}'. Your character's name
must be between 2 and 20 characters long, and
contain only letters. Please try again.
"""
while True:
name = input('What would you like your first name to be?\n').capitalize()
if (1 < len(name) <= 20) and name.isalpha():
new_character.firstName = name
break
print(NAME_ERROR_MESSAGE.format(name=name)

Code worked in coursera sandbox editor but fails in python 3

I am super new to Python. I've been taking a Python Course on Coursera and fooling around with a little bit of code. Prior to today I was doing the class on a chromebook, and therefore using the sandbox tool provided. I've purchased an actual PC to download python since. I wrote a little code that was working just fine in the sandbox tool, but when I enter it into python it keeps booting me out. Can anyone spot anything obviously wrong with my code that I should change?
It should take an input of a date, exercise, and then keep looping through asking you about your sets and reps, saving results as tuples in a dictionary, until you enter 0, where it exits the loop, and prints the results. Stumped!
dt = input("Date:")
ex = input("Exercise:")
d = dict()
set = 0
while True:
wrk = input("Insert as Reps x Weight: ")
if wrk == "0":
break
set = set + 1
d[set] = wrk
print(dt)
print(ex)
print(d)
Indentation is really important in Python since it uses whitespace to differentiate between blocks of code.
Here,
observe the indentation of the while statement. Note that the indentation in the if block remains the same. This is because we want break to execute only if wrk is 0.
On the other hand, we keep set+1 outside because the condition did not match and we wanted our program to keep running.
python
dt = input("Date:")
ex = input("Exercise:")
d = dict()
set = 0
while True:
wrk = input("Insert as Reps x Weight: ")
if wrk == "0":
break
set = set + 1
d[set] = wrk
print(dt)
print(ex)
print(d)
This works as expected.

How would you make variables in python (you'll see)

Please Note That This Happened In 2019 So I picked up a few things from then
So please don't judge me.
So I have decided to try and make a very basic language in python.
And it is pretty basic right now but I want to improve it.
And one thing all languages need: variables
And right now I have this:
# Some other if statements up here
# neon is the name of the variable
# Something programmed real quickly to show example
elif neon[0:6] == ("addvar"):
var = neon[7:]
elif neon.startswith("add"+ var):
invar = neon.split("add"+ var , 1)[1]
elif neon.startswith("out"+ var):
print(invar)
YES it is very messy and horrid but I had to start with something and it is
very buggy. I had to start working on math so I skipped out on the variables. I tried a few tests before e. g. Appending data to a list and whatnot.
My Problem:
It only lets me have one variable
But now I wonder if there is a way that finally goes through the lexer and parser
Please tell me if there is
Use a dictionary to hold all your variables.
variables = {}
# some other code here
elif neon.startswith("addvar "): # addvar variablename
var = neon.split()[1]
variables[var] = None # create empty variable
elif neon.startswith("add "): # add variablename value
_, var, value = neon.split()
variables[var] = value
elif neon.startswith("out "): # out variablename
var = neon.split()[1]
print(variables[var])

Creating Decision Tree for Simple Game

I am currently a new student learning python. This is my first real experience doing much computer coding. For my project I must create a fill in the blank quiz with three different levels of difficulty. Once the user chooses a difficulty the game should print a different paragraph based on the difficulty. Each section of the game works fine but I am having trouble creating the "difficulty chooser." No matter the difficulty I choose, the game rolls through the easy, medium, and the hard level in order and then crashes.
Below I have included the introductory text and the difficulty chooser. I would love some help. I am sure there are really obvious things I don't see. Thank you!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
You can do with if else if you only want to print something but if you have separate code block for each level then define a function for each level and use this pattern :
You can define the function blocks and call them basis on user input something like:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
Then invocation of function block will be:
difficulty_choice[num]()
Add a conditional for the input.
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
Under each if statement put your game code.
The reason your code goes through all the difficulties is because of this line:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
When Python sees something like easy_game(), it calls the easy_game function and replaces it with the result. You don't want to call the function yet though, so you can take off the parenthesis to store just the function instead:
difficulty_choice = [easy_game, medium_game, hard_game]
This will mean you have to call the function after you take it out of the array.
As for the crash, when you use raw_input() you get a string back. That means when you type in the 1 to decide for an easy game, you get the character 1, which is represented by the number 49. That's why your code goes through everything and crashes: Your 1 is really a 49. In fact, if you type 1 < '1' into the interpreter, you'll get True back.
To fix that, you can pass the result of raw_input() to the int() function, which will parse it and give you the proper integer (or throw an exception if it can't be parsed). The last line of introduction would then look like game_chooser(int(difficulty)).
You could also skip most of the code of game_chooser by just indexing into the array (that's what they're for, after all):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()

make a global condition break

allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly.
i have seen questions regarding this particular problem on here before - but i have a separate question from them and did not want to hijack those threads. the question:
"a substring is any consecutive sequence of characters inside another string. The same substring may occur several times inside the same string: for example "assesses" has the substring "sses" 2 times, and "trans-Panamanian banana" has the substring "an" 6 times. Write a program that takes two lines of input, we call the first needle and the second haystack. Print the number of times that needle occurs as a substring of haystack."
my solution (which works) is:
first = str(input())
second = str(input())
count = 0
location = 0
while location < len(second):
if location == 0:
location = str.find(second,first,0)
if location < 0:
break
count = count + 1
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
print(count)
if you notice, i have on two separate occasions made the if statement that if location is less than 0, to break. is there some way to make this a 'global' condition so i do not have repetitive code? i imagine efficiency becomes paramount with increasing program sophistication so i am trying to develop good practice now.
how would python gurus optimize this code or am i just being too nitpicky?
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution:
first = str(input())
second = str(input())
def count_needle(first, second):
location = str.find(second,first)
if location == -1:
return 0 # none whatsoever
else:
count = 1
while location < len(second):
location = str.find(second,first,location +1)
if location < 0:
break
count = count + 1
return count
print(count_needle(first, second))
Idea:
use function to structure the code when appropriate
initialise the variable location before entering the while loop save you from checking location < 0 multiple times
Check out regular expressions, python's re module (http://docs.python.org/library/re.html). For example,
import re
first = str(input())
second = str(input())
regex = first[:-1] + '(?=' + first[-1] + ')'
print(len(re.findall(regex, second)))
As mentioned by Matthew Adams the best way to do it is using python'd re module Python re module.
For your case the solution would look something like this:
import re
def find_needle_in_heystack(needle, heystack):
return len(re.findall(needle, heystack))
Since you are learning python, best way would be to use 'DRY' [Don't Repeat Yourself] mantra. There are lots of python utilities that you can use for many similar situation.
For a quick overview of few very important python modules you can go through this class:
Google Python Class
which should only take you a day.
even your aproach could be imo simplified (which uses the fact, that find returns -1, while you aks it to search from non existent offset):
>>> x = 'xoxoxo'
>>> start = x.find('o')
>>> indexes = []
>>> while start > -1:
... indexes.append(start)
... start = x.find('o',start+1)
>>> indexes
[1, 3, 5]
needle = "ss"
haystack = "ssi lass 2 vecess estan ss."
print 'needle occurs %d times in haystack.' % haystack.count(needle)
Here you go :
first = str(input())
second = str(input())
x=len(first)
counter=0
for i in range(0,len(second)):
if first==second[i:(x+i)]:
counter=counter+1
print(counter)
Answer
needle=input()
haystack=input()
counter=0
for i in range(0,len(haystack)):
if(haystack[i:len(needle)+i]!=needle):
continue
counter=counter+1
print(counter)

Categories