text
stringlengths 37
1.41M
|
---|
"""
This is a demo task.
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].
"""
def solution(A):
A = set(A)
B = {x for x in range(1, max(A) + 1)}
# only positive numbers check
if all(i < 0 for i in A):
return 1
# check if list are equal, return len + 1
elif A == B:
return len(A) + 1
else:
return min(list(B - A)) if list(B - A) else 1
print(solution([0]))
print(solution([1, 3, 6, 8, 4, 1, 2]))
#
# print(solution([1, 2, 3]))
#
# print(solution([-1, -2, -3]))
|
import turtle
import random
turtle.screensize(canvwidth=500, canvheight=500)
def main():
value = 0
turtle.setpos(0, 0)
iteration = 1
while True:
targetX = random.randint(-400, 400)
targetY = random.randint(-400, 400)
value += find(targetX, targetY)
print("Current Average: " + str(value / iteration) + " Iteration: " + str(iteration))
iteration += 1
turtle.reset()
print("Average: " + str(value/100))
def find(targetX, targetY):
turtle.speed("fastest")
turtle.hideturtle()
turtle.pensize(5)
prevX = 0
prevY = 0
turtle.penup()
turtle.color("red")
turtle.setpos(int(targetX), int(targetY))
turtle.dot()
turtle.color("blue")
turtle.setpos(0,0)
turtle.dot()
turtle.color("black")
moves = 0
while (abs(turtle.xcor() - int(targetX)) > 25 or abs(turtle.ycor() - int(targetY)) > 25):
moves += 1
turtle.pendown()
angle = random.randint(0,361)
distance = random.randint(0,100)
prevX = turtle.xcor()
prevY = turtle.ycor()
turtle.setheading(angle)
turtle.forward(distance)
if(turtle.xcor() < -400 or turtle.xcor() > 400 or turtle.ycor() < -400 or turtle.ycor() > 400):
turtle.color("white")
turtle.setpos(prevX, prevY)
turtle.color("black")
return moves
main()
turtle.done()
|
# Problem Set 2019 - Problem 8
# Peter McGowan
# Started 2019-03-10
# Write a program that outputs today’s date and time in the format ”Monday, January 10th 2019 at 1:15pm”.
from datetime import datetime as dt # import datetime module
i = dt.now() # current datetime is set as value of i
def suffix(d): # if statement to set correct suffix for the date
if d in (1, 21, 31):
return "st"
elif d in (2, 22):
return "nd"
elif d in (3, 23):
return "rd"
else:
return "th"
currentDate = i.strftime("%d") # extract current date from current datetime, to allow for removal of any leading zero
currentHour = i.strftime("%I") # extract current hour from current datetime, to allow for removal of any leading zero
print(f'{i.strftime("%A, %B ")}{int(currentDate)}{suffix(i.day)} {i.year} at {int(currentHour)}{i.strftime(":%M%p")}')
# f-string consisting of (full name of day), (full name of month) (date) (date suffix) (year) at (hour in 12hr clock):(minutes)(AM/PM)
# both the current date and current hour are explicitly declared as integers in order to remove any leading zero they may have
|
from bitarray import bitarray
"""
This class performs the PCY algorithm
"""
class PCY:
#Constructor that takes in the threshold percentage and the name of the file
def __init__(self, thresholdPercentage, fileName):
self.thresholdPercentage = thresholdPercentage
self.file = open(fileName, "r")
#The hash function that will be used to create the buckets
def hashFunction(self, i, j):
code = (i+j) % 100000
return code
#Function that actually runs the algorithm
def runAlg(self, chunk):
self.file.seek(0)
self.dataChunk = (int)(88162 * (chunk / 100))
self.threshold = (int)(self.dataChunk * (self.thresholdPercentage / 100))
bitVector, freqNums = self.passOne()
self.file.seek(0)
freqPairs = self.passTwo(freqNums, bitVector)
return freqPairs
#This function performs the first pass of the PCY algorithm
def passOne(self):
"""
For this pass, there are four main variables used. The first one, allNums, is a dictionary that stores each
singleton as the key and its frequency as the value. The second variable, freqNums, is a simple list that
stores all the frequent singletons. The third variable, buckets, is an array that represents the buckets that
the pairs are hashed to. Each index in the list represents that specific bucket, ex. index 0 consists of the count
of all the pairs that hashed to bucket 0. The fourth variable, bitVector, is the bit vector which will store
0 or 1 at each index based on if that specific bucket is frequent or not
:return:
"""
allNums = {}
freqNums = []
buckets = [0] * 100000
bitVector = bitarray(len(buckets))
bitVector.setall(0)
"""
Following the PCY algorithm, along with adding 1 to the frequency of each item in a basket, I also create all the
possible pairs from the items in that basket and hash them to the buckets
"""
for i in range(self.dataChunk):
line = self.file.readline()
nums = list(map(int, line.split()))
for i in range(len(nums)):
num1 = nums[i]
if num1 in allNums:
allNums[num1] = allNums.get(num1) + 1
if allNums.get(num1) == self.threshold:
freqNums.append(num1)
else:
allNums[num1] = 1
for j in range(i+1, len(nums)):
num2 = nums[j]
hashCode = self.hashFunction(num1, num2)
buckets[hashCode] += 1
#If the bucket has now become frequent, we sit the bit vectore at that index to be 1
if buckets[hashCode] == self.threshold:
bitVector[hashCode] = 1
#In this case, we return the bit vector rather than the buckets as that will be used in the next pass in
#order to save memory
return bitVector, freqNums
#This function performs the second pass of the PCY algorithm
def passTwo(self, freqNums, bitVector):
candidatePairs={}
"""
Unlike A-Priori algorithm, PCY does not consider all possible pairs of the frequent singletons to be a candidate
pair. In this for loop, we do create all the possible pairs from the frequent singletons, but we also only
add those pairs as candidate pairs that satisfy the requirement of hashing to a value of 1 in the bit vector
"""
for i in range(len(freqNums)):
for j in range(i+1, len(freqNums)):
hashCode = self.hashFunction(freqNums[i], freqNums[j])
if (bitVector[hashCode] == 1):
if freqNums[i] < freqNums[j]:
pair=str(freqNums[i]) + ',' + str(freqNums[j])
else:
pair=str(freqNums[j]) + ',' + str(freqNums[i])
candidatePairs[pair] = 0
#Now, we find the frequency of all the candidate pairs, similar to A-Priori
freqPairs=[]
for i in range(self.dataChunk):
line = self.file.readline()
nums = list(map(int, line.split()))
for x in range(len(nums)):
num1 = nums[x]
if num1 in freqNums:
for j in range(x+1, len(nums)):
num2 = nums[j]
if num2 in freqNums:
if num1 < num2:
pair = str(num1) + ',' + str(num2)
else:
pair = str(num2) + ',' + str(num1)
if pair in candidatePairs:
candidatePairs[pair] = candidatePairs.get(pair) + 1
if candidatePairs[pair] == self.threshold:
freqPairs.append(pair)
return freqPairs
|
#!/usr/bin/env python3
def divide(a:float, b:float):
try:
# Intentionally raise an error.
x = a / b
except Exception as e:
# Except clause:
print("- Error occurred")
raise e
else:
print("-- Hi, this is the else block!")
return x
finally:
# Finally clause:
print("--- Finally is always executed!")
print('='*10)
aa = divide(10, 3)
print(aa)
print('='*10)
aa = divide(10, 5)
print(aa)
print('='*10)
aa = divide(10, 0)
print(aa)
|
#!/usr/bin/env python3
lista = [ "nose", "tampoco", 100 ]
lista_nueva = list()
lista_nueva02 = list()
print('='*10)
try:
val = element
lista_nueva.append(val)
print("-- Dentro del try", val)
val = val + 20
lista_nueva02.append(val)
except Exception as e:
print("-- except", val, e)
continue
else:
print("-- Else del try", val)
break
print('#'*10)
print(lista_nueva)
print(lista_nueva02)
|
import calendar
yy = 2020
mm = 11
yy = int(input("Enter year:"))
mm = int(input("Enter month:"))
print(calendar.month(yy,mm))
bye = input("To 'exit' the progrm type Exit: ")
|
# 序列指元素有序的排列并且通过下标偏移量访问到它一个或多个元素
# 序列分为字符串“abc”,列表[ 0, 'adad'],元组 ( "aaa","ccc")
# 随便输入年份判断生肖星座
chinese_zodiac = "鼠牛虎兔蛇马羊猴鸡狗猪"
# 通过下标输出元素
print(chinese_zodiac[0])
# 通过下标输出多个元素
print(chinese_zodiac[0:4])
# 从后往前输出
print(chinese_zodiac[-1])
# 判断元素是否在序列中 元素 in 序列
print('人' in chinese_zodiac)
print('猪' in chinese_zodiac)
# 两个序列的连接 序列+序列
print(chinese_zodiac + 'wwwwww')
# 重复操作符 *整数
print(chinese_zodiac * 3)
zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座',u'巨蟹座', u'狮子座', u'处女座', u'天秤座',u'天蝎座', u'射手座')
zodiac_days = ((1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22), (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23))
a = (2, 15)
zodiac_day = filter(lambda x: x <= a, zodiac_days)
# print(list(zodiac_day))
zodiac_len = len(list(zodiac_day)) % 12
print(zodiac_len)
print(zodiac_name[zodiac_len])
|
# 映射类型:字典 dict
# 字典包含哈希值和指向的对象 {'哈希值':对象}
# 建立一个空对象
dict1 = {}
print(type(dict1))
# 如何给字典增加值
dict2 = {'x': 1, 'y': 2}
dict2['z'] = 3
print(dict2)
# 统计生肖和星座
chinese_zodiac = "猴鸡狗猪鼠牛虎兔龙蛇马羊"
zodiac_name = (u'摩羯座', u'水瓶座', u'双鱼座', u'白羊座', u'金牛座', u'双子座', u'巨蟹座', u'狮子座', u'处女座', u'天秤座', u'天蝎座', u'射手座')
zodiac_days = (
(1, 20), (2, 19), (3, 21), (4, 21), (5, 21), (6, 22), (7, 23), (8, 23), (9, 23), (10, 23), (11, 23), (12, 23)
)
# 创建统计生肖和星座的字典
c_zodiac = {}
zodiac = {}
# 初始化赋值
for item in chinese_zodiac:
c_zodiac[item] = 0
for item in zodiac_name:
zodiac[item] = 0
# 记录每次用户的星座和年份
while True:
# int转化成整数
int_year = int(input('请输入年份:'))
int_month = int(input('请输入月份:'))
int_day = int(input('请输入月份:'))
n = 0
while zodiac_days[n] < (int_month, int_day):
if int_month == 12 and int_day > 23:
break
n += 1
print(zodiac_name[n])
print('%s年的生肖是%s' % (int_year, chinese_zodiac[int_year % 12]))
c_zodiac[chinese_zodiac[int_year % 12]] += 1
zodiac[zodiac_name[n]] += 1
# 打印字典
for item in c_zodiac.keys():
print('%s 有 %d 个' % (item, c_zodiac[item]))
for item in zodiac.keys():
print('%s 有 %d 个' % (item, zodiac[item]))
|
def split(string, pattern):
result = []
arr_of_index = []
if pattern in string:
if string[0] != pattern and string[-1] != pattern:
string = pattern + string + pattern
elif string[0] != pattern and string[-1] == pattern:
string = pattern + string
elif string[0] == pattern and string[-1] != pattern:
string = string + pattern
for i in range(len(string)):
if string[i] == pattern:
arr_of_index.append(i + 1)
else: raise Exception("Patten was not found in the string.")
for i in range(len(arr_of_index)-1):
result.append(string[arr_of_index[i] : arr_of_index[i+1]-1])
return result
def count_words_of_symbvols(string, pattern):
arr_of_words = split(string, ' ')
n = len(pattern)
counter = 0
for i in arr_of_words:
if len(i) >= n:
if ''.join(i[0:n]) == pattern:
counter += 1
return counter
|
from list import list
def isalpha(string):
alphabet = list('qwertyuiopasdfghjklzxcvbnm')
for i in string:
if i.lower() not in alphabet:
return False
else: return True
|
from random import randint
def generate_random_matrix(n):
return [[randint(-100, 100) for j in range(n)] for i in range(n)]
def print_formatted_matrix(matrix, text):
print(text)
print('\n'.join([''.join(['{:4}'.format(j) for j in i]) for i in matrix]))
print('\n\n')
|
from logic.count_polinomic_words import count_polinoms
from string_func.split import split
def main():
string = input("Enter a string: ")
print('Number of polinomic words in string:', count_polinoms(split(string, ' ')))
if __name__ == '__main__':
main()
|
def alghoritm(number):
result = []
while True:
if number == 1:
break
if number <= 0:
raise Exception("Number do not fit the task.")
if number % 3 == 0 and number != 6:
number /= 3
result.append(3)
else:
number -= 5
result.append(5)
if number % 3 == 0 and number != 0 and number != 6:
number /= 3
result.append(3)
return result[::-1]
def print_formatted_answer(arr_of_numbers):
result = ['(' for x in range(len(arr_of_numbers))]
result.append('1 ')
for i in arr_of_numbers:
if i == 3:
result.append('* 3) ')
else:
result.append('+ 5) ')
print(''.join(result))
|
import sys
date=input("Enter the date: ")
dd,mm,yy=date.split('/')
t_date=7
t_month=1
t_year=2020
dd=int(dd)
mm=int(mm)
yy=int(yy)
if (yy>t_year):
print("Sorry ,cannot check for a future date.")
sys.exit(0)
elif ((yy==2020) and (mm>t_month)):
print("Sorry ,cannot check for a future date..")
sys.exit(0)
elif (yy==t_year and mm== t_month and dd> t_date):
print("Sorry ,cannot check for a future date.")
sys.exit(0)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max1=31
elif(mm==4 or mm==6 or mm==9 or mm==11):
max1=30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
max1=29
else:
max1=28
if(mm<1 or mm>12):
print("Date is invalid.")
elif(dd<1 or dd>max1):
print("Date is invalid.")
else:
print("Date is Valid") |
'''
Find if Given number is power of 2 or not.
More specifically, find if given number can be expressed as 2^k where k >= 1.
Input:
number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range)
Output:
return 1 if the number is a power of 2 else return 0
Example:
Input : 128
Output : 1
'''
class Solution:
# @param A : string
# @return an integer
def power(self, A):
A=int(A)
if(A<=1):
return 0
if(bin(A)[2:].count('1')==1):
return 1
return 0
|
n = int(input())
steps = input()
level = 0
valley = 0
if steps[0] == "U":
level+=1
else:
level-=1
for i in range(1,len(steps)):
if steps[i] == "U":
level += 1
else:
level -= 1
if level == 0 and steps[i]=="U":
valley += 1
print(valley)
|
def caseChange():
string = input("Enter any sentence: ")
print(string.swapcase()) |
# OOP (Object Oriented Programming)
class Student:
default_gpa = 2.0
def __init__(self, name, major, gpa, is_on_probation):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
def __init__(self, name, major, gpa, is_on_probation):
self.name = major
self.gpa = default_gpa
def student():
return self
class Teacher:
def __init__(self, name):
self.name = name
|
# Lopez Chaidez Luis Enrique DDSIV
def ordenar(number1, number2):
"""Function that determines what number is bigger
Args:
number1 ([type]): [description]
number2 ([type]): [description]
Returns:
[type]: [description]
"""
if number1 == number2:
print(str(number1) + ' es igual a ' + str(number2))
return [number1, number2]
if number1 > number2:
print(str(number1) + ' es mayor que ' + str(number2))
return [number1, number2]
else:
print(str(number2) + ' es mayor que ' + str(number1))
return [number2, number1]
def multiplos(number1, number2):
"""Function that prints if one number is multiple of the other
Args:
number1 (int): Number to know if is multiple of number2
number2 (int): Number to know if number1 is multiple of it
"""
if number1 == 0 or number2 == 0:
print('El numero ' + str(number1) + ' es multiplo de ' + str(number2))
return
if (number1 % number2) == 0:
print('%d es multiplo de %d' % (number1, number2))
else:
print('%d no es multiplo de %d' % (number1, number2))
def line():
print('-------------------------------')
number1 = 0
number2 = 0
loop = True
while loop:
line()
print('1. Introducir los numeros')
print('2. Ver los multiplos')
print('3. Ordenar de mayor a menor')
print('4. Salir')
opcion = input()
if opcion == '1':
line()
number1 = int(input('Introduzca el primer numero: '))
number2 = int(input('Introduzca el segundo numero: '))
elif opcion == '2':
line()
multiplos(number1, number2)
elif opcion == '3':
line()
print(ordenar(number1, number2))
elif opcion == '4':
loop = False
|
#luis Enrique Lopez Chaidez DDSIV
#Crea una tupla con valores ya predefinidos del 1 al 10,
# pide un índice por teclado y muestra el valor correspondiente del índice de la tupla.
nombres = ('Ana','Enzo','Eric','Eva','Hugo','Iván','Juan','Lara','Leo','Raúl')
cycle = True
while cycle:
try:
print(nombres[int(input('Introduce un numero del 1 al 10: ')) - 1])
cycle= False
except IndexError as index:
print('Este numero no es de el 1 al 10\n')
except ValueError as value:
print('Introdujo un valor incorrecto\n')
|
with open('pi_millions.txt') as file_object:
content = file_object.readlines()
print("This is SSSSSSS")
pi_number = ''
for s in content:
pi_number += s.strip()
#print(pi_number)
birthday = input("Enter your birthday, format:ddmmyyyy: ")
if birthday in pi_number:
print("Hurray! Your birthday appears in the first million digits of PI!")
else:
print("wooooo! Your birthday does not appear in the first million digits of PI")
#filename = 'pi_digits.txt'
# print("This is another")
# #with open(filename) as f:
# for line in content:
# print(line)
|
class Investment:
def __init__(self, principal, interest):
self.principal = principal
self.interest = interest
def value_after(self, n):
valueAfter = int(self.principal) * ((1 + (int(self.interest)/100)) ** int(n))
return str(valueAfter)
def __str__(self):
return 'Principal - '+ format(self.principal) + ', Interest rate - ' + format(self.interest) + '%'
#print('Principal - ', self.principal , ', Interest rate - ', self.interest,'%')
amount = Investment(eval(input('Enter the principal: ')), eval(input('Enter the interest rate: ')))
value = amount.value_after(int(input('enter the year: ')))
outp = amount.__str__()
print(outp)
print('The value is ' + value) |
import random
all_lessons = ('语文', '数学', '英语', '美术', '思品', '手工', '体育', '科学', '书法',)
var_lessons = []
for row in range(1,6):
row_data = []
for col in range(1,3):
if col == 1:
row_data.append(row)
else:
row_data.append(random.choice(all_lessons))
#print(row_data)
var_lessons.append(row_data)
print(var_lessons)
|
#################################################################
#################### PROBLEM 04 #################################
#################################################################
"""
Write a program to convert the time inputted in minutes into hours and remaning minutes.
"""
## SOLUTION
time = int(input("Enter the time in minutes:"))
hours = time/60
mins = time%60
print("Hours are:", hours)
print("Minutes are:", mins)
|
#Variaveis.
vCartao = float(input('Quanto dinheiro há no seu cartão :'))
vPassagem = float(input('Quanto custa uma passagem :'))
dUso = float(input('Quantos vezes em um dia você utiliza este meio de transporte :'))
#Calculo de quantas passagens é possível utilizar.
print('O total de passagens que podem ser utilizadas é de {:.2f} .'.format(vCartao / (vPassagem * dUso)))
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import turtle
import random
# Crea una ventana y un objeto Turtle
window = turtle.Screen()
window.bgcolor('black')
pen = turtle.Turtle()
pen.speed(0)
pen.hideturtle()
# Lista de colores para los corazones
colors = ['red', 'white', 'pink', 'purple', 'blue']
# Función para dibujar un corazón en una posición aleatoria
def draw_heart(x, y, color):
pen.penup()
pen.goto(x, y)
pen.pendown()
pen.color(color)
pen.begin_fill()
pen.left(45)
pen.forward(100)
pen.circle(50, 180)
pen.right(90)
pen.circle(50, 180)
pen.forward(100)
pen.end_fill()
# Dibuja 50 corazones en posiciones aleatorias
for i in range(50):
x = random.randint(-200, 200)
y = random.randint(-200, 200)
color = random.choice(colors)
draw_heart(x, y, color)
# Cierra la ventana al hacer clic en ella
window.exitonclick()
|
#!/usr/bin/env python
import sys
from Queue import PriorityQueue
def boolean_retrieval(inverted_list, q_words):
words, ret = [], []
for word in q_words:
if word not in inverted_list:
return ret
words.append(word)
n = len(words)
# current index for each id
idx = [0] * n
# initialize priority queue
# in PQ, (current_word, id) is stored
# cur_max_word stores the maximum word in PQ
PQ = PriorityQueue()
cur_max_doc = ""
for i in range(n):
cur_doc = inverted_list[words[i]][0]
PQ.put((cur_doc, i))
cur_max_doc = max(cur_max_doc, cur_doc)
while True:
cur_min_doc, id = PQ.get()
if cur_min_doc == cur_max_doc:
ret.append(cur_min_doc)
idx[id] += 1
if idx[id] >= len(inverted_list[words[id]]):
return ret
next_doc = inverted_list[words[id]][idx[id]]
cur_max_doc = max(cur_max_doc, next_doc)
PQ.put((next_doc, id))
if __name__ == "__main__":
if len(sys.argv) < 2:
print "inverted file name needed."
exit()
# read inverted list from file specific by first arg
inverted_list = {}
file = open(sys.argv[1], "r")
line = file.readline()
while line:
parts = line.strip().split(" ")
inverted_list[parts[0]] = parts[1:]
line = file.readline()
q_line = sys.stdin.readline()
while q_line:
q_words = q_line.strip().split(" ")
doc = boolean_retrieval(inverted_list, q_words)
print doc
q_line = sys.stdin.readline()
|
# Introduction to Programming, Task 15: CapStone Project II
# Megan van Zyl, 23/04/2019
# Python code to make use of nested loops to create a number pyramid
for i in range (1, 10): #number of rows
for j in range(1, i + 1): #number of columns
print(i * j, end=" ")
print("\n") #program prints a new line
|
from sys import stdin
class MatrixError(BaseException):
def __init__(self, m1, m2):
self.matrix1 = m1
self.matrix2 = m2
class Matrix:
def __init__(self, matrix):
# создание копии
self.M = list(map(list, matrix))
def __str__(self):
s = list()
for row in self.M:
s.append('\t'.join(map(str, row)))
return '\n'.join(s)
def size(self):
return len(self.M), len(self.M[0])
def __add__(self, other):
if self.size() == other.size():
rows = list()
(c, r) = self.size()
for i in range(c):
line = list()
for j in range(r):
line.append(self.M[i][j] + other.M[i][j])
rows.append(line)
return Matrix(rows)
else:
raise MatrixError(self, other)
def __mul__(self, other):
rows = list()
(c, r) = self.size()
for i in range(c):
line = list()
for j in range(r):
line.append(self.M[i][j] * other)
rows.append(line)
return Matrix(rows)
__rmul__ = __mul__
def transpose(self):
tM = list()
(c, r) = self.size()
for j in range(r):
line = list()
for i in range(c):
line.append(self.M[i][j])
tM.append(line)
self.M = tM
return self
@staticmethod
def transposed(x):
tM = list()
(c, r) = x.size()
for j in range(r):
line = list()
for i in range(c):
line.append(x.M[i][j])
tM.append(line)
return Matrix(tM)
# m1 = [[-10, 20, 50, 2443], [-5235, 12, 4324, 4234]]
# m = Matrix(m1)
# m1[0][0] = 0
# print(m)
exec(stdin.read())
|
from math import sqrt, fabs
a = float(input())
b = float(input())
c = float(input())
# Дискриминант
d = b**2 - 4*a*c
if d >= 0:
d = sqrt(d)
x1 = (-b - d) / 2 / a
x2 = (-b + d) / 2 / a
if fabs(x1 - x2) < 1e-60:
print(x1)
else:
print(x1, x2)
# elif d == 0:
# x1 = -b / 2 / a
# print(x1)
|
n = int(input())
va = n == 1 or (n > 20 and ((n-1) % 10 == 0))
vy0 = n == 2 or n == 3 or n == 4
vy2 = ((n-2) % 10 == 0)
vy3 = ((n-3) % 10 == 0)
vy4 = ((n-4) % 10 == 0)
vy = vy0 or (n > 20 and (vy2 or vy3 or vy4))
if va:
print(n, 'korova')
else:
if vy:
print(n, "korovy")
else:
print(n, "korov")
|
"""
Creates a convolutionaly neural network (CNN) in Tensorflow and trains the network
to identify the facial emotion in an input image.
"""
import tensorflow as tf
from cvision_tools import detect_face, crop_face, convert_to_gray, resize_with_pad, over_sample, under_sample
from CohnKanadeDataset import CohnKanadeDataset
import numpy as np
from sklearn.preprocessing import LabelEncoder
import pickle
import os
image_height = 64
image_width = 64
image_n_channels = 1
n_epochs = 100
batch_size = 10
initial_learning_rate = 0.001
decay_steps = 2000
decay_rate = 1/2
reg_constant = 0
EMOTION_DECODER_PATH = "./model/emotion_decoder.pickle"
EMOTION_PREDICTION_MODEL_PATH = "./model/emotion_model1"
COHN_KANADE_DATA_FILE_PATH = "./data/cohn_kanade.pickle"
def prepare_emotion_data():
""" Prepares training and test data for emotion detection model from Cohn-Kanade image dataset
(Face area in each image is detected and cropped)
Args:
Returns:
X_train: a numpy array of the train face image data
X_test: a numpy array of the test face image data
y_emotion_train: a numpy array of the train emotion lables
y_emotion_test: a numpy array of the test emotion lables
"""
dataset = CohnKanadeDataset()
dataset.read(image_height=image_height, image_width=image_width)
X_train = np.array(dataset.X_train).astype('float32')
X_test = np.array(dataset.X_test).astype('float32')
X_train = X_train / 128 - 1
X_test = X_test / 128 - 1
y_emotion_train = np.array(dataset.y_train)
y_emotion_test = np.array(dataset.y_test)
return X_train, X_test, y_emotion_train, y_emotion_test
def create_emotion_decoder():
""" Creates a emotion label decoder for Cohn-Kanade dataset
Args:
Returns:
emotion_dec: a python dictionary to decode emotion labels
"""
emotion_dec = {0 : 'neutral',
1 : 'anger',
2 : 'contempt',
3 : 'disgust',
4 : 'fear',
5 : 'happy',
6 : 'sadness',
7 : 'surprise'}
pickle.dump(emotion_dec, open(EMOTION_DECODER_PATH, 'wb'))
return emotion_dec
def train_emotion_model(X_train, X_test, y_train, y_test):
""" Creates a convoluational neural network (CNN) and trains the model to detect facial
emotion in an input image
Args:
X_train: a numpy array of the train image data
X_test: a numpy array of the test image data
y_train: a numpy array of the train emotion lables
y_test: a numpy array of the test emotion lables
Returns:
"""
emotion_uniques, emotion_counts = np.unique(y_train, return_counts=True)
print(emotion_uniques)
print(emotion_counts)
num_emotion_outputs = len(emotion_uniques)
with tf.name_scope("cnn_graph_emotion"):
X = tf.placeholder(tf.float32, shape = [None, image_height, image_width, image_n_channels], name="X")
#y = tf.placeholder(tf.float32, shape = [None, image_height, image_weight, image_n_channels])
y = tf.placeholder(tf.int32, shape = [None])
training = tf.placeholder_with_default(False, shape=[], name='training')
#
residual1 = tf.layers.conv2d(X, filters=16, kernel_size=4,
strides=4, padding='SAME',
activation=tf.nn.elu, name="residual1")
conv11 = tf.layers.conv2d(X, filters=8, kernel_size=2,
strides=1, padding='SAME',
activation=tf.nn.elu, name="conv11")
pool12 = tf.nn.max_pool(conv11, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
conv13 = tf.layers.conv2d(pool12, filters=16, kernel_size=4,
strides=1, padding='SAME',
activation=tf.nn.elu, name="conv13")
pool14 = tf.nn.max_pool(conv13, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
layer1_out = tf.add(residual1, pool14)
#
layer1_out_drop = tf.layers.dropout(layer1_out, 0.3, training=training)
#
residual2 = tf.layers.conv2d(layer1_out_drop, filters=64, kernel_size=4,
strides=4, padding='SAME',
activation=tf.nn.elu, name="residual2")
conv21 = tf.layers.conv2d(layer1_out, filters=32, kernel_size=2,
strides=1, padding='SAME',
activation=tf.nn.elu, name="conv21")
pool22 = tf.nn.max_pool(conv21, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
conv23 = tf.layers.conv2d(pool22, filters=64, kernel_size=4,
strides=1, padding='SAME',
activation=tf.nn.elu, name="pool22")
pool24 = tf.nn.max_pool(conv23, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")
layer2_out = tf.add(residual2, pool24)
#
pool4_flat = tf.reshape(layer2_out, shape=[-1, 64 * 4 * 4])
pool4_flat_drop = tf.layers.dropout(pool4_flat, 0.5, training=training)
fc1 = tf.layers.dense(pool4_flat_drop, 32, activation=tf.nn.elu, name="fc1")
fc1_drop = tf.layers.dropout(fc1, 0.5, training=training)
logits_emotion = tf.layers.dense(fc1_drop, num_emotion_outputs, name="logits_emotion")
Y_proba_emotion = tf.nn.softmax(logits_emotion, name="Y_proba_emotion")
global_step = tf.Variable(0, trainable=False, name="global_step")
learning_rate = tf.train.exponential_decay(initial_learning_rate, global_step, decay_steps, decay_rate)
with tf.name_scope("train_emotion"):
xentropy_emotion = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_emotion, labels=y)
loss_emotion = tf.reduce_mean(xentropy_emotion)
reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss_emotion_reg = loss_emotion + reg_constant * sum(reg_losses)
optimizer_emotion = tf.train.AdamOptimizer(learning_rate=learning_rate) # beta1=0.8
#optimizer_emotion = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9, use_nesterov=True)
training_op_emotion = optimizer_emotion.minimize(loss_emotion_reg, global_step=global_step)
with tf.name_scope("eval_emotion"):
correct_emotion = tf.nn.in_top_k(logits_emotion, y, 1)
accuracy_emotion = tf.reduce_mean(tf.cast(correct_emotion, tf.float32))
with tf.name_scope("init_and_save"):
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as train_emotion_sess:
init.run()
print("Training for emotion identification")
for epoch in range(n_epochs):
n_it = X_train.shape[0]//batch_size
for it in range(n_it):
X_batch = X_train[it*batch_size:(it+1)*batch_size,:,:,:]
y_batch = y_train[it*batch_size:(it+1)*batch_size]
train_emotion_sess.run(training_op_emotion, feed_dict={X: X_batch, y: y_batch, training: True})
acc_batch = accuracy_emotion.eval(feed_dict={X: X_batch, y: y_batch})
acc_train = accuracy_emotion.eval(feed_dict={X: X_train[1:200], y: y_train[1:200]})
acc_test = accuracy_emotion.eval(feed_dict={X: X_test, y: y_test})
print(epoch, "Last batch accuracy:", acc_batch, "Train accuracy:", acc_train, "Test accuracy:", acc_test)
save_path_emotion = saver.save(train_emotion_sess, EMOTION_PREDICTION_MODEL_PATH)
def main():
if os.path.isfile(COHN_KANADE_DATA_FILE_PATH):
X_train, X_test, y_train, y_test = pickle.load(open(COHN_KANADE_DATA_FILE_PATH, 'rb'))
else:
X_train, X_test, y_train, y_test = prepare_emotion_data()
print(len(X_train))
print(len(X_test))
X_train, y_train = over_sample(X_train, y_train)
X_test, y_test = over_sample(X_test, y_test)
pickle.dump([X_train, X_test, y_train, y_test], open(COHN_KANADE_DATA_FILE_PATH, 'wb'))
print(len(X_train))
emotion_decoder = create_emotion_decoder()
train_emotion_model(X_train, X_test, y_train, y_test)
if __name__ == "__main__":
main() |
def solution(numbers, hand):
pos = {1: [0, 0], 2: [0, 1], 3: [0,2], 4: [1, 0], 5: [1,1], 6: [1,2], 7: [2,0], 8: [2,1], 9: [2,2], "*": [3, 0], 0: [3, 1], "#": [3, 2]}
pair = {1: "L", 4: "L", 7: "L", 3: "R", 6: "R", 9: "R"}
answer = ''
left, right = pos["*"], pos["#"]
for number in numbers:
if number in pair.keys():
answer += pair[number]
if pair[number] == "L":
left = pos[number]
else:
right = pos[number]
else:
ll = abs(left[0] - pos[number][0]) + abs(left[1] - pos[number][1])
rr = abs(right[0] - pos[number][0]) + abs(right[1] - pos[number][1])
if ll < rr:
answer += "L"
left = pos[number]
elif ll > rr:
answer += "R"
right = pos[number]
elif ll == rr:
if hand == "left":
answer += "L"
left = pos[number]
else:
answer += "R"
right = pos[number]
return answer |
### TLE 발생
# s = input()
# p = input()
#
# idxs = []
# for i, sub in enumerate(s):
# if sub == p[0]:
# idxs.append(i)
#
# for idx in idxs:
# if s[idx: idx+ len(p)] == p:
# print(1)
# break
# else:
# print(0)
### 통과한 풀이
# import re
#
# s = input()
# p = input()
#
# pattern = re.compile(p)
# if pattern.search(s):
# print(1)
# else:
# print(0)
import re
pattern = re.compile("[a-z]+")
print(pattern.search("3 python"))
|
def check(x, y, type, columns, beams):
# 기둥인 경우
if type == 0:
if y == 0 or (x, y) in beams or (x - 1, y) in beams or (x, y - 1) in columns:
return True
# 보인 경우
else:
if (x, y - 1) in columns or (x + 1, y - 1) in columns or ((x - 1, y) in beams and (x + 1, y) in beams):
return True
return False
def solution(n, build_frame):
answer = []
columns = []
beams = []
for x, y, a, b in build_frame:
# 삭제하는 경우
if b == 0:
# 기둥
if a == 0:
columns.remove((x, y))
dx = [-1, 0, 0]
dy = [1, 1, 1]
dtype = [1, 1, 0]
for i in range(3):
nx = x + dx[i]
ny = y + dy[i]
type = dtype[i]
if (nx, ny, type) in answer:
if not check(nx, ny, type, columns, beams):
columns.append((x, y))
break
else:
answer.remove((x, y, 0))
# 보
else:
beams.remove((x, y))
dx = [0, 1, -1, 1]
dy = [0, 0, 0, 0]
dtype = [0, 0, 1, 1]
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
type = dtype[i]
if (nx, ny, type) in answer:
if not check(nx, ny, type, columns, beams):
beams.append((x, y))
break
else:
answer.remove((x, y, 1))
# 설치하는 경우
if b == 1:
# 기둥
if a == 0:
if check(x, y, a, columns, beams):
columns.append((x, y))
answer.append((x, y, 0))
# 보
else:
if check(x, y, a, columns, beams):
beams.append((x, y))
answer.append((x, y, 1))
answer.sort(key=lambda x: (x[0], x[1], x[2]))
return answer |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
app = Flask(__name__)
def connect_to_db(app):
"""Connect the database to our Flask app."""
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///lifelogger'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.app = app
db.init_app(app)
def add_new_weekly_question(question_short, question_long):
"""Adds a new question to the weekly review."""
QUERY = """INSERT INTO questions (question_short, question_long)
VALUES (:question_short, :question_long)
"""
db.session.execute(QUERY, {'question_short': question_short,
'question_long': question_long})
db.session.commit()
print "Successfully added new question: {} // {}".format(
question_short, question_long)
def answer_weekly_question(question_short, answer):
"""Fills in a new answer to a question for the weekly review."""
QUERY = """INSERT INTO weeklyreview (date, question, answer)
VALUES (current_date, :question_short, :answer)
"""
db.session.execute(QUERY, {'question_short': question_short,
'answer': answer})
db.session.commit()
print "Answered question {} with {}".format(question_short, answer)
def get_question_long(question_short):
"""Returns the long version of the question given the short version."""
QUERY = """SELECT question_long
FROM questions
WHERE question_short = :question_short
"""
cursor = db.session.execute(QUERY, {'question_short': question_short})
question_long = cursor.fetchone()[0]
return question_long
def get_last_week_questions(last_week):
"""Returns a list of questions that were answered last week."""
QUERY = """SELECT question, answer
FROM weeklyreview
WHERE date = :last_week
"""
cursor = db.session.execute(QUERY, {'last_week': last_week})
last_questions_answers = []
for question in cursor.fetchall():
short_question = question[0]
answer = question[1]
short_question.strip()
answer.strip()
last_questions_answers.append((short_question, get_question_long(short_question), answer))
return last_questions_answers
if __name__ == "__main__":
connect_to_db(app)
db.session.close()
|
#Написать функцию, которая принимает на вход две строки
#Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0
#Если строки одинаковые, вернуть 1
#Если строки разные и первая длиннее, вернуть 2
#Если строки разные и вторая строка 'learn', возвращает 3
#Вызвать функцию несколько раз, передавая ей разные параметры и выводя на экран результаты
def strings(str1, str2):
if type(str1) != str and type(str2) != str:
return 0
elif str1 == str2:
return 1
elif str1 != str2 and len(str1) > len(str2):
return 2
elif str1 != str2 and str2 == 'learn':
return 3
print(strings('apple', 'apple'))
print(strings('apple', 'app'))
print(strings('apple', 'learn'))
print(strings(2.1, 2)) |
#!/usr/bin/python3
with open('12.in') as f:
instructions = [(i[0], int(i[1:])) for i in f]
angle_map = {0: 'E', 90: 'N', 180: 'W', 270: 'S'}
class Boat:
def __init__(self):
self.angle = 0
self.loc = [0, 0]
def action(self, instr):
if instr[0] == 'E':
self.loc[0] += instr[1]
elif instr[0] == 'N':
self.loc[1] += instr[1]
elif instr[0] == 'W':
self.loc[0] -= instr[1]
elif instr[0] == 'S':
self.loc[1] -= instr[1]
elif instr[0] == 'L':
self.angle = (self.angle + instr[1]) % 360
elif instr[0] == 'R':
self.angle = (self.angle - instr[1]) % 360
elif instr[0] == 'F':
self.action((angle_map[self.angle], instr[1]))
def navigate(self, instructions):
for instr in instructions:
self.action(instr)
boat = Boat()
boat.navigate(instructions)
print(abs(boat.loc[0]) + abs(boat.loc[1]))
class Boat:
def __init__(self):
self.angle = 0
self.loc = [0, 0]
self.waypoint_loc = [10, 1]
def action(self, instr):
if instr[0] == 'E':
self.waypoint_loc[0] += instr[1]
elif instr[0] == 'N':
self.waypoint_loc[1] += instr[1]
elif instr[0] == 'W':
self.waypoint_loc[0] -= instr[1]
elif instr[0] == 'S':
self.waypoint_loc[1] -= instr[1]
elif instr[1] == 180:
self.waypoint_loc = [-self.waypoint_loc[0], -self.waypoint_loc[1]]
elif (instr[0] == 'L' and instr[1] == 90) or (instr[0] == 'R' and instr[1] == 270):
self.waypoint_loc = [-self.waypoint_loc[1], self.waypoint_loc[0]]
elif (instr[0] == 'R' and instr[1] == 90) or (instr[0] == 'L' and instr[1] == 270):
self.waypoint_loc = [self.waypoint_loc[1], -self.waypoint_loc[0]]
elif instr[0] == 'F':
self.loc = [self.loc[i] + instr[1] * self.waypoint_loc[i] for i in range(2)]
def navigate(self, instructions):
for instr in instructions:
self.action(instr)
boat = Boat()
boat.navigate(instructions)
print(abs(boat.loc[0]) + abs(boat.loc[1]))
|
#!/usr/bin/python3
import pandas as pd
import numpy as np
def get_fuel(array):
fuel = np.floor(array / 3) - 2
if fuel < 0:
return 0
return fuel
data = pd.read_csv('input-1')
fuels_1 = np.floor(data['numbers'] / 3) - 2
print(sum(fuels_1))
fuel_total = 0
for module in data['numbers']:
fuel = get_fuel(module)
while fuel > 0:
fuel_total += fuel
fuel = get_fuel(fuel)
print(fuel_total)
|
def squareEach(nums):
entry = 0
for i in nums:
nums[entry] = i**2
entry = entry+1
def main():
print('This program squares numbers that you enter.')
nums = input('Please enter your numbers separated by comma: ')
nums = nums.split(',')
entry = 0
for i in nums:
nums[entry] = int(i)
entry = entry+1
squareEach(nums)
print('Here are your new numbers: ',nums)
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 3 04:14:08 2016
@author: kiaph
"""
from graphics import *
from button import Button
from dieview import DieView
def window():
pointA = Point(125,75)
pointB = Point(125,175)
pointC = Point(125,275)
pointD = Point(350,150)
pointE = Point(500,150)
pointF = Point(450,275)
pointG = Point(475,50)
pointX = Point(575,25)
win = GraphWin("Crap Heaven",600,350)
win.setBackground("purple")
pt = win.getMouse()
bA = Button(win,pointA,150,50,"Bet 1000!")
bB = Button(win,pointB,150,50,"Bet 100!")
bC = Button(win,pointC,150,50,"Bet 10!")
bD = DieView(win,pointD,100)
bE = DieView(win,pointE,100)
bF = Button(win,pointF,200,50,"Bank Account")
button2 = Button(win,pointG,150,50,"Win!")
button1 = Button(win,pointX,25,25,"X")
button2.activate
button2.active
while not button2.clicked(pt):
if button2.clicked(pt):
win.close()
pt = win.getMouse()
window()
|
from math import *
def squareEach(nums):
entry = 0
for i in nums:
nums[entry] = i**2
entry = entry + 1
def main():
print("Square a list of numbers. ")
nums = input("Enter a list of numbers seperated by a space: ")
nums = nums.split()
entry = 0
for i in nums:
nums[entry] = int(i)
entry = entry + 1
squareEach(nums)
print("The square of your numbers are: ",nums)
main()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 18:05:23 2016
@author: kiaph
"""
def main():
print("This program calculates the numeric value of a name.")
""" Ask for the name to be calculated to numeric value"""
name = input("Enter your name: ")
name.lower()
""" Index the alphabet"""
# pha = [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
# 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
pha = " abcdefghijklmnopqrstuvwxyz"
summ = 0
for i in name:
pha.find(i)
summ = pha.find(i) + summ
print("The numeric value of your name is", summ)
main() |
def main():
hours = eval(input("Please input the number of hours: "))
#print(hours)
wage = eval(input("Please input the hourly wage: "))
#print(wage)
if hours < 40:
print("The total amount earned is", hours*wage)
else:
ovrtime = hours - 40
print("Overtime is", ovrtime,"hours.")
regtime = hours - ovrtime
print("Regular time is", regtime,"hours.")
total = (regtime*wage) + (ovrtime*(wage*1.5))
print("The total amount earned is ${0}".format(total))
main()
|
from graphics import *
def main():
win = GraphWin()
shape = Rectangle(Point(50,50),Point(100,100))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
center = Point(100,100)
for i in range(10):
p = win.getMouse()
c = shape.getCenter()
dx = p.getX() - c.getX()
dy = p.getY() - c.getY()
#Point(p.getX(),p.getY()).draw(win)
newShape = Rectangle(Point(p.getX(),p.getY()),Point(p.getX()+50,p.getY()+50))
newShape.setOutline("red")
newShape.setFill("red")
newShape.draw(win)
exmsg = Text(center, 'Please click again to exit.')
exmsg.draw(win)
m = win.getMouse()
win.close()
main()
|
def main():
grade = ["F++++","F","D","C","B","A"]
score = input("Enter your score on the quiz 0-5: ")
print("You made a", grade[score] ," on your quiz.")
main()
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 4 13:15:32 2016
@author: kiaph
This small script will sum numbers from 0 to your desired value n.
"""
def main():
print(" This program will sum numbers starting from 0 ending at n. ")
n = eval(input("Please enter a value for n: "))
total = 0
p = n
i = 0
if n < 0:
print("Please try again, without use of a negative number.")
if n == 0:
print("The sum of numbers between 0 and 0 is 0")
print("Do you really need help with such a thing?")
print("Please try harder next time.")
else:
while i != n:
i = i + 1
### print("the current value of n is: ", p)
### this was used for trouble shooting.
total = total + i
p = p - 1
else:
print( total, "is the sum of the numbers between 0 and ", n )
main() |
# -*- coding: utf-8 -*-
"""
Created on Wed May 4 07:05:26 2016
@author: kiaph
"""
"""
def printfile():
#fname = input("Enter filename: ")
fname = 'UserNames.prn'
infile = open(fname, "r")
data = infile.read()
print(data)
print("------------------------------------------------------------------------------")
printfile()
def newcode():
someFile = 'UserNames.prn'
infile = open(someFile, "r")
line = infile.readline()
print(line)
print("----------------------------------------------------------------------------------")
newcode()
def othercode():
infile = open('UserNames.prn', "r")
for i in range(5):
line = infile.readline()
print(line[:-1])
print("----------------------------------------------------------------------------")
othercode()
def othercode():
infile = open('UserNames.prn', "r")
for i in range(5):
line = infile.readline()
print(line)
print("-------------------------------------------------------------------------------")
othercode()
def othercode2():
infile = open('UserNames.prn', "r")
for i in range(5):
line = infile.readline()
print(line, end="")
print("-------------------------------------------------------------------------")
othercode2()
def othercode3():
infile = open('UserNames.prn', "r")
for line in infile.readlines():
print(line)
infile.close()
print("---------------------------------------------------------------------------")
othercode3()
def othercode4():
infile = open('UserNames.prn', "r")
for line in infile:
print(line)
infile.close()
print("---------------------------------------------------------------------------")
othercode4()
def write1():
outfile = open('outputfile',"w")
print('Woah doggy',file=outfile)
outfile.close()
print("---------------------------------------------------------------------------")
infile = open('outputfile', "r")
for line in infile.readlines():
print(line)
infile.close()
print("---------------------------------------------------------------------------")
write1()
def userfile():
infile = open('UserNames.prn',"r")
outfile = open('NamesOnly.prn',"w")
for line in infile:
first, last, gender, score, major = line.split()
uname = (first[0] + last[:7]).lower()
print(uname, file=outfile)
infile.close()
outfile.close()
pinfile = open('NamesOnly.prn', "r")
for line in pinfile:
print(line)
pinfile.close()
print("---------------------------------------------------------------------------")
userfile()
def userfile1():
infile = open('UserNames.prn',"r")
soutfile = open('females',"w")
for line in infile:
first, last, gender, score, major = line.split()
x = first
print(x)
y = last
print(y)
z = gender
print(z)
if z == 'f':
print(x,y,file=soutfile)
soutfile.close()
pinfile = open('females', "r")
for line in pinfile:
print(line)
pinfile.close()
print("---------------------------------------------------------------------------")
userfile1()
"""
class Sortme:
############# this class will sort the file by given criteria.
def __init__(self,filename,row,collumn):
file = filename
x = row
y = collumn
if collumn == 'n':
self.datafinder2(file,x)
else:
self.datafinder3(file,x,y)
def datafinder3(self,filename,row,collumn):
filename = "UserNames.prn"
infile = open(filename, 'r')
objects = []
for line in infile:
lines = []
for i in line.split():
lines.append(i)
objects.append(lines)
print(objects[0][1])
infile.close()
def datafinder2(self,filename,row):
filename = "UserNames.prn"
infile = open(filename, 'r')
objects = []
for line in infile:
lines = []
for i in line.split():
lines.append(i)
objects.append(lines)
print(objects[0][1])
infile.close()
|
import graphics
from graphics import Rectangle
from graphics import Point
from graphics import Text
def main():
win = graphics.GraphWin()
shape = Rectangle(Point(75,75),Point(125,125))
shape.setOutline('Red')
shape.setFill('Red')
shape.draw(win)
for i in range(10):
p = win.getMouse()
tx = p.getX()-25
ty = p.getY()-25
bx = p.getX()+25
by = p.getY()+25
Rectangle(Point(tx,ty),Point(bx,by)).draw(win)
Text(Point(100,180),'Click again to quit!').draw(win)
win.getMouse()
win.close()
main()
|
import re
import six
# Default Luhn check digits (base-10)
DIGITS = '0123456789'
def luhn_checksum(number, chars=DIGITS):
'''
Calculates the Luhn checksum for `number`
:param number: string or int
:param chars: string
>>> luhn_checksum(1234)
4
'''
length = len(chars)
number = [chars.index(n) for n in reversed(str(number))]
return (
sum(number[::2]) +
sum(sum(divmod(i * 2, length)) for i in number[1::2])
) % length
def luhn_calc(number, chars=DIGITS):
'''
Calculate the Luhn check digit for ``number``.
:param number: string
:param chars: string
>>> luhn_calc('42')
'2'
'''
checksum = luhn_checksum(str(number) + chars[0], chars)
return chars[-checksum]
def luhn_append(number, chars=DIGITS):
'''
Append the Luhn check digit of ``number`` to the input.
:param number: string
:param chars: string
>>> luhn_append('666')
'6668'
'''
return str(number) + luhn_calc(number, chars)
def strip(value, chars):
'''
Removes characters in ``chars`` from input ``value``.
:param value: string
:param chars: iterable
>>> strip('hello.world', '.')
'helloworld'
'''
return ''.join([x for x in value if x not in chars])
def to_decimal(number, strip='- '):
'''
Converts a number to a string of decimals in base 10.
>>> to_decimal(123)
'123'
>>> to_decimal('o123')
'83'
>>> to_decimal('b101010')
'42'
>>> to_decimal('0x2a')
'42'
'''
if isinstance(number, six.integer_types):
return str(number)
number = str(number)
number = re.sub(r'[%s]' % re.escape(strip), '', number)
# hexadecimal
if number.startswith('0x'):
return to_decimal(int(number[2:], 16))
# octal
elif number.startswith('o'):
return to_decimal(int(number[1:], 8))
# binary
elif number.startswith('b'):
return to_decimal(int(number[1:], 2))
else:
return str(int(number))
|
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("edward favorite language is " +
favorite_languages['edward'].title() + ".")
print("\n#6.1")
My_Friend ={
'First_Name': 'Muhammad', 'Last_Name': 'Ali',
'Age': 26, 'City': 'Karachi',
}
print("My Friend's FirstName is:" + My_Friend['First_Name'].title() +"")
print("My Friend's LastName is:" + My_Friend['Last_Name'].title() +"")
print("My Friend's Age is:"+str(My_Friend['Age']))
print("My Friend's City is:" + My_Friend['City'].title() +"")
print("\n#6.2")
Favorite_Numbers={
'Umair': 3,
'Saad': 5,
'Sumair': 8,
'Kashif': 29,
'Faraz': 39,
}
for key, value in Favorite_Numbers.items():
print(key + ":" + str(value) + "\n")
print("\n#6.3")
Glossary = {
'List': 'a collection of items in a particular order.',
'Tuple': 'an immutable list is called a tuple.',
'Dictionary': 'a collection of key-value pairs.',
'Spark': 'is a cluster computing framework',
'Dispersion': 'refers to measures of how spread out our data is.',
}
for key, value in Glossary.items():
print(key + "\n" + value + "\n")
|
# Exercise #1
# name1 = raw_input("What is your name?")
# name2 = raw_input("What is your partner's name?")
#
# if name1 > name2:
# print "My name is greater!"
# elif name2 > name1:
# print "Their name is greater."
# else:
# print "Our names are equal!"
# Exercise #2
# date = raw_input("What is the date?")
#
# if date >= 15:
# print "Oh, we're halfway there!"
# else:
# print "The month is still young."
# Exercise #3
# today = raw_input("What day is it today? ")
#
# if today == "Monday":
# print "Yaaas Monday! Here we go!"
# elif today == "Tuesday":
# print "Sigh, it's only Tuesday."
# elif today == "Wednesday":
# print "Humpday!"
# elif today == "Thursday":
# print "#tbt"
# elif today == "Friday":
# print "TGIF"
# else:
# print "Yeah, it's the freakin' weekend!"
# Exercise #4, #5
# age = input("What is your age? "))
#
# if age >= 18 :
# print "Yay! I can vote!"
# else :
# print "Aww, I cannot vote."
# # Exercise #6
# age = input("What is your age? ")
#
# if age >= 21:
# print "I can vote and go to a bar!"
# Exercise #7
# age = input("What is your age? ")
#
# if age >= 21:
# print "I can go to a bar."
# elif age >= 18:
# print "I can vote, but I cannot go to a bar."
# else :
# print "I cannot vote or go to a bar."
#
# # # Exercise #8
# number = input("Enter a number.")
#
# if number % 2 == 0:
# print "The number is even."
# else:
# print "The number is odd."
# # # Exercise #9
# number = input("Enter a number. ")
#
# if number % 2 != 0:
# print "The number is odd."
# else:
# print "The number is even."
# Exercise #10
# num1 = input("Enter a number. ")
# num2 = input("Enter another number. ")
#
# if num1 % 2 == 0 and num2 % 2 == 0:
# print "Both numbers are even."
# else:
# print "Both numbers are not even."
# Exercise #11
# num1 = input("Enter a number. ")
# num2 = input("Enter another number. ")
#
# if num1 % 2 == 0 and num2 % 2 == 0:
# print "Both numbers are even."
# elif num1 % 2 == 0 and num2 % 2 != 0:
# print "%i is even AND %i is odd." % (num1, num2)
# elif num1 % 2 != 0 and num2 % 2 == 0:
# print "%i is odd AND %i is even." % (num1, num2)
# else:
# print "Both numbers are odd."
# Exercise #12, #13
color = raw_input("What is your favorite color? ")
if color == ("blue" or "red" or "yellow"):
print "My favorite color is a primary color!"
else:
print "My favorite color is a secondary color."
|
list = [11,3,7,2,22,34,9,0,65]
def sort(listName):
for index in range(len(listName) - 1, 0, -1):
for secondIndex in range(index):
if(listName[secondIndex] > listName[secondIndex + 1]):
temp = listName[secondIndex]
listName[secondIndex] = listName[secondIndex + 1]
listName[secondIndex + 1] = temp
#print listName
return listName
print(sort(list))
|
#利用urllib模組的urlretrieve做下載,帶入第一個參數為URL,第二個參數為檔案名稱
from selenium import webdriver
import urllib.request
from bs4 import BeautifulSoup
chrome_path = "D:\PycharmProjects\selenium_driver_chrome\chromedriver.exe" #chromedriver.exe執行檔所存在的路徑
driver = webdriver.Chrome(chrome_path) #開啟Chrome瀏覽器
driver.get("https://www.ptt.cc/bbs/Beauty/M.1515902682.A.579.html")
#print(driver.page_source)
soup = BeautifulSoup(driver.page_source, 'html.parser')
#print(soup)
image = soup.find_all("a")
fileName="picture"
count = 0
for element in image:
#print(element.get('href')[len(element.get('href'))-3:len(element.get('href'))])
if element.get('href')[len(element.get('href'))-3:len(element.get('href'))] == "jpg":
urllib.request.urlretrieve(element.get('href'), fileName+str(count)+".jpg")
count = count +1
print(element.get('href'))
#print(image)
driver.close() |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 2 23:07:21 2021
@author: orkun.yuzbasioglu
"""
from KMeans import KMeans, generate_data
# Training data generation
sample_count_per_class = 200 # number of data samples for each cluster
training_data = generate_data(sample_count_per_class) # generate data using a function
# Create kMeans clustering object
k_means = KMeans(cluster_count=5, max_iteration=7)
# Perform kMeans clustering training, i.e, find and plot cluster centers
k_means.fit(training_data) |
# Uses python3
import sys
def fibonacci_partial_sum_naive(from_, to):
sum = 0
current = 0
next = 1
for i in range(to + 1):
if i >= from_:
sum += current
current, next = next, current + next
return sum % 10
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum%10
def get_fibonacci_fast(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current
def find_pisano_period_occurence(mod_list):
found_occurence_counter = 0
for index in range(2,len(mod_list)):
found_occurence_counter = found_occurence_counter + 1
if mod_list[index] == 0:
if mod_list[index+1] == 1 and mod_list[index+2] == 2:
break
if found_occurence_counter == len(mod_list) - 2:
return 0
else:
return index
def fibonacci_partial_sum_fast(from_, to, occurence):
sum = 0
from_num = from_%occurence
to_num = to%occurence
for i in range(from_num, to_num+1):
sum = sum + fib_list[i]
return sum%10
if __name__ == '__main__':
input = sys.stdin.read();
from_, to = map(int, input.split())
mod_list = list()
fib_list = list()
for i in range(0,63):
mod_list.append(fibonacci_sum_naive(i))
fib_list.append(get_fibonacci_fast(i))
occurence = find_pisano_period_occurence(mod_list)
print(fibonacci_partial_sum_fast(from_, to, occurence)) |
# Uses python3
def calc_fib(n):
if (n <= 1):
return n
return calc_fib(n - 1) + calc_fib(n - 2)
def get_fibonacci_fast(n):
if n <= 1:
return n
previous = 0
current = 1
for _ in range(n - 1):
previous, current = current, previous + current
return current
if __name__ == "__main__":
n = int(input())
print(get_fibonacci_fast(n)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 5 11:34:31 2019
@author: DFSCHMIDT
"""
import numpy as np
import math
from scipy.special import ellipkinc, ellipeinc
from numpy.random import random_sample as rand
def create_ellipsoid(ellipsoid, npoints=1000):
"""
Create ellipsoid with a, b and c as half-axes and
npoints the number of points (has to be an integer)
return an array with shape (npoints, 3)
"""
# create an array of zeros from size npoints x 3
points = np.zeros((npoints, 3))
# create a vector of npoints angles theta ]0;2pi]
theta = rand(npoints)*2.*np.pi
# create a vector of npoints angles phi ]0;pi]
phi = rand(npoints)*np.pi
a = ellipsoid['a']
b = ellipsoid['b']
c = ellipsoid['c']
points[:, 0] = a*np.cos(theta)*np.sin(phi) # x
points[:, 1] = b*np.sin(theta)*np.sin(phi) # y
points[:, 2] = c*np.cos(phi) # z
return points
def ellipsoid_area(ellipsoid):
"""
Compute the surface of a define ellipsoid with its half-axes (a, b, c)
"""
c, b, a = sorted([ellipsoid['a'], ellipsoid['b'], ellipsoid['c']])
if a == b == c:
area = 4*np.pi*a**2
else:
phi = np.arccos(c/a)
m = (a**2 * (b**2 - c**2)) / (b**2 * (a**2 - c**2))
temp = ellipeinc(phi, m)*np.sin(phi)**2 + ellipkinc(phi, m)*np.cos(phi)**2
area = 2*np.pi*(c**2 + a*b*temp/np.sin(phi))
return area
def mid_ellipsoid(bounding_ellipsoid, included_ellipsoid):
"""
Compute the middle ellipsoid
It is the average ellipsoid between the bounding one and the included one
"""
a = (bounding_ellipsoid['a'] + included_ellipsoid['a'])/2.
b = (bounding_ellipsoid['b'] + included_ellipsoid['b'])/2.
c = (bounding_ellipsoid['c'] + included_ellipsoid['c'])/2.
volume = 4./3.*np.pi*a*b*c
return {'volume': volume,
'a': a,
'b': b,
'c': c}
def add_noise(points, amplitude):
"""
Add noise to a 3D array with a given amplitude
"""
# collects the number of points from the points array in create_sphere
npoints = points.shape[0]
# create an array of npoints x 3
# with floats btw ]-1;0] multiplied by an amplitude
dX = (rand((npoints, 3)) - 1.)*amplitude
points += dX # add noise to points
return
def compute_center(points):
"""
Compute center of a cloud of points (3D array expected)
"""
center = np.average(points, axis=0)
return center
def unit_vector(vector):
"""
Returns the unit vector of the vector.
"""
return vector / np.linalg.norm(vector)
def angle_between(v1, v2):
"""
Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
def angle_between_2D(v1, v2):
"""
Returns the angle [0, 2pi[ in radians between 2D vectors 'v1' and 'v2'::
>>> angle_between((1, 0), (0, 1))
1.5707963267948966
"""
dot = v1[0]*v2[0] + v1[1]*v2[1] # dot product between [x1, y1] and [x2, y2]
det = v1[0]*v2[1] - v1[1]*v2[0] # determinant
angle = np.arctan2(det, dot) # atan2(y, x) or atan2(sin, cos)
if angle < 0. :
angle += 2.*np.pi
return angle
def angle_between_3D_inplane(v1, v2, vn):
"""
Returns the angle in radians between 3D vectors 'v1' and 'v2'
in a known plane with normal unit (to be normalized if not!) vector vn::
>>> angle_between((1, 0), (0, 1))
1.5707963267948966
"""
dot = v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2] # dot product
det = v1[0]*v2[1]*vn[2] + v2[0]*vn[1]*v1[2] + vn[0]*v1[1]*v2[2] - v1[2]*v2[1]*vn[0] - v2[2]*vn[1]*v1[0] - vn[2]*v1[1]*v2[0] # determinant
angle = math.atan2(det, dot) # atan2(y, x) or atan2(sin, cos)
return angle
def rotation(angles, order='xy'):
""""
Compute rotation array with theta angle rotating along the x axis
and phi rotating along the y axis
Order is 'xy' = rotation along x first and then along y,
or 'yx' = rotation along y first and then along x
"""
theta, phi = angles
Rx = [[1, 0, 0], [0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]]
Ry = [[np.cos(phi), 0, -np.sin(phi)], [0, 1, 0],
[np.sin(phi), 0, np.cos(phi)]]
if order == 'xy':
M = np.dot(Rx, Ry)
elif order == 'yx':
M = np.dot(Ry, Rx)
return M
def rotate_aggregate(coords, mat=None, angles=None, **kwargs):
"""
Apply a rotation onto an aggregate
"""
if mat is None:
if angles is None:
raise RuntimeError('Need angles or matrix to rotate')
mat = rotation(angles, **kwargs)
coords_rot = np.dot(coords, mat)
return coords_rot
|
# -*- coding: utf-8 -*-
import os
import threading
from abc import abstractmethod, ABCMeta
__author__ = "Romain Mormont <[email protected]>"
__version__ = "0.1"
class Logger(object):
"""A base class loggers. A logger is an object which print or not the messages it is passed according to
the verbosity level. Base class are responsible for defining the printing policy.
"""
SILENT = 0
ERROR = 1
WARNING = 2
INFO = 3
DEBUG = 4
def __init__(self, level, prefix=True, pid=True):
"""Build a logger object with the given level of verbosity
Parameters
----------
level: int
Verbosity level
prefix: boolean:
True for displaying the prefix, false otherwise
pid: boolean
True for displaying the pid in the prefix, false for the tid
"""
self._level = level
self._prefix = prefix
self._pid = pid
@property
def level(self):
return self._level
@level.setter
def level(self, level):
self._level = level
def d(self, msg):
"""Alias for self.debug
Parameters
----------
msg: string
The message to log
"""
self.debug(msg)
def debug(self, msg):
"""Logs a information message if the level of verbosity is above or equal DEBUG
Parameters
----------
msg: string
The message to log
"""
self._log(Logger.DEBUG, msg)
def i(self, msg):
"""Alias for self.info
Parameters
----------
msg: string
The message to log
"""
self.info(msg)
def info(self, msg):
"""Logs a information message if the level of verbosity is above or equal INFO
Parameters
----------
msg: string
The message to log
"""
self._log(Logger.INFO, msg)
def w(self, msg):
"""Alias for self.warning
Parameters
----------
msg: string
The message to log
"""
self.warning(msg)
def warning(self, msg):
"""Logs a information message if the level of verbosity is above or equal WARNING
Parameters
----------
msg: string
The message to log
"""
self._log(Logger.WARNING, msg)
def e(self, msg):
"""Alias for self.error
Parameters
----------
msg: string
The message to log
"""
self.error(msg)
def error(self, msg):
"""Logs a information message if the level of verbosity is above or equal ERROR
Parameters
----------
msg: string
The message to log
"""
self._log(Logger.ERROR, msg)
def _log(self, level, msg):
"""Check the verbosity level, if it is above, actually prints the message
Parameters
----------
level: int
Verbosity level of the message
msg: string
The message
"""
if self._level >= level:
formatted = self._format_msg(level, msg)
self._print(formatted)
@abstractmethod
def _print(self, formatted_msg):
pass
def prefix(self, level):
from datetime import datetime
now = datetime.now().isoformat()
if self._pid:
pid = "{}".format(os.getpid()).zfill(6)
fid = "pid:{}".format(pid)
else:
tid = "{}".format(threading.current_thread().ident).zfill(6)
fid = "tid:{}".format(tid)
return "[{}][{}][{}]".format(fid, now, self.level2str(level))
@classmethod
def level2str(cls, level):
if level == cls.DEBUG:
return "DEBUG"
elif level == cls.WARNING:
return "WARN "
elif level == cls.ERROR:
return "ERROR"
else: # info
return "INFO "
def _format_msg(self, level, msg):
if self._prefix:
rows = ["{} {}".format(self.prefix(level), row) for row in msg.splitlines()]
return os.linesep.join(rows)
else:
return msg
class StandardOutputLogger(Logger):
"""A logger printing the messages on the standard output
"""
def _print(self, formatted_msg):
print (formatted_msg)
class FileLogger(Logger):
"""A logger printing the messages into a file
"""
def __init__(self, filepath, level, prefix=True):
"""Create a FileLogger
Parameters
----------
filepath: string
Path to the logging file
level: int
Verbosity level
prefix: bool
True for adding a prefix for the logger
"""
Logger.__init__(self, level, prefix=prefix)
self._file = open(filepath, "w+")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def _print(self, formatted_msg):
self._file.write(formatted_msg)
def close(self):
"""Close the logging file
"""
self._file.close()
class SilentLogger(Logger):
"""A logger that ignore messages
"""
def __init__(self, prefix=True):
Logger.__init__(self, Logger.SILENT, prefix=prefix)
def _print(self, formatted_msg):
pass
class Loggable(object):
"""A base class to be implemented by any component that can produce logs through a logger.
By default the logger object is set with a SilentLogger.
"""
__metaclass__ = ABCMeta
def __init__(self, logger=SilentLogger()):
self._logger = logger
@property
def logger(self):
"""Get the logger of the loggable object
Returns
-------
logger: Logger
The logger object
"""
return self._logger
@logger.setter
def logger(self, logger):
"""Set the logger of the loggable object
Parameters
----------
logger: Logger
The logger object to set
"""
self._logger = logger
|
nota1=float(input("Digite a primeira nota do aluno: "))
nota2=float(input("Digite a segunda nota do aluno: "))
media=(nota1+nota2)/2
print("A média entre {:.2f} e {:.2f} é: {:.2f}".format(nota1,nota2,media)) |
print(-=-*20)
print("Analisador de Triangulos")
print(-=-*20)
primeiro= float(input("Primeiro Segmento: "))
segundo= float(input("Segundo Segmento: "))
terceiro= float(input("Terceiro Segmento: "))
if primeiro< segundo + terceiro and segundo< primeiro + terceiro and terceiro< primeiro+segundo:
print("Os segmentos podem formar um triangulo!")
else:
print("Os segmentos não podem formar um triangulo!") |
num = int(input("Primeiro valor: "))
num2 = int(input("Segundo valor: "))
if num > num2:
print("O primeiro valor é maior")
elif num < num2:
print("O segundo valor é maior")
elif num == num2:
print("Não existe valor maior, os dois são iguais") |
print("="*15)
print("10 TERMOS DE UMA PA")
print("="*15)
termo1 = int(input("Primeiro termo: "))
razao = int(input("Razão: "))
decimo= termo1+(10-1)*razao
count = 1
while count <=10:
print("{}".format(termo1), end= ' -> ')
termo1 += razao
count +=1
print("ACABOU") |
def sum_square_even_root_odd(nums):
list=[]
for num in nums:
if num%2==0:
list.append(num**2)
else:
list.append(num**0.5)
return round(sum(list),2) |
nota1= float(input("Primeira nota: "))
nota2= float(input("Segunda nota: "))
media = (nota1+nota2)/2
print("Tirando {} e {}, a média do aluno é {}".format(nota1,nota2,media))
if media<5.0:
print("O aluno está REPROVADO")
elif media>=5.0 and media<6.9:
print("O aluno está em RECUPERAÇÃO")
elif media>=7.0:
print("O aluno está APROVADO")
|
numero = int(input("Digite um número"))
unidade= numero % 10
dezena = numero // 10 % 10
centena = numero // 100 % 10
milhar = numero // 1000 % 10
print("Unidade: {}".format(unidade))
print("Dezena: {}".format(dezena))
print("Centena: {}".format(centena))
print("Milhar: {}".format(milhar)) |
'''Exercício Python 055: Faça um programa que leia o peso de cinco pessoas. No final,
mostre qual foi o maior e o menor peso lidos.'''
lista=[]
for i in range (0,5):
lista.append(float(input("Digite o peso: ")))
print("O menor peso lido foi {}".format(min(lista)))
print("O menor peso lido foi {}".format(max(lista))) |
'''Exercício Python 064: Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.
No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).'''
num = int(input("Digite um número ou [999] para parar"))
lista = []
while(num!=999):
lista.append(num)
num = int(input("Digite um número ou [999] para parar"))
print("Você digitou {} números, e a soma deles é {} ".format(len(lista),sum(lista))) |
import time
import random
def jogada(jogador):
if jogador == 0:
return "pedra"
elif jogador == 1:
return "papel"
elif jogador ==3:
return"tesoura"
print('Suas opções:')
print("[0] PEDRA")
print("[1] PAPEL")
print("[2] TESOURA")
jogador = int(input("Qual é a sua jogada?"))
computador = random.randint(0,2)
print("JO")
time.sleep(1)
print("KEN")
time.sleep(1)
print("PO!!!")
time.sleep(1)
jogador = jogada(jogador)
computador = jogada(computador)
print("-=-"*5)
print("Computador jogou {}".format(computador))
print("Jogador jogou {}".format(jogador))
print("-=-"*5)
if jogador == "pedra" and computador == "tesoura":
print("Jogador ganhou")
elif jogador == "pedra" and computador =="papel":
print("Computador ganhou")
elif jogador == "pedra"and computador =="pedra":
print("Empate")
elif jogador == "papel" and computador == "papel":
print("Empatou")
elif jogador == "papel" and computador == "pedra":
print("Jogador ganhou")
elif jogador =='papel' and computador == "tesoura":
print("Computador ganhou")
elif jogador =="pedra" and computador == "pedra":
print("Empatou")
elif jogador == "pedra" and computador == "tesoura":
print("Jogador ganhou")
elif jogador =='pedra' and computador == "papel":
print("Computador ganhou")
|
print("="*15)
print("10 TERMOS DE UMA PA")
print("="*15)
termo1 = int(input("Primeiro termo: "))
razao = int(input("Razão: "))
decimo= termo1+(10-1)*razao
for i in range(termo1,decimo,razao):
print("{}".format(i), end= ' -> ')
print("ACABOU") |
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(7, 14)))
print("Şifreniz Bu;")
print("Your password is here;")
print(password) |
def MaxLenList(array, unique_array=[], final_array=[]):
unique_array = list(set(map(lambda x : x[0], array)))
final_array = sorted([max(filter(lambda x : i in x, array)) for i in unique_array])
return [(i,len(i)) for i in final_array]
array = ["aa", "bbbb", "b", "ffffff", "fff", "wwwwwwww", "wwww"]
print(MaxLenList(array))
|
'''
2019年6月26日21:14:42
通过这个 pyqt5 工程来学习 pyqt5
顺便作为未来写工程时候的参考
https://github.com/maicss/PyQt5-Chinese-tutorial/blob/master/hello_world.md
这里面的教程很棒,很感谢
'''
'''
In this example, we create a simple
window in PyQt5.
'''
# sys模块包含了与Python解释器和它的环境有关的函数
# 这里引入了PyQt5.QtWidgets模块,这个模块包含了基本的组件
import sys
from PyQt5.QtWidgets import QApplication, QWidget
# 一个python的文件有两种使用的方法,第一是直接作为脚本执行,第二是import到其他的python脚本中被调用(模块重用)执行。
# 因此if __name__ == 'main': 的作用就是控制这两种情况执行代码的过程,
# 在if __name__ == 'main': 下的代码只有在第一种情况下(即文件作为脚本直接执行)才会被执行,而import到其他脚本中是不会被执行的。
if __name__ == '__main__':
# 每个PyQt5应用都必须创建一个应用对象。sys.argv是一组命令行参数的列表。Python可以在shell里运行,这个参数提供对脚本控制的功能。
app = QApplication(sys.argv)
# QWidge控件是一个用户界面的基本控件,它提供了基本的应用构造器。默认情况下,构造器是没有父级的,没有父级的构造器被称为窗口(window)
w = QWidget()
# resize()方法能改变控件的大小,这里的意思是窗口宽250px,高150px
w.resize(250, 150)
# move()是修改控件位置的的方法。它把控件放置到屏幕坐标的(300, 300)的位置。注:屏幕坐标系的原点是屏幕的左上角
w.move(300, 300)
# 给这个窗口添加了一个标题,标题在标题栏展示(虽然这看起来是一句废话,但是后面还有各种栏,还是要注意一下,多了就蒙了)
w.setWindowTitle('Simple')
w.show()
# 最后,我们进入了应用的主循环中,事件处理器这个时候开始工作。主循环从窗口上接收事件,并把事件传入到派发到应用控件里。
# 当调用exit()方法或直接销毁主控件时,主循环就会结束。sys.exit()方法能确保主循环安全退出。外部环境能通知主控件怎么结束。
# exec_()之所以有个下划线,是因为exec是一个Python的关键字
# app.exec_()是指程序一直循环运行直到主窗口被关闭终止进程(如果没有这句话,程序运行时会一闪而过)
sys.exit(app.exec_()) |
def countPrimes(t):
# '''
# 1부터 t까지의 수 중에서 소수의 개수를 반환합니다.
# '''
testArr = [1]*(t+1)
testArr[0],testArr[1] = 0,0
count = 0
for i in range(2, t+1):
# print("this is testArr[",i,"]:",testArr[i])
if testArr[i] == 1:
j = 2
count = count + 1
while i*j <= t:
testArr[i*j] = 0
j = j+1
return count
def main():
# '''
# 이 부분은 수정하지 마세요.
# '''
t = int(input())
print(countPrimes(t))
if __name__ == "__main__":
main()
|
from datetime import datetime
from elasticsearch import Elasticsearch
from typing import List
import json
document_text = """The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit’s UI will ask if you’d like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you’re happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code."""
es = Elasticsearch()
def search_es(search_query, search_text) -> List[str]:
doc = {
'id': '2',
'content': search_text
}
res = es.index(index="test-offset", id=2, body=doc)
print(res['result'])
es.indices.refresh(index="test-offset")
es_query = """{
"query": {
"query_string": {
"query": "%s"
}
},
"highlight": {
"fields": {
"content": {
"type": "offset"
}
},
"fragment_size": 50
}
}""" % (search_query)
res = es.search(index="test-offset", body=json.loads(es_query))
print("Got %d Hits:" % res['hits']['total']['value'])
snippets = []
for hit in res['hits']['hits']:
for snippet in hit["highlight"]["content"]:
snippets.append(snippet)
return snippets
print(search_es('the', document_text))
|
Keys = []
shuffle_arr = [[]]
reduct_arr = [[]]
def map(filename,filepath):
A = []
f = open(filename,"r")
lines = f.read().split('\n')
for line in lines:
A.append((line, 1))
return A
def shuffle(lines):
for w in lines:
key, val = w
if not Keys.__contains__(key):
Keys.append(key)
shuffle_arr.append([])
i = Keys.index(key)
shuffle_arr[i].append((key, val))
b = 3
def reduce():
i = 0
shuffle_arr.remove(shuffle_arr[len(shuffle_arr) - 1])
for entry in shuffle_arr:
amount = 0
key, num = entry[0]
for e in entry:
amount += 1
reduct_arr.append([])
reduct_arr[i].append((key, amount))
i += 1
if __name__ == "__main__":
fruit = map("fruit.txt", '')
basket = map("basket.txt", '')
shuffle(fruit)
shuffle(fruit)
reduce()
print('------- SHUFFLE -------')
for ent in shuffle_arr:
for entr in ent:
key, value = entr
print(str(key) + ' ' + str(value))
print(' ')
print('------- REDUCTION -------')
for ent in reduct_arr:
for entr in ent:
key, value = entr
print(str(key) + ' ' + str(value))
print() |
from math import *
class X:
def __init__(self, x, y):
self.x = x
self.y = y
class Y:
def __init__(self, z):
self.z = z
objX = X(-4.5, 0.75*10**(-4))
objY = Y(0.845*10**2)
def show(X, Y):
print(' x = ', X.x,'\n', 'y = ', X.y,'\n', 'z = ', Y.z,'\n')
show(objX, objY)
def solution(X, Y):
print(((8 + abs(X.x - X.y) ** 2 + 1) ** (1 / 3) / (X.x ** 2 + X.y ** 2 + 2)) - exp(abs(X.x - X.y)) * (tan(Y.z) ** 2 + 1) ** X.x)
solution(objX, objY)
|
"""
Utility functions to deal with vectors in n-dimensional space.
"""
import numpy as np
# Utility functions
def hstack(v, n):
"""Return array with vector v in each of the n columns"""
return np.kron(np.ones((n, 1)), v).T
def row_product(vec, arr):
"""
Multiply the rows of `array` by the elements of `vector`.
Parameters
----------
array : array-like
N-vector
matrix : array-like
Nx... matrix
Returns
-------
out : array-like
Nx... matrix whose rows are those of `array`, scaled by the
corresponding entries in `vector`.
"""
# return np.einsum('a...,a... -> a...', vector, array)
vec = np.array(vec)
arr = np.array(arr)
return vec[:, np.newaxis]*arr
# Linear algebra
def is_float_equal(v1, v2, tol=1e-7):
"Equality of floating point vectors."
return (np.abs(v1 - v2) < tol).all()
def normalize(array):
"""Normalize rows of array to unit length. Array can be real or complex."""
norms = np.sqrt(np.sum(array*array.conjugate(), axis=1))
return array/hstack(norms, array.shape[1])
# Random vectors and matrices
def random_vector(length, iscomplex=False):
"""Return a random vector of a given length.
INPUT:
-- ``length`` - length of the random vector.
-- ``iscomplex`` (default `False`) - whether to return a complex vector.
"""
size = (1, length)
return random_array(size, iscomplex)[0]
def random_array(size, iscomplex=False):
"""Return a random matrix of a given length.
INPUT:
-- ``size`` - tuple containing size of the array.
-- ``iscomplex`` (default `False`) - whether to return a complex array.
"""
A = np.random.rand(*size)
if iscomplex: A = A + 1j*np.random.rand(*size)
return A
|
# Name: Janae Dorsey
# File: bumper.py
#
# Purpose: This program will create a simulation with two "cars" that change direction when they collide or when they
# hit a wall.
#
# Certification of Authenticity:
# I certify that this lab is entirely my own work.
from graphics import *
from random import randint
import math
from time import sleep
#returns a random integer in the range[-move_amount, +move_amont]
def get_random(move_amount):
return randint(-move_amount, move_amount)
#returns boolean based on the collision of the two balls and changes color of balls upon collision
def did_collide(car1, car2):
distance = math.sqrt((car2.getCenter().getX()-car1.getCenter().getX())**2 + (car2.getCenter().getY()-car1.getCenter().getY())**2)
if distance <= sum([car1.getRadius(),car2.getRadius()]):
random_color(car1)
random_color(car2)
return True
else:
return False
#returns boolean based on the ball hitting a vertical wall and changes color if so
def hit_vertical(car, width):
if car.getCenter().getX() <= car.getRadius() or car.getCenter().getX() >= width - car.getRadius():
random_color(car)
return True
else:
return False
#returns boolean based on the ball hitting a horizontal wall and changes color if so
def hit_horizontal(car, height):
if car.getCenter().getY() <= car.getRadius() or car.getCenter().getY() >= height - car.getRadius():
random_color(car)
return True
else:
return False
#returns a random color
def random_color(car):
car.setFill(color_rgb(randint(0, 255), randint(0, 255), randint(0, 255)))
car.setFill(color_rgb(randint(0, 255), randint(0, 255), randint(0, 255)))
def main():
#assigns dimensions of windown
width, height = 500, 500
#creates window
win = GraphWin("Joyride Bumper Cars", width, height)
#draws first circle with random starting positon, color, and velocity
car1 = Circle(Point(randint(35, 280), randint(35, 280)), 35)
car1.draw(win)
random_color(car1)
x1_vel = get_random(15)
y1_vel = get_random(15)
#draws second circle with random starting position, color, and velocity
car2 = Circle(Point(randint(35, 280), randint(35, 280)), 35)
car2.draw(win)
random_color(car2)
x2_vel = get_random(20)
y2_vel = get_random(20)
#creates loop for the movement of the cars
for i in range(1000):
#moves cars
sleep(.03)
car1.move(x1_vel, y1_vel)
car2.move(x2_vel, y2_vel)
#tests if balls collides and changes their directions if so
if did_collide(car1, car2):
x1_vel = -(x1_vel)
y1_vel = -(y1_vel)
x2_vel = -(x2_vel)
y2_vel = -(y2_vel)
#tests if first ball hits horizontal wall and changes its direction if so
if hit_horizontal(car1, width):
y1_vel = -(y1_vel)
#tests if second ball hits horizontal wall and changes its direction if so
if hit_horizontal(car2, width):
y2_vel = -(y2_vel)
#tests if first ball hits vertical wall and changes its direction if so
if hit_vertical(car1, height):
x1_vel = -(x1_vel)
#tests if second ball hits vertical wall and changes its direction if so
if hit_vertical(car2, height):
x2_vel = -(x2_vel)
main()
|
# -*- coding:utf-8 -*-
def gradient(x,y):
theart0 = 0
theart1 = 0
# learning rate define 0.5
learningRate = 0.01
for i in range(100000):
sum0 = 0
sum1 = 0
for j in range(len(x)):
print(len(x))
sum0 += theart0 + theart1*x[j] - y[j] #从1加到m
print(sum0)
sum1 += (theart0 + theart1 * x[j] - y[j])*x[j] # 从1加到m
print(sum1)
temp0 = theart0 - learningRate*(1/len(x))*sum0
print(temp0)
temp1 = theart1 - learningRate*(1/len(x))*sum1
print(temp1)
theart0 = temp0
theart1 = temp1
return theart1,theart0
if __name__ == '__main__':
x = [1,2,2,3,3,4,5,6,6,6,8,10]
y = [-890,-1411,-1560,-2220,-2091,-2878,-3537,-3268,-3920,-4163,-5471,-5157]
print(gradient(x,y)) |
import pandas as pd
import operator
# Read the dataframe
df = pd.read_csv('statistics.csv')
# Same values, excluding the values for unrecognised files
df_filtered = df.loc[df['Predicted sentence'] != "unknownvalueerror"]
# WER calculation
#~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("WER calculation")
print("~" * 30)
#mean cijelog stupca
WER_mean = df["WER from jiwer"].mean()
print("Mean WER:", WER_mean)
# Get rows with maximum WER
print("Maximum WER")
max_WER_rows = df.loc[df['WER from jiwer'].idxmax()]
print("Correct: ", max_WER_rows["Corrected sentence"], " Predicted: ", max_WER_rows["Predicted sentence"])
# Get rows with minimum WER
print("Minimum WER")
min_WER_rows = df.loc[df['WER from jiwer'].idxmin()]
print("Correct: ", min_WER_rows["Corrected sentence"], " Predicted: ", min_WER_rows["Predicted sentence"])
# WER calculation without the unrecognised files
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("WER calculation without the unrecognised files")
print("~" * 30)
WER_mean = df_filtered["WER from jiwer"].mean()
print("Mean WER:", WER_mean)
# Get rows with maximum WER
print("Maximum WER")
max_WER_rows = df_filtered.loc[df_filtered['WER from jiwer'].idxmax()]
print("Correct: ", max_WER_rows["Corrected sentence"], " Predicted: ", max_WER_rows["Predicted sentence"])
# Get rows with minimum WER
print("Minimum WER")
min_WER_rows = df_filtered.loc[df_filtered['WER from jiwer'].idxmin()]
print("Correct: ", min_WER_rows["Corrected sentence"], " Predicted: ", min_WER_rows["Predicted sentence"])
print("~" * 30) #end of section
# MER calculation
#~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("MER calculation")
print("~" * 30)
MER_mean = df["MER from jiwer"].mean()
print("Mean MER:", MER_mean)
# Get rows with maximum WER
print("Maximum MER")
max_MER_rows = df.loc[df["MER from jiwer"].idxmax()]
print("Correct: ", max_MER_rows["Corrected sentence"], " Predicted: ", max_MER_rows["Predicted sentence"])
# Get rows with minimum WER
print("Minimum MER")
min_MER_rows = df.loc[df["MER from jiwer"].idxmin()]
print("Correct: ", min_MER_rows["Corrected sentence"], " Predicted: ", min_MER_rows["Predicted sentence"])
# MER calculation without the unrecognised files
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("MER calculation without the unrecognised files")
print("~" * 30)
MER_mean = df_filtered["MER from jiwer"].mean()
print("MeanMER:", MER_mean)
# Get rows with maximum WER
print("Maximum MER")
max_MER_rows = df_filtered.loc[df_filtered['MER from jiwer'].idxmax()]
print("Correct: ", max_MER_rows["Corrected sentence"], " Predicted: ", max_MER_rows["Predicted sentence"])
# Get rows with minimum WER
print("Minimum WER")
min_MER_rows = df_filtered.loc[df_filtered['MER from jiwer'].idxmin()]
print("Correct: ", min_MER_rows["Corrected sentence"], " Predicted: ", min_MER_rows["Predicted sentence"])
# TODO: find rows with maximum and minimum MER
print("~" * 30) #end of section
# WIL calculation
#~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("WIL calculation")
print("~" * 30)
WIL_mean = df["WIL from jiwer"].mean()
print("Mean WIL:", WIL_mean)
# Get rows with maximum WILL
print("Maximum WIL")
max_WIL_rows = df.loc[df["WIL from jiwer"].idxmax()]
print("Correct: ", max_WIL_rows["Corrected sentence"], " Predicted: ", max_WIL_rows["Predicted sentence"])
# Get rows with minimum WILL
print("Minimum WIL")
min_WIL_rows = df.loc[df["WIL from jiwer"].idxmin()]
print("Correct: ", min_WIL_rows["Corrected sentence"], " Predicted: ", min_WIL_rows["Predicted sentence"])
# WILL calculation without the unrecognised files
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print("\n" + "~" * 30)
print("WILL calculation without the unrecognised files")
print("~" * 30)
WIL_mean = df_filtered["WIL from jiwer"].mean()
print("MeanWIL:", WIL_mean)
# Get rows with maximum WILL
print("Maximum WIL")
max_WIL_rows = df_filtered.loc[df_filtered['WIL from jiwer'].idxmax()]
print("Correct: ", max_WIL_rows["Corrected sentence"], " Predicted: ", max_WIL_rows["Predicted sentence"])
# Get rows with minimum WILL
print("Minimum WIL")
min_WIL_rows = df_filtered.loc[df_filtered['WIL from jiwer'].idxmin()]
print("Correct: ", min_WIL_rows["Corrected sentence"], " Predicted: ", min_WIL_rows["Predicted sentence"])
# TODO: find rows with maximum and minimum WIL
print("~" * 30) #end of section
# Words statistics
#~~~~~~~~~~~~~~~~~~~
with open("affected_words.txt") as f:
content = f.readlines()
good_words = dict()
swapped_words = dict()
swapped_with = dict()
deleted_words = dict()
inserted_words = dict()
for row in content:
row_splitted = row.split()
state = row_splitted[0]
word = row_splitted[1]
if state == "good":
if word not in good_words:
good_words[word] = 1
else:
good_words[word] += 1
if state == "swap":
word2 = row_splitted[2]
if word not in swapped_words:
swapped_words[word] = 1
swapped_with[word] = [word2]
else:
swapped_words[word] += 1
swapped_with[word].append(word2)
if state == "delete":
if word not in deleted_words:
deleted_words[word] = 1
else:
deleted_words[word] += 1
if state == "insert":
if word not in inserted_words:
inserted_words[word] = 1
else:
inserted_words[word] += 1
print("\n" + "~" * 30)
print("Good")
print("~" * 30)
print("Most common good word:", max(good_words.items(), key=operator.itemgetter(1)))
print("Least common good word:", min(good_words.items(), key=operator.itemgetter(1)))
print("\n" + "~" * 30)
print("Swapped")
print("~" * 30)
most_common_swapped = max(swapped_words.items(), key=operator.itemgetter(1))
print("Most common swapped word:", most_common_swapped)
print("Was swapped with", swapped_with[most_common_swapped[0]])
least_common_swapped = min(swapped_words.items(), key=operator.itemgetter(1))
print("Least common swapped word:", least_common_swapped)
print("Was swapped with", swapped_with[least_common_swapped[0]])
print("\n" + "~" * 30)
print("Deleted")
print("~" * 30)
print("Most common deleted word:", max(deleted_words.items(), key=operator.itemgetter(1)))
print("Least common deleted word:", min(deleted_words.items(), key=operator.itemgetter(1)))
print("\n" + "~" * 30)
print("Inserted")
print("~" * 30)
print("Most common inserted word:", max(inserted_words.items(), key=operator.itemgetter(1)))
print("Least common inserted word:", min(inserted_words.items(), key=operator.itemgetter(1)))
|
def Pivot(arr,low,high):
pi = arr[high]
index = low - 1
for j_index in range(low,high):
if arr[j_index] < pi:
index = index + 1
arr[index], arr[j_index] = arr[j_index],arr[index]
arr[index + 1],arr[high] = arr[high],arr[index + 1]
return index + 1
def Quick_Sort(arr,low,high):
if low < high:
pivot = Pivot(arr,low,high)
Quick_Sort(arr,low,pivot-1)
Quick_Sort(arr,pivot+1,high)
return arr
|
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def getName(self):
return self.firstname + " " + self.lastname
def __str__(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self, first, last)
self.staffnumber = staffnum
def getEmployee(self):
return self.getName() + ", " + self.staffnumber
def __str__(self):
return Person.__str__(self) + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
print(x.getName)
print(y.getEmployee)
print(x)
print(y)
|
# numbers=(10, 2, 3, 4, 5, 6)
# print(any(numbers))
# print(max(numbers))
# print(min(numbers))
# print(len(numbers))
# print("sorted:")
# print(sorted(numbers))
# print("sum:")
# print(sum(numbers))
# n=(10, 4, 3, 8, 5, 6)
# print("kortejni max", max(n))
# print("kortejni min", min(n))
# print(max(n)+min(n))
# n=(10, 4, 3, 8, 5, 6)
# print("kortejni sum", sum(n))
# print("kortejni len", len(n))
# print(sum(n)/len(n))
# 2-usul
# n=(10, 4, 3, 8, 5, 6)
# urta_arifmetik=sum(n)/len(n)
# print(urta_arifmetik)
# 3-usul
# n=(10, 4, 3, 8, 5, 6)
# i=0
# Summa=0
# for number in n:
# i+=1
# Summa+=number
# urta_arifmetik=Summa/i
# print(urta_arifmetik)
#
#
# a=(1, 4, 10, 6, 7)
# print(a[0::2])
# print(a[1::2])
# 4-masala avval juft o'rindagilarini keyin toq o'rindagilarini chiqarish
# a=(1, 4, 10, 6, 7)
# juft=[]
# toq=[]
# for i in range(len(a)):
# if (i+1)%2==0:
# juft.append(a[i])
# else:
# toq.append(a[i])
# print(juft)
# print(toq)
# 5-masala kortejni toq indeksli elementlarini kvadratini chiqaruvchi dastur tuzing
# a = (1, 2, 3, 4, 5, 6) # (1, 6, 2, 5, 3, 4) bu faqat juft sonli uchun
# b = list(a)
# c = []
# for i in range(len(b)):
# c.append(b[0])
# c.append(b[-1])
# b.pop(0)
# b.pop(-1)
# if not b:
# break
# a = tuple(c)
# print(a)
# maxsus masala 2
# a = (1, 2, 3, 4, 5, 6, 7, 8)
# b = list(a)
# c = []
# for i in range(len(b)):
# c.append(b[0])
# if b[0] == b[-1]:
# break
# c.append(b[-1])
# b.pop(0)
# b.pop(-1)
# if not b:
# break
# a = tuple(c)
# print(a)
# Maxsus masala
a=(1,2,3,4,5,6,8)
b=list(a)
mk=[]
k=len(b)-1
for i in range(len(b)//2):
mk.append(b[i])
mk.append(b[k])
k-=1
print(mk)
|
# Дано 3 числа. Визначити чи всі числа непарні. Числа вводяться з клавіатури
def check(digit):
if digit % 2 != 0:
print(digit, " is odd.")
else:
print(digit, " is even.")
first = int(input("Enter first digit: "))
second = int(input("Enter second digit: "))
third = int(input("Enter third digit: "))
check(first)
check(second)
check(third)
# Дано три числа. Якщо перше число більше третього, то поміняти іх місцями.
if first > third:
first, third = third, first
print(first, " ", second, " ", third)
# Відомо, що 1 дюйм дорівнює 2.54 см.
# Розробити програму, що переводить дюйми в сантиметри и навпаки.
# Діалог с користувачем реалізувати через систему меню.
inch = 2.54
print("1. from inches to centimeters\n2. From centimeters to inches")
choise = int(input("Enter your choise: "))
data = float(input("Enter weight: "))
if choise == 1:
print("In ", data, " inches = ")
data *= inch
print(data, " centimeters.")
elif choise == 2:
print("In ", data, " centimeters = ")
data /= inch
print(round(data, 2), " inches.")
#Протягом тижня вимірювали температуру повітря. Знайти кількість днів, коли температура перевищувала 10o С
counter = 0
for item in range(8):
day_temperature = float(input("Enter temperature for day: "))
if day_temperature > 10:
counter += 1
print("the temperature exceeded 10 degrees ", counter, " times this week") |
import math
import argparse
import sys
# credit_principal = 'Credit principal: 1000'
# final_output = 'The credit has been repaid!'
# first_month = 'Month 1: paid out 250'
# second_month = 'Month 2: paid out 250'
# third_month = 'Month 3: paid out 500'
#
# # write your code here
#
# # print(credit_principal)
# # print(first_month)
# # print(second_month)
# # print(third_month)
# # print(final_output)
#
# print('Enter the credit principal:')
# cp = int(input())
# print('What do you want to calculate?')
# print('type "m" - for count of months,')
# print('type "p - for monthly payments:')
# calc = input()
# if calc == 'm':
# print('Enter monthly payment:')
# payment = int(input())
# months = cp / payment
# if months == 1:
# print('It takes 1 month to repay the credit')
# else:
# print('It takes '
# + str(months)
# + ' months to repay the credit')
# else:
# print('Enter count of months:')
# months = int(input())
# if cp % months == 0:
# payment = int(cp / months)
# print('Your monthly payment = '
# + str(payment))
# else:
# payment = int(cp/months + 1)
# last_payment = cp - ((months - 1) * payment)
# print('Your monthly payment = '
# + str(payment)
# + ' with last month payment = '
# + str(last_payment))
#
# i = 0.01
#
#
# def main():
# print('What do you want to calculate?')
# print('type "n" - for count of months,')
# print('type "a" - for annuity monthly payment,')
# print('type "p" - for credit principal:')
# calc = input()
# if calc == 'n':
# number_months()
# elif calc == 'a':
# payment()
# elif calc == 'p':
# credit_principal()
# else:
# main()
# return
#
#
# def credit_principal():
# payment = float(input('Enter monthly payment:'))
# periods = float(input('Enter count of periods:'))
# interest = float(input('Enter credit interest:')) / (12 * 100)
# i_formula = (1 + interest) ** periods
# p = math.ceil(payment / ((interest * i_formula) / (i_formula - 1)))
# print(f'Your credit principal = {p}!')
# return
#
#
# def number_months():
# cp = float(input('Enter credit principal:'))
# payment = float(input('Enter monthly payment:'))
# interest = float(input('Enter credit interest:')) / (12 * 100)
# n = math.ceil(math.log((payment / (payment - interest * cp)), 1 + interest))
# years = math.floor(n / 12)
# months = n % 12
# if n == 1:
# print(f'You need {months} month to repay this credit!')
# elif n < 12:
# print(f'You need {months} months to repay this credit!')
# elif n == 12:
# print(f'You need {years} year to repay this credit!')
# elif n % 12 == 0:
# print(f'You need {years} years to repay this credit!')
# else:
# print(f'You need {years} years and {months} months to repay this credit!')
# return
#
#
# def payment():
# cp = float(input('Enter credit principal:'))
# periods = float(input('Enter count of periods:'))
# interest = float(input('Enter credit interest:')) / (12 * 100)
# i_formula = (1 + interest) ** periods
# a = math.ceil(cp * ((interest * i_formula) / (i_formula - 1)))
# print(f'Your annuity payment = {a}!')
#
# def differentiated_payment():
#
#
#
# main()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--type', type=str, help='annuity or diff.')
parser.add_argument('--payment', type=int, help='refers to the monthly payment.')
parser.add_argument('--principal', type=int, help='refers to the credit principal')
parser.add_argument('--periods', type=int, help='refers to the number of months.')
parser.add_argument('--interest', type=float, help='refers to the interest rate\
without a percentage sign')
args = parser.parse_args()
if len(sys.argv) == 5 and negative([args.payment, args.principal, args.periods,
args.interest]):
if args.type == 'annuity':
if args.payment is None:
monthly_payment(args.principal, args.periods, args.interest)
elif args.principal is None:
credit_principal(args.payment, args.periods, args.interest)
elif args.periods is None:
number_of_months(args.principal, args.payment, args.interest)
else:
'Incorrect parameters'
elif args.type == 'diff':
differentiated_payment(args.principal, args.interest, args.periods)
else:
print('Incorrect parameters')
else:
print('Incorrect parameters')
return
def monthly_payment(cp, periods, interest):
i = nominal_interest(interest)
i_formula = (1 + i) ** periods
a = math.ceil(cp * ((i * i_formula) / (i_formula - 1)))
print(f'Your annuity payment = {a}!')
total = a * periods
overpayment = total - cp
print('\n' + f'Overpayment = {overpayment}')
def credit_principal(payment, periods, interest):
i = nominal_interest(interest)
i_formula = (1 + i) ** periods
p = math.ceil(payment / ((i * i_formula) / (i_formula - 1)))
print(f'Your credit principal = {p}!')
total = payment * periods
overpayment = total - p
print('\n' + f'Overpayment = {overpayment}')
def number_of_months(cp, payment, interest):
i = nominal_interest(interest)
n = math.ceil(math.log((payment / (payment - i * cp)), 1 + i))
years = math.floor(n / 12)
months = n % 12
if n == 1:
print(f'You need {months} month to repay this credit!')
elif n < 12:
print(f'You need {months} months to repay this credit!')
elif n == 12:
print(f'You need {years} year to repay this credit!')
elif n % 12 == 0:
print(f'You need {years} years to repay this credit!')
else:
print(f'You need {years} years and {months} months to repay this credit!')
total = payment * n
overpayment = total - cp
print('\n' + f'Overpayment = {overpayment}')
def differentiated_payment(cp, interest, periods):
i = nominal_interest(interest)
total = 0
for current_period in range(1, periods + 1):
payment = math.ceil((cp / periods) + i
* (cp - ((cp * (current_period - 1)) / periods)))
print(f'Month {current_period}: paid out {payment}')
total = total + payment
overpayment = total - cp
print('\n' + f'Overpayment = {overpayment}')
def nominal_interest(interest):
i = interest / (12 * 100)
return i
def negative(args):
for argument in args:
if argument is not None and argument < 0:
return False
return True
main()
|
import input
def isTargetText(some_text):
uppers = some_text[1:4] + some_text[5:8]
lowers = some_text[0] + some_text[4] + some_text[8]
if uppers.isupper() == True and lowers.islower() == True:
return True
else:
return False
def findInBlock(lots_of_text):
i = 0
results = ''
while i < len(lots_of_text) - 8:
segment = lots_of_text[i:i+9]
if isTargetText(segment) == True:
results += segment[4]
i += 1
return results
text = input.text.replace('\n', '')
print findInBlock(text) |
import input
def calculate_wrapping_paper(l, w, h):
side_1 = l * w
side_2 = w * h
side_3 = l * h
smallest = min(side_1, side_2, side_3)
return 2*side_1 + 2*side_2 + 2*side_3 + smallest
def calculate_ribbon(l, w, h):
dimensions = [l, w, h]
dimensions.sort()
wrap = dimensions[0]*2 + dimensions[1]*2
cubic_feet = l * w * h
return wrap + cubic_feet
def handle_packages(puzzle_input):
wrapping_paper = 0
ribbon = 0
packages = puzzle_input.split('\n')
for package in packages:
dimensions = package.split('x')
l = int(dimensions[0])
w = int(dimensions[1])
h = int(dimensions[2])
wrapping_paper += calculate_wrapping_paper(l, w, h)
ribbon += calculate_ribbon(l, w, h)
return wrapping_paper, ribbon
paper, ribbon = handle_packages(input.puzzle_input)
print(str(paper) + ' square feet of paper')
print(str(ribbon) + ' feet of ribbon')
|
import input
from itertools import permutations
def process_input(puzzle_input):
data = puzzle_input.split('\n')
cities = []
processed = {}
for datum in data:
datum = datum.split(' ')
processed[datum[0] + ' to ' + datum[2]] = int(datum[-1])
if datum[0] not in cities:
cities.append(datum[0])
if datum[2] not in cities:
cities.append(datum[2])
return cities, processed
def calculate_route(route, data):
distance = 0
i = 0
while i < len(route)-1:
departing = route[i]
arriving = route[i+1]
key = departing + ' to ' + arriving
if key in data:
distance += data[key]
else:
distance += data[arriving + ' to ' + departing]
i += 1
return distance
def find_route(cities, data):
options = permutations(cities)
shortest_distance = calculate_route(cities, data)
longest_distance = 0
for option in options:
distance = calculate_route(option, data)
if distance < shortest_distance:
shortest_distance = distance
if distance > longest_distance:
longest_distance = distance
return shortest_distance, longest_distance
cities, processed_input = process_input(input.puzzle_input)
shortest, longest = find_route(cities, processed_input)
print(shortest)
print(longest) |
import csv
import abc
class Calibrator(abc.ABC):
def __init__(self):
self.horizontal = 0
self.depth = 0
def process_input(self, input_file):
with open(input_file) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
instruction = row[0].split()[0]
amount = int(row[0].split()[1])
position = self.adjust_position(instruction, amount)
def adjust_position(self, instruction, amount):
pass
class PositionCalibratorSimple(Calibrator):
def __init__(self):
super().__init__()
def adjust_position(self, instruction, amount):
if instruction == 'up':
self.depth -= amount
elif instruction == 'down':
self.depth += amount
else:
self.horizontal += amount
class PositionCalibratorComplex(Calibrator):
def __init__(self):
super().__init__()
self.aim = 0
def adjust_position(self, instruction, amount):
if instruction == 'up':
self.aim -= amount
elif instruction == 'down':
self.aim += amount
else:
self.horizontal += amount
self.depth += (amount * self.aim)
calibrator = PositionCalibratorSimple()
calibrator.process_input('input.csv')
print('Part 1: {}'.format(calibrator.horizontal * calibrator.depth))
calibrator = PositionCalibratorComplex()
result = calibrator.process_input('input.csv')
print('Part 2: {}'.format(calibrator.horizontal * calibrator.depth))
|
string = input('Enter the word you want to check : ').lower()
reversed_string = string[::-1]
if reversed_string == string :
print('It is a palindrome')
else :
print('It is not a palindrome')
|
def extraLongFactorals(n):
total = n
while n > 1:
total *= n-1
n -= 1
print(total)
return total
if __name__ == "__main__":
extraLongFactorals(25) |
# Starting with traditional Hello World! greet.
print("Hello world!")
#Simple add method
def add(number1,number2):
return number1 + number2
#test input numbers
num1 = 5
num2 = 8
print(F'Add {num1} and {num2}')
print(F'{num1} + {num2} = {add(num1,num2)}')
person1 = {"name": "Pradeep", "age": 36, "gender":"male"}
class Person:
def __init__(this,name,age,gender):
this.name = name
this.age = age
this.gender = gender
def display(this):
print(F'Name :- {this.name}\nAge :- {this.age}\nGender :- {this.gender}\n')
people = [Person("Pradeep", 36,"male"),Person("Sushma", 34,"female"),Person("Tanuj", 6,"male"),Person("Tanay", 6,"male")]
#print(people)
#print(person1)
print(F'Person details \n')
for person in people:
person.display()
#for i in range(0,10,2):
# print(i)
print(type(num1))
print(type("num1"))
print(type(True)) |
def get_rank(string):
"""
Parses a string representing a rank. Returns a string in the correct form
for the lookup table. Returns None if the input could not be parsed.
"""
if "ace" in string or string=="a":
return "A"
if "king" in string or string=="k":
return "K"
if "queen" in string or string=="q":
return "Q"
if "jack" in string or string=="j":
return "J"
if "ten" in string or string=="10" or string=="t":
return "T"
if "nine" in string or string=="9":
return "9"
if "eight" in string or string=="8":
return "8"
if "seven" in string or string=="7":
return "7"
if "six" in string or string=="6":
return "6"
if "five" in string or string=="5":
return "5"
if "four" in string or string=="4":
return "4"
if "three" in string or string=="3":
return "3"
if "two" in string or string=="2":
return "2"
return None
def get_suiting(string):
"""
Parses a string representing the suiting (suited/offsuit) of the player's
two hole cards. Returns True if suited, False if offsuit.
Returns None if the input could not be parsed.
"""
if "of" in string or "un" in string:
# handles offsuit, unsuited, etc.
return False
if "suit" in string:
return True
return None
def get_players(string):
"""
Parses a string representing the number of other players (i.e. excluding
the player) in the round. Currently supports only 1-9 other players.
Returns a string in the correct form for the lookup table.
Returns None if the input could not be parsed.
"""
if "nine" in string or string=="9":
return 9
if "eight" in string or string=="8":
return 8
if "seven" in string or string=="7":
return 7
if "six" in string or string=="6":
return 6
if "five" in string or string=="5":
return 5
if "four" in string or string=="4":
return 4
if "three" in string or string=="3":
return 3
if "two" in string or string=="2":
return 2
if "one" in string or string=="1":
return 1
return None
|
#斐波那契数列数列
#使用递归求出斐波那契数列数列的第N个值
#时间复杂度为指数阶
def Fib_seq(n):
if (n < 1):
return -1;
if n == 1 or n == 2 :
return 1;
return Fib_seq(n - 1) + Fib_seq(n - 2)
#设置一个长度为N的数组,初始化数组的每个值为-1
#设置下标为0及1的值为1
#使用循环,取数组数列的前俩项之和,赋值个当前项
#时间复杂度为O(n),相比Fib_seq时间负载度大大降低
#空间复杂度为O(n)
def Fib_seq1(n):
if n < 1:
return -1
fib_list = [-1] * (n)
# print(fib_list)
fib_list[0] = 1;
fib_list[1] = 1;
for i in range(2,n,1):
fib_list[i] = fib_list[i - 1] + fib_list[i - 2]
print(fib_list)
return fib_list[-1];
#通过俩个变量记录数列的前俩项
#时间复杂度为O(n)
#空间复杂度降低为O(1)
def Fib_seq2(n):
if n < 1:
return -1
if n == 1 or n == 2:
return 1
num1 = 1
num2 = 1
for i in range(2,n,1):
num2 = num1 + num2
num1 = num2 - num1;
return num2;
#递归的变换方式
def Fib_seq3(a,b,n):
if n == 0:
return b
return Fib_seq3(a + b, a,n - 1)
'''
a = b*q + a*q + a*p
b = b*p + a*q
其中p=0,q=1
把这种变换称为T变换,那么对于T的平方来说,有:
a = (bp+aq)p+(bq+aq+ap)*q+(bq+aq+ap)*p = b(2pq+q^2)+a(p^2+2pq+3q^2)
b = (bp+aq)p+(bq+aq+ap)q = b(p^2+q^2)+a(q^2+2pq)
时间复杂度为O(logn)
'''
def Fib_seq4(a ,b ,p ,q , count):
if (count == 0):
return b
else:
if count % 2 == 0 :
return Fib_seq4(a,b,(p*p+q*q),(2*p*q+q*q),(count/2));
else:
return Fib_seq4((b*q+a*q+a*p),(b*p+a*q),p,q,(count -1));
num = 12
# print(Fib_seq(num))
# print(Fib_seq1(num))
# print(Fib_seq2(num))
# print(Fib_seq3(1,0,num))
# print(Fib_seq4(1,0,0,1,num))
def Fib_seq(n):
if n < 1:
return -1
fib_list = [-1] * (n)
# print(fib_list)
fib_list[0] = 1;
fib_list[1] = 1;
for i in range(2,n,1):
fib_list[i] = fib_list[i - 1] + fib_list[i - 2]
print(fib_list)
return fib_list;
fib_list = Fib_seq(12)
for i in range(1,len(fib_list)):
print(fib_list[i - 1] ,"比" ,fib_list[i] , ":",(fib_list[i - 1]/fib_list[i]))
|
class Nutrition:
def __init__(self, age, weight, height, gender):
self.age = age
self.weight = weight
self.height = height
self.heightMeters = self.height/100
self.gender = gender
self.BMI = self.weight / (self.heightMeters * self.heightMeters)
print("Nutrition Information")
print(self.age, self.weight, self.height, self.heightMeters, self.gender, self.BMI)
def TotalEnergyExpenditure(self):
if self.gender is "male":
return (66 + (13.7 * self.weight) + (5 * self.height) - (6.8 * self.age)) * (0.5)
else:
return (655 + (9.6 * self.weight) + (1.8 * self.height) - (4.7 * self.age)) * (0.5)
def BodyMassIndex(self):
return self.weight/(self.heightMeters*self.heightMeters)
#Based off of the 2015 Dietary Guidelines for Americans Advisory Group where no more than 10% of daily caloric intake should be from sugar.
def SugarIntake(self):
tee = self.TotalEnergyExpenditure()
print(tee)
self.recommendedMaxSugarIntake = 0.1 * tee
self.recommendedMinSugarIntake = 0.06 * tee
def SugarGramsToCalories(self, gramsSugar):
return 4 * gramsSugar
def AppropriateGoals(self, calorieIntake=0, sugarIntake=0):
self.SugarIntake()
if calorieIntake is 0:
calorieIntake = self.TotalEnergyExpenditure()
if sugarIntake is 0:
sugarIntake = self.recommendedMaxSugarIntake
CI = True
SI = True
#People need at least 1200 calories or 60% of daily expenditure.
if calorieIntake < 0.7 * self.TotalEnergyExpenditure():
print("Calorie Intake not Appropriate")
CI = False
if sugarIntake < 0.5 * self.recommendedMinSugarIntake:
print("Sugar Intake not Appropriate")
SI = False
return CI, SI
def AppropriateGoalsBMI(self):
CI = True
SI = True
print("BMI")
print(self.BMI)
classification = self.BMIClassification(self.BMI)
if classification < 1:
CI = False
return CI, SI
def BMIClassification(self, BMI):
#Underweight
if BMI < 18.5:
return 0
#Normal
if BMI < 25:
return 1
#Overweight
if BMI < 30:
return 2
#Obese
return 3 |
# #range()范围练习
# for value in range(1,10):
# print(value)
#
# #范围转数字列表练习
# numbers=list(range(1,10))
# print(numbers)
#
# #奇数链表创建,加步长
# odd_numbers=list(range(1,10,2))
# print(odd_numbers);
#
# #以下是数字列表及范围处理的几种写法
# squares=[]
# for value in range(1,10):
# square=value**2
# squares.append(square)
# print(squares)
#
# squares=[]
# for value in range(1,10):
# squares.append(value**2)
# print(squares)
#
# #这里的for语句没有冒号
# squares=[value**2 for value in range(1,10)]
# print(squares)
#
# #数字统计计算练习(无输出)
# digits=[1,2,3,4,5,5,6,7,8,0,9]
# min(digits)
# max(digits)
# sum(digits)
#
# #列表处理之切片(这玩意跟定范围差不多,不像之前的单个弹出去)
# #省略写法的方式python通用(不写头从头始,不写尾到尾停,可以负数反着来)
# players=['charles','martina','michael','florence','eli']
# print(players[0:4])
# print(players[:3])
# print(players[4:])
# print(players[-2:])#注意负数位置
#
# #切片遍历
# players=['charles','martina','michael','florence','eli']
# for player in players[0:3]:
# print(player.title())
#
# #复制列表和指向区别
# my_players=['charles','martina','michael','florence','eli']
# fri_players=my_players[:]
# fri_players.append('liko')
# print(my_players)
# print(fri_players)
#
# my_players=['charles','martina','michael','florence','eli']
# fri_players=my_players#这玩意就是相当于指针的指向
# fri_players.append('liko')
# print(my_players)
# print(fri_players)
#
# #圆括号之元组(跟列表处理相似不过不能改单个元素)
# dimensions=(200,15)
# print(dimensions[0])
# print(dimensions[1])
# #整体修改加遍历
# dimensions=(200,29)
# for dimension in dimensions:
# print(dimension)
#
# #注意PEP8指南https://python.org/dev/peps/pep-00008/
#
# #if语句演示
# cars=['audi','bmw','subaru','toyota']
#
# for car in cars: #依然是注意冒号
# if car == 'bmw':
# print(car.upper())
# else:
# print(car.title())
#
# #检查条件即为逻辑运算(布朗值的运算) 一般有字符之转化成小写进行比较(在字符串无特殊要求的时候)
# #相等、不等、大于、小于和与或非运算
#
# #检查多个条件and or
# age_0=22
# age_1=1
#
# print(age_0>2 and age_1<2)
# print(age_0>2 or age_1<34)
#
# #检查特定值在列表之中 in
# cars=['audi','bmw','subaru','toyota']
# print('audi' in cars)
# print('sasa' in cars)
#
# #检查特定值不在列表中 not in
# cars=['audi','bmw','subaru','toyota']
# if 'sasa' not in cars:
# print("sasa is not in cars")
#
# #if语句之if-elif-else
# #elif==else if
# #多个elif做代码块,else可以省略,这些个玩意跟其他语言类似
#
# #for循环变量调用列表的值可以跟if做嵌套
# #确定列表是否为空,先调用if判断,举例:
# #多个列表条件可以嵌套
# requested=[]
# #列表为空返回False
# if requested:
# print("True")
# else:
# print("False")
#
# #注意由于程序的美观性和独立性,注意空格的使用
#
# #------------------------------------------记得总结列表、元组、字典------------------------------------------------------
# #字典结构
# alien_0 = {'color' : 'green','point': 5 }
# print(alien_0['color'])
# print(alien_0['point'])
#
# #其中的'color'一类称为键,而'green'一类称为其值
# #召唤键,返回值 key & value
#
# #添加键-值对
# alien_0['x_position'] = 0
# alien_0['y_position'] = 25
# print(alien_0) #这玩意的打印跟列表一样,python只关心键-值匹配的关系
#
# #键的值修改
# alien_0['color'] = 'yellow'
# print(alien_0['color'])
#
# #删除键-值对,永远消失
# del alien_0['point']
# print(alien_0)
#
# #字典这玩意可以用来撞库和检索,创建个空的在后面加key和value
# #字典这玩意可以多行搞,再加个字符串拼接啥的美滋滋
#
# #遍历所有键-值对.items()
# #---即用俩变量,for循环。。。for key,value in zidian.items():
# alien_0 = {'color' : 'green','point': '5' } #注意不能打印int,必须转化成str
# for key,value in alien_0.items():
# print(key.upper()+value)
#
# #遍历所有的键.keys()
# # //.keys()可以省略,python默认遍历键
# # //顺序输出有sorted(zidian.keys())
# #---用一个变量,for循环。。。for key in zidian.keys():
# for key in alien_0.keys():
# print(key.upper())
#
# #遍历所有的值.values()
# # //重复有set()
# # //集合关系有set(zidian.values())
# #---用一个变量,for循环。。。for value in zidian.values():
# for value in alien_0.values():
# print(value.title())
#
# #字典可以跟列表互相嵌套,也可以自身嵌套
# #举个例子
# #储存外星人的空列表
# aliens = []
#
# #代码创建外星人
# for alien_num in range(30):
# alien = {'color' : 'green' ,'point' : 5}
# aliens.append(alien)
# print(aliens)
# print("创建外星人的数目为:"+str(len(aliens)))
#
# #修改特定特征的外星人
# for alien in aliens:
# if alien['color'] == 'green':
# alien['point'] = 10 ;
# print(aliens)
#
# #字典中嵌套列表
#
# fav_languages={
# 'jen':['python','ruby'],
# 'sara':['c'],
# 'edward':['java','go'],
# 'phil':['python','haskell'],
# }
# for name,languages in fav_languages.items(): #注意缩进别乱打空格
# print("\n"+name+"'s fav languages following")
# for language in languages:
# print("\t"+language)
#
#输入函数input()#字典嵌套字典
#---就是键->键->值这样多重嵌套的结果
# //在python2.x输入是raw_input
#message=input("提醒用户输入部分:")
#print(message)
#多行字符串提示方法,变量储存字符,然后字符串运算,然后再输出,记得加\n
#prompt="这是第一行"
#prompt+="\n这是第二行"
#string=input(prompt)
#print(string)
#input是字符串输入,可以用int()进行类型转换得到整型的数
#求模运算也就是取余运算%
#evennumber偶数,oddnumber奇数
#while当型循环,注意实际情况的对于条件的需要情况,,当然可以设置标志变量控制条件False or True
#强制退出break,跳出循环continue
# number=0
# while number<=10:
# number+=1
# if number%2==0:
# continue
# print(number)
#
# #注意死循环的运用情况
# confirmed=[]
# unconfirmed=['a','b','c']
# #注意写法
# while unconfirmed:
# confirmed.append(unconfirmed.pop()) #精简写法
# for user in confirmed:
# print(user)
#
# #while用来删除列表的特定值.remove()
# pets=['dog','cat','rabbit','goldfish','cat','dog']
#
# while 'cat' in pets:
# pets.remove('cat')
# print(pets)
#
# #while用来字典输入
# #设置控制循环的标志变量
# #注意字典的写入!!!!!!----------------------ctrl + / 整段注释和消除 或者""" """-----------------------------------
# # responses={}
# # active=True
# # while active:
# # name=input("please input the name")
# # response=input("please input the response")
# # responses[name]=response
# #
# # repeat=input("if other needs to be asked?(y/n)")
# # if repeat == 'n':
# # active =False
# #
# # print("the results are followed")
# # for name,response in responses.items():
# # print(name +"\t"+ response)
#
# #字典写入的两个变量的键-值对关系的配对
#
# #定义函数之def 在C中是函数类型的定义比如int void float double啥的
# #之前就定义了需要传递的参数变量
# def greet_user(username):
# print("Hi "+username)
# greet_user('joole')
#
# # def 这是一个函数(hanshu):
# # print(hanshu)
# # 这是一个函数('222')
#
# #实参顺序关联称为位置实参
# #名称-值对应的关键字实参,无关位置,直接赋值
# def des_pet(animal_type,pet_name):
# print("动物种类"+animal_type)
# print("宠物名称"+pet_name)
# des_pet(animal_type='dog',pet_name='jojo')
# #可以直接在函数中预设默认值,这一点跟C不一样
#
# #预设默认值为空可以使那一项的形参变为可选的!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
# #函数可以混用位置实参,关键字实参和默认值
# #建议可以的情况下尽量与C统一避免C编程的不必要的麻烦
# #返回值return返回给函数,返回值可以是字符串、列表、字典,,-------------------------任意类型--------------------------------
#
# #可以向函数传递列表,一改都改了
#
# #function_name(list_name[:])通过切片做副本
#
# #传递任意数目的实参。。。 *了解一下,这玩意也就是个---------元组---------。。。
# #使用任意数目的关键字实参。。。 **了解一下,这玩意也就是个------字典---------。。。键值对的匹配!!!-------------------
# def make_pizza(*toppings):
# """打印顾客点的所有配料"""
# print(toppings)
#
# make_pizza('ddsdsds','sadasdas','asddasdaasd','asdasdsadasd')
#
# """
# 结合使用位置实参和任意数量实参的时候!!!一定要把任意数目的实参放在最后guess why?
# """
#
# """
# import 用于导入模块下的所有函数
# 要在同一目录下.py文件,,然后.运算了解一下
#
# 特定函数的导入from module_name import function_name_0,function_1,function_2
#
# import module_name as xxx
# from module_name import function_name as xxx
#
# 用as语句指定别名
# 导入所有的函数 from module_name import * ##运用泛的方法(Linux了解一下)
# 泛的方法直接用函数就行,没必要属于的点运算 ##不推荐使用(冲突覆盖的问题)
# """
#
#默认值的赋值符号两边不要有空格
#----------------------------------------------------类-----------------------------------------------------------------
#Dog类实例
""""""
# class Dog():
# """一次模拟小狗的尝试"""
# def __init__(self,name,age):
# """初始化name和age"""
# self.name = name
# self.age = age
# def dogset(self,down):
# self.down = down
# #继承实例
# class Dogger(Dog):
# def __init__(self,name,age):
# super().__init__(name,age)
#
#
# with open("test.txt") as file_test:
# lines = file_test.readlines()
# print(file_test)
# for line in lines:
# print(line.rstrip())
# print(lines)
#
# filename = "test.txt"
# with open(filename) as file_aa:
# for aa in file_aa:
# print(aa.rstrip())
#
# #注意with的截停
# #.replace(a,b)将a替换为b
#
# filename = "testwrite"
# #"r"只读打开,"w"清空原文件写入,"a"附加append,"r+"读写打开
# with open(filename,"w") as file_object:
# file_object.write("this is a python write test file")
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip())
#
# #只能写入字符串,用str()转换
# #写入多行需要自己在后面加换行符
#
# with open (filename,"a") as file_object:
# file_object.write("\nthis is append file test")
# with open(filename) as file_object:
# for line in file_object:
# print(line.rstrip())
#---------------------------------------------文件读写------------------------------------------------------------------
#异常处理的示例
# print("Give me two numbers,and I will divide them.")
# print("Enter 'q' to quit.")
#
# while True:
# frist_number = input("Frist Number:")
# if frist_number == 'q':
# break
# second_number = input("Second Number:")
# if second_number == 'q':
# break
# try:
# answer=int(frist_number)/int(second_number)
# except ZeroDivisionError:
# print("You can not divide by 0")
# else:
# print(answer)
#FileNotFoundError找不到文件异常
#用split()方法以空格为分隔符将字符串拆成多个部分
# filename='alice.txt'
# try:
# with open(filename) as f_obj:
# contents = f_obj.read()
# except FileNotFoundError:
# msg = "Sorry, the file "+ filename + "does not exist."
# print(msg)
# else:
# words=contents.split()
# num_words=len(words)
# print(num_words)
#多次调用某一种功能就写个函数重复利用,那个通过拆分和列表长度确认单词量
#测试语句的意义在于之前就考虑到情况,然后不让用户看到traceback
#失败时一声不吭
#打开的文件名嵌套写法可以是,将文件名储存到列表之中然后循环调取,然后调函数循环打开
#python里面有pass语句直接不执行而跳过
# try:
# xxx
# except FileNotFoundError:
# pass
#外部因素所导致的错误都需要异常预分析
#------------------------------------------------储存数据---------------------------------------------------------------
#利用json.dump()储存数据,用json.load()加载,del索引删除,remove()特定项,写法不一样
# import json
#
# neirong = " this a json file write and load test file"
# filename = 'jsonfiletest.json'
# with open(filename,'w') as f_json:
# json.dump(neirong,f_json)
#
# with open(filename) as f_json:
# aa=json.load(f_json)
# print(aa)
#判断文件,发生FileNotFoundError错误就except创建
##代码重构可以通过分解函数返回值,进行判断(按照实际情况封装)
#try-except-else语句要用好,分解任务
#----------------------------------------------测试代码-----------------------------------------------------------------
#位于unittest module中
#先导入unittest模块以及需要被测试的函数,再创建一个继承unittest.TestCase的类,用于测试的类需要之前继承
#举例代码
# import unittest
# import function_xx from module_xx
# class NameTestCase(unittest.TestCase):
# def test_function(self):
# (需要处理的预处理)
# (调用unittest的方法)
#unittest.main()#这玩意让此运行
#处理的话就是调用其断言方法
#调用被测试模块的方法和参数然后跟另一项进行判断
# formatted_name = get_formatted_name('xxx','xxx')
# self.assertEqual(formatted_name,'xxxxxx')
#测试通过 . ,不通过 E 然后进行告知(具体问题具体对待)
#测试未通过原因有很多,一个个排除然后解决掉
#添加其他测试直接在类的下面添加测试的方法就好了命名以test_的规则(会自动运行测试)
#-----------------------------------------------------------------------------------------------------------------------
#--------------------------------------------unittest.TestCase中的断言方法-----------------------------------------------
# assertEqual(a,b) a==b
# assertNotEqual(a,b) a!=b
# assertTrue(x) x == True
# assertFalse(x) x == False
# assertIn(item,list) item在list中
# assertNotIn(item,list) item不在list中
#-----------------------------------------------------------------------------------------------------------------------
#setUp()方法
# def setUp(self):
# """创建一组对象和答案,跟普通的方法写法一样,建立实例设置属性"""
|
def stringList(data):
if(data==data[::-1]):
print(data+" is a pallindrome")
else:print(data+" Sorry . is not a pallindrome")
#a=input("Please give a String: ")
stringList("madam")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from operator import itemgetter
import sys
current_word = None
current_count = 0
word = None
# input comes from STDIN
for line in sys.stdin:
# удаляем проблемы в начале и конце строчки
line = line.strip()
# разбиваем каждую по символу таба
# чтобы получить ключ и значение (число вхождений)
word, count = line.split('\t', 1)
# пытаемся перевести строку в число (число вхождений)
try:
count = int(count)
except ValueError:
# если перевести не получилось
# то просто игнорируем эту строку и
continue # продолжаем выполнение
# Следующий блок отработает только потому,
# что хадуп сначала отсортирует значения по ключу
# а только потом пошлёт их нашему редуктору
if current_word == word:
current_count += count
else:
if current_word:
# записывает результат в стандартный поток вывода
# опять же разделяя значения табом.
print '%s\t%s' % (current_word, current_count)
current_count = count
current_word = word
# не забудем напечатать и последнее слово (если оно есть)
if current_word == word:
print '%s\t%s' % (current_word, current_count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.