blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
0197aaa5a0b5d0a29726f2b008b632b31dd98a1d | DouglasAllen/Python-projects | /my_code/wr_files.py | 556 | 3.75 | 4 | the_file = open('temp.txt', 'w')
print(the_file)
the_file.close()
the_file = open('temp.txt', 'r')
the_file.read()
the_file.close()
with open('my_list.py', 'r') as my_file:
read_data = my_file.read()
print(read_data)
print(my_file.closed)
#~ with open('my_list.pl', 'r') as my_file:
#~ read_data = my_file.read()
my_file = open('my_list.py', 'r')
for line in my_file:
# Appends a space instead of a newline
print(line, end='')
my_file.close()
f = open('workfile', 'wb')
f.write(b'0123456789abcdef')
f.seek(-3, 2)
f.seek(-3, 2)
f.close |
8955f7bc9a508a7540b60afd515c11a27a0d4ad4 | vck3000/SYNCS_Hackathon_2021 | /backend/src/engine/item.py | 466 | 3.53125 | 4 | from .coord import Coord
class Item:
def __init__(self, size: Coord, mass_density: int, strength: int):
self.size = size
self.mass_density = mass_density
self.strength = strength
def get_area(self):
return self.size.x * self.size.y
def get_mass(self):
return self.get_area() * self.mass_density
def get_inverse(self):
return Item(Coord(self.size.y, self.size.x), self.mass_density, self.strength)
|
bfb1f30eb1356884c5971ec11c8304b453fe3d36 | symbooo/LeetCodeSymb | /demo/21.MergeTwoSortedLists.py | 2,753 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
YES, WE CAN!
@Time : 2018/8/29 8:55
@Author : 兰兴宝 echolan@126.com
@File : 21.MergeTwoSortedLists.py
@Site :
@Project : LeetCodeSymb
@Note : [describe how to use it]
"""
# Enjoy Your Code
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
"""
合并两个有序单向链表
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
def symb(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
new_list = ListNode(None)
head = new_list
while l1 and l2:
if l1.val <= l2.val:
new_list.next = l1
l1 = l1.next
else:
new_list.next = l2
l2 = l2.next
new_list = new_list.next
new_list.next = l1 if l1 else l2
return head.next
# 高赞答案
# iteratively
def mergeTwoLists1(self, l1, l2):
dummy = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next
# recursively
def mergeTwoLists2(self, l1, l2):
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
# in-place, iteratively
def mergeTwoLists(self, l1, l2):
if None in (l1, l2):
return l1 or l2
dummy = cur = ListNode(0)
dummy.next = l1
while l1 and l2:
if l1.val < l2.val:
l1 = l1.next
else:
nxt = cur.next
cur.next = l2
tmp = l2.next
l2.next = nxt
l2 = tmp
cur = cur.next
cur.next = l1 or l2
return dummy.next
if __name__ == '__main__':
list1 = ListNode(1)
list1.next = ListNode(2)
list1.next.next = ListNode(4)
list2 = ListNode(1)
list2.next = ListNode(3)
list2.next.next = ListNode(4)
examples = [
[list1, list2],
]
solution = Solution()
for example in examples:
print(example, solution.symb(*example))
|
956c588867ec2cffbaa6f7559ef2bebe287d7259 | doonguk/algorithm | /20200409/98.py | 346 | 3.765625 | 4 | def isValid(self, s: str) -> bool:
open_set = set(["(", "[", "{"])
bracket_map = {"(": ")", "{": "}", "[": "]"}
stack = list()
for v in s:
if v in open_set:
stack.append(v)
elif stack and v == bracket_map[stack[-1]]:
stack.pop()
else:
return False
return stack == [] |
203b430f5b592bf3c45c56459a1db2acc1435ad9 | ultimate010/codes_and_notes | /547_intersection-of-two-arrays/intersection-of-two-arrays.py | 1,490 | 3.609375 | 4 | # coding:utf-8
'''
@Copyright:LintCode
@Author: ultimate010
@Problem: http://www.lintcode.com/problem/intersection-of-two-arrays
@Language: Python
@Datetime: 16-06-19 09:15
'''
class Solution:
# @param {int[]} nums1 an integer array
# @param {int[]} nums2 an integer array
# @return {int[]} an integer array
def intersection(self, nums1, nums2):
hash = {}
for n in nums1:
hash[n] = 0
ret = []
for n in nums2:
if hash.get(n, -1) == 0:
hash[n] = 1
ret.append(n)
return ret
def intersection2(self, nums1, nums2):
n1 = sorted(nums1)
n2 = sorted(nums2)
i, j = 0, 0
nn1, nn2 = len(n1), len(n2)
ret = []
while i < nn1 and j < nn2:
while i < nn1 and n1[i] < n2[j]:
i += 1
if i == nn1:
break
while j < nn2 and n2[j] < n1[i]:
j += 1
if j == nn2:
break
if n1[i] == n2[j]:
if len(ret) > 0 and ret[-1] == n1[i]:
pass
else:
ret.append(n1[i])
i += 1
j += 1
return ret
def intersection1(self, nums1, nums2):
# Write your code here
s1 = set(nums1)
s2 = set(nums2)
return list(s1 & s2) |
2ea7cfb747d3aaf7e2ade9b29f89b6fde1ff8cfb | fearnoevil7/PythonStack | /python/fundamentals/functions_basic2.py | 1,046 | 3.875 | 4 | # def countdown(num):
# array = []
# for i in range (num, -1, -1):
# array.append(i)
# return array
# b = countdown(5)
# print(b)
# def print_and_return(array):
# for i in range(0, len(array), 1):
# print(array[i])
# if i == 2:
# return (array[i])
# b = print_and_return([7, 2])
# print(b)
# def first_plus_length(array):
# for i in range(len(array)):
# if i == 0:
# array[i] += len(array)
# return array[i]
# b = first_plus_length([1, 2, 3, 4, 5])
# print(b)
# def greater_than_second(array):
# count = 0
# newarray = []
# for i in range(len(array)):
# if array[i] > array[1]:
# newarray.append(array[i])
# count += 1
# if len(array) == 2:
# return "false"
# print(count)
# return newarray
# b = greater_than_second([5, 2, 3, 2, 1, 4])
# print(b)
# def dis_length_dat_value(a,b):
# for i in range(0, a , 1):
# print(b)
# d = dis_length_dat_value(6, 2)
# print(d)
|
dedf2ce88bc1bac8b85fd1be3c76a23751b26da3 | anaghsoman/Py2 | /dt_cipher.py | 1,130 | 3.515625 | 4 | #!/usr/bin/python
import string
def get_order(key):
key = key.replace(' ', '')
order = len(key) * [None]
sorted_key = sorted(key)
for i, ch in enumerate(sorted_key):
order[i] = key.index(ch)
key = key.replace(ch, 'z', 1) # string is immutable
# print order
return order
def transpose(message, key):
message = message.replace(' ', '')
order = get_order(key)
mes_len = len(message)
cols = len(key)
rows = mes_len // cols + 1
message = message + (' ' * (rows*cols - mes_len))
str_list = [message[i:i+cols] for i in range(0, mes_len, cols)]
print '\n'.join(str_list)
newstr = ''
for i in order:
for s in str_list:
newstr = newstr + s[i]
newstr = newstr.replace(' ', '')
return newstr
# double transposition
def dt_cipher(message, key1, key2):
newstr = transpose(message, key1)
newstr = transpose(newstr, key2)
print newstr
if __name__ == "__main__":
# test case from http://users.telenet.be/d.rijmenants/en/handciphers.htm
dt_cipher('WE CONFIRM THE DELIVERY OF THE DOCUMENTS X', 'ALADIN', 'CONSPIRACY')
|
2aeaaafa212680b91e0343554f22164e5c9fd047 | KrishnaB7/python | /graphics/tkinter/pattern4.py | 771 | 3.515625 | 4 | #! /usr/bin/python3
import time
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=800, height=800)
canvas.pack()
d = canvas.create_oval(700, 300, 800, 400, fill="springgreen")
e = canvas.create_oval(0, 400, 100, 500, fill="aqua")
k = canvas.create_oval(300, 0, 400, 100, fill="springgreen")
l = canvas.create_oval(400, 700, 500, 800, fill="aqua")
for x in range(20):
for x in range(165):
canvas.move(k, 0, 5)
canvas.move(l, 0, -5)
canvas.move(d, -5, 0)
canvas.move(e, 5, 0)
tk.update()
time.sleep(0.01)
for x in range(165):
canvas.move(k, 0, -5)
canvas.move(l, 0, 5)
canvas.move(d, 5, 0)
canvas.move(e, -5, 0)
tk.update()
time.sleep(0.001)
canvas.mainloop()
|
8ccc3fa469cb3870eacf04f86d92476e1f233db5 | BoobeshP/turtle-projects | /turtle p05 (stars).py | 390 | 3.5 | 4 | import turtle as t
a = t.Turtle()
a.getscreen().bgcolor("black")
a.penup()
a.goto(-200,50)
a.pendown()
a.hideturtle()
a.color("orange")
a.speed(0)
def star(t,size):
if size <=10:
return
else:
for i in range(5):
t.begin_fill()
t.forward(size)
star(t,size/3)
t.left(216)
t.end_fill()
star(a,360)
t.done() |
16bbfb1f29636ac714f3cd2e227fe96f6ab98465 | microsoftdealer/first_repo | /quad.py | 1,863 | 3.609375 | 4 | import copy
def draw_matrix(matrix):
for row in matrix:
print(row)
def count_quads(matrix_raw):
r = 0
t = 0
matrix = copy.deepcopy(matrix_raw)
quad_counter = 0
length = len(matrix) * len(matrix[0])
for sym in range(length):
if matrix[r][t] == 0:
pass
else:
quad_counter += 1
wide, height = def_quad_size(matrix, r, t)
matrix = zeroize_quad(matrix, wide, height, r, t)
t += 1
if t >= len(matrix[0]):
t = 0
r += 1
draw_matrix(matrix_raw)
print(f'Number of quads in matrix is equal to {quad_counter}')
return quad_counter
def def_quad_size(matrix, r, t):
wide = check_right(matrix, r, t)
poss_height = []
for num in range(wide):
poss_height.append(check_down(matrix,r,t))
t += 1
height = min(poss_height)
return wide, height
def zeroize_quad(matrix, wide, height, r, t, zeroize=True):
for row in matrix[r:r+height]:
temp_t = t
for val in row[t:t+wide]:
if zeroize:
matrix[r][temp_t] = 0
else:
matrix[r][temp_t] = 1
temp_t += 1
r += 1
return matrix
def check_right(matrix, r, t, wide=0):
wide += 1
t += 1
if t >= len(matrix[0]):
return wide
if matrix[r][t] == 1:
return check_right(matrix, r, t, wide=wide)
else:
return wide
def check_down(matrix, r, t, height=0):
if r + 1 > len(matrix):
return height
elif matrix[r][t] == 1:
r += 1
height += 1
return check_down(matrix, r, t, height=height)
else:
return height
if __name__ == "__main__":
matr = [[1,0,1,1,0,1],
[0,0,1,1,0,0],
[1,0,0,1,0,1],
[1,0,1,1,0,1]]
print(count_quads(matr)) |
c98800866e3a69c635fad3904fe51209d93e7777 | battyone/Solar_Flare | /alphaestimator2.py | 969 | 3.5 | 4 | import numpy as np
import powerlaw
def get_alpha(data):
data = np.array(data)
result = powerlaw.Fit(data)
xminimum = result.power_law.xmin
#xmin from power law package
xminimum = xminimum - 0.5
summand1 = 0
datanew = []
#alpha2 is the estimation from powerlaw package
alpha2 = result.power_law.alpha
#xmin the smallest value in data
xminimum = min(data)
for i in range(len(data)):
if data[i] > xminimum:
datanew.append(data[i])
data = datanew
for dt in data:
summand1 = summand1 + np.log(dt/xminimum)
#logsum = sum(np.log(data))
#alpha is the estimation from this function
alpha = 1 + len(data) * (summand1) ** (-1)
sigma = (alpha - 1)/(len(data)**(0.5)) + (1/(len(data)))
print(alpha)
print(sigma)
print(xminimum)
return alpha, sigma, alpha2
|
29602cd959c065b4e1bf7fb81bc4c991fb7fbc35 | marcellinuselbert/Python-Course-2020 | /criminal.py | 854 | 3.65625 | 4 | import time
def rapih(dictionary):
for key,value in dictionary.items():
print (f'{key} : {value}' )
john = {
"Fullname" : "John Smith",
"Age" : "25",
"Crime" : "Stealing"
}
bill = {
"Fullname" : "Bill Turner",
"Age" : "30",
"Crime" : "Drug Dealing"
}
rose = {
"Fullname" : "Rose Miller",
"Age" : "45",
"Crime" : "Car Theft"
}
james = {
"Fullname" : "James Richard",
"Age" : "27",
"Crime" : "Burglary"
}
real_password = "america"
b= 0
password =""
while password != real_password:
password = input("password please: ")
while b < 3:
b += 1
for x in range(0,4):
time.sleep(0.5)
print("logging in"+"." * x)
print("\n")
print("MOST WANTED LIST")
print("----------------")
rapih(john)
print(" \n")
rapih(bill)
print(" \n")
rapih(rose)
print(" \n")
rapih(james)
|
cbea9a7015b18790931168722ce31112a380aa67 | mkieft/Computing | /Python/Week 8/Lab 8 Q 6.py | 332 | 3.984375 | 4 | #Lab 8 Q 6
#Maura Kieft
#10/20/2016
#6. Write a function which test divisibility (mod
def main():
x=eval(input("Enter first integer: "))
y=eval(input("Enter second integer: "))
divis(x,y)
def divis(a,b):
if a%b==0:
print(a,"is complete divisible by ",b)
else:
print("There is a remainder")
main()
|
d6d8c45347009a4bbc6a3a2301a30aa8cb21ec22 | kilura69/softuni_proj | /0_admission_prep/02_conditional_statements/03_gymnastics.py | 1,108 | 4.15625 | 4 |
# ******* 03.gymnastics (nested condtiinal statements) *************************
country = input()
tool = input()
difficulty = 0
performance = 0
if country == 'Russia':
if tool == 'ribbon':
difficulty = 9.100
performance = 9.400
elif tool == 'hoop':
difficulty = 9.300
performance = 9.800
elif tool == 'rope':
difficulty = 9.600
performance = 9.000
elif country == 'Bulgaria':
if tool == 'ribbon':
difficulty = 9.600
performance = 9.400
elif tool == 'hoop':
difficulty = 9.550
performance = 9.750
elif tool == 'rope':
difficulty = 9.500
performance = 9.400
elif country == 'Italy':
if tool == 'ribbon':
difficulty = 9.200
performance = 9.500
elif tool == 'hoop':
difficulty = 9.450
performance = 9.350
elif tool == 'rope':
difficulty = 9.700
performance = 9.150
score = (difficulty + performance)
percent = (20 - score) / 20 * 100
print(f"The team of {country} get {score:.3f} on {tool}.")
print(f"{percent:.2f}%")
|
8f7331a4a15e542fbee7ae708e7bafedacaf6960 | cristearadu/CodeWars--Python | /arithmetic.py | 418 | 3.9375 | 4 | def arithmetic(a, b, operator):
return{
'add': a+b,
'subtract': a-b,
'multiply': a*b,
'divide': a/b
}[operator]
print(arithmetic(10,3,'add'))
def arithmetic(a,b,operator):
dict_op_a_b ={
'add': a+b,
'subtract': a-b,
'multiply': a*b,
'divide': a/b
}
return dict_op_a_b[operator]
print(arithmetic(10,3,'subtract'))
|
7e2ad29afcbcfa78fda469b8be665b9cf7025478 | Anirudh-Muthukumar/Python-Code | /string append.py | 168 | 3.5 | 4 | t=input()
for _ in range(t):
s=raw_input()
p=''
dollar=0
for i in s:
if i not in p:
dollar+=1
p+=i
print dollar |
1f4df1c91897663025259af6071d33e1daf5224f | VanessaVallarini/uri-online-Python-3 | /2510.py | 122 | 3.734375 | 4 | t=int(input())
for i in range(t):
nome=input()
if nome!="Batman":
print("Y")
else:
print("N")
|
3e96e16af9b164196a86fc7c4493e2d1a4c48e3d | Darvillien37/Forebot-Py | /Storage/XP.py | 374 | 3.59375 | 4 | from random import randint
def getXPFromMessage(message: str):
'''
Get an amount of XP based off a message string
'''
# the smallest maximum amount
minMax = int(len(message) / 3)
if minMax < 3:
minMax = 3
amount = randint(1, minMax)
return amount
def calculate_xp_for_next_level(currLvl):
return (3 * pow(currLvl, 1.5)) + 100
|
fd8ebb441d42745a9f4514ac78ba076a10ecaf85 | mpsb/practice | /codewars/python/cw-give-me-a-diamond.py | 1,253 | 4.0625 | 4 | '''
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.
Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\n).
Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
'''
def diamond(n):
if((n%2==0) | (n<0)):
return None
space = " "
asterisk = "*"
newline = "\n"
diamond = ""
space_num = int(1*n/2)
asterisk_num = 1
for i in range(int(n/2)+1): # top part
diamond += space*space_num
diamond += asterisk*asterisk_num
diamond += newline
space_num -= 1
asterisk_num += 2
space_num += 2
asterisk_num -= 4
for i in range(int(n/2)+1): # bottom part
if(asterisk_num <= 0):
break
diamond += space*space_num
diamond += asterisk*asterisk_num
diamond += newline
space_num += 1
asterisk_num -= 2
return diamond |
6c11e1bbef0680fb6fe780f9a31b298866dedac5 | muhammad-masood-ur-rehman/Skillrack | /Python Programs/username-domain-extension.py | 550 | 3.984375 | 4 | Username Domain Extension
Username Domain Extension: Given a string S which is of the format USERNAME@DOMAIN.EXTENSION, the program must print the EXTENSION, DOMAIN, USERNAME in the reverse order.
Input Format:
The first line contains S.
Output Format:
The first line contains EXTENSION.
The second line contains DOMAIN.
The third line contains USERNAME.
Boundary Condition:
1 <= Length of S <= 100
Example Input/Output 1:
Input:
abcd@gmail.com
Output:
com
gmail
abcd
s=input().split('@')
a=s[0]
s=s[1]
s=s.split('.')
b=s[0];c=s[1]
print(c,b,a,sep='\n')
|
0e9d72e568ffe6e07f6c96bb05cbb7f60351a8a0 | Dayoming/PythonStudy | /codingdojang/unit07/string_03.py | 487 | 3.71875 | 4 | # 문자열에 + 를 사용하면 문자열이 연결되고, * 를 사용하면 문자열이 반복됨
# 문자열1 + 문자열2
# 문자열 * 정수
hello = 'Hello, '
world = 'world!'
print(hello + world)
print(hello * 3)
# 0 또는 음수를 곱하면 빈 문자열이 나오며 실수는 곱할 수 없다.
print(hello + str(10))
# 문자열에 정수를 더하려고 하면 에러가 발생
# 이때는 str를 사용하여 숫자(정수, 실수)를 문자열로 변환하면 됨
|
529b79bcce69130a53c308a9b2ba0290e1931355 | dangerous3/geekbrains-python-algorithms-and-data-structures | /m2-cycles-functions-recursion/task6.py | 1,093 | 3.921875 | 4 | '''
В программе генерируется случайное целое число от 0 до 100. Пользователь должен его отгадать не более чем за 10 попыток.
После каждой неудачной попытки должно сообщаться, больше или меньше введенное пользователем число, чем то, что загадано.
Если за 10 попыток число не отгадано, вывести ответ.
'''
import random as rd
num = rd.randint(0, 100)
attempts = 0
your = int(input("Введите целое число от 0 до 100: "))
while attempts < 10:
if your == num:
print(f"Вы угадали: загаданное число {your}!")
break
else:
attempts += 1
your = int(input("Неверно! Попробуйте еще раз угадать число от 1 до 100: "))
if attempts > 9:
print(f"Вы не угадали загаданное число {num} за {attempts} попыток")
|
b52dbc3940779236c4850fd04db19454bc27d0c4 | workwithfattyfingers/testPython | /first_project/nameletter.py | 200 | 3.6875 | 4 | name= input("Please enter name")
i=0
tem_var = ""
while i < len(name):
if name[i] not in tem_var:
tem_var += name[i]
print(f"{name[i]} : {name.count(name[i])}")
# i=i+1
i += 1
|
9d89f2604608df29eb0bc9c619a885433c1df8c1 | palaciosdiego/pythoniseasy | /src/FunctionsAssignment.py | 450 | 3.59375 | 4 | # Functions
def album():
name = "The Dark Side of the Moon"
return name
def artist():
artist = "Pink Floyd"
return artist
def yearReleased():
year = 1973
return year
def tryBooleans(code):
value = "Enter T or F"
if(code == "T"):
value = True
elif(code == "F"):
value = False
return value
print(artist())
# code variable must contain T or F to return Tue or False
print(tryBooleans("T"))
|
6bcd645dd8a4c79003cf4dc4cda1a460f4cddda9 | sanjingysw/github_sync | /python学习/高级变量/ysw_07_zifucuan.py | 2,582 | 4.09375 | 4 | str1 = "hello hello world!"
# 只有当字符串中需要双引号""时,才用单引号''定义字符串
str2 = '我的外号是"大西瓜"!'
'''
# 遍历字符串,字符串一个一个显示
print(str1[5])
for c in str2:
print(c)
# 获取字符串长度,获取字符串出现的次数
print(len(str2))
print(str1.count("llo"))
#index 获取字符串第一次出现的位置 ,注意单引号双引号的配合使用
print(str2.index('"'))
# 判断字符串中是否只包含空格或者制表符
space_str = "\n\t\r a"
print(space_str.isspace())
# 判断字符串中是只包含数字
# 都不能判断浮点数(小数)
# isdigit方法 还可判断 unicode数字
# isnumeric方法 除unicode数字外,还可判断汉字数字
# 实际开发中尽量使用isdecimal方法
num_str = "壹一千零一"
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
# 判断字符串是否以某段字符开头
hello_str = "hello world"
print(hello_str.startswith("hello"))
# 判断字符串是否以某段字符结束
print(hello_str.endswith("ld"))
# 查找指定字符串,返回索引位置
# 与index区别是:如果不包含指定字符,index报错,find返回-1
print(hello_str.find("llo"))
print(hello_str.find("abc"))
# 替换字符串,会返回一个新字符串,但是不改变原字符串
print(hello_str.replace("world", "python"))
print(hello_str)
poem1 = ["登鹳雀楼",
"作者:王之涣",
"白日依山尽",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for poem_str1 in poem1:
#print(poem_str)
# 对齐
print("|%s|" % poem_str1.rjust(20, " "))
# 去除空白字符
poem2 = ["\t\n登鹳雀楼",
"作者:王之涣",
"白日依山尽\t\n",
"黄河入海流",
"欲穷千里目",
"更上一层楼"]
for poem_str2 in poem2:
# 先用strip 方法 去除字符串中的空白字符或制表符
# 再用center 方法 居中显示
print("|%s|" % poem_str2.strip().center(10, " "))
'''
# 拆分和连接
poem_str3= "\t\n登鹳雀楼\t作者:王之涣\t白日依山尽\t\n黄河入海流\n欲穷千里目\n\n\n更上一层楼"
print(poem_str3)
# split方法 拆分字符串,返回一个列表
# split方法用分隔符(默认为空白字符即空格和制表符)把字符串拆分成一个列表。
poem_list = poem_str3.split()
print(poem_list)
# 合并,用空格作为分隔符,把列表拼接成一个字符串
result = " ".join(poem_list)
print(result) |
935ab12aaf5d9eaa843ed52189121c3ed759a985 | Cadols/LearnPython | /lpthw/11-20/ex19_add2.py | 381 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def func(name):
print("What's your name?")
print("My name is %s.\n" % name)
# 1
func("Will")
# 2
func("Will" + "Wang")
# 3
name1 = 'Hello'
func(name1)
# 4
func(name1 + "Will")
# 5
name2 = 'Woo'
func(name1 + name2)
# 6
name3 = input("Please input your name.\n> ")
func(name3)
# 7
func(name1 + name3)
# 8
func(func('What?'))
# 9
# 10 |
deeb2e019422ff7e7f7d7b39eef6fc24e9732089 | jmcguire/learning | /algorithms/sorting/bubble_sort.py | 603 | 4.25 | 4 | # bubble sort:
#
# type: transposition
# best time: O(n)
# average time: O(n²)
# worst time: O(n²)
#
# look at each pair, if they're out of order then swap them
# go through the entire list twice
def bubble_sort(A):
#print "from %d to %d" % (len(A)-1, 0)
for i in xrange(len(A)-1, 0, -1):
#print " from %d to %d" % (0, i-1)
for j in xrange(1, i+1):
#print " checking %d:%s and %d:%s" % (j, A[j], j-1, A[j-1])
if A[j] < A[j-1]:
#print " %s < %s, swap" % (A[j], A[j-1])
A[j], A[j-1] = A[j-1], A[j]
#else: print " %s !< %s" % (A[j], A[j-1])
|
d541e2d4bda0ee5f3ed661cc0d9a0373fe9420de | Rkluk/uri | /2108 Contanto Caracters.py | 345 | 3.9375 | 4 | bigger = ''
while True:
st = input()
if st == '0':
break
st = st.split()
numlist = []
for c in st:
if bigger == '' or len(c) >= len(bigger):
bigger = c
numlist.append(str(len(c)))
r = '-'.join(numlist)
print(r)
print('')
print('The biggest word: {}'.format(bigger))
|
d61fae9e17f2a1b08caf1528fdf3fbfa6477017a | ibardi/PythonCourse | /session05/exercise3a.py | 2,825 | 4.3125 | 4 | import turtle
import math
tom = turtle.Turtle ()
print(tom)
def polygon(t,length,n):
for i in range(n):
t.fd(length)
t.lt(360/n)
def invpolygon(t,length,n):
for i in range(n):
t.fd(length)
t.rt(360/n)
def circle (t,r):
circumference = 2 * math.pi * r
n = 150
length = circumference / n
polygon(t,length,n)
def invcircle (t,r):
circumference = 2 * math.pi * r
n = 50
length = circumference / n
invpolygon(t,length,n)
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int (arc_length / 3 ) + 1
step_length = arc_length / n
step_angle = angle / n
for i in range(n):
t.fd(step_length)
t.lt(step_angle)
radius = 120
def hourglass(t):
"""
This function draws the hour glass with the two circles inside. It calculates the circles radius based on
the parameters given for the trianglelength, which in turn is based on the defined radius.
"""
triangleleg = radius
standardturn = 360 / 3
#Turtle moves left to creat the BOTTOM part of the hourglass.
tom.fd(triangleleg)
#Turtle turns left
tom.lt(standardturn)
#Turtle moves forwards to create another side of the triangle AND the left side of the top triangle.
tom.fd(triangleleg / 2)
#I am using the formula radius = (2*a) / p, where a, is area of the triangle, and p is the perimeter of a triangle.
# Since its an equilaterle triangle, I use the formula: Area = sqrt of 3, devided by 4 * length of side to the power of 2.
areatriangle = ((3**0.5)/4) * triangleleg**2
incircleradius = (2 * areatriangle) / (triangleleg *3)
circle(tom,incircleradius)
#Turtle continues on its original path
tom.fd(triangleleg *1.5)
#Turtle turns to a parallel (facing east).
tom.lt(360- (360 + (standardturn)))
#Turtle draws the top line
tom.fd(triangleleg)
#Turtle turns towards the center of the circle
tom.rt(standardturn)
#Turtle crosses the center of the circle to form last two missing lines of both triangles.
tom.fd(triangleleg /2)
#Turtle does the other circle
invcircle(tom,incircleradius)
#Turtle continues on its path
tom.fd(triangleleg *1.5)
#Turtle points perpendicular
tom.lt(90)
hourglass(tom)
circle(tom,radius)
#Now we line up so that we only have to run the hourglass function again. Its, easier for us to line up by using exisitng lines.
#Turns back on the long diagonal line
tom.lt(90)
#moves to the center
tom.fd(radius)
#Turns to the right.
tom.rt(90)
#moves to position of start
tom.fd(radius)
#We set an appropriate heading start NORTH (90).
tom.setheading(90)
#We re-run the hourglass function.
hourglass(tom)
turtle.mainloop() |
447e627472285ca9ae2a6c437093a5d153486eac | saquibfortuity/python_github | /conditional.py | 168 | 4.125 | 4 | age = input("enter your age")
age = int (age)
if age > 18:
print("you can vote")
elif age < 18:
print("you cannot vote")
else:
print("register yourself")
|
a8e79bd8a22849ec228ff39f040fc94a23733216 | schleppington/HackerRank | /Maximum Perimeter Triangle/maxtriangle.py | 435 | 3.59375 | 4 | n = int(raw_input().strip())
arr = map(int, raw_input().strip().split())
if(n<3 or n>50):
print -1
else:
arr.sort()
triangle = [0,0,0]
for i in xrange(n):
if(triangle[0]+triangle[1]>triangle[2]):
print(str(triangle[0])+" "+str(triangle[1])+" "+str(triangle[2]))
break
elif(i+3>len(arr)):
print -1
break
else:
triangle = arr[n-3-i:]
|
e62912381c050532e582e3e3a50ab1c314be6ad5 | samirgadkari/Intro-Python-I | /src/03_modules.py | 1,041 | 4 | 4 | """
In this exercise, you'll be playing around with the sys module,
which allows you to access many system specific variables and
methods, and the os module, which gives you access to lower-
level operating system functionality.
"""
import sys
# See docs for the sys module: https://docs.python.org/3.7/library/sys.html
# Print out the command line arguments in sys.argv, one per line:
for arg in sys.argv:
print(arg)
# Print ut the OS platform you're using:
print('Platform:', sys.platform)
# Print out the version of Python you're using:
maj, min, mic, release, serial = sys.version_info
print('Python version:', str(maj) + '.' + str(min) + \
'.' + str(mic), 'release:', release, 'serial:', serial)
import os
# See the docs for the OS module: https://docs.python.org/3.7/library/os.html
# Print the current process ID
print('Process ID:', os.getpid())
# Print the current working directory (cwd):
print('Current working directory:', os.getcwd())
# Print out your machine's login name
print('Login name:', os.getlogin())
|
b01934680f22ae16b3e695dfcfeb55eb8fb9c7a2 | lotusstorm/stepik_courses | /kurs_1/step_4.py | 698 | 4.25 | 4 | import math
def main():
'''
В зависимости от заданной в fig фигуры
запрашивает стороны этой фигуры затем
вычисляет площадь
'''
fig = str(input())
if fig == "прямоугольник":
print(int(input('сторона: ')) * int(input('сторона: ')))
elif fig == "треугольник":
a, b, c = [int(input('сторона: ')) for _ in range(3)]
p = (a + b + c) / 2
print(math.sqrt(p * (p - a) * (p - b) * (p - c)))
elif fig == "круг":
print(3.14 * (int(input('радиус: ')) ** 2))
if __name__ == '__main__':
main()
|
61bc9e888cf3ddd8d2545166d772cf899bb62f8d | maverick-zhang/Algorithms-Leetcode | /leetcode_day11/Q92_reverse_list2.py | 1,035 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 输入: 1->2->3->4->5->NULL, m = 2, n = 4
# 输出: 1->4->3->2->5->NULL
# 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
i = 1
pre_reverse = None # 代表反转区间前面的一个节点
cur = head
while i < m:
pre_reverse = cur
cur = cur.next
i += 1
pre = None
while i < n:
next = cur.next
cur.next = pre
pre = cur
cur = next
i += 1
if cur == head:
return head
if pre_reverse is not None:
pre_reverse.next.next = cur.next
pre_reverse.next = cur
cur.next = pre
return head
else:
head.next = cur.next
cur.next = pre
return cur
|
ff31fa44a164a29e91943212fdade97aa38e9b21 | FRAndrade/Python | /python/listadeexercicio/EstrutrutaDeDecisao/vogal/vogal.py | 134 | 3.75 | 4 | letra=input("Digite a letra: ")
vogais = ["a","e","i","o","u"]
if(letra in vogais):
print("É vogal!")
else:
print("É consoante!")
|
9a099c54f36cf12596d4265def943a64556f085a | rlebrao/10-Days-of-statistics | /quartiles.py | 806 | 3.6875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
size = input()
data = list(map(int,(input().split())))
data.sort()
def getMedian(data, size):
size = int(size)
dataNumber = []
for i in data:
dataNumber.append(int(i))
dataNumber.sort()
if(size % 2 == 0):
return (dataNumber[(int(size/2))] + dataNumber[int(size/2)-1])/2
else:
return int(dataNumber[int(((size + 1)/2)) -1])
median = getMedian(data, size)
if(int(size) %2 == 0):
median_pos = data.index(round(median)+1)
else:
median_pos = data.index(round(median))
L_half = data[:median_pos]
U_half = data[(median_pos):]
q_two = round(median)
q_one = round(getMedian(L_half, len(L_half)))
q_three = round(getMedian(U_half, len(U_half)))
print(q_one)
print(q_two)
print(q_three)
|
1cddef78ca17b74166f910c78f554b74559004cd | pxblx/programacionPython | /practica01/alternativas/E10Alternativas.py | 976 | 4.125 | 4 | """
Ejercicio 10 de alternativas
Algoritmo que pida los puntos centrales x1, y1, x2, y2 y los radios r1,r2 de dos circunferencias y las clasifique en
uno de estos estados:
- Exteriores.
- Tangentes exteriores.
- Secantes
- Tangentes interiores.
- Interiores.
- Concentricas.
"""
import math
# Pedir valores
x1 = int(input("Introduce el valor para x1: "))
y1 = int(input("Introduce el valor para y1: "))
x2 = int(input("Introduce el valor para x2: "))
y2 = int(input("Introduce el valor para y2: "))
r1 = int(input("Introduce el valor para r1: "))
r2 = int(input("Introduce el valor para r2: "))
# Resultado
d = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
if (r1 + r2) < d:
print("Exteriores.")
if (r1 + r2) == d:
print("Tangentes exteriores.")
if (r1 + r2) > d > abs(r1 - r2):
print("Secantes.")
if d == abs(r1 - r2):
print("Tangentes interiores.")
if 0 < d < abs(r1 - r2):
print("Interiores.")
if d == 0:
print("Concentricas.")
|
cac58590f3e67f338242119cc18d97dfd13b5634 | malikdamian/codewars | /6kyu/Count characters in your string.py | 311 | 4.28125 | 4 | """
The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.
What if the string is empty? Then the result should be empty object literal, {}.
"""
def count(string):
return {char: string.count(char) for char in string}
|
f306d4a266b79909d285c7c0ffc722c9634b335b | Artekaren/Trainee-Python | /D14_genera_patron.py | 466 | 3.8125 | 4 | #Desafío14: Generar patrón
#Debe crear un programa que logre replicar el siguiente patrón, donde el usuario ingrese un número, y ese número corresponderá al número de filas que se debe generar. La soluciṕon debe estar dentro delprograma llamado genera_patron.py .
#1
#12
#123
#1234
#12345
num = int(input("Ingrese número\n"))
for i in range(1,num+1): #i son las filas
for j in range(1,i+1): #j son las columnas
print(j,end="")
print()
|
73c7371de9d4017beb5a10e2e087ec65bc8bd765 | saikiranrede/Coding-challenges | /password_checker.py | 313 | 3.859375 | 4 | correct_password = "python123"
name = input("Enter your name: ")
surname = input("Enter your surname: ")
password = input("Enter your password: ")
while correct_password != password:
password = input("Wrong passwrod!!, Enter again: ")
message = "Hi %s %s, you're logged in" % (name, surname)
print(message)
|
4140dfb0b29b264b5ca20c7f8b621ec71db6cd38 | vinniechandak/python-basics | /dictionaries.py | 839 | 4.40625 | 4 | # This is about dictionary data structure in python.
d = {'a': 'b', 'c': 'd', 'e': 'f'};
print("Print Dictionary ==> " , d);
d['Vinod'] = 'Chandak'; # appending element to dictionary
print("Print Amended Dictionary ==> " , d);
d['a'] = 'Modified key a'; # value overriding.
print("Print Value Overridden Dictionary ==> ",d);
print("Print Dictionary as a Tuple ==> " , d.items()); # print items of a dictionary in a tuple format.
print("Print Dictionary Keys ==> " ,d.keys()); # print keys of a dictionary.
print("Print Dictionary Values ==> " ,d.values()); # print values of a dictionary.
print("Print Dictionary Contains Key? ==> " ,d.__contains__('a')); # checking whether key exists in dictionary or not.
print("Print Dictionary Value by Key ==> " ,d.get('Vinod')); # get value by key. if key doesn't exists it returns None.
|
3ed1150049f7e7a4d52d8a4f090210a41ba2a277 | avanish981/python | /graphs/breadth_first_search.py | 830 | 4.03125 | 4 | # Breadth First Search
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edges(self,_from,_to):
for t in _to:
self.graph[_from].append(t)
def display(self):
print self.graph
def bfs(self,graph,start):
queue = [start]
visited = []
while queue:
a = queue.pop(0)
if a not in visited:
visited.append(a)
for neighbor in graph[a]:
queue.append(neighbor)
print visited
def main():
G = Graph()
G.add_edges(1,[2,7,8])
G.add_edges(2,[3,6])
G.add_edges(3,[4,5])
G.add_edges(8,[9,12])
G.add_edges(9,[10,11])
G.display()
G.bfs(G.graph,1)
if __name__ == '__main__':
main()
|
f60c174f523f0724ac9adf42472f097bc3a04240 | neM0s/books | /for_and_back.py | 263 | 3.8125 | 4 | # Type your code here
def pattern_sum(a, b):
sum = 0
for i in range(1, b+1):
sum = sum + (a ** i)
return sum
print(pattern_sum(5,3))
a = 1
b = 3
stringunio = str(a)
for i in range(b):
stringunio = stringunio + stringunio(a)
print str |
2ce770f2b33dae55a2f633670db9eca305f91066 | coley-dot-jpg/CS177.BoilerGoldRush | /project3 w music and score. WIP.py | 26,394 | 4 | 4 | #
# CS 177 - project3.py
# Devin Ersoy, 00305545351 Juliana Peckenpaugh, 0030606114, Emelie Coleman, 0031104038
# Following Coding Standards and Guidelines
# This program creates a control window and a game window. The control window is used to get a payer's
# name, start a game, or exit a game. The program has a game window where the players name will appear
# what round they're on, and how many clicks have happened. Also in this window, a 15x15 grid of black
# circles will appear and when clicked they change colors to their 'hidden' color. When the user finds
# the gold circle that marks the end of the round, a message is displayed and the user may continue.
# When the game ends, the players name and score is written to a file called 'scores.txt.' and displayed
# in controlwin. In addition, this program will also draw a red circle which increases score by 5 once
# clicked. After the game completes, the golden circle will animate for 5 seconds and remove 2 clicks
# based on times it was clicked. Once exit is clicked, the game will close. Otherwise, game will continue
# running after 5 rounds with a restart. For extra additions, there are sounds for every click on circles
# along with respective celebration sounds and bummer sound when redcirc is clicked. In addition, after
# the 5th round, there is a video with the creators of the project clapping. The last addition is an
# easter egg. Once the q button is typed, cheats are activated for the game outlining where goldcirc and
# redcirc is until the next round.
#
# Import necessary libraries
from graphics import *
from time import time, sleep
from math import sqrt
from random import randint
import platform
import os
# Import winsound if system is windows
if platform.system() == 'Windows':
import winsound
####################################################################################################################################################################
# Define the game control function
def GameControl():
# Create control window
win = GraphWin('Game Control', 250, 200, autoflush=False)
# Create and display Boiler Gold Hunt! title
titlebar = Rectangle(Point(0,0), Point(250, 30))
titlebar.setFill('black')
titlebar.draw(win)
title = Text(Point(125, 15), 'BOILER GOLD HUNT!')
title.setStyle('bold')
title.setSize(13)
title.setFill('gold')
title.draw(win)
# Create and display player name entry box and title
name = Text(Point(80,50), 'PLAYER NAME')
name.setStyle('bold')
name.setSize(10)
name.draw(win)
inputbox = Entry(Point(185,50), 6)
inputbox.setSize(16)
inputbox.setFill('white')
inputbox.draw(win)
# Create and display the top scores and text title
topscores = Text(Point(125,80), 'TOP SCORES')
topscores.setStyle('bold')
topscores.setSize(13)
topscores.draw(win)
# Open the file
scoresfile = open('scores.txt', 'r')
# Make the file a list of strings
scores = scoresfile.readlines()
top3 = []
# Get the top 3 names and scores
i = 0
while i < 3:
if len(scores) == i:
break
top3.append(scores[i].rstrip('\n').replace(' ', '').split(','))
place = Text(Point(95,100+i*17), top3[i][0])
place.setSize(11)
place.draw(win)
score = Text(Point(155,100+i*17), top3[i][1])
score.setSize(11)
score.draw(win)
i += 1
# Close the file
scoresfile.close()
# Create and display New Game button
newgamerect = Rectangle(Point(5, 155), Point(105, 190))
newgamerect.setFill('gold')
newgamerect.draw(win)
newgamelabel = Text(Point(55, 172.5), 'NEW GAME')
newgamelabel.setStyle('bold')
newgamelabel.setSize(10)
newgamelabel.draw(win)
# Create and display Exit button
exitrect = Rectangle(Point(180, 155), Point(245,190))
exitrect.setFill('black')
exitlabel = Text(Point(212.5, 172.5), 'EXIT')
exitlabel.setFill('white')
exitlabel.setStyle('bold')
exitlabel.setSize(10)
exitrect.draw(win)
exitlabel.draw(win)
# Return the inputbox and graphics window
return inputbox, win
####################################################################################################################################################################
# Define the goldhunt funtion
def GoldHunt():
# Create the window
win = GraphWin('GoldHunt', 480, 520, autoflush=False)
# Create and display black recatngle for
rclabel = Rectangle(Point(0, 0), Point(480, 40))
rclabel.setFill('black')
rclabel.draw(win)
# Display round label
rounds = Text(Point(60, 20), 'Round: 0')
rounds.setFill('gold')
rounds.setStyle('bold')
rounds.setSize(11)
rounds.draw(win)
# Display clicks title
clicks = Text(Point(420, 20), 'Clicks: 0')
clicks.setFill('gold')
clicks.setStyle('bold')
clicks.setSize(11)
clicks.draw(win)
# Return the round, clicks, and window
return win, rounds, clicks
####################################################################################################################################################################
# Define the MakeCircles function
def MakeCircles(name, win):
# Display where the players name will appear in the game window
player = Text(Point(240, 20), 'Player: {0}'.format(name))
player.setStyle('bold')
player.setFill('gold')
player.draw(win)
# Start with an empty list and fill is with 225 black circle in a grid shape
circles = []
for i in range(15):
for j in range(15):
circle = Circle(Point(30 + i*30, 70 + j*30), 15)
circle.setFill('black')
circle.setOutline('black')
circles.append(circle)
# Draw these circles in the game window
for circle in circles:
circle.draw(win)
# Make the list of appropriate colors for the circle based on where the gold circle is
randnum = randint(0,224)
# Start with a list of the color white for each circle
colors = ['white' for i in range(225)]
# Whatever index the gold circle is then assign gold, gray, and tan to appropriate circles
for i in range(225):
if i == randnum:
colors[i] = 'gold'
if i in [randnum-1, randnum+1, randnum+16, randnum+15, randnum+14, randnum-16, randnum-15, randnum-14]:
colors[i] = 'tan'
if i in [randnum-32, randnum-31, randnum-30, randnum-29, randnum-28, randnum+28, randnum+29, randnum+30, randnum+31, randnum+32, randnum-2, randnum+2, randnum-17, randnum-13, randnum+17, randnum+13, randnum-13]:
colors[i] = 'lightgray'
# Create a random integer for which the red circle will be placed
randrednum = randint(0,224)
# Define a while loop to iterate until red circle location is not that of red index
while randrednum == randnum:
randrednum = randint(0,224)
# Color specified circle to red
colors[randrednum] = 'red'
# Reset Cheats to normal board
circles[randnum].setOutline('black')
circles[randrednum].setOutline('black')
# Return list of circles and color assignments
return circles, colors, player, randrednum, randnum
###################################################################################################################################################################
# Define the goldmess function
def goldmess(golddistance, controlwin, ghwin, circles, goldcirc, roundcontinues, click, clickcount, player, roundn, clicks):
print("goldmess")
# If the click is in the gold circle, display winning message, moves all circles except gold circle down, and restart round.
if golddistance < 15:
print("yoooo")
# Play tada sound
digsound('tada.wav')
# Displays congratulatory message
Congrats = Text(Point(240, 280), 'You win!')
Congrats.setSize(15)
Congrats.setStyle('bold')
# Make all circles besides the gold circle fall off the screen
for i in range(47):
for circle in circles:
if circle != goldcirc:
update(10 ** 10)
circle.move(0, 10)
# Undraw circles once passed win to preserve space
if circle.getCenter().y > 520:
circle.undraw()
# Check if exit button is clicked and close program accordingly (cliclose not used to prevent slowing down of program)
click = controlwin.checkMouse()
if click != None and (165 <= click.x <= 245 and 140 <= click.y <= 190):
controlwin.close()
ghwin.close()
os._exit(0)
# If newgame is clicked, reset game
if click != None and (5 <= click.x <= 105 and 120 <= click.y <= 190):
print("wowzers")
clickcount = 0
roundn = 0
player.undraw()
roundcontinues = False
print("Reset Game!")
# Define the previous time
oldtime = time()
# Initialize current time
timepass = time() - oldtime
# Store a random interval between 5 and 10 as randtime
randtime = randint(5,10)
# Initialize circle movement and iterator
dx,dy = 3,-5
i = 0
# Define a while loop to run until 5-10 seconds have passed
while timepass < randtime:
# Find amount of time passed
timepass = time() - oldtime
# Update frame rate so goldcirc is clickable
update(60)
# Undraw goldcirc
goldcirc.undraw()
# Find center of goldcirc
center = goldcirc.getCenter()
# Check if click is on goldcirc
gameclick = ghwin.checkMouse()
if gameclick != None:
distance = sqrt(((gameclick.x-center.x)**2)+((gameclick.y-center.y)**2))
# If click is on goldcirc, subtract two from clickcount and play coin sound
if distance <= goldcirc.getRadius() and clickcount > 1:
clickcount -= 2
clicks.setText('Clicks: {0}'.format(clickcount))
digsound('coin.wav')
# Redraw goldcirc in new moved location
goldcirc = Circle(Point(center.x + dx, center.y + dy),15-i)
goldcirc.setFill('gold')
goldcirc.draw(ghwin)
center=goldcirc.getCenter()
# If border is hit, bounce the goldcirc away
if center.x not in range(0,480):
dx *= -1
if center.y not in range(60,520):
dy *= -1
# Make the circle smaller each time loop repeats
i += .02
# Check if exit button is clicked and close program accordingly
# (cliclose not used to prevent slowing down of program)
click = controlwin.checkMouse()
if click != None and (165 <= click.x <= 245 and 140 <= click.y <= 190):
controlwin.close()
ghwin.close()
os._exit(0)
# Otherwise, if newgame is clicked, reset the game
elif click != None and (5 <= click.x <= 105 and 120 <= click.y <= 190):
print("wowzers")
clickcount = 0
roundn = 0
player.undraw()
roundcontinues = False
print("Reset Game!")
# If circle gets as small as possible in time interval,
# break from loop to prevent it from getting larger
if 15 - i < 0.1:
break
# Undraw the golden circle
goldcirc.undraw()
# Displays congratulatory message
Congrats = Text(Point(240, 280), 'You win!')
Congrats.setSize(15)
Congrats.setStyle('bold')
Congrats.draw(ghwin)
# Click to start new round
Continue = Text(Point(240, 300),
'Click to continue...')
Continue.setSize(11)
Continue.setStyle('italic')
Continue.draw(ghwin)
ghwin.getMouse()
# When click is detected, undraw messages and gold circle in order to prepare for next round
Congrats.undraw()
Continue.undraw()
# Stop current round
roundcontinues = False
# Return necessary variables and round stoppage
return roundcontinues, clickcount, roundn, clicks
###################################################################################################################################################################
# Define the cliclose function
def cliclose(controlwin, ghwin, click):
# Slow down program to capture clicks better
sleep(0.03)
# Check for any clicks on the exitgame control
click = controlwin.checkMouse()
# If exit button is clicked, close the program
if click != None and (165 <= click.x <= 245 and 140 <= click.y <= 190):
controlwin.close()
ghwin.close()
os._exit(0)
###################################################################################################################################################################
# Define the chegclick function
def chegclick(controlwin, ghwin, click, roundn, clickcount, letsago, roundcontinues):
print("chegclick")
# Initialize game click
gameclick = None
# Define a while loop to check if new game button is clicked and if goldwin is clicked
while gameclick == None:
gameclick = ghwin.checkMouse()
# Call the newgtwist function
roundn, letsago, roundcontinues, clickcount = newgtwist(click, roundn, letsago, roundcontinues, controlwin, clickcount, ghwin)
# If new game button is clicked, restart the game
if roundcontinues == False:
break
# Return necessary variables to main
return gameclick, roundn, clickcount, letsago, roundcontinues
###################################################################################################################################################################
# Define the checklick function
def checlick(controlwin, ghwin):
print("checlick")
# Initialize click
click = None
# Define a while loop to check for click on new game or exit buttons
while click == None:
# Wait for a click in controlwin
click = controlwin.getMouse()
# If click is in new game button, return the click and start game
if (5 <= click.x <= 120 and 140 <= click.y <= 190):
print("Its in")
letsago = True
return click, letsago
# If click is on exit button, close windows and the program
elif (180 <= click.x <= 245 and 120 <= click.y <= 190):
controlwin.close()
ghwin.close()
os._exit(0)
# Otherwise, re-initialize click to repeat loop
else:
click = None
###################################################################################################################################################################
# Define the newgtwist function
def newgtwist(click, roundn, letsago, roundcontinues, controlwin, clickcount, ghwin):
# Slow down program to capture clicks
sleep(0.03)
# Check for click in controlwin
click = controlwin.checkMouse()
# Call the cliclose function
cliclose(controlwin, ghwin, click)
# If there is a click on the new game button, restart game with round and click counter reset
if click != None:
if (5 <= click.x <= 105 and 120 <= click.y <= 190):
print("wowza")
clickcount = 0
letsago = True
roundcontinues = False
if roundn > 0:
roundn = 0
print("Reset Game!")
# Return necessary variables to main
return roundn, letsago, roundcontinues, clickcount
###################################################################################################################################################################
# Define the digsound() function
def digsound(track):
# Play chosen track with compatibility for each operating system
if platform.system() == 'Windows':
winsound.PlaySound(track, winsound.SND_ASYNC)
if platform.system == 'Linux':
os.system('aplay ' + track + '&')
if platform.system == 'Darwin':
os.system('afplay ' + track + '&')
###################################################################################################################################################################
# Define the main() function
def main():
# Call GoldHunt and GameControl functions and assign appropriate variables
ghwin, rounds, clicks = GoldHunt()
playername, controlwin = GameControl()
# Intialize variables for while loops and round counts
playing = True
click = None
roundn = 0
clickcount = 0
# Play background music while user enters name
digsound('WiiMusic.wav')
# Initialize variable to count number of loop iterations
realit = 0
# While loop to continue gameplay
while playing:
# Call the checlick function if playing loop is in first iteration
# in order to initiate gameplay
if realit == 0:
click, letsago = checlick(controlwin, ghwin)
# Increase loop variable iteration by one to avoid calling checlick
realit += 1
# Get the users name from entry box
name = playername.getText()
# If name equals nothing, do not start game
if name == '':
print(name)
realit = 0
letsago = False
# Update frames to smoothen gameplay
update(60)
# If the player has entered their name and clicks new game,
# a grid of circles appears and gameplay begins
if letsago == True and name != '' or roundn >= 1:
print("newgame")
# When round begins, add one to the round count
roundn += 1
# Show the round count to user
rounds.setText('Rounds: {0}'.format(roundn))
# Call the MakeCircles() function to get a new circle set each round
circles, colors, player, randrednum, randnum = MakeCircles(name, ghwin)
# Find which circle is the gold circle
circnum = colors.index('gold')
goldcirc = circles[circnum]
# While loop for each individual round that counts clicks, sets circle fill,
# and tells user when they have found the gold circle
roundcontinues = True
while roundcontinues:
print("round continues")
# Check for mouse click in control window here so exit or new game can be clicked whenever
cliclose(controlwin, ghwin, click)
# Call the chegclick function
gameclick, roundn, clickcount, letsago, roundcontinues = chegclick(controlwin, ghwin, click, roundn, clickcount, letsago, roundcontinues)
# Call the cliclose function
cliclose(controlwin, ghwin, click)
# If q is pressed, activate cheats by outlining where border of goldcirc and redcirc is
key = controlwin.checkKey()
print(key)
if key == 'q':
goldcirc.setOutline('gold')
circles[randrednum].setOutline('red')
# Get player name from entry box
name = playername.getText()
# If entry box is not empty and new game button is pressed,
# reset the board and get out of loop
if roundcontinues == False and name != '':
print("break")
print(name)
for circle in circles:
update(90)
circle.undraw()
player.setText('')
rounds.setText('Rounds: {0}'.format(roundn))
clicks.setText('Clicks: {0}'.format(clickcount))
break
# Initialize variable to check if click is in controlwin
cloak = True
# Define a while loop to pause program until a name is entered into controlwin
while name == '':
# Update frames to smoothen game
update(60)
# Set name value to blank
player.setText('')
# Get player name
name = playername.getText()
# Repeat the round
roundcontinues = True
# Call the cliclose function
cliclose(controlwin, ghwin, click)
# Check for click on goldwin
cloak = ghwin.checkMouse
# If there is a click on goldwin while name is empty, ignore it
if cloak != None:
cloak = None
# If there is a name in controlwin entry box, continue gameplay
if cloak != None:
# Fill the clicked circles with the assigned color if it has been clicked
for j in range(225):
center = circles[j].getCenter()
distance = sqrt(((gameclick.x - center.x)**2) + ((gameclick.y - center.y)**2))
goldcenter = goldcirc.getCenter()
golddistance = sqrt(((gameclick.x - goldcenter.x)**2) + ((gameclick.y - goldcenter.y)**2))
# If the click is detected on within the circle(in radius), fill it with assigned color
# Add one to click counter when the circle is clicked and color is revealed
# If a red circle is clicked, add 5 to current click count
# Update click count only if circle was not previously revealed
if distance < 15 and circles[j].config["fill"] == "black":
print(abs(distance - golddistance))
if abs(distance - golddistance) < 86:
circles[j].setFill(colors[j])
clickcount += 1
digsound('digclick.wav')
elif j == randrednum:
print('hey')
circles[j].setFill('red')
clickcount += 5
digsound('trombone.wav')
else:
circles[j].setFill("white")
clickcount += 1
if circles[j].config["fill"] != "red":
digsound('digclick.wav')
# Update the click count text
clicks.setText('Clicks: {0}'.format(clickcount))
# Call the goldmess function
roundcontinues, clickcount, roundn, clicks = goldmess(golddistance, controlwin, ghwin, circles, goldcirc, roundcontinues, click, clickcount, player, roundn, clicks)
# Get out of playing loop to stop game after 5th round
if roundn == 5:
# Open the file to read its data
scorefile = open('scores.txt', 'r')
# Save the file as a list
scoredata = scorefile.readlines()
# Close the file
scorefile.close()
# Create an updated version without extra characters
NameScoreL = []
# Append the recently made score in the correct format
NameScoreL.append([name, clickcount])
# If the data from the scores file is not empty retrive it, reformat it and append it into the formatted list of names and scores.
if scoredata != []:
for item in scoredata:
NameScoreL.append(item.rstrip('\n').replace(' ', '').split(','))
for item in NameScoreL:
item[1] = int(item[1])
# Sort the list according to the score (second item in each list)
NameScoreL = sorted(NameScoreL, key=lambda x: x[1])
# Open the file again in order to manipulate it
scorefile = open('scores.txt', 'w')
# Write this updated list to the file
for item in NameScoreL:
scorefile.write(('{0}, {1}\n').format(item[0], item[1]))
scorefile.close()
# If the scores file is empty then just write the newly made score to it.
elif scoredata == []:
# Open the file again in order to manipulate it
scorefile = open('scores.txt', 'w')
# Write the new name and score into file
scorefile.write(('{0}, {1}\n').format(name, clickcount))
# Close the file
scorefile.close()
# Update the top 3 display and give user a chance to exit game for good or start new
controlwin.close()
ghwin.close()
# Call functions and assign appropriate variables
ghwin, rounds, clicks = GoldHunt()
playername, NEWGAME, EXIT, controlwin = GameControl()
# Close all windows to stop program and stop background music
ghwin.close()
controlwin.close()
# Play sound at end of the game
digsound('endgame.wav')
sleep(2.5)
main()
|
a906bbc1f0ba8b914af5bdd18781acfe319fc64b | Cyclone96/Bootcamp | /Guessthenumber.py | 1,494 | 4.0625 | 4 | import random
number = random.randint(1, 10)
player_name = input("State your name: ")
number_of_guesses = 0
print('Hola '+ player_name+ ' Guess any number between 1 to 10:')
print()
def game():
number = random.randint(1, 10)
print("You got five guesses to make starting now....!")
i = 1
r = 1
while i<6:
user_number = int(input('Enter your number: '))
if user_number < number:
print("Your guess is too low")
print()
print("You now have " + str(5-i)+ " chances left" )
i = i+1
elif user_number > number:
print("Your guess is too high")
print()
print("You now have " + str(5-i)+ " chances left" )
i = i+1
elif user_number == number:
print("\nYou have guessed the correct number!")
print("Yaaay! Keep going!!! :)")
r = 0;
break
else:
print("Invalid Choice")
print("You have " + str(5-i)+ " chances left" )
continue
if r==1:
print("Dang!!! You lost!!")
print()
print("My choice was = " + str(number))
print("Try again next round!")
def main():
game()
while True:
another_game = input("Do you wish to play again?(y/n): ")
if another_game == "y":
game()
else:
break
main()
print("\nThe End! Thanks for coming :)") |
3df395d1649f498f66b47fdee9cff2e50e2158b9 | Jackyzzk/Algorithms | /搜索-DFS-03-0547. 朋友圈-并查集.py | 2,488 | 3.578125 | 4 | class UnionFindSet(object):
def __init__(self, n):
self.parent = [i for i in range(n)]
self.depth = [0] * n
self.count = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
px = self.find(a) # parent_x
py = self.find(b)
if px == py:
return
self.count -= 1
if self.depth[px] < self.depth[py]:
self.parent[px] = py
else:
self.parent[py] = px
if self.depth[px] == self.depth[py]:
self.depth[px] += 1
class Solution(object):
"""
班上有 N 名学生。其中有些人是朋友,有些则不是。他们的友谊具有是传递性。
如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友。
所谓的朋友圈,是指所有朋友的集合。
给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系。
如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道。
你必须输出所有学生中的已知的朋友圈总数。
输入:
[[1,1,0],
[1,1,0],
[0,0,1]]
输出: 2
说明:已知学生0和学生1互为朋友,他们在一个朋友圈。
第2个学生自己在一个朋友圈。所以返回2。
输入:
[[1,1,0],
[1,1,1],
[0,1,1]]
输出: 1
说明:已知学生0和学生1互为朋友,学生1和学生2互为朋友,所以学生0和学生2也是朋友,所以他们三个在一个朋友圈,返回1。
N 在[1,200]的范围内。
对于所有学生,有M[i][i] = 1。
如果有M[i][j] = 1,则有M[j][i] = 1。
链接:https://leetcode-cn.com/problems/friend-circles
"""
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
n = len(M)
ufs = UnionFindSet(n)
for i in range(n):
for j in range(i):
if M[i][j]:
ufs.union(i, j)
return ufs.count
def main():
# grid = \
# [[1,1,0],
# [1,1,0],
# [0,0,1]]
grid = \
[[1,1,0,0],
[1,1,0,1],
[0,0,1,0],
[0,1,0,1]]
# grid = \
# [[1,1,0],
# [1,1,1],
# [0,1,1]]
# grid = [[1]]
# grid = \
# [[1,0,0,1],
# [0,1,1,0],
# [0,1,1,1],
# [1,0,1,1]]
grid = \
[[1,1,1],
[1,1,1],
[1,1,1]]
test = Solution()
ret = test.findCircleNum(grid)
print(ret)
if __name__ == '__main__':
main()
|
b0068da9c5509cce9f44b7ab16015327c6585c12 | rusheelkurapati30/Python | /oxfordDictionary.py | 1,620 | 3.515625 | 4 | # Program on oxford dictionary to print the meaning of the given word.
import requests
app_id = "cd9f1a0d"
app_key = "1f766ec01c258b21809ed532ff88579f"
language = "en-gb"
word_id = input("\nPlease enter a word: ")
url = "https://od-api.oxforddictionaries.com:443/api/v2/entries/" + language + "/" + word_id.lower()
response = requests.get(url, headers={"app_id": app_id, "app_key": app_key})
print(type(response))
if response:
definitionData = eval(response.text)
print(type(definitionData))
definitionList = []
for result in definitionData['results'][0]["lexicalEntries"][0]["entries"][0]['senses']:
definitionList.append(result['definitions'][0])
# print(definitionList)
print("\nThe list of meanings available for " + word_id + " is: \n")
counter = 0
for definition in definitionList:
counter += 1
print(str(counter) + ". " + definition)
else:
print("\nNo matches found please try again with different word")
# for result in definitionData['results']:
# for lexicalEntry in result['lexicalEntries']:
# for entry in lexicalEntry['entries']:
# for sense in entry['senses']:
# definitions = []
# for definition in wordMeaning["results"][0]["lexicalEntries"][0]["entries"][0]["senses"]:
# definition.append(sense["definitions"][0]
# x = wordMeaning["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["definitions"][0]
# y = wordMeaning["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["subsenses"][0]["definitions"][0] |
c131c5141baf172e34d220ab98ed9e78cf9384b7 | Aasthaengg/IBMdataset | /Python_codes/p03573/s049454534.py | 137 | 3.625 | 4 | args = input().split()
a = int(args[0])
b = int(args[1])
c = int(args[2])
if a == b:
print(c)
elif a == c:
print(b)
else:
print(a) |
464ef743d367211f28dd54f311c3f360ad32a737 | songyingxin/python-algorithm | /排序算法/select_sort.py | 921 | 4.0625 | 4 | # -*- coding:utf-8 -*-
import util
def find_smallest(arr, left, right):
smallest = arr[left]
smallest_index = left
for i in range(left, right + 1):
if arr[i] < arr[smallest_index]:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
for i in range(len(arr)):
smallest_index = find_smallest(arr, i, len(arr)-1)
arr[i], arr[smallest_index] = arr[smallest_index], arr[i]
return arr
if __name__ == "__main__":
test_time = 100
max_size = 10
max_value = 10
min_value = 0
for i in range(test_time):
arr1 = util.get_random_array(max_size, min_value, max_value)
arr2 = arr1.copy()
selection_sort(arr1)
if arr1 != sorted(arr2):
print("the false sample is {}".format(arr2))
print("the result of the false is {}".format(arr1))
break
|
dde6e505ef16327ef1738fe759999c99dc8a1fab | LiHuaigu/Tomasulo_Simulatior | /mem.py | 552 | 3.578125 | 4 | from tabulate import tabulate
class mem(object):
def __init__(self, name, value):
self.name = name
self.value = value
class Memory(object):
def __init__(self, size, values):
self.memoryList = []
self.size = size
for i in range(size):
mem = mem("R"+str(i), values[i])
self.memoryList.append(mem)
def load_in_memory_ByName(self, name):
return self.memoryList[int(name[1:])]
def store_in_memory(self, name, value):
self.memoryList[int(name[1:])] = value
|
2c1b3fd327c5b326fd66ba5eb8dc5657f3865913 | ChocolatePadmanaban/Learning_python | /Day7/part_11.py | 401 | 3.890625 | 4 | # milti dimenstional element finding(find the location of first occurance)
A= [[1,2],[2,[5,6]],3]
def Extract(a, e):
for i in a:
b = [a.index(i)]
if i == e:
print(i)
break
elif type(i) == list and Extract(i,e) != None:
c = Extract(i,e)
b = b + Extract(i,e)
else:
break
return b
print(Extract(A, 1)) |
47944a85911ec15b8d430ab832320dafed06de48 | CiyoMa/leetcode | /searchForARange.py | 1,100 | 3.515625 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return a list of length 2, [index1, index2]
def searchRange(self, A, target):
low = 0
high = len(A) - 1
# find lower bound, first target
lowerBound = -1
while low <= high:
mid = (low + high) / 2
if A[mid] == target and (mid == low or mid - 1 >= 0 and A[mid-1] < target):
lowerBound = mid
break
elif A[mid] < target:
low = mid + 1
else:
high = mid - 1
# find higher bound, last target
higherBound = -1
low = 0
high = len(A) - 1
while low <= high:
mid = (low + high) / 2
if A[mid] == target and (mid == high or mid + 1 <= len(A) and A[mid+1] > target):
higherBound = mid
break
elif A[mid] <= target:
low = mid + 1
else:
high = mid - 1
return [lowerBound, higherBound]
A = [5, 7, 7, 8, 8, 10]
target = 10
s = Solution()
print s.searchRange(A, target) |
f1076cefdf169812644489c76ffd38daddd3e3b7 | cgarrido2412/PythonPublic | /Learning Tutorials/Automate The Boring Stuff/sending_email.py | 997 | 3.53125 | 4 | import smtplib
import datetime
#Connecting to outlook smtp server and establishing tls session
smtpObj = smtplib.SMTP('smtp-mail.outlook.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
#login and authentication
email = str(input('Please enter your e-mail:'))
password = str(input('Please enter your password:'))
smtpObj.login(email, password)
#Defining subject and message body
subj = str(input('Subject:'))
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = str(input('Message:'))
#source and destination e-mail addresses
from_addr = email
to_addr = str(input("Please enter who you'd like to send an e-mail to:"))
#Appending subject and message body into a single variable
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, message_text )
#Sending the e-mail. Having blindcopy defined will send BCC e-mail
blindcopy = str(input('Please enter an address to blind copy to:'))
smtpObj.sendmail(email, blindcopy, msg)
smtpObj.quit()
|
a10dc0c1c050f14f5b4c76bcead2f2805d2bbfcd | indo-seattle/python | /rakesh/Exercise2.py | 154 | 4.09375 | 4 | print("Exercise 2 - String Concatenation")
fName = str(input())
lName = str(input())
fullname = fName + " " + lName
print("The full name is " + fullname)
|
a23e15ae8dbf80097241b05617fd065e6fdd3a6b | lion7500000/python-selenium-automation | /Python program/longest_words.py | 456 | 4.21875 | 4 | str = input ('Input text:')
# converting string to list
list_str = str.split()
# index max word = 0
max_word = 0
# for i in range(1,len(list_str)):
# if len(list_str[max_word])<len(list_str[i]):
# max_word = i
#
# print (list_str[max_word])
#alternative
def max (str):
max = 0
for i in str.split(' '):
if max< len(i):
max = len(i)
word = i
print (f'Longest word - {word}, {max} symbols')
max(str)
|
79e7f531f1e83f7ec118c6acd9d28c19355bb3b3 | angadsinghsandhu/tensortorch | /Examples/regression_eg.py | 942 | 3.734375 | 4 | from Framework.RegressionFramework import NeuralNetwork
from Framework.predict import predict_regression as predict
from Framework.normalize import normalize
from Data_Creation import regression_data
def run():
# getting data
x_train, y_train = regression_data.data(values=1000)
# normalizing data
# x_train = normalize(x_train)
offset = 0
factor = 1
# instantiating object
network = NeuralNetwork(x_train, y_train, learning_rate=0.06, num_layers=4)
# displaying base information
network.displayNN()
# running our network
for i in range(3):
network.train() # training our network
# # display functions
# network.displayNN_forward(i)
# network.displayNN_backward(i)
network.displayNN_loss(i)
network.resetloss() # resetting our loss after each iteration
print("\n\n")
# predicting our data
predict(network, offset, factor)
|
d2bab5b3e5e8443923a0a7967243c40766f3763d | noahsug/connect4ann | /data_generation/heuristic.py | 1,057 | 3.59375 | 4 | import board
class Heuristic:
def setState(self, state):
self.state = state
def getMove(self):
pass
##
# Report the result of a game, or that it is unfinished.
# @param {GameState} state
# @return {int} The game result:
# 2 for unfinished game,
# 1 for first player victory,
# -1 for second player victory,
# 0 for draw
##
def getGameResult(self):
if self.state.getWinner() != None:
return self.state.getWinner()
moves = [move for move in self.state.getAvailableMoves()]
if len(moves) is 0:
return 0
return board.UNFINISHED
##
# Get a move that will either immediately result in victory or prevent immediate defeat.
# return {int} the column to place in, or None for no forced moves.
##
def getForcedMove(self):
for move in self.state.getAvailableMoves():
if self.isForced(move):
return move
return None
def isForced(self, move):
for player in [1, -1]:
if self.state.getLineCompleteness(move, player).hasWin():
return True
|
472614957563d51493fbf6a12a47a267906f2c00 | nkhanhng/namkhanh-fundamental-c4e15 | /session2/sum-n.py | 209 | 3.796875 | 4 | x = int(input("Enter a number: "))
total = 0 #squence = range(n+1)
#result = sum(squence)
for i in range(x + 1):
total += i
print(total)
#c2
|
fcf4ede757ff0851657472ae0a4f1848e7274043 | jbhennes/CSCI-220-Programming-1 | /Chapter 13 - Algorithms/Student.py | 2,260 | 3.921875 | 4 | # Student.py
# Author: RoxAnn H. Stalvey
# Student class
# Student's data members: id number, firstName, lastName,
# list of grades, date of enrollment
from Date import Date
class Student:
def __init__(self, stuNum, firstName, lastName, grades, date):
self.studentNumber = stuNum
self.firstName = firstName
self.lastName = lastName
self.grades = []
for grade in grades:
self.grades.append(grade)
#clone date for enrollDate instead of setting enrollDate = date
self.enrollDate = Date()
self.enrollDate.setDate(date.getMonth(),date.getDay(),date.getYear())
def addGrade(self, grade):
self.grades.append(grade)
def getStudentNumber(self):
return self.studentNumber
def getName(self):
return self.firstName + " " + self.lastName
def getFirst(self):
return self.firstName
def getLast(self):
return self.lastName
def getGrades(self):
return self.grades
def getEnrollDate(self):
return self.enrollDate
def setName(self, first, last):
self.firstName = first
self.lastName = last
def setGrades(self, grades):
self.grades = []
for grade in grades:
self.grades.append(grade)
def setEnrollDate(self, date):
self.enrollDate = Date()
self.enrollDate.setDate(date.getDay(),date.getMonth(),date.getYear())
def calcAvg(self):
total = 0.0
count = 0
for grade in self.grades:
count = count + 1
total = total + grade
if count == 0:
avg = -1
else:
avg = total / count
return avg
def __str__(self):
out = "Student number: " + str(self.getStudentNumber())
out = out + "\nStudent name: " + self.getName()
out = out + "\nEnroll Date: " + str(self.getEnrollDate())
if len(self.grades) != 0:
out = out + "\nGrades: " + str(self.getGrades())
out = out + "\nAverage: " + str(self.calcAvg())
else:
out = out + "\nThis student has no grades."
return out
|
3f9041d3d1c2b9444d5929b395c869d754232ac7 | klistwan/project_euler | /108.py | 619 | 3.640625 | 4 |
from time import time
print "#108 - Diophantine Equation: What is the least value of n for which\n\
the number of distinct solutions exceeds one-thousand?\n"
start = time()
result = 0
def main(e):
n = 30
while True:
c = 0
for x in xrange(n+1,n*2+1):
y = float(-n*x)/(n-x)
if y % 1 == 0 and y > 0:
c += 1
if c > e:
return n
if n % 10000 == 0: print n
n += 30
result = main(1000)
print "Answer:", result
print "\ndone in", str(time()-start), "Seconds"
print "any key to continue..."
getch()
|
0a27a09c20487c9ba37cc36439a347776823a56d | nanfeng729/code-for-test | /python/python_course/pythonStudyDay3/whilelianxi.py | 541 | 3.96875 | 4 |
# 导入random模块
# 使用random模块下的randrange()函数随机生成一个数字
# n = random.randrange(0, 100)
# 从键盘输入数字猜n的值,如果猜大了给出猜大了的提升,如果猜小了给出猜小了的提升
# 猜错了一直猜下去,猜对了结束程序
import random
from random import randrange
n = randrange(0, 100)
m = int(input("猜:"))
while m != n:
if m>n:
print("猜大了")
else:
print("猜小了")
m = int(input("继续猜:"))
print("猜对了") |
c58316c7acba0d93a5628cc8e0c70101e36c462b | afrid18/Data_structures_and_algorithms_in_python | /chapter_4/exercise/C_4_14.py | 851 | 3.515625 | 4 | # IntheTowersofHanoipuzzle,wearegivenaplatformwiththreepegs,a, b, and c, sticking out of it. On peg a is a stack of n disks, each larger than the next, so that the smallest is on the top and the largest is on the bottom. The puzzle is to move all the disks from peg a to peg c, moving one disk at a time, so that we never place a larger disk on top of a smaller one. See Figure 4.15 for an example of the case n = 4. Describe a recursive algorithm for solving the Towers of Hanoi puzzle for arbitrary n. (Hint: Consider first the subproblem of moving all but the nth disk from peg a to another peg using the third as “temporary storage.”)
""" A recursive algorithm to solve towers of hanoi problem """
def ToH(n, from_rod, to_rod, aux_rod):
if n == 1:
print("Move 1 from rod", from_rod , "to", to_rod)
return
ToH(n-1,
|
80f095435fbb7c1575644a5bd9663c1a8473136f | NishantNair14/complex--number-calculator | /code.py | 1,699 | 3.515625 | 4 | # --------------
import pandas as pd
import numpy as np
import math
#Code starts here
class complex_numbers:
def __init__(self,real,imag):
self.real=real
self.imag=imag
#return(self.real,'+' if self.imag>=0 else '-', abs(self.imag))
print(self.real,'+',self.imag,'i')
def __add__(self,other):
x=self.real+other.real
y=self.imag+other.imag
return complex_numbers(x,y)
def __sub__(self,other):
x=self.real-other.real
y=self.imag-other.imag
return complex_numbers(x,y)
def __mul__(self,other):
x=(self.real*other.real)-(self.imag*other.imag)
y=(self.imag*other.real)+(self.real*other.imag)
return complex_numbers(x,y)
def __truediv__(self,other):
x=(self.real*other.real+self.imag*other.imag)/(pow(other.real,2)+pow(other.imag,2))
y=(self.imag*other.real-self.real*other.imag)/(pow(other.real,2)+pow(other.imag,2))
return complex_numbers(x,y)
def absolute(self):
x=math.sqrt(pow(self.real,2)+pow(self.imag,2))
return x
def argument(self):
x=math.degrees(math.atan(self.imag/self.real))
return round(x,2)
def conjugate(self):
x=self.real
y=-self.imag
return complex_numbers(x,y)
comp_1=complex_numbers(3,5)
comp_2=complex_numbers(4,4)
comp_sum=comp_1+comp_2
comp_diff=comp_1-comp_2
comp_prod=comp_1*comp_2
comp_quot=comp_1/comp_2
comp_abs=comp_1.absolute()
print(comp_abs)
comp_arg=comp_1.argument()
print(comp_arg)
comp_conj=comp_1.conjugate()
print(comp_conj)
|
2b8ea0ec1523bc137fc4c35d365cacf4358991b9 | wecchi/univesp_com110 | /Sem2-Texto21.py | 1,308 | 4.1875 | 4 | '''
Texto de apoio - Python3 – Conceitos e aplicações – uma abordagem didática (Ler: seções 2.3, 2.4 e 4.1) | Sérgio Luiz Banin
Problema Prático 2.1
Escreva expressões algébricas Python correspondentes aos seguintes comandos:
(a)A soma dos 5 primeiros inteiros positivos.
(b)A idade média de Sara (idade 23), Mark (idade 19) e Fátima (idade 31).
(c)O número de vezes que 73 cabe em 403.
(d)O resto de quando 403 é dividido por 73.
(e)2 à 10a potência.
(f)O valor absoluto da distância entre a altura de Sara (54 polegadas) e a altura de Mark (57 polegadas).
(g)O menor preço entre os seguintes preços: R$ 34,99, R$ 29,95 e R$ 31,50.
'''
a = 1 + 2 + 3 + 4 + 5
b = (23 + 19 + 31) / 3
c = 403 // 73
d = 403 % 73
e = 2 ** 10
f = abs(54 - 57)
g = min(34.99, 29.95, 31,50)
print('(a)A soma dos 5 primeiros inteiros positivos.', a)
print('(b)A idade média de Sara (idade 23), Mark (idade 19) e Fátima (idade 31).', b)
print('(c)O número de vezes que 73 cabe em 403.', c)
print('(d)O resto de quando 403 é dividido por 73.', d)
print('(e)2 à 10a potência.', e)
print('(f)O valor absoluto da distância entre a altura de Sara (54 polegadas) e a altura de Mark (57 polegadas).', f)
print('(g)O menor preço entre os seguintes preços: R$ 34,99, R$ 29,95 e R$ 31,50. ', g)
|
6100a7aceb52152b245f8889db0dcf2f4e074eb4 | M45t3rJ4ck/Py-Code | /HD - Intro/Task 17/Homework/alternative.py | 516 | 4.34375 | 4 | # Create a program called “alternative.py” that reads in a sting and makes
# each alternate character an Uppercase character and each other alternate
# character a lowercase character.
# Collecting user input
U_string = input("Please enter your sentence to convert: \n").lower()
U_string = list(U_string)
while len(U_string) > 0:
if len(U_string) >= 3:
string = U_string[::2]
string = str(string)
U_string = string.upper()
print(str(U_string))
input("Press enter to exit")
|
e24147247fc053f8a7b844f840adbeb6c81fa259 | chydream/python | /base/obj7.py | 2,302 | 3.609375 | 4 | # 1.异常处理 异常类 Exception
def test_divide():
try:
5/0
except:
print("报错了,除数不能为0")
def test_div(num1,num2):
return num1 / num2
# 2.自定义异常
class ApiException(Exception):
err_code = ''
err_msg = ''
def __init__(self, err_code = None,err_msg = None):
self.err_code = self.err_code if self.err_code else err_code
self.err_msg = self.err_msg if self.err_msg else err_msg
def __str__(self):
return 'Error:{0} - {1}'.format(self.err_code, self.err_msg)
class InvalidCtrlExec(ApiException):
err_code = '40001'
err_msg = '不合法的调用凭证'
class BadPramsException(ApiException):
err_code = '40002'
err_msg = '2个参数必须都是整数'
def divide(num1,num2):
if not isinstance(num1,int) or not isinstance(num2, int):
raise BadPramsException()
if num2 == 0:
print(3)
raise ApiException('400000', '除数不能为0!!!')
return num1 / num2
# 抛出异常及异常的传递,如果在异常产生的地方不捕获,那么它会一层一层的往上传递
def my_for():
for x in range(1,10):
print(x)
if x == 5:
raise ApiException('1', '我故意的') # 抛出异常
def do_sth():
print('开始do_sth')
my_for()
print('结束do_sth')
def test_trans():
print('开始测试')
try:
do_sth()
except ApiException as e: # 捕获异常
print('我在最外层捕获到了:{0}'.format(e))
print('结束测试')
if __name__ == '__main__':
test_trans()
# try:
# divide(5, 1)
# except BadPramsException as e:
# print(1)
# print(e)
# except ApiException as a:
# print(2)
# print(a)
# else:
# print('没有异常发声')
# test_divide()
# try:
# f = open('demo.py', 'r', encoding='utf-8')
# res = f.read()
# # rest = test_div(5/'s')
# # print(rest)
# except (ZeroDivisionError, TypeError) as e:
# print(e)
# finally:
# try:
# f.close()
# print('文件关闭')
# except:
# pass
# except TypeError:
# print("请输入数字类型")
# rest = test_div(5 / 's')
# print(rest)
|
6797066f06fa4e56aa0741334551e044c5da157d | Naz2020/python | /phone_number.py | 1,893 | 3.96875 | 4 | '''
Anas Albedaiwi
albedaiwi1994@gmail.com
'''
def _check_first_format(phone_number):
if len(phone_number) < 14:
return False
if phone_number[0] == '(' and phone_number[4] == ')' and phone_number[5] == ' ' and phone_number[9] == '-':
digits= [1, 2, 3, 6, 7, 8, 10, 11, 12, 13]
for d in digits:
if not phone_number[d].isdigit():
return False
return True
else:
return False
def _check_second_format(phone_number):
if len(phone_number) < 12:
return False
if phone_number[3] == '-' and phone_number[7] =='-':
digits = [0, 1, 2, 4, 5,6, 8, 9, 10, 11]
for d in digits:
if not phone_number[d].isdigit():
return False
return True
else:
return False
def _convert_first_to_second(phone_number):
digits = [1, 2, 3, 6, 7, 8, 10, 11, 12, 13]
new_number = ''
dash = [3, 7]
counter = 0
for d in digits:
new_number+=phone_number[d]
counter+=1
if counter in dash:
new_number += '-'
return new_number
def standardize_phone_number(phone_number):
if _check_second_format(phone_number):
return phone_number
if _check_first_format(phone_number):
return _convert_first_to_second(phone_number)
return None
print(standardize_phone_number('(123) 456-7890'))
print(standardize_phone_number('123-456-7890'))
|
4ca0559dc1ae075a6e2b8c6ada8647ee2ca79794 | saurabhpiyush1187/python_project | /pythonProject/common_factors2.py | 1,142 | 4 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from math import sqrt
# Write your code here
# Function to calculate gcd of two numbers
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
# Function to calculate all common divisors
# of two given numbers
# a, b --> input integer numbers
def commDiv(a, b):
# find GCD of a, b
n = gcd(a, b)
print("gcd is " + str(n))
# Count divisors of n
result = 0
for i in range(1, int(sqrt(n)) + 1):
# if i is a factor of n
if n % i == 0:
# check if divisors are equal
if n / i == i:
result += 1
else:
result += 2
return result
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
a, b = str(input()).split(' ')
a, b = int(a), int(b)
print(commDiv(a, b))
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
c72203bcb69712eca8a6ad97a7485da81c09d042 | AFatWolf/cs_exercise | /2.3- Let start python/assignment4.py | 175 | 3.828125 | 4 | total_legs = int(input("total legs:"));
num_turtles = int(input("number of turtles:"))
num_cranes = (total_legs - num_turtles*4)//2
print("number of cranes are:", num_cranes)
|
1b8afdc67d9b4fd21e143e7bb17db3b4da7e7954 | disatapp/Operating-Systems | /Operating Systems/Homework2/Problem3.py | 1,035 | 3.734375 | 4 | # Pavin Disatapundhu
# disatapp@onid.oregonstate.edu
# CS344-400
# homework#2 Question3
import os
import sys
import urllib2
import urlparse
def main(argv):
win = ''
wout = ''
infolder = os.environ['HOME']+"/Downloads"
if len(argv) == 3:
win = argv[1]
wout = argv[2]
if not os.path.isdir(infolder):
os.mkdir(infolder)
print 'New download folder created!!'
if win and wout:
wget(win, wout, infolder)
else:
sys.exit('Invalid: please enter 2 arguments.')
def rephrase(url):
if not urlparse.urlparse(url).scheme:
url = "http://"+url
return url
def wget(url, outfile, inf):
fname = outfile
try:
w = urllib2.urlopen(rephrase(url))
d = w.read()
output = open(inf + "/" + outfile, "wb")
output.write(d)
print "Write success!! Find file in /User/<name>/Downloads folder"
except urllib2.HTTPError, e:
sys.exit(str(e))
except urllib2.URLError, e:
sys.exit(str(e))
if __name__ == "__main__":
main(sys.argv)
|
e4b892a58f40e89206477d0c220daecb02046440 | knparikh/IK | /LinkedLists/longest_balanced_parenthese_string/longest_parenthese_string.py | 1,283 | 4 | 4 | #!/bin/python3
# Given a string with brackets (, ), find longest substring which is balanced.
import sys
import os
# Use a stack to record positions of open bracket. When ) bracket is encountered, pop last char (mostly a ''('').
# If stack is not empty, record length of current string as curr index - index before popped char, if more than max.
# If stack is empty, push current index to start counting for next substring.
def find_max_length_of_matching_parentheses(brackets):
inp = list(brackets)
max_len = 0
stack = [-1]
for i in range(len(inp)):
if inp[i] == '(':
stack.append(i)
else:
#char is ')', pop last char , mostly ( bracket
stack.pop()
# Record the length of this newly found balanced parenthese string if more than max
if len(stack) > 0:
len_str = i - stack[-1]
max_len = max(max_len, len_str)
else:
# Stack is empty. Push this index to make base of next string
stack.append(i)
return max_len
if __name__ == "__main__":
try:
brackets = str(raw_input())
except:
brackets = None
res = find_max_length_of_matching_parentheses(brackets);
print(str(res) + "\n")
|
2002bf7e49fbe8c7bf4ecce82d8993913d44e541 | AshishOhri/machine_learning_course_python | /simple_linear_regression/simple_linear_regression.py | 1,186 | 4.40625 | 4 | '''
This notebook is a simple implementation of linear regression from scratch in python.
'''
# Equation y=theta(0)*x0+theta(1)*x1
# We are trying to get the values of theta which is where the learning in machine learning takes place.
import numpy as np
def hyp_fn(theta,X): # hypothesis function
return theta.T@X
def cost_fn(theta,X,m,y): # cost function
h=hyp_fn(theta,X)
return 1/(2*m)*np.sum((h-y).T@(h-y))
def gradient_fn(theta,X,m,y,alpha=0.3): # calculates the gradient descent, changing the value of theta iteratively
for i in range(100):
h=hyp_fn(theta,X)
theta-=alpha/m*(X@(h-y))
print('Cost/Error:',cost_fn(theta,x,len(x),y))
return theta
theta=np.array([[0,0]]).T # shape (before transpose): 1X2 (after transpose):2X1
y=np.array([[2]]) #shape: 1X1
x=np.array([[0],[1]]) # shape: 2X1
y=y.astype('float32')
x=x.astype('float32')
theta=theta.astype('float32')
theta=gradient_fn(theta,x,len(x),y)
print('\nTheta = ',theta)
print("y=%f*x0+%f*x1"%(theta[0],theta[1])) # We get the equation of theta as y=2x and rightly so
# This can be cross checked by looking at the values of y and x array |
adef42fb162acdfcb4b6e1703a6256afa7e6be35 | Ojitos369/sumaVectores-MulpiplicacionComplejos | /src/vectores.py | 1,146 | 3.65625 | 4 | #----------- IMPORTACIONES ----------
from src.extras import limpiar
import src.menus as menus
import matplotlib.pyplot as plt
#----------- FUNCIONES ----------
def suma(v1,v2):
vr = [0,0]
vr[0] = v1[0]+v2[0]
vr[1] = v1[1]+v2[1]
return vr
def main():
vector1 = menus.vectores('primer')
vector2 = menus.vectores('segundo')
resultado = suma(vector1,vector2)
print('la suma de los vectores: ')
print(f'{vector1}+{vector2} = {resultado}')
x1 = [0,vector1[0]]
y1 = [0,vector1[1]]
x2 = [0,vector2[0]]
y2 = [0,vector2[1]]
rx = [0,resultado[0]]
ry = [0,resultado[1]]
xs1 = [vector2[0], resultado[0]]
ys1 = [vector2[1], resultado[1]]
xs2 = [vector1[0], resultado[0]]
ys2 = [vector1[1], resultado[1]]
plt.plot(rx,ry, 'x-k', label='resultado', linewidth = 4)
plt.plot(x1,y1, '^-r', label='vector1', linewidth = 3)
plt.plot(x2,y2, '^-m', label='vector2', linewidth = 3)
plt.plot(xs1,ys1, '--r', label='suma1', linewidth = 2)
plt.plot(xs2,ys2, '--m', label='suma2', linewidth = 2)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Suma')
plt.show()
|
081532556a5e23e852475e7a0d064d671b32c3a4 | tlyons9/draftcompanion | /tap_beer.py | 2,982 | 3.515625 | 4 | import requests
import csv
import pandas
# starting off, we need to get the beer sheet from the internet
# given the league settings, get the correct beer sheet.
kickers = ['Greg Zuerlein', 'Justin Tucker', 'Harrison Butker', 'Stephen Gostokowski',
'Wil Lutz', "Ka'imi Fairbairn", 'Mason Crosby', 'Jake Elliot', 'Brett Maher',
'Michael Badgley', 'Robbie Gould', 'Matt Prater', 'Adam Vinatieri', 'Jason Myers',
'Graham Gano']
defenses = ['Bears', 'Jaguars', 'Rams', 'Ravens', 'Vikings', 'Chargers', 'Texans',
'Browns', 'Saints', 'Broncos', 'Patriots', 'Cowboys', 'Bills', 'Eagles', 'Seahawks']
def tap(url):
df = pandas.read_csv(url)
df.to_csv('tap.csv')
# now we need to create a dictionary from the csv file.
def pour():
pour = csv.DictReader(open('tap.csv'))
players = {}
for sip in pour:
name = sip["Name"].title()
del sip["Name"]
players[name] = sip
playersdf = pandas.DataFrame(players)
playersdf.to_csv('players.csv')
# remove a player from the available players list
def draft(player):
player = player.title()
if player in kickers:
kickers.remove(player)
elif player in defenses:
defenses.remove(player)
else:
players = pandas.read_csv('players.csv', header=0, index_col=0)
players = players.drop(columns=player)
players.to_csv('players.csv')
# display top 5 players available from each role
def serve():
qbs = []
rbs = []
wrs = []
tes = []
ecr = []
ks = []
dst = []
players = pandas.read_csv('players.csv', header=0, index_col=0)
playersECR = players.T
playersECR["ECR"] = playersECR["ECR"].astype(float)
playersECR = playersECR.sort_values(by=["ECR"])
playersECR = playersECR.T
for player in players:
if players[player]["Position"] == "QB":
if len(qbs) < 10:
qbs.append([player, players[player]["ECR"],
players[player]["ECR vs ADP"]])
elif players[player]["Position"] == "RB":
if len(rbs) < 10:
rbs.append([player, players[player]["ECR"],
players[player]["ECR vs ADP"]])
elif players[player]["Position"] == "WR":
if len(wrs) < 10:
wrs.append([player, players[player]["ECR"],
players[player]["ECR vs ADP"]])
elif players[player]["Position"] == "TE":
if len(tes) < 10:
tes.append([player, players[player]["ECR"],
players[player]["ECR vs ADP"]])
else:
continue
for playerECR in playersECR.keys():
if len(ecr) < 10:
ecr.append([playerECR, playersECR[playerECR]["ECR"],
playersECR[playerECR]["ECR vs ADP"]])
for kicker in kickers:
if len(ks) < 10:
ks.append(kicker)
for defense in defenses:
if len(dst) < 10:
dst.append(defense)
return qbs, rbs, wrs, tes, ecr, ks, dst
|
f8f10d0a0a538ff53c5afc9338b507063738e153 | fionnmccarthy/pands-problem-sheet | /secondstring.py | 904 | 4.1875 | 4 | # secondstring.py
# Weekly Task 03.
# This program asks a user to input a string and outputs every second letter in reverse order.
# author: Fionn McCarthy - G00301126.
# The input function is used below in order to get the user to enter a sentence.
input_string = input('Please enter a sentence:')
# From research I gathered the formula used here for string slicing is - str_object[start_pos:end_pos:step].
# As we want the full length of the string we do no enter the 'start_pos' or the 'end_pos' as we will use the full string.
# The '-' below is used to reverse the string.
# The '2' is used to print every second letter.
# Combining the above we now reverse the string and print every second letter
print(input_string[::-2])
# References
# https://www.journaldev.com/23584/python-slice-string for the string slicing formula
# https://docs.python.org/3/library/functions.html python built in functions |
fb97a2b7ecc888f642eb51ff5f288f681da56c7a | aiswaryasaravanan/practice | /hackerrank/12-30-gameOfStack_half.py | 477 | 3.609375 | 4 | def popValue(a,b):
if len(a)>0 and len(b)>0:
return a.pop() if a[len(a)-1] < b[len(b)-1] else b.pop()
elif len(a)==0 and len(b)>0:
return b.pop()
else :
return a.pop()
def twoStacks(x, a, b):
a.reverse()
b.reverse()
count=0
poppedValue=popValue(a,b)
while x-poppedValue >= 0:
x=x-poppedValue
count+=1
poppedValue=popValue(a,b)
return count
a=[4,2,4,6,1]
b=[2,1,8,5]
print(twoStacks(10,a,b)) |
62be46a0eba7962abb218ae7ddfa73af768b272a | ChenWenHuanGoGo/tulingxueyuan | /练习/random模块.py | 658 | 4.0625 | 4 | import random
# random.random()获取0-1之间的随机小数,[0,1)
for i in range(10):
print(random.random())
# random.randint(x,y),返回[x,y]之间的随机整数
print(random.randint(1,10))
# random.randrange(start, stop[, step=1]),取[x,y),步进默认为1,可修改,整数
print(random.randrange(1,10,step=5))
# random.choice() 随机获取序列中的值,一定是一个序列
print(random.choice((0,5,6,8)))
# random.shuffle()随机打乱序列,返回None
list1 = [1,2,3,4,5]
print(random.shuffle(list1))
print(list1)
# random.uniform()随机获取指定范围内的值,包括小数
for i in range(5):
print(random.uniform(1,2)) |
cfb5d02fa68ec617a2260e31e739d888135212ad | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1_neat/16_0_1_MisterStabbeh_problem_A.py | 407 | 3.5 | 4 | def solution(starting_num):
if starting_num == 0:
return "INSOMNIA"
counting_set = set()
i = 1
while len(counting_set) < 10:
result = str(i * starting_num)
counting_set.update(set(result))
i += 1
return result
num_of_test_cases = int(input())
for i in range(1, num_of_test_cases + 1):
test_case = input()
print("Case #{}: {}".format(i, solution(int(test_case))))
|
3bcc6da0be94b3a346e1a4727fcde54836c8e925 | blacklc/Practice-for-python | /src/Test/logicTest.py | 671 | 3.984375 | 4 | #!/usr/bin/env python
#coding:utf-8
'''
Created on 2016年5月11日
@author: lichen
'''
#逻辑判断
arr1=['name1','name2',1]
i=10
#在录入数字的时候使用input,在录入字符串的时候使用raw_input
#n=input('please enter a number:')
#或者使用强制类型转换
n=int(raw_input('please enter a number:'))
if n >= i:
print "the number >10"
elif n==6:
print "the number=6"
else:
if n==4:
print "the number=4 \n"
else:
print "the number !=6 and !=4 \n"
for member in arr1:
print member,
arr3=range(1,6)
print "range list is"+'\n',arr3
m=4
sum1=0
while m>0:
sum1=sum1+m
m=m-1
print 'sum=%d\n' %(sum1)
|
10bd457622b1560038f9214e95e270cc9722e2a3 | ananyaarv/Python-Projects | /DrinkBasedonNumber/main.py | 438 | 3.921875 | 4 | # Name: Ananya Arvind
# Date: 3/10/2021
# Period: 8
# Activity: Lab 2.04 Part 1
prize=['A Pepsi', 'A Root Beer', 'A Mountain Dew', 'A Sierra Mist', 'A Water Bottle', 'A Coca-Cola', 'A Doctor Pepper', 'A Lemonade', 'A Sunny D', 'A Fanta']
userinput=input("Pick a number from 1 to 10:")
userinput= int(userinput)
if(userinput<1 or userinput>10):
print("That is not in between 1 and 10. You get no prize!")
else:
print(prize[userinput - 1]) |
d703bf16375648a8835448edb8591e9f1ac59ed8 | daniel-reich/ubiquitous-fiesta | /yfTyMb3SSumPQeuhm_12.py | 451 | 3.828125 | 4 |
memo = {1: 1, 2: 1}
def matrix_mult(A, B):
C = [[0 for row in range(len(A))] for col in range(len(B[0]))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k]*B[k][j]
return C
A = [[1, 1], [1, 0]]
A = matrix_mult(A, A)
n = 2
while n < 10**6:
A = matrix_mult(A, A)
n *= 2
f = A[0][1]
memo[n] = f
def fibonacci(n):
return memo[n]
|
9079bab375f92982900cdc7fab976c4bae565a68 | juneadkhan/InterviewPractice | /singleNumber.py | 566 | 3.90625 | 4 | """
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Input: nums = [4,1,2,1,2]
Output: 4
"""
def singleNumber(nums):
counts = Counter(nums) # Counts all occurences of values in nums
for value, count in counts.items(): # For all the values and their counts
if count == 1: # if the count is 1
return value # Return that value as that is the one that has only 1 element. |
2668991cb4092afbe5b687314f4ab9ee9408b42b | joeyoun9/Muto | /muto/accessories/__init__.py | 545 | 3.546875 | 4 | '''
This will hold useful side functions and methods
'''
import time, calendar
def s2t(str, fmt):
'''
Use functions to grab an epoch time from a
string formatted by fmt. Formatstrings can be
identified in the strtotime module/guide
str = time string
fmt = format string
'''
return calendar.timegm(time.strptime(str, fmt))
def file_len(fname):
'''
As usual, thanks SilentGhost on stack overflow
'''
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
|
78dfc7706f6c0465efafcf7f8ed121499bd4e5ee | a5192179/readStockAccountBill | /computeProfit/testClass.py | 971 | 3.90625 | 4 | class ClassA:
member_A = 0
list_A = []
def __init__(self):
self.selfmember_A = 1
self.selflist_A = []
self.selflist_A.append(1)
def add(self, num):
self.selfmember_A = num
self.selflist_A.append(num)
A1 = ClassA()
print('-------A1 ori-------')
print(A1.member_A)
print(A1.list_A)
print(A1.selfmember_A)
print(A1.selflist_A)
A1.member_A = 2
A1.list_A.append(2)
A1.add(2)
print('-------A1 after A1 add 2-------')
print(A1.member_A)
print(A1.list_A)
print(A1.selfmember_A)
print(A1.selflist_A)
print('-------A2 after A1 add 2-------')
A2 = ClassA()
print(A2.member_A)
print(A2.list_A)
print(A2.selfmember_A)
print(A2.selflist_A)
A2.member_A = 3
A2.list_A.append(3)
A2.add(3)
print('-------A2 after A2 add 3-------')
print(A2.member_A)
print(A2.list_A)
print(A2.selfmember_A)
print(A2.selflist_A)
print('-------A1 after A2 add 3-------')
print(A1.member_A)
print(A1.list_A)
print(A1.selfmember_A)
print(A1.selflist_A) |
42d17f73bf5f810c82ff5d69ee84f9b2b8306c9a | kevalrathod/Python-Learning-Practice | /OOP/polymorphism.py | 227 | 3.84375 | 4 | #overidding Polymorphism
class ABC:
def Speak(self):
print("afakfh")
class XYZ:
def Speak(self):
print("gaduia")
def typesOfSpeak(spktyp):
spktyp.Speak()
obj1 = ABC()
obj2 = XYZ()
typesOfSpeak(obj1)
typesOfSpeak(obj2) |
2458582079217f0f22100e393be606f1f51b7150 | samutrujillo/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,382 | 3.890625 | 4 | #!/usr/bin/python3
"""
class Square
"""
from .rectangle import Rectangle
class Square(Rectangle):
"""docstring for ."""
def __init__(self, size, x=0, y=0, id=None):
""" class constructor"""
super().__init__(size, size, x, y, id)
def __str__(self):
"""Defines print attribute """
attributes = "[Square] ({}) {}/{} - {}"
return attributes.format(self.id, self.x, self.y, self.width)
@property
def size(self):
""" Getter of the size attribute """
return self.width
@size.setter
def size(self, value):
""" setter of the size attribute """
self.width = value
self.height = value
def update(self, *args, **kwargs):
"""method that assigns attributes"""
if len(args):
i = 0
keys_of_attributes = ['id', 'size', 'x', 'y']
for value in args:
if i < 4:
setattr(self, keys_of_attributes[i], value)
i += 1
else:
for keys_of_attributes, value in kwargs.items():
setattr(self, keys_of_attributes, value)
def to_dictionary(self):
""" Returns a square dictionary """
dic = {
'id': self.id,
'size': self.width,
'x': self.x,
'y': self.y
}
return dic
|
288ec9d83e5e7854248227151cac9af41d635724 | berubejd/SQLite3-Helper | /sqlite3_helper.py | 2,058 | 3.703125 | 4 | #!/usr/bin/env python3.8
import sqlite3
from collections import namedtuple
from contextlib import contextmanager
def namedtuple_factory(cursor, row):
"""
Usage:
con.row_factory = namedtuple_factory
Source:
http://peter-hoffmann.com/2010/python-sqlite-namedtuple-factory.html
"""
fields = [col[0] for col in cursor.description]
Row = namedtuple("Row", fields)
return Row(*row)
@contextmanager
def open_db(name):
"""
Based upon:
https://github.com/talkpython/100daysofcode-with-python-course/blob/master/days/79-81-sqlite3/demos/generatedb.py
"""
try:
conn = sqlite3.connect("%s.sqlite3" % name)
conn.row_factory = namedtuple_factory
yield conn
finally:
conn.close()
if __name__ == "__main__":
name = "db"
characters = [
("Albus", "Dumbledore", 150),
("Minerva", "McGonagall", 70),
("Severus", "Snape", 45),
("Rubeus", "Hagrid", 63),
("Argus", "Filch", 50),
]
with open_db(name) as conn:
try:
with conn:
# While ideally this should include 'IF EXISTS'
# don't include it in order to provide proper feedback
conn.execute("DROP TABLE hp_chars")
print("NOTICE: Old hp_chars table deleted.")
except sqlite3.OperationalError:
# Table was not present
pass
with conn:
conn.execute(
"CREATE TABLE hp_chars(first_name TEXT, last_name TEXT, age INTEGER)"
)
print(f"NOTICE: New hp_chars table in {name}.sqlite3 has been created.\n")
try:
with conn:
conn.executemany("INSERT INTO hp_chars VALUES (?, ?, ?)", characters)
except sqlite3.IntegrityError:
print("ERROR: There was an issue inserting all HP characters!")
with conn:
for row in conn.execute("SELECT first_name, age FROM hp_chars"):
print(f"{row.first_name} was {row.age} years old.")
|
7cac2c46c6a3c3425c371dce46388fc134a844ca | rmuzyka/pyhon | /pluralsight-python-standard-library.py | 660 | 3.625 | 4 | from collections import Counter
from collections import defaultdict
from collections import namedtuple
from app
c = Counter()
c['bananas'] += 2
c['apples'] += 1
c['apples'] += 3
c['bananas'] -= 1
print c.most_common()
print c['lemons']
class Fraction(object):
def __init__(self):
self.n = 1
self.d = 2
def __repr__(self):
return '{0}/{1}'.format(self.n, self.d)
f=Fraction()
frac_dict = defaultdict(Fraction)
print frac_dict['frroo']
print frac_dict['frrwqwqwoo']
ServerAddress = namedtuple('ServerAddresed', ['ip_address', 'port'])
local_web_server = ServerAddress('127.0.0.1', 80)
print local_web_server
# CSV
|
4d3823fab86c4a20f4143ba4d96760a51088dd4e | barnamensch056/DS_Algo_CP | /Python for CP & DS Algo/size_of_tree.py | 1,178 | 3.671875 | 4 | class Node:
def __init__(self,info):
self.right=None
self.info=info
self.left=None
class BinaryTree:
def __init__(self):
self.root=None
def create(self,val):
if self.root==None:
self.root=Node(val)
else:
current=self.root
while True:
if val<current.info:
if current.left:
current=current.left
else:
current.left=Node(val)
break
elif val>current.info:
if current.right:
current=current.right
else:
current.right=Node(val)
break
else:
break
def sizeofBinaryTree(root):
if root==None:
return 0
else:
return sizeofBinaryTree(root.left)+1+sizeofBinaryTree(root.right)
if __name__ == "__main__":
tree=BinaryTree()
t= int(input())
arr=list(map(int,input().split()))
for i in range(t):
tree.create(arr[i])
print(sizeofBinaryTree(tree.root))
|
c792c81e6357bdfcae75b075c7595d69c09096af | zmh19941223/heimatest2021 | /04、 python编程/day04/3-code/17-列表和元组的转化.py | 183 | 3.84375 | 4 | list1 = [1,2, 4, 2]
tuple1 = tuple(list1) # 把list1转化为元组类型
print(tuple1)
tuple2 = (3, 6, 12, 100)
list2 = list(tuple2) # 把元组tuple2转化为列表
print(list2) |
20e5c691d8a999a1066a083e5418a7b4cdf92748 | sppliyong/day01 | /day03/zuoye6.py | 363 | 3.703125 | 4 | import math
if __name__ == '__main__':
str1=input("请输入一个数:")
a=int(str1)
mlist=[]
while True:
b=a%2
mlist.append(b)
a=a//2
if a==0:
break
print(mlist)
mlist.reverse()
print(mlist)
bb=""
for i in mlist:
bb+=str(i)
print("这个数的二进制是:"+bb)
|
25475bbccc69ea6ed2d42cd138a9446c81712a56 | nikhilmborkar/fsdse-python-assignment-3 | /letter_digit.py | 196 | 3.515625 | 4 | def letterAndDigit(s1):
d = {"DIGITS":0, "LETTERS":0}
for i in s1:
if i.isalpha():
d['LETTERS'] +=1
elif i.isdigit():
d['DIGITS'] +=1
return d
|
1e5c622d7598a03464b70f3ec0b7773a4353a753 | klaus2015/py_base | /code/day05/r7.py | 429 | 4 | 4 | """
在列表中[54, 25, 12, 42, 35, 17],选出最小值(不使用min)
"""
list01 = [54, 25, 12, 42, 35, 17]
# 假设第一个值为最小值
min_value = list01[0]
# for item in list01:
# if min_value > item: # 如果item小于最小值,将item赋值给min_value
# min_value = item
# print(min_value)
for i in range(1,len(list01)):
if min_value > list01[i]:
min_value = list01[i]
print(min_value)
|
21242c868dcaf41a84467d957bc433000caa3d2e | blaz-k/lesson | /vaja/main1.py | 188 | 3.9375 | 4 | #secret number
secret = 26
guess = int(input("Guess my number: "))
if guess == secret:
print("Congratulations, you guessed it!")
else:
print("it is not correct. lets go again!")
|
1672ca44a3e5aaab504163dc494cc71bcbc53123 | rmcclorey1125/Python-practice | /LCalc.py | 734 | 3.984375 | 4 | print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
names = name1 + name2
lower_case_names = names.lower()
t = lower_case_names.count("t")
r = lower_case_names.count("r")
u = lower_case_names.count("u")
e = lower_case_names.count("e")
true = t + r + u + e
l = lower_case_names.count("l")
o = lower_case_names.count("o")
v = lower_case_names.count("v")
love = + l + o + v + e
score = str(true) + str(love)
if int(score) < 10 or int(score) > 90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif int(score) > 40 and int(score) < 50:
print(f"Your score is {score} you are alright together.")
else:
print(f"Your score is {score}")
|
b7e2eb687f865d2b5251d172ea77f76c241b2eb8 | zsbati/PycharmProjects | /Key Terms Extraction/Topics/Math functions/Octahedron/main.py | 170 | 3.875 | 4 | import math
edge = int(input())
area = round(2 * math.sqrt(3.0) * math.pow(edge, 2), 2)
volume = round(math.sqrt(2.0) * math.pow(edge, 3) / 3, 2)
print(area, volume)
|
a81fd8e5397ea5d9361ddc55675d93a58e8828e5 | Fernandoleano/Rock-Paper-Scissors | /code/python/Rock_Paper_Scissors.py | 1,830 | 3.96875 | 4 | '''
My TODO LIST:
This sucks but hey I made it at least am pro coder 😎
when I was stuck I used this website: https://thehelloworldprogram.com/python/python-game-rock-paper-scissors/
Rock Paper Scissors with bot
1. I need random with the bot with a choice or randint (randint is easier to use)
2. many functions for bot and gamer / player optinal/ a lot of if statements making a while loop
3. add user ability to play
'''
from random import randint
# welcome for gamers
def welcome():
print("wassup gamers 🎮 are you able to beat the hard AI named Joe mama 👁️👄👁️ ? good luck gamers 🎮")
print("also you have to put caps or your not a true gamer\n")
welcome()
# if they Typed these with caps it will play
bot = ["Rock", "Paper", "Scissors"]
# AI
AI = bot[randint(0,2)]
# gamer why I named this why not yall gamers also this means player as well lol
gamer = False
# type(gamer)
# Debugging
# how the game will run
# the while loop
while gamer == False:
# user interface
gamer = input("Rock, Paper, Scissors: ")
# if elif else statement
if (AI == gamer):
print("You tied with a bot! uhhhhhh")
if (AI == "Rock")and(gamer == "Paper"):
print("Pog you beat a bot!😲")
elif (AI == "Paper")and(gamer == "Scissors"):
print("Pog you beat a bot!😲")
elif (AI == "Scissors")and(gamer == "Rock"):
print("Pog you beat a bot!😲")
elif (AI == "Paper")and(gamer == "Rock"):
print("You really lost to a bot unpog 😢")
elif (AI == "Scissors")and(gamer == "Paper"):
print("You really lost to a bot unpog 😢")
elif (AI == "Rock")and(gamer == "Scissors"):
print("You really lost to a bot unpog 😢")
else:
print("bruh what did you put!")
gamer = False
AI = bot[randint(0,2)]
|
f7fdf2b87245100ac416b5ba5fc54783456adbc7 | pedroth/python_experiments | /Test/ExpExperiment.py | 1,991 | 3.53125 | 4 | import math
import matplotlib.pyplot as plt
def powInt(x, n):
if n == 0:
return 1
elif n == 1:
return x
else:
q = math.floor(n / 2)
r = n % 2
if r == 0:
return powInt(x * x, q)
else:
return x * powInt(x * x, q)
def expEuler(x, n):
if n == 0:
return 1
else:
return powInt(1.0 + (1.0 * x / n), n)
def expTaylor(x, n):
acc = 0
for k in range(0, n + 1):
acc += (1.0 * powInt(x, k)) / math.factorial(k)
return acc
def expHybrid(x, n, k):
if n == 0:
return 1
else:
acc = 0
t = (1.0 * x) / n
for l in range(0, k + 1):
acc += (1.0 * powInt(t, l)) / math.factorial(l)
return powInt(acc, n)
def exp_experiment(t, n):
for i in range(0, n):
print(str(i) + "\t" + str(expEuler(t, i)) + "\t" + str(expHybrid(t, i, 2)) + "\t" + str(
expHybrid(t, i, 3)) + "\t" + str(
expHybrid(t, i, 10)) + "\t" + str(expTaylor(t, i)) + "\t" + str(
math.exp(t)))
def exp_error_experiment(t, n):
exp = math.exp(t)
acc = [[], [], [], [], []]
for i in range(0, n):
acc[0].append(math.fabs(expEuler(t, i) - exp))
acc[1].append(math.fabs(expTaylor(t, i) - exp))
acc[2].append(math.fabs(expHybrid(t, i, 2) - exp))
acc[3].append(math.fabs(expHybrid(t, i, 3) - exp))
acc[4].append(math.fabs(expHybrid(t, i, 10) - exp))
print(str(i) + "\t" + str(acc[0][i]) + "\t" + str(acc[1][i]) + "\t" + str(acc[2][i]) + "\t" + str(
acc[3][i]) + "\t" + str(acc[4][i]))
plt.plot(acc[0], 'r', label='euler')
plt.plot(acc[1], 'g', label='taylor')
plt.plot(acc[2], 'b', label='hybrid2')
plt.plot(acc[3], 'c', label='hybrid3')
plt.plot(acc[4], 'y', label='hybrid10')
plt.xlabel('iterations')
plt.ylabel('error')
plt.legend()
plt.show()
# exp_experiment(100, 150)
exp_error_experiment(10, 150)
|
c95dd53b471aaca77d3ba32f95607f5e8a6877f4 | yannsantos1993/Exercicios-Python | /Modulo_1/Lista UFMG/33.py | 516 | 4.0625 | 4 | '''33 - Escreva um algoritmo em PORTUGOL que calcule o resto da divisão de A por B (número inteiros e positivos),
ou seja, A mod B, através de subtrações sucessivas. Esses dois valores são passados pelo usuário através do teclado. '''
contador = 0
soma_a = 0
soma_b = 0
a = int(input("Digite um número:"))
for contador in range (a):
soma_a += 1
b = int(input("Digite um número:"))
for contador in range (b):
soma_b += 1
print(f"O produto entre os número informados equivale a {soma_a**soma_b}") |
2470f13bf9b0455e1f52301fc0b8f1f70b0e9894 | paul0920/leetcode | /question_leetcode/442_2.py | 492 | 3.71875 | 4 |
# nums = [4, 3, 2, 7, 8, 2, 3, 1]
nums = [4, 4, 2, 3]
for i in range(len(nums)):
while i != nums[i] - 1 and nums[i] != nums[nums[i] - 1]:
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
# !!! The following order is incorrect because the 2nd element,
# nums[nums[i] - 1], uses the new nums[i] value !!!
# nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
print nums
print [nums[i] for i in range(len(nums)) if i != nums[i] - 1]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.