m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
def main():
if '01' in m:
n = m.replace('01','Janauary')
print n
elif '02' in m:
n = m.replace('02','February')
print n
elif '03' in m:
n = m.replace('03','March')
print n
elif '04' in m:
n = m.replace('04','April')
print n
elif '05' in m:
n = m.replace('05','May')
print n
elif '06' in m:
n = m.replace('06','June')
print n
elif '07' in m:
n = m.replace('07','July')
print n
elif '08' in m:
n = m.replace('08','August')
print n
elif '09' in m:
n = m.replace('09','September')
print n
elif '10' in m:
n = m.replace('10','October')
print n
elif '11' in m:
n = m.replace('11','November')
print n
elif '12' in m:
n = m.replace('12','December')
print n
main()
for example, this scrpt can output 01/29/1991 to January/29/1991, but I want it output to January,29,1991 How to do it? how to replace the " / " to " , "?
Please don't do it this way; it's already wrong, and can't be fixed without a lot of work. Use datetime.strptime() to turn it into a datetime, and then datetime.strftime() to output it in the correct format.
Take advantage of the datetime module:
m = raw_input('Please enter a date(format:mm/dd/yyyy)')
# First convert to a datetime object
dt = datetime.strptime(m, '%m/%d/%Y')
# Then print it out how you want it
print dt.strftime('%B,%d,%Y')
Just like you replace all of the other strings - replace('/',',').
You might find a dictionary to be helpful here. It would be "simpler." You could try something as follows.
m = raw_input("Please enter a date(format:mm/dd/yyyy): ")
month_dict = {"01" : "January", "02" : "February", "03" : "March", ...}
# then when printing you could do the following
date_list = m.split("/") # This gives you a list like ["01", "21", "2010"]
print(month_dict[date_list[0]] + "," + date_list[1] + "," + date_list[2]
That will basically get you the same thing in 4 lines of code.
I have just rewrite your code more compact:
m = '01/15/2001'
d = {'01' : 'Jan', '02' : 'Feb'}
for key, value in d.items():
if key in m:
m = m.replace(key, value)
Related
I'm doing a coding challenge and every time I submit I get a the wrong answer with a "No response on stdout" Do you know what I can do? Here is the link to the problem: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
def countingValleys(n, s):
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
s = input()
result = countingValleys(n, s)
fptr.write(str(result) + '\n')
fptr.close()
N=int(input())
S = input()
L = 0
V = 0
for el in S:
if s == 'U':
L+= 1
if L == 0:
V += 1
else:
L -= 1
print(V)
You are probably returning the value instead of using the print() function. The problem specification says that you have to print it.
As a Beginner, I was trying to make 1-line Calculator using Python... And I come to this.
I converted the user input into list and then used the list elements to get the result.
For example in case if multiplication I took the elements before the sign, combined them and then the elements after the sign and combined them.Then Multiply the together.
question = list(input("Enter Your Question: "))
def convert(list):
s = [str(i) for i in list]
combined = int("".join(s))
list = combined
return(combined)
multiply = "*"
add = "+"
substract = "-"
divide = "/"
if multiply in question:
for multiply in question:
position1 = question.index("*")
before_num = question[0: int(position1)]
aft = len(question)
after_num = question[int(position1) + 1: int(aft)]
num_before = convert(before_num)
num_after = convert(after_num)
print(int(num_before) * int(num_after))
break
elif add in question:
for add in question:
position1 = question.index("+")
before_num = question[0: int(position1)]
aft = len(question)
after_num = question[int(position1) + 1: int(aft)]
num_before = convert(before_num)
num_after = convert(after_num)
print(int(num_before) + int(num_after))
break
elif substract in question:
for substract in question:
position1 = question.index("-")
before_num = question[0: int(position1)]
aft = len(question)
after_num = question[int(position1) + 1: int(aft)]
num_before = convert(before_num)
num_after = convert(after_num)
print(int(num_before) - int(num_after))
break
elif divide in question:
for divide in question:
position1 = question.index("/")
before_num = question[0: int(position1)]
aft = len(question)
after_num = question[int(position1) + 1: int(aft)]
num_before = convert(before_num)
num_after = convert(after_num)
print(int(num_before) / int(num_after))
break
else:
print("Check Your Question Again")
end_program_ans = input("Press Enter to continue")
This Works Perfect but is there a simpler way.
read_data = input("Enter Your Question: ")
if "*" in read_data:
data1,data2 = read_data.split("*")
print(float(data1)*float(data2))
elif "+" in read_data:
data1,data2 = read_data.split("+")
print(float(data1)+float(data2))
elif "-" in read_data:
data1,data2 = read_data.split("-")
print(float(data1)-float(data2))
elif "/" in read_data:
data1,data2 = read_data.split("/")
print(float(data1)/float(data2))
else:
print("Please Enter Proper data")
I want a program so I can enter a big integer and it will do a calculation like this:
62439 = (6 - 2 + 4 - 3 + 9)
Basically it splits them up and the first and third should be added and the second and the fourth should be subtracted. Please follow the loop sort of method. I can't have the elif and if working in the same run of the loop.
num = input("Input any number: ")
total = 0
p = 0
x= 0
q = 0
number = len(num)
if len(num) ==5 :
total = 0
for i in range(0,(number)):
p = p+2
q = q +1
if x == 2 and q == p:
total = total+(int(num[q]))
x=1
p=p-1
elif x == 1 and q == p :
total = total-(int(num[q]))
x=2
p=p-1
print("your number is: ",total)
I expect it to repeat the loop as many times as there are numbers in the integer that is entered e.g (333) executes 3 times
num = input("Enter a number: ")
sum = 0
do_add = True
try:
for digit in num:
if do_add:
sum += int(digit)
else:
sum -= int(digit)
do_add = not do_add
except Exception:
print("Invalid input")
else:
print("The result is", sum)
Why not just perform the calculation:
num = input("Input any number: ")
if len(num) == 5:
total = int(num[0])-int(num[1])+int(num[2])-int(num[3])+int(num[4])
print("your number is: ",total)
Maybe like this:
def main():
digits = input("Enter a number: ")
assert digits.isdigit()
result = sum(int(digit) * [1, -1][index%2] for index, digit in enumerate(digits))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Or like this if you wanna be more deliberate - also easier to extend:
def main():
from operator import add, sub
digits = input("Enter a number: ")
assert digits.isdigit()
operations = [add, sub]
result = 0
for index, digit in enumerate(digits):
result = operations[index%len(operations)](result, int(digit))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Or just go overkill (also known as "taking advantage of the standard library"):
def main():
from itertools import cycle
from operator import add, sub
from functools import reduce
while True:
digits = input("Enter a number: ")
if digits.isdigit():
break
operation_iter = cycle([sub, add])
def operation(a, b):
return next(operation_iter)(a, b)
result = reduce(operation, map(int, digits))
print(f"Result: {result}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Doesn't let me to input values to x.
It runs and it says that is completed with exit code 0. Why?
def donuts():
x = int(input("How many donutes?"))
if x < 10:
print("Numbers of donuts: "+ x)
else:
print("Number of donute: many")
def litere():
x = input("Type a word! : ")
if len(x) <= 2:
print("NULL")
else:
k = len(x) -1
print(x[0:3] + x[k-2])
if ' name ' == ' main ':
donuts()
__name__ is a variable. It should have quotes around it. When you surround it with quotes python treats it like a regular string. Replace the bottom with
if __name__ == "__main__":
donuts()
Remove quotes around '__name__' so it becomes __name__:
def donuts():
x = int(input("How many donutes?"))
if x < 10:
print("Numbers of donuts: "+ x)
else:
print("Number of donute: many")
def litere():
x = input("Type a word! : ")
if len(x) <= 2:
print("NULL")
else:
k = len(x) -1
print(x[0:3] + x[k-2])
if __name__ == "__main__":
donuts()
Here is the change I made to your code:
if __name__ == "__main__":
donuts()
I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.