Getting started with programming in Python Continued from Last time
It seems that most of the parts I did last time will be diverted, Speaking of what was solved last time
・ Obtain 6-digit identification number from standard input ・ Add the acquired 6-digit identification numbers (hereinafter referred to as special matters) (Of the 6 digits, the odd digits are multiplied by 2, and if the calculation result of the multiplication is 2 digits, each digit is divided individually. Add up)
Here is the next problem, but in the problem from the beginning it is "arbitrary number of digits" It's not always a 6-digit number.
Book answer
char digit;
int checksum = 0;
int position = 1;
cout << "Enter a number with an even number of digits: ";
digit = cin.get();
while(digit != 10) {
if (position % 2 == 1) checksum += digit - '0';###The odd numbers remain the same
else checksum += doubleDigitValue(digit - '0');###Double the even number
digit = cin.get();
position++;
}
cout << "Checksum is " << checksum << ". \n";
if (checksum % 10 == 0){
cout << "Checksum is divisible by 10. Valid. \n";
}else{
cout << "Checksum is not divisible by 10. Invalid. \n";
}
・ ・ ・
test02.py
#!/usr/bin/env python
#coding:utf-8
import sys
from ConsoleOut import cout
from test import doubleDigitValue
def number():
checksum = 0
position = 0
cout << "Enter a number with an even number of digits:"
digits = input()
while position < len(digits):
digits = digits[position]
if position % 2 == 1:
checksum += int(digit)
else:
checksum += doubleDigitValue(int(digit))
position += 1
cout << "Checksum is " + str(checksum) + ". \n";
if checksum % 10 == 0:
cout << "Checksum is divisible by 10. Valid .\n"
else:
cout << "Checksum is not divisible by 10. Invalud. \n"
・ ・ ・(Terminal output result)
>>> from test02 import number
>>> number()
Enter a number with an even number of digits:49927398716
Checksum is 70.
Checksum is divisible by 10. Valid .
I was thinking about how to find the odd number by summing up the number of characters entered. A very simple and easy-to-understand method of only even numbers and only odd numbers that you commented on last time I used it because I was taught.
Also, try using raw_input () that you taught me in standard input. I tried, but because I was using Python3.5, I got a NameError and got a NameError. Since it was on the reference site that sys.stdin.readline () can be used in Python3 I tried it, but it didn't work and the code is the same as last time.
In this article "Python Tips: I want to get a string from standard input" sys.stdin. There was a way to use readline ().
Recommended Posts