Three consecutive characters that are also alphabetical - python-3.x

Write a program that accepts a word as input and determines whether or not it has three consecutive letters that are also consecutive letters in the alphabet.
This one has been hard for me. My though process was to use ord() and get a mean, and if the mean = the 2nd character it was right.
word = input("Please enter a word:")
n = len(word)
for i in range(n-2):
i = 0
if ord (word [i+1]) - ord (word [i]) == 1:
print("This works!")
elif ord (word [i+2] - ord (word [i+1] - ord (word [i]) == 1:
print ("This also works.
else:
print("This doesn't work.")

Using the mean is not a good idea. The mean of 8,9,10 is 9, but so is the mean of 5,9,13.
How about doing what the question states:
def consec(s, n=3):
l = len(s)
if l < n:
raise ValueError("String too short to contain repetition of length {}".format(n))
for i in range(l-2):
# Check if you get the same letter by adding 1 or 2 to the next ones
# or by substracting 1 or 2...
if ord(s[i]) == ord(s[i+1])+1 == ord(s[i+2])+2 or \
ord(s[i]) == ord(s[i+1])-1 == ord(s[i+2])-2:
return s[i:i+3]
return ""
This is case-sensitive, by the way:
In [11]: consec("cba")
Out[11]: 'cba'
In [12]: consec("Abc")
Out[12]: ''
In [13]: consec("cdskj sdoifsdjflkduf sdfjstudfu0gnfgsba")
Out[13]: 'stu'

Related

Having an issue relating to finding an Armstrong number from a list in Python [duplicate]

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

Python 3 for beginners Control Flow, While Loops and Break Statements

I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.

Simple Python program to convert roman numerals to the international system

I've tried to put together a basic program to convert roman numbers to conventional numbers and I seem to have made some mistake and right now it's a hit or miss.Do take a look at the code.I've described it better in the code as comments.Thanks!
def roman(roman_num):
inter_dic = {
"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000
}
output = 0
num = roman_num.upper()
#this is to ensure that the number appears as uppercase alphabets
for numeral in num:
numeral_index = num.index(numeral)
#I've squeezed an exception here to handle the last digit in the number
try:
#for the additive part
if inter_dic[numeral] > inter_dic[num[numeral_index + 1]]:
output += inter_dic[numeral]
#for the subtraction part
elif inter_dic[numeral] < inter_dic[num[numeral_index + 1]]:
output -= inter_dic[numeral]
elif inter_dic[numeral] == inter_dic[num[numeral_index + 1]]:
output += inter_dic[numeral]
#the following line is actually dead code,but I've added it just in case.
else:
print("There was an error.")
#the IndexError will be called when the last digit is reached and so the last digit
#will be added
except IndexError:
output += inter_dic[numeral]
return output
assert roman("cxcix") == 199
#this returns an assertion error
#when the function is called,the output is 179
This should do what you want:
def roman(roman_num):
inter_dic = {
"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000
}
x = list(map(lambda x: inter_dic[x], roman_num.upper()))
for idx in range(len(x)-1):
if x[idx+1] > x[idx]:
x[idx] *= -1
return x
decimal = roman("cxcix")
print(decimal) # Output: [100, -10, 100, -1, 10]
print(sum(decimal)) # Output: 199
This works on the assumption that the numbers are properly structured. As in, the numbers represented should be in order of the biggest to the smallest.
The above code will work even if you just give it one character, because the loop is based on the range(len() - 1) of the given list that is created when we translate the letters into their integers.
If x == [100] then len(x)-1 == 0 which will just terminate the for-loop immediately, so we will not encounter any IndexError inside of the loop.
To explain what is happening in your code that differs from my version we can create a simple example here:
lst = list("abcabc")
for idx, letter in enumerate(lst):
print(f"Letter: {letter}, list.index: {lst.index(letter)}, Actual index: {idx}")
Output:
Letter: a, list.index: 0, Actual index: 0
Letter: b, list.index: 1, Actual index: 1
Letter: c, list.index: 2, Actual index: 2
Letter: a, list.index: 0, Actual index: 3
Letter: b, list.index: 1, Actual index: 4
Letter: c, list.index: 2, Actual index: 5
If we look at the documentation for list.index, we can see this description:
index(self, value, start=0, stop=2147483647, /)
Return first index of value.
Raises ValueError if the value is not present.
So because there are repeated values inside of lst when we call to check for it's index, it just returns the first value that matches the variable we give it.

How do I compare two lists and return a list with elements that share the same index?

I need to take a user input of 4 digits, compare it to a randomly generated 4 digit number, and then return the values they have in common in the same indices.
So for example:
Secret number: 4667
User input: 3608
Output: _ 6 _ _
Unfortunately, when I run what I've written already, it prints the digits in whatever position they're in on the secret number regardless of their position in the user input, and then it also returns a number of "_" for each iteration in the for loop.
Here's what I have so far:
from random import randint
def randomNumber():
numberList = []
digits = 0
while digits != 4:
numberList += [randint(0,9)]
digits += 1
return numberList
secretNumber = randomNumber()
guessNumber = list(input("Enter a four digit number: "))
guessNumber = list(map(int, guessNumber))
guessList = guessNumber.copy()
correctNumbers = []
numberPosition = []
numberPosition.clear()
for number in guessNumber:
if number in secretNumber:
correctNumbers.append(number)
for n in secretNumber:
if n == number:
numberPosition.append(n)
else:
numberPosition.append("_")
I apologize if there's any spacing/tabbing issues with this code block, I copied it over from a Jupyter notebook.
Thanks!
I think the iteration logic is somewhat incorrect. Considering the example -
In [10]: secretNumber = [4,6,6,7]
In [11]: guessNumber = [3,6,0,8]
In [12]: for i in range(len(secretNumber)):
...: if secretNumber[i] == guessNumber[i]:
...: numberPositions.append(secretNumber[i])
...: else:
...: numberPositions.append("_")
...:
In [13]: numberPositions
Out[13]: ['_', 6, '_', '_']
You basically need to iterate only once for the length of either lists (4 in this case) and update the numberPositions variable.
Here's a oneliner of the above code if you are interested -
In [12]: "".join([str(secretNumber[i]) if secretNumber[i] == guessNumber[i] else "_" for i in range(len(secretNumber))])
Out[12]: '_6__'
try this:
def f(a, b):
for i in range(min(len(a), len(b))):
if a[i] == b[i]:
yield i, a[i]
else:
yield i, None
a, b = '123456', '2335678'
print(''.join(['_' if c is None else c for _, c in f(a, b)]))
This one-line code will do it:
In [1]: ''.join(a if a==b else '_' for a, b in zip(secretNumber,guessNumber))
Out[1]: '_6__'

Building a recursive function in Python 3

For an intro comp sci lab I'm trying to build a recursive function that counts the number of occurrences of a given letter in a string without using built in methods or loops. I'm pretty stumped without the use of myStr.count. Can anyone offer a tip? should I try something that checks the identity of myStr[0] and returns 0 if letter != myStr[0]?
def count(letter, myStr, theLen):
#Code for def count
def main():
print ("The count of letter a is: ", count("a", "abacdadaad", 10))
print ("The count of letter b is: ", count("b", "abacdadaad", 10))
print ("The count of letter c is: ", count("c", "abacdadaad", 10))
print ("The count of letter d is: ", count("d", "abacdadaad", 10))
main()
Usually, when writing something recursively, the main problem is to determine what is the condition for return. Obviously, when counting letters in a string, it is the moment when you are testing the last character of the string.
You could try:
def recursive(string, letter):
if len(string) == 1 and string == letter:
return 1;
elif len(string) == 1:
return 0;
if string[0] == letter:
count = 1 + recursive(string[1:], letter)
else:
count = recursive(string[1:], letter)
return count

Resources