I'm beginning in programming and using Pycharm. I adopted 79 lines as maximous line length. But now I don't know if using an extra tab to indent the next line, since the previous line is already indented under the first. This shows what I mean:
I can use this:
if len(word) % 2 == 1:
cent = len(word) // 2
if (word[cent] == 'a' or word[cent] == 'e' or word[cent] == 'i'
or word[cent] == 'o' or word[cent] == 'u'):
print('The word's center is a lowercase vowel')
Or this:
if len(word) % 2 == 1:
cent = len(word) // 2
if (word[cent] == 'a' or word[cent] == 'e' or word[cent] == 'i'
or word[cent] == 'o' or word[cent] == 'u'):
print('The word's center is a lowercase vowel')
Either ways worked.
So, is there a convention for these situation.
Thanks all in advance!
Have a great day :)
Per PEP8 https://www.python.org/dev/peps/pep-0008/#maximum-line-length:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
As for indentation on subsequent lines, More indentation included to distinguish this from the rest.:
https://www.python.org/dev/peps/pep-0008/#indentation
Code would look like this:
if len(word) % 2 == 1:
cent = len(word) // 2
if (word[cent] == 'a' or word[cent] == 'e' or word[cent] == 'i'
or word[cent] == 'o' or word[cent] == 'u'):
print("The word's center is a lowercase vowel")
You can use \ as last character in a line to signify "this line continues in the next line" - this helps where "normal" python code can not be broken (not your case).
Your example is better suited by
vowels = set("aeiou") # maybe faster then list-lookup if used several times
if word[cent] in vowels:
or by
if word[cent] in "aeiou":
or by
def isVowel(ch):
return ch in "aeiou"
if isVowel(word[cent]):
PEP-8 maximum line lenght tells about how to "format correctly".
Related
I am working on this problem: https://dmoj.ca/problem/coci18c3p1
Basically, iterate a list of capital letters and find how many times the letters 'H', 'O', 'N' and 'I',
in that exact order, there are.
Anything in between the first 'H' and the first 'O' gets ignored, even if it one of the target letters. Same for any letters in between the 'O' and the 'N'. And so on.
You just go from start to finish once. No combinations, permutations, etc.
Find the first 'H'. Then the first 'O', after the previous 'H'. Then the next 'N' after the previous 'O'.
Etc.
They run a bunch of unit tests to make sure your code passes.
They do NOT tell you or show you the unit tests. Just the results.
My code cleanly passes the first six, but fails the last five.
I'm just looking to see if anybody can find a flaw in my logic and point it out to me.
I can't make it fail.
Samples:
input: HHHHOOOONNNNIIII
output: 1
input: PROHODNIHODNIK
output: 2
input: HONIIONIHHONI
output: 2
input: HONIHONIHONI
output: 3
input: HOHONINI
output: 1
input: HIONHION
output: 1
TLE means time limit exceeded. My code is to slow?
My code:
# DMOJ problem coci18c3p1
lst = list(input().upper())
if not 1 <= len(lst) <= 100000:
print(0)
raise SystemExit
filtered = [x for x in lst if x in 'HONI']
# print(filtered)
letters = 'H', 'O', 'N', 'I'
if any(i not in filtered for i in letters):
print(0)
raise SystemExit
count = 0
while True:
if 'H' not in filtered:
break
h = filtered.index("H")
count += 1
if h != 0:
filtered = filtered[h:]
if 'O' not in filtered:
break
o = filtered.index("O")
count += 1
if o != 0:
filtered = filtered[o:]
if 'N' not in filtered:
break
n = filtered.index("N")
count += 1
if n != 0:
filtered = filtered[n:]
if 'I' not in filtered:
break
i = filtered.index("I")
count += 1
if i != 0:
filtered = filtered[i:]
print(count//4)
Yes, TLE means the tests are failing because your solution is not fast enough. Indeed, your solution makes many passes over the input. First, I'll go over the improvements you can make to your approach.
Instead of using a slice to create a new list, you can control the starting position of the search for index(). The second argument of that function is the index for the start of the search.
Instead of checking if the character is in the list, rely on catching the exception index() raises. This will avoid a redundant search (checking if the character exists requires a search).
The above may improve your time a bit, but it may not be good enough. It's actually possible to find the solution in a single pass. The basic idea is to keep track of which character you need to find next. For example, if you already found "H", then you need to look for "O". Once you have found "I", you can increment the count, and then start looking for "H" again.
# No need to convert the input into a list; a string can be indexed directly.
string = input().upper()
count = 0
targets = ["H", "O", "N", "I"]
target = 0
for i in range(len(string)):
# Check if the current character matches the target.
if string[i] == targets[target]:
# There is a match. Move to the next target.
# if the end is reached, cycle back to the first target (H).
target = (target + 1) % len(targets)
# Check if the last target has been found.
if string[i] == targets[-1]:
count += 1
print(count)
I found this question to be interesting and I would like to share this here and find reasonably good codes, specific to py :
Given a string S having characters from English alphabets ['a' - 'z'] and '.' as the special character (without quotes).
Write a program to construct the lexicographically smallest palindrome by filling each of the faded character ('.') with a lower case alphabet.
Definition:
The smallest lexicographical order is an order relation where string s is smaller than t, given the first character of s (s1 ) is smaller than the first character of t (t1 ), or in case they
are equivalent, the second character, etc.
For example : "aaabbb" is smaller than "aaac" because although the first three characters
are equal, the fourth character b is smaller than the fourth character c.
Input Format:
String S
Output Format:
Print lexicographically smallest palindrome after filling each '.' character, if it
possible to construct one. Print -1 otherwise.
Example-1
Input:
a.ba
Output:
abba
Example-2:
Input:
a.b
Output:
-1
Explanation:
In example 1, you can create a palindrome by filling the '.' character by 'b'.
In example 2, it is not possible to make the string s a palindrome.
You can't just copy paste questions from NPTEL assignments and ask them here without even trying!
Anyways,since the "code" is your only concern,try copy pasting the lines below:
word = input()
length = len(word)
def SmallestPalindrome(word, length):
i = 0
j = length - 1
word = list(word) #creating a list from the input word
while (i <= j):
if (word[i] == word[j] == '.'):
word[i] = word[j] = 'a'
elif word[i] != word[j]:
if (word[i] == '.'):
word[i] = word[j]
elif (word[j] == '.'):
word[j] = word[i]
else: # worst case situation when palindrome condition is not met
return -1
i = i + 1
j = j - 1
return "".join(word) # to turn the list back to a string
print(SmallestPalindrome(word, length)) #Print the output of your function
s=input()
s=list(s)
n=len(s)
j=n
c=0
for i in range(n):
j=j-1
if((s[i]==s[j]) and (i==j) and (s[i]=='.' and s[j]=='.')):
s[i]='a'
s[j]='a'
elif(s[i]==s[j]):
continue
elif((s[i]!=s[j]) and (i!=j) and (s[i]=='.' or s[j]=='.')):
if(s[i]!='.'):
s[j]=s[i]
else:
s[i]=s[j]
elif((i==j) and (s[i]=='.')):
s[i]=a
else:
c=c+1
break
if(c<1):
for k in s:
print(k,end="")
else:print("-1")
I am currently attempting to create a GPA calculator where the user types in his grade as a letter and it should convert into a number. However, it is not running the first if statement while running the break statement.
I have searched for answers and none have been able to fix the code. How can I alter or change the if statement so it appends to the list?
Here is the code:
yourGrade = {}
while True:
score = str(input("Enter your letter grades: "))
if score.lower() == 'A' or score.lower() == 'A+' or score.lower() == 'A-':
yourGrade.append(int(4))
print(yourGrade)
if score.lower() == 'done':
break
print(yourGrade)
You are checking if a variable in all lower-case is equal to a string literal with capitals in it.
Try this:
if score.lower() == 'a' or score.lower() == 'a+' or score.lower() == 'a-':
I'm trying to get a function to put correct guesses in their blanks in a hangman program, but all it does is, whatever the guess and no matter whether it's right or wrong, it just gradually reveals the word. Where am I going wrong?
code:
while lettersrevealed!=word:
guess=getGuess(lettersrevealed)
for i in range(len(word)):
if guess in word:
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
ex:
(secret word is badger)
Guess a letter:
a
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
OR:
Guess a letter:
h
b*****
ba****
bad***
badg**
badge*
badger
Guess a letter:
The issue is with the for loop
for i in range(len(word)): # This will run 6 times for "badger" | 0, 1, .., 5
if guess in word:
# blanks == ****** then gradually gets the next letter added replacing a *
blanks = blanks[:i] + word[i] + blanks[i+1:]
print(blanks)
You probably want something like this.
def convert_to_blanks(word, letters):
return ''.join(c if c in letters else '*' for c in word)
>>> word = 'badger'
>>> letters = set()
>>> convert_to_blanks(word, letters)
'******'
>>> letters.add('g')
>>> letters
{'g'}
>>> convert_to_blanks(word, letters)
'***g**'
And so you have a while loop prompting for letter something like this.
guessed = set()
word = 'badger'
while True:
guess = input("Guess a letter")
guessed.add(guess)
blanks = convert_to_blanks(word, guessed)
print(blanks)
if blanks == word:
break
the second "else" statement gives a syntax error. I don't understand why. what is wrong with the code?
Pardon me, still a beginner
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break
You can see in the Python 3 flow control documentation an example of an if statement. It can only have one else statement because that is what is run when all other cases (if and elif) didn't match. When are you expecting the second else to run?
As was pointed out in another answer, indentation in python matters.
Is this perhaps the indentation you are looking for?
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break