Python之5个简单趣题熟悉基础语法
1 九九乘法表
print("........ Multiplication Table")
# Display the number title
print(" |", end = '')
for j in range(1, 10):
....print(" ", j, end = '')
print() # Jump to the new line
print("-----------------------------------------")
# Display table body
for i in range(1, 10):
....print(i, "|", end = '')
....for j in range(1, 10):
........# Display the product and align properly
........if i >= j:
............print(format(i * j, '4d'), end = '')
....print()# Jump to the new line
output:
Python|5个简单趣题熟悉基础语法
也可以写成:
for i in range(1, 10):
....print(' ')
....for j in range(1, i+1):
........print("%d*%d=%d" % (j, i, i*j),end="")
output:
Python|5个简单趣题熟悉基础语法
2 最大公约数
2.1 使用简单循环
# Prompt the user to enter two integers
a = eval(input("Enter first integer: "))
b = eval(input("Enter second integer: "))
gcd = 1
k = 2
while k <= a/2 and k <= b/2:
.... if a % k == 0 and b % k == 0:
........ gcd = k
.... k += 1
print("The greatest common divisor for",
.... a, "and", b, "is", gcd)
output:
Enter first integer: 125
Enter second integer: 2525
The greatest common divisor for 125 and 2525 is 25
2.2 也可以用辗转相除法:
a = eval(input("Enter first integer: "))
b = eval(input("Enter second integer: "))
def gcd(x,y):
....while(x%y != 0):
........g = x%y
........x = y
........y = g
....return g
print("The greatest common divisor for",
....a, "and", b, "is", gcd(a,b))
3 蒙特卡罗模拟求pi
假设一个矩形的面积是4,矩形内切圆的半径是1,算出圆的面积也是π。
Python|5个简单趣题熟悉基础语法
在正方形内随机产生一个点,这个点落在圆内的概率为:
圆面积/矩形面积 = π/4
import random
NUMBER_OF_TRIALS = 1000000 # Constant,要随机产生一千万个点
numberOfHits = 0
for i in range(NUMBER_OF_TRIALS):
....x = random.random() * 2 - 1
....y = random.random() * 2 - 1
....if x * x + y * y <= 1:
........numberOfHits += 1
pi = 4 * numberOfHits / NUMBER_OF_TRIALS
print("PI is", pi)
注意两个知识点:
随机函数random()的返回值:0 <= random() <1.0
圆方程:x² +y ² = 1
output1:
PI is 3.140228
try again:
PI is 3.141368
4 自然数内的前50个素数,每行显示10个
Python|5个简单趣题熟悉基础语法
output:
Python|5个简单趣题熟悉基础语法
也可以写成函数的形式:
Python|5个简单趣题熟悉基础语法
5 十进制转与16进制的相互转换
5.1 十进制转16进制
Python|5个简单趣题熟悉基础语法
output:
Enter a decimal number: 1000
The hex number for decimal 1000 is 3E8
5.2 十六进制转十进制
Python|5个简单趣题熟悉基础语法
output:
Enter a hex number: 3e8
The decimal value for hex number 3e8 is 1000
附代码1
NUMBER_OF_PRIMES = 50 # Number of primes to display
NUMBER_OF_PRIMES_PER_LINE = 10 # Display 10 per line
count = 0 # Count the number of prime numbers
number = 2 # A number to be tested for primeness
print("The first 50 prime numbers are")
while count < NUMBER_OF_PRIMES: # Repeatedly find prime numbers
....isPrime = True #Is the current number prime?
....divisor = 2
....while divisor <= number / 2:
........if number % divisor == 0:
# If true, the number is not prime
............isPrime = False # Set isPrime to false
............break # Exit the for loop
........divisor += 1
....if isPrime: # Display the prime number and increase the count
........count += 1 # Increase the count
........print(format(number, '5d'), end = '')
........if count % NUMBER_OF_PRIMES_PER_LINE == 0:
# Display the number and advance to the new line
............print() # Jump to the new line
....number += 1 # Check if the next number is prime
附代码2
def isPrime(number):................# Check whether number is prime
....divisor = 2
....while divisor <= number / 2:
........if number % divisor == 0: # If true, number is not prime............
............return False............# number is not a prime
........divisor += 1
....return True.................... # number is prime
def printPrimeNumbers(numberOfPrimes):
....NUMBER_OF_PRIMES = 50........ # Number of primes to display
....NUMBER_OF_PRIMES_PER_LINE = 10 # Display 10 per line
....count = 0.................... # Count the number of prime numbers
....number = 2.................... # A number to be tested for primeness
....
....while count < numberOfPrimes: # Repeatedly find prime numbers
....................................# Print the prime number and increase the count
........if isPrime(number):
............count += 1............ # Increase the count
............print(number, end = " ")
............if count % NUMBER_OF_PRIMES_PER_LINE == 0:
....................................# Print the number and advance to the new line
................print()
....................................# Check if the next number is prime
........number += 1
def main():
....print("The first 50 prime numbers are")
....printPrimeNumbers(50)
main()............................ # Call the main function
附代码3
....................# Convert a decimal to a hex as a string
def decimalToHex(decimalValue):
....hex = ""
....while decimalValue != 0:
........hexValue = decimalValue % 16
........hex = toHexChar(hexValue) + hex
........decimalValue = decimalValue // 16
....
....return hex
....................# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
....if 0 <= hexValue <= 9:
........return chr(hexValue + ord('0'))
....else:.................................... # 10 <= hexValue <= 15
........return chr(hexValue - 10 + ord('A'))
def main():
....................# Prompt the user to enter a decimal integer
....decimalValue = eval(input("Enter a decimal number: "))
....print("The hex number for decimal",
........decimalValue, "is", decimalToHex(decimalValue))
main()........................................ # Call the main function
附代码4:
def main():
........................# Prompt the user to enter a hex number
....hex = input("Enter a hex number: ").strip()
....decimal = hexToDecimal(hex.upper())
....if decimal == None:
........print("Incorrect hex number")
....else:
........print("The decimal value for hex number",
............hex, "is", decimal)
def hexToDecimal(hex):
....decimalValue = 0
....for i in range(len(hex)):
........ch = hex[i]
........if 'A' <= ch <= 'F' or '0' <= ch <= '9':
............decimalValue = decimalValue * 16 +
................hexCharToDecimal(ch)
........else:
............return None
....return decimalValue
def hexCharToDecimal(ch):
....if 'A' <= ch <= 'F':
........return 10 + ord(ch) - ord('A')
....else:
........return ord(ch) - ord('0')
main()................ # Call the main functio