Python error while finding greatest number - python

I am trying techgig problem of finding greatest of 3 numbers. problem as follows
You just need to take three number as input from stdin and you need to
find greatest of them.
Input Format
You will be taking three numbers as an input from stdin one on each line respectively.
Constraints
-100000 <= N <= 100000
Output Format
You need to print the greatest of the three numbers to the stdout.
Sample TestCase 1
Input
902
100
666
I done this
''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
import sys
def main():
s=sys.stdin.read()
s=s.split("\n")
a=int(s[0])
b=int(s[1])
c=int(s[2])
temp=0
e=[a,b,c]
for i in e:
if i > temp:
temp=i
print(temp)
'''if (a>b) and (a>c):
temp = a
elif (b>a) and (b>c):
temp = b
else:
temp = c
print(temp)'''
main()
It has predefined input 902, 100, 666. My code shows 902 output and expected also shows 902, but its showing failed, Why? In above code commented or non commented thing both showing failed.

I might be wrong but the output says to print using the stdout: You need to print the greatest of the three numbers to the stdout. The print in python is the same as sys.stdout.write(str(99) + '\n'). Try using stdout to print the result.
sys.stdout.write(str(temp))

temp is being initialized as 0, but the input allows for negative numbers. 0 will considered larger than any negative input though. This means your algorithm will fail for test cases that have negative input.
Initialize temp to a value smaller than the minimum allowed input:
temp = -100001 # One less than the minimum

Actually they are looking for the output as mentioned and though the logic of your code is right but the output will give a new line which will be considered wrong. To fix this we use within print statement (end = "")
so the right code becomes
Hope it helps, keep coding.

Related

How to do this recursion method to print out every 3 letters from a string on a separate line?

I'm making a method that takes a string, and it outputs parts of the strings on separate line according to a window.
For example:
I want to output every 3 letters of my string on separate line.
Input : "Advantage"
Output:
Adv
ant
age
Input2: "23141515"
Output:
231
141
515
My code:
def print_method(input):
mywindow = 3
start_index = input[0]
if(start_index == input[len(input)-1]):
exit()
print(input[1:mywindow])
printmethod(input[mywindow:])
However I get a runtime error.... Can someone help?
I think this is what you're trying to get. Here's what I changed:
Renamed input to input_str. input is a keyword in Python, so it's not good to use for a variable name.
Added the missing _ in the recursive call to print_method
Print from 0:mywindow instead of 1:mywindow (which would skip the first character). When you start at 0, you can also just say :mywindow to get the same result.
Change the exit statement (was that sys.exit?) to be a return instead (probably what is wanted) and change the if condition to be to return once an empty string is given as the input. The last string printed might not be of length 3; if you want this, you could use instead if len(input_str) < 3: return
def print_method(input_str):
mywindow = 3
if not input_str: # or you could do if len(input_str) == 0
return
print(input_str[:mywindow])
print_method(input_str[mywindow:])
edit sry missed the title: if that is not a learning example for recursion you shouldn't use recursion cause it is less efficient and slices the list more often.
def chunked_print (string,window=3):
for i in range(0,len(string) // window + 1): print(string[i*window:(i+1)*window])
This will work if the window size doesn't divide the string length, but print an empty line if it does. You can modify that according to your needs

Error "invalid syntax" appears when trying to redirect using input/output in Python shell

I tried to practice input/output redirection in the Python shell. I have a file named SentinelValue.py which is where I have this code to add up the numbers in another file:
data = eval(input("Enter an integer (the input ends " + "if it is 0): "))
sum = 0
while data != 0:
sum += data
data = eval(input("Enter an integer (the input ends " + "if it is 0): "))
print("The sum is", sum)
The other file "Numbers.txt" contains numbers:
1
2
3
4
5
6
7
8
9
0
and my output.txt file is where I want the sum to show.
I tried using:
python SentinelValue.py < Numbers.txt > output.txt
but on shell, it highlights "SentinelValue" & says "invalid syntax".
I don't know why it's not working.
There are several things wrong with your code:
As already suggested in the comments, do not use eval() for a direct user input (or pretty much any time, in 99% cases when you think you need it - you don't!). A simple int() conversion should be more than enough without all the dangers of eval().
Connected with the previous, eval() evaluates the input. Further more, on Python 2.x input() itself does the evaluation (it's an equivalent of eval(raw_input())) so whenever it encounters an invalid input it will pop a SyntaxError.
Even if it doesn't pop a SyntaxError, it will most certainly pop a TypeError as eval() expects a string and it will receive an integer from the inner input().
You're printing the "Enter an integer..." prompt to STDOUT which will result it ending up in your output.txt (where you redirect the STDOUT).
You're shadowing the built-in sum() by using it as one of your variables. That's a bad practice that can lead to many problems and unexpected results down the line.
So, with all that in mind, here's how to rewrite it to address these issues:
# Let's first make sure it works on Python 2.x and 3.x by shadowing the input
try:
input = raw_input # on Python 2.x use raw_input instead of input
except NameError:
pass
result = 0 # tip: use a name that's not already built-in, like result
while True: # loop 'forever'...
data = input() # don't print anything when asking for input
try:
data = int(data) # don't print anything to STDOUT
if not data: # only if the integer is 0
break
result += data # add to the final result
except ValueError: # risen if the input is not an integer...
pass # so just ignore it
print("The sum is: " + str(result)) # finally, print the result

Python - Zip code to Barcode

The code is supposed to take a 5 digit zip code input and convert it to bar codes as the output. The bar code for each digit is:
{1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
For example, the zip code 95014 is supposed to produce:
!!.!.. .!.!. !!... ...!! .!..! ...!!!
There is an extra ! at the start and end, that is used to determine where the bar code starts and stops. Notice that at the end of the bar code is an extra ...!! which is an 1. This is the check digit and you get the check digit by:
Adding up all the digits in the zipcode to make the sum Z
Choosing the check digit C so that Z + C is a multiple of 10
For example, the zipcode 95014 has a sum of Z = 9 + 5 + 0 + 1 + 4 = 19, so the check digit C is 1 to make the total sum Z + C equal to 20, which is a multiple of 10.
def printDigit(digit):
digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
return digit_dict[digit]
def printBarCode(zip_code):
sum_digits=0
num=zip_code
while num!=0:
sum_digits+=(num%10)
num/=10
rem = 20-(sum_digits%20)
answer=[]
for i in str(zip_code):
answer.append(printDigit(int(i)))
final='!'+' '.join(answer)+'!'
return final
print printBarCode(95014)
The code I currently have produces an output of
!!.!.. .!.!. !!... ...!! .!..!!
for the zip code 95014 which is missing the check digit. Is there something missing in my code that is causing the code not to output the check digit? Also, what to include in my code to have it ask the user for the zip code input?
Your code computes rem based on the sum of the digits, but you never use it to add the check-digit bars to the output (answer and final). You need to add code to do that in order to get the right answer. I suspect you're also not computing rem correctly, since you're using %20 rather than %10.
I'd replace the last few lines of your function with:
rem = (10 - sum_digits) % 10 # correct computation for the check digit
answer=[]
for i in str(zip_code):
answer.append(printDigit(int(i)))
answer.append(printDigit(rem)) # add the check digit to the answer!
final='!'+' '.join(answer)+'!'
return final
Interesting problem. I noticed that you solved the problem as a C-style programmer. I'm guessing your background is in C/C++. I's like to offer a more Pythonic way:
def printBarCode(zip_code):
digit_dict = {1:'...!!',2:'..!.!',3:'..!!.',4:'.!..!',5:'.!.!.',
6:'.!!..',7:'!...!',8:'!..!.',9:'!.!..',0:'!!...'}
zip_code_list = [int(num) for num in str(zip_code)]
bar_code = ' '.join([digit_dict[num] for num in zip_code_list])
check_code = digit_dict[10 - sum(zip_code_list) % 10]
return '!{} {}!'.format(bar_code, check_code)
print printBarCode(95014)
I used list comprehension to work with each digit rather than to iterate. I could have used the map() function to make it more readable, but list comprehension is more Pythonic. Also, I used the Python 3.x format for string formatting. Here is the output:
!!.!.. .!.!. !!... ...!! .!..! ...!!!
>>>

I'm having trouble with input and output from files

I'm having some trouble with my code in python. I just started learning input and output in class, and how to have python read in data from text files(barely. I'm still a huge beginner). Anyways, my assignment is that I have to have my program read in data from a file and run it through my program. Problem is, I don't have a good idea on how to do that and was wondering if you guys could help me out. The text file just contains a huge life of numbers for python to use in my program. My program finds the mean, median, and standard deviation of a list of numbers that are given to it. Now, instead of user input data, my professor wants python to use data from a file that was already pre-written.
My code:
import math
def mean(values):
average = sum(values)*1.0/len(values)
return average
def deviation(values):
length = len(values)
m = mean(values)
total_sum = 0
for i in range(length):
total_sum += (values[i]-m)**2
root = total_sum*1.0/length
return math.sqrt(root)
def median(values):
if len(values)%2 != 0:
return sorted(values)[len(values)//2]
else:
midavg = (sorted(values)[len(values)//2] + sorted(values)[len(values)//2-1])//2.0
return midavg
def main():
x = [15, 17, 40, 16, 9]
print (mean(x))
print (deviation(x))
print (median(x))
main()
Now, I have to edit my code so it opens the file, takes the data, and reads the data through my equations. Only problem is, I don't have a good idea on how to do that. Could anyone please help?
I've tried basic input and output myself, but it's done no justice in helping me with the bigger picture.
def main():
total=0
input = open('Stats.txt')
for nextline in input:
mylist = nextline.split()
for n in mylist:
total+=int(n)
print(total)
You have to fill your list from the file.
Open the file and iterate over the lines. Convert the content of the line to an integer and append it to your list. If you don't cxonvert the data you'll get strings and those won't work with mathematical operations. Close your file.
Now work with your list.
filename = 'newfile.txt'
data = []
source = open(filename)
for line in source:
data.append(int(line))
source.close()
print(mean(data))
print(deviation(data))
# more stuff with data
There is a way to let Python close the file for you so you won't have to remember it.
with open(filename) as source:
for line in source:
data.append(int(line))
According to your edit this might not be what you want. If the numbers are in one line, rather than one number per line, you'll have to take a different approach (split).

Python Min-Max Function - List as argument to return min and max element

Question: write a program which first defines functions minFromList(list) and maxFromList(list). Program should initialize an empty list and then prompt user for an integer and keep prompting for integers, adding each integer to the list, until the user enters a single period character. Program should than call minFromList and maxFromList with the list of integers as an argument and print the results returned by the function calls.
I can't figure out how to get the min and max returned from each function separately. And now I've added extra code so I'm totally lost. Anything helps! Thanks!
What I have so far:
def minFromList(list)
texts = []
while (text != -1):
texts.append(text)
high = max(texts)
return texts
def maxFromList(list)
texts []
while (text != -1):
texts.append(text)
low = min(texts)
return texts
text = raw_input("Enter an integer (period to end): ")
list = []
while text != '.':
textInt = int(text)
list.append(textInt)
text = raw_input("Enter an integer (period to end): ")
print "The lowest number entered was: " , minFromList(list)
print "The highest number entered was: " , maxFromList(list)
I think the part of the assignment that might have confused you was about initializing an empty list and where to do it. Your main body that collects data is good and does what it should. But you ended up doing too much with your max and min functions. Again a misleading part was that assignment is that it suggested you write a custom routine for these functions even though max() and min() exist in python and return exactly what you need.
Its another story if you are required to write your own max and min, and are not permitted to use the built in functions. At that point you would need to loop over each value in the list and track the biggest or smallest. Then return the final value.
Without directly giving you too much of the specific answer, here are some individual examples of the parts you may need...
# looping over the items in a list
value = 1
for item in aList:
if item == value:
print "value is 1!"
# basic function with arguments and a return value
def aFunc(start):
end = start + 1
return end
print aFunc(1)
# result: 2
# some useful comparison operators
print 1 > 2 # False
print 2 > 1 # True
That should hopefully be enough general information for you to piece together your custom min and max functions. While there are some more advanced and efficient ways to do min and max, I think to start out, a simple for loop over the list would be easiest.

Categories

Resources