blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2a2bc666a41dd220c7cc361efa52eaef34c89938
blogSoul/Python_summary
/Make_Algorithm/Algorithm/tree.py
436
3.765625
4
class Tree(object): def __init__(self, name = 'root', childern = None): self.data = None self.chilern = [] if childern is not None: for child in childern: self.add_child(child) def __repr__(self): return self.name def add_child(self, node): assert isinstance(node, Tree) self.children.append(node) root = Tree() root.data = "root" print(root.data)
23b389daa4ac03e36b78deb616ca02df063863ff
ajiehust/rosalind
/Algorithms_Heights/ms.py
776
3.671875
4
#!/usr/bin/env python ''' Merge Sort Problem Title: Merge Sort Rosalind Armory ID: ms URL: http://rosalind.info/problems/ms/ ''' import sys def fr(fn): with open(fn) as f: n = int(f.readline().strip()) lst = map(int, f.readline().strip().split(" ")) assert len(lst) == n return lst def mer(lst1, lst2): result = [] while lst1 and lst2: result.append(lst1.pop(0) if lst1[0] <= lst2[0] else lst2.pop(0)) return result + lst1 + lst2 def ms(lst): if len(lst) <= 1: return lst mid = len(lst) / 2 lst1 = ms(lst[:mid]) lst2 = ms(lst[mid:]) return mer(lst1, lst2) def main(): sys.stdout = open("ms.out", "w") print " ".join(map(str, ms(fr("ms")))) if __name__ == '__main__': main()
2751eec7008a4bdc4ce08f51e0f6d164dc67ba7e
lonesloane/Python-Snippets
/data_persistence/databases/sqlite_sample.py
1,633
3.71875
4
import sqlite3 def create_table(): conn = sqlite3.connect('lite.db') # creates the db file if does not exist yet cursor = conn.cursor() query_create = "CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)" cursor.execute(query_create) conn.commit() conn.close() def insert_data(item, quantity, price): conn = sqlite3.connect('lite.db') # creates the db file if does not exist yet cursor = conn.cursor() query_insert_data = "INSERT INTO store VALUES (?, ?, ?)" cursor.execute(query_insert_data, (item, quantity, price)) conn.commit() conn.close() def view_data(): conn = sqlite3.connect('lite.db') # creates the db file if does not exist yet cursor = conn.cursor() query_view_data = "SELECT * FROM store" cursor.execute(query_view_data) rows = cursor.fetchall() conn.close() return rows def delete_data(item): conn = sqlite3.connect('lite.db') # creates the db file if does not exist yet cursor = conn.cursor() query_delete_data = "DELETE FROM store WHERE item = ?" cursor.execute(query_delete_data, (item,)) conn.commit() conn.close() def update_data(item, quantity, price): conn = sqlite3.connect('lite.db') # creates the db file if does not exist yet cursor = conn.cursor() query_update_data = "UPDATE store set quantity = ?, price = ? WHERE item = ?" cursor.execute(query_update_data, (quantity, price, item)) conn.commit() conn.close() #insert_data('Coffee Cup', 10, 2.3) print(view_data()) #delete_data('Coffee Cup') update_data('Wine Glass', 25, 8.75) print(view_data())
7700e29089050e077cb8deb2447163ddc9041e62
desve/netology
/tasks/9/9-4.py
429
3.59375
4
# Диагонали: параллейные главной print("Введите размермассива n=") n = int( input()) a = [] a = [[0] * n for i in range(n)] for i in range(n): for j in range(n): if i == j: a[i][j] = 0 elif j > i: a[i][j] = j - i elif j < i: a[i][j] = i - j for row in a: print(" ".join([str(elem) for elem in row]))
88106c1baf8927bc1420c7a2a3b35553d4b71b45
hyccc/myPython
/5 练习/Craps赌博游戏.py
1,416
3.953125
4
''' Craps赌博游戏 规则:玩家掷两个骰子,每个骰子点数为1-6,如果第一次点数和为7或11,则玩家胜; 如果点数和为2、3或12,则玩家输庄家胜。 若和为其他点数,则记录第一次的点数和,玩家继续掷骰子,直至点数和等于第一次掷出的点数和则玩家胜; 若掷出的点数和为7则庄家胜。 author: Ethan ''' import random def dice(): x = random.randint(1, 6) y = random.randint(1, 6) return x + y if __name__ == '__main__': i = 1 first = dice() if first == 7 or first == 11: print("掷色子{}次,和为{},玩家胜".format(i, first)) elif first == 2 or first == 3 or first == 12: print("掷色子{}次,和为{},庄家胜".format(i, first)) else: print("掷色子第{}次,和为{},无人获胜".format(i, first)) while True: i += 1 throw_dice = dice() if throw_dice == first: print("掷色子第{}次,和为{},玩家胜".format(i, throw_dice)) break elif throw_dice == 7: print("掷色子第{}次,和为{},庄家胜".format(i, throw_dice)) break else: print("掷色子第{}次,和为{},无人获胜".format(i, throw_dice)) def name(): print(__name__)
4bbd3e0b97efb468a3eb6f0098ee6bbab2920a97
daodewang/learn
/learn.py
2,122
3.640625
4
''' pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key=lambda pair: pair[1]) print(pairs) __import__('os').system('dir') def f(a): a.append(1) print(a) f(pairs) print(pairs) b=7 def f(a): print(a+b) f(2) print(b) # IO-input name = 'Liming' print('my name is %s.' % name) print(f'my name is {name!s}.') age = eval(input('input your age\n')) print(age) # IO-file f = open('1.jpg', 'rb') #s = f.read(4) for s in f: print(s) print(f.tell()) f.close() # IO-json import json f = open('testj.json', 'r') #l = [123,'123',[123,'123']] s = json.load(f) print(s) print(type(s)) #f.write(s) f.close() # try def bool_return(): try: a=1 print('try') return 1/0 except: print('except') else: print('else') finally: print('final') print(bool_return()) s = input('请输入除数:') try: result = 20 / int(s) print('20除以%s的结果是: %g' % (s, result)) except ValueError: print('值错误,您必须输入数值') except ArithmeticError: print('算术错误,您不能输入0') else: print('没有出现异常') # class class MyClass: i = 12345 def __f(self): return 'hello world' x = MyClass() #x._f() MyClass.bb=12345 x.aa = '123' print(x._MyClass__f()) def fn(self, name='world'): print('Hello, %s.' % name) dct = {'hello':fn, 'i':10} Hello = type('Hello', (object,), dct) #He = type('Hello') print(type(Hello)) h = Hello() print(h.i) '''''' MyClass.ff = fn x.ff() class ListMetaclass(type): def __new__(cls, name, bases, attrs): attrs['add'] = lambda self, value: self.append(value) return type.__new__(cls, name, bases, attrs) class MyList(list, metaclass=ListMetaclass): pass # generator def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) ''' import re input_str = 'I LIKE Python3 and Pyth i like Python2.7' pattern = r'(P|p)yth(on)' match_python = re.findall(pattern, input_str) print(match_python) s = input_str match = re.search(pattern, s) if match: print(match)
2582227f9093e3d1a445c49070adf28f9e5cb24b
marcelodias/documents
/python/ifelifelse_grandfinale.py
449
3.75
4
# Tenha certeza que the_flying_circus() retorna True def the_flying_circus(): if 5 * 2 == 15: # Comece seu codigo aqui! print "Comparadores" # Nao esqueca de recuar # o codigo dentro deste bloco! elif "Verdade" or "Falso": print "Identificacao" # Continue aqui. # Voce vai querer adicionar tambem a declarao else! else: return True
b834aae53691f239c06462f1273a290d980b6879
TakuroKato/AOJ
/ITP1_5_B.py
532
3.5625
4
# -*- coding:utf-8 -*- def frame(H,W): for i in range(W): print('#',end='') print('') for j in range(1,H-1): for i in range(W): if i == 0 or i == W-1: print('#',end='') else: print('.',end='') print('') for i in range(W): print('#',end='') print('') import sys for i in sys.stdin: H,W = map(int,i.split()) if H == 0 and W == 0: break print('') frame(H,W) #if H == 0 and W == 0: # break
30b666c1593d645fdbd044328c029d11bfd3f697
yunzhuz/code-offer
/second/6.py
600
3.578125
4
class listnode(): def __init__(self,data,next=None): self.data = data self.next = next def solution(p): l = [] l.append(p.data) while p.next: l.append(p.next.data) p = p.next l = l[::-1] nhead = listnode(l[0]) np = nhead for i in l[1:]: node = listnode(i) np.next = node np = np.next return nhead if __name__ == '__main__': l = [1,2,3,4,5] head = listnode(l[0]) p = head for i in l[1:]: node = listnode(i) p.next = node p = p.next print(solution(head).next.data)
5c03445a52e35c6741684fb37fd4881bb3e5fa43
q-riku/Python3-basic2
/01 函数式编程-匿名函数和高阶函数/test3.py
308
3.828125
4
#函数名 = lambda[参数列表]:表达式 def my_func(f, arg): return f(arg) #f(5) x=5 print(my_func(lambda x: 2*x*x, 5)) #这个带有参数的; g = lambda y:2*y print(g(3)) #这个不带参数的写法; gg = lambda :123 print(gg()) #可以有N个参数; ggg = lambda x,y,z:x+y+z print(ggg(1,2,3))
68e4274640efa7ab69d5959f2bf726e6a6fbb120
MatheusBorgesKamla/MachineLearningStudy
/Regression/SimpleLinearRegression/code.py
2,065
4
4
import numpy as np %matplotlib inline import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values #Splitting the dataset into the Training set and Test set #Nao precisei fazer os passos anteriores de preprocessamento pois #dados nao necessitam para tratamento from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) #Nao e necessario o feature scaling pois a biblioteca para regressao linear simples já trata isso automaticamente #Fitting Simple Linear Regression to the Training Set #primeiro temos que importar a classe de regressao linear from sklearn.linear_model import LinearRegression #inicializando o objeto da classe regressor = LinearRegression() #Vamos preencher com os dados de treino regressor.fit(X_train, y_train) #A partir daqui ja possuimos nosso modelo, ja foi determinado a relacao entre o X e o y #Ja foi aplicado o metodo dos minimos quadrados para achar a reta # Predicting the Test set results y_pred = regressor.predict(X_test) #Agora a partir do conjunto de teste X iremos prever o y, utiliza do coef. angular e linear e dos pontos X de teste para achar os y # Visualising the Training set results plt.scatter(X_train, y_train, color = 'red') #Estamos passando as coordenadas X e Y dos pontos que queremos plotar e a cor que queremos #Vermelho sera os pontos reais plt.plot(X_train, regressor.predict(X_train), color = 'blue') #Em azul plotaremos a reta prevista para os pontos de treino plt.title('Salary vs Experience (Training set)') #Titulo do nosso grafico plt.xlabel('Years of Experience') #Titulo do eixo x plt.ylabel('Salary') #Titulo do eixo y plt.show() #Comando para mostrar na tela # Visualising the Test set results plt.scatter(X_test, y_test, color = 'red') plt.plot(X_train, regressor.predict(X_train), color = 'blue') plt.title('Salary vs Experience (Test set)') plt.xlabel('Years of Experience') plt.ylabel('Salary') plt.show()
df78ebfcbce68fb1afb17541a9340ceaeab598f4
xmliszt/capstone-ocr
/src/writer.py
437
3.75
4
import os class Writer: def __init__(self): self.txt = "" def append(self, txt): self.txt += txt def write(self, filename): if not os.path.exists("output"): os.mkdir("output") output_path = os.path.join("output", filename) with open(output_path, "w", encoding="utf-8") as fh: fh.write(self.txt) print("Written to file: {}".format(output_path))
b8235df3821a2cfe8b3791e31e9d6bd4fb9d39d3
gottun510/tdd_vending-machine-4
/tests/test_vending.py
1,644
3.5
4
# from unittest import TestCase from vending_machine.hoge.coin import Coin, VendingMachine class TestVendingMachine(): def test_check_coin(self): machine = VendingMachine() assert machine.check_coin(Coin(50)) == True assert machine.check_coin(Coin(40)) == False def test_treat_coin(self): machine = VendingMachine() machine.treat_coin(Coin(50)) assert machine.contained[0].amount == Coin(50).amount assert machine.treat_coin(Coin(20)).amount == 20 # def test_catch_coin(self): # machine = VendingMachine() # machine.check_coin(Coin(50)) # assert Coin(50).amount == machine.contained[0].amount # machine_invalid = VendingMachine() # coin30 = Coin(30) # result = machine_invalid.check_coin(coin30) # assert result == coin30 # assert machine_invalid.contained == [] def test_coin_total(self): machine = VendingMachine() machine.treat_coin(Coin(500)) machine.treat_coin(Coin(100)) machine.treat_coin(Coin(50)) assert 500 + 100 + 50 == machine.coin_total() def test_refund(self): machine = VendingMachine() machine.treat_coin(Coin(500)) machine.treat_coin(Coin(100)) machine.treat_coin(Coin(50)) assert [Coin(500).amount, Coin(100).amount, Coin(50).amount] == [coin.amount for coin in machine.refund()] assert [] == [coin.amount for coin in machine.contained] # def test_catch_coin_invalid(self): # class TestStock(): # def test_check(self): # assert stock.check() == []
86b41459e33672e4c6710f11d23468658f9c8aeb
kooshanfilm/Python
/Python_Code_Challenge/P3.py
744
4.03125
4
import random theasurus = { "weather" : ['balmy', 'summery','hot','cold'], "cold" : ['a', 'b','c','d'], 'happy': ['e','f','g','h'], 'sad':['s','a','d','d2'] } print ("Welcome to my app") print ("\n Choose a word from our list") print ("\n Here are words for you") for key in theasurus.keys(): print ("\t - " + key) choice = raw_input("\n What world would you like to get: ").lower().strip() if choice in theasurus.keys(): index = random.randint(0,4) print(" Your random word is " + theasurus[choice][index]) else: print("Sorry not here") choice = raw_input(" Would you like to see everything: ").lower().strip() if choice == "yes": for key,value in theasurus.items(): print(key.title())
8a7f593a47db0ae92d6553eb83d07ce4c0a79afa
menard-noe/LeetCode
/Check If It Is a Straight Line.py
498
3.703125
4
from typing import List class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: (x1, y1), (x2, y2) = coordinates[:2] for i in range(2, len(coordinates)): (x, y) = coordinates[i] if ((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)): return False return True if __name__ == "__main__": coordinates = [[0,0],[0,1],[0,-1]] solution = Solution() print(solution.checkStraightLine(coordinates))
477c023f9a378c32985a18850ad49e599a8e9c88
Wanpeng66/Python_learning
/面向对象编程/枚举类.py
446
3.890625
4
# 跟java枚举差不多的功能 from enum import Enum, unique # @unique装饰器会检查枚举类中有没有重复的值 @unique class Weekday(Enum): Sun = 7 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 if __name__ == "__main__": # 既可以用成员名称引用枚举常量,又可以直接根据value的值获得枚举常量。 print(Weekday.Sun) print(Weekday(2)) print(Weekday.Sun.value)
02c89757a976f76787b1f7de06d0115451413316
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/leap/bfb631919e8744bb9459e94a9042996c.py
155
3.765625
4
def is_leap_year (year): if not (year % 4 == 0): return False elif (year % 100 == 0) and not (year % 400 == 0): return False else: return True
3bd877d708ec1a267ca60197d5ac53fae9da7d59
MudretsovaSV/Python
/compare.py
353
4
4
num1=float(raw_input(" : ")) num2=float(raw_input(" : ")) if num1<num2: print num1, " ", num2 if num1>num2: print num1, " ", num2 if num1==num2: print num1, "", num2 if num1!=num2: print num1, " ", num2
144744cd9c61c7e12c2fdd50e28a4baa96099a08
tai34tw/III_Python
/III_Homework/1_Selection/5_refund.py
1,309
4
4
'''5. 選擇性敘述的練習-refund 輸入在某商店購物應付金額與實付金額。 實付金額小於應付金額,則印出”金額不足”。 實付金額等於應付金額,則印出”不必找錢”。 實付金額大於應付金額,則輸出找回金額最少的鈔票數和錢幣數。 假設幣值只有1000, 500, 100元紙鈔和50, 10, 5, 1元硬幣。 說明:若買了132元的商品,付1000元,應找回一張500元,三張100元,一個50元硬幣,一個10元硬幣,一個5元硬幣和三個1元硬幣。 ''' payment = eval(input('應付金額:')); money = eval(input('實付金額:')) if payment == money: print('不必找錢') elif money < payment: print('金額不足') elif money > payment: diff = money - payment thousand = diff//1000 five_hundred = diff % 1000 // 500 one_hundred = diff % 1000 % 500 // 100 fifty = diff % 1000 % 500 % 100 // 50 ten = diff % 1000 % 500 % 100 % 50 // 10 five = diff % 1000 % 500 % 100 % 50 % 10 // 5 one = diff % 1000 % 500 % 100 % 50 % 10 % 5 print("應找回",thousand,"張1,000元",five_hundred,"張500元", one_hundred,"張100元",fifty,"個50元硬幣", ten,"個10元硬幣", five,"個5元硬幣", one,"個10元硬幣")
dc79207c4023d82a329200227c3825bf2a42c8b5
sumnous/Leetcode_python
/searchRotatedArray.py
1,026
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2013-12-11 @author: Ting Wang ''' # Suppose a sorted array is rotated at some pivot unknown to you beforehand. # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # You are given a target value to search. If found in the array return its index, otherwise return -1. # You may assume no duplicate exists in the array. import math def searchRotatedArray(data, target): first = 0 last = len(data) while first != last: mid = int(math.floor((first + last) / 2)) if target == data[mid]: return mid if data[first] <= data[mid]: if target >= data[first] and target < data[mid]: last = mid else: first = mid +1 else: if target > data[mid] and target <= data[last - 1]: first = mid +1 else: last = mid return -1 if __name__ == '__main__': A = [4,5,6,7,0,1,2,3] print searchRotatedArray(A, 3)
0c5d586e62b671e4ea1d0612a0e8decd6f8d0913
InfoTech-Academy/Python_Week_4
/Homework Ersin Öztürk/number_guessing_game.py
1,198
3.796875
4
import random import time def rand_find(a, b): lst = [i for i in range(a, b + 1)] chosen = random.sample(lst, 1) return chosen[0] def control_selection(c, p): global t0 global t1 global count global final if count==0: t0 = time.time() if c - p < 0: count += 1 return print("\nthe guess is too high!") elif c - p > 0: count += 1 return print("\nthe guess is too low!") else: count += 1 t1 = time.time() final = 1 return print("\n"+str(c) + " is correct answer") count = 0 final = 0 r1 = int(input("Please enter the starting range as an integer: ")) r2 = int(input("Please enter the finish range as an integer: ")) com_chosen = rand_find(r1, r2) while True: player_input = int(input("Please chose your guess: ")) control_selection(com_chosen, player_input) if final == 1: print("Congratulations!") print("Total selection: ", count) print("Total time: ", int(t1 - t0)," second") break else: print("Your selection is false, Please try again!") print("The game finished!")
119a1c0e9f51c3a54d261991c89c723d2633315e
KarashDariga/TSIS3
/3.py
307
3.828125
4
def fun(n): return lambda a: a * n doubler = fun(2) # lambda a: a * 2 print(doubler(3)) print(doubler(6)) # in this doubler it;s lambda triple = fun(3) # lambda a: a * 3 print(triple(3)) print(triple(6)) multiple_100 = func(100) # lambda a: a * 100 print(multiple_100(5)) print(multiple_100(6))
64da55f9441652a7e9499754bdf0aea827defa0a
Baidaly/datacamp-samples
/18 - Hypothesis Testing in Python/chapter 1/1 - Calculating the sample mean.py
736
3.890625
4
''' The late_shipments dataset contains supply chain data on the delivery of medical supplies. Each row represents one delivery of a part. The late columns denotes whether or not the part was delivered late. A value of "Yes" means that the part was delivered late, and a value of "No" means the part was delivered on time. Let's begin our analysis by calculating a point estimate (or sample statistic), namely the proportion of late shipments. late_shipments is available, and pandas is loaded as pd. ''' # Print the late_shipments dataset print(late_shipments) # Calculate the proportion of late shipments late_prop_samp = late_shipments["late"].value_counts()["Yes"] / len(late_shipments) # Print the results print(late_prop_samp)
1066477f7e1f42c807c7f8bc4d0c711e871d3945
IgnatIvanov/Hypercar-Service-Center_JetBrains_Academy
/Topics/Queue in Python/Oral exam/main.py
412
3.65625
4
from collections import deque board = deque() exit_door = deque() n = int(input()) while n != 0: n -= 1 record = str(input()) if 'READY' in record: board.append(record.split()[1]) elif 'EXTRA' in record: board.append(board.popleft()) elif 'PASSED' in record: # print(board.popleft()) exit_door.append(board.popleft()) for name in exit_door: print(name)
f6d6d381b7c5ff78b3577c89a25318415c2bbbc3
leoelm/interview_training
/5.1.py
277
3.671875
4
from random import random, choice A = [random() for i in range(10)] def quicksort(l): if len(l) <= 1: return l pivot = choice(l) left = [i for i in l if i <= pivot] right = [i for i in l if i > pivot] return quicksort(left) + quicksort(right)
d315521ca81c4f3ff0570b9f3c4a2cc6a19764d0
StanLong/Python
/02爬虫/urllib.request的使用.py
1,524
3.5
4
# 使用xpath解析站长之家下载前十页的图片 import urllib.request from lxml import etree def create_request(page): if page == 1: url = 'https://sc.chinaz.com/tupian/qinglvtupian.html' else: url = 'https://sc.chinaz.com/tupian/qinglvtupian_' + str(page) + '.html' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36', } request = urllib.request.Request(url = url, headers= headers) return request def get_content(request): response = urllib.request.urlopen(request) content = response.read().decode('utf-8') return content def down_load(content): tree = etree.HTML(content) # 一般涉及到图片的网站都会涉及懒加载 name_list = tree.xpath('//div[@class="item"]/img/@alt') src_list = tree.xpath('//div[@class="item"]/img/@data-original') for i in range(len(name_list)): name = name_list[i] src = src_list[i] url = 'https:' + src print(name, url) urllib.request.urlretrieve(url=url, filename='./tupian/' + name + '.jpg') if __name__ == '__main__': start_page = int(input('请输入起始页码')) end_page = int(input('请输入结束页码')) for page in range(start_page, end_page+1): # 请求对象的定制 request = create_request(page) # 获取网页源码 content = get_content(request) # 下载图片 down_load(content)
e0e6ceb3add0b292a8d3e54f50b222a5d05f8253
erickmiller/AutomatousSourceCode
/AutonomousSourceCode/data/raw/squareroot/d4622eb3-3c06-40d3-a4d9-c5d9fd988b84__newton_rhapson_sqrt.py
839
4.34375
4
##print " this program computes square root of a number using" ##print "newton-rhapson method" ## ##number=float(input("Enter the number whose square root is desired ")) ## ##guess_estimate = float(number/2.0) ## ##while (guess_estimate*guess_estimate != number): ## ## quotient = (number / guess_estimate) ## new_guess = (quotient+guess_estimate)/2 ## if guess_estimate ==new_guess: ## print "the square root is", guess_estimate ## break ## else: ## guess_estimate = new_guess import math def average(a,b): return (a+b)/2.0 def improve (guess,x): return average(guess, x/guess) def good_enough(guess,x): d = abs(guess*guess-x) return (d < 0.000001) def square_root(x): guess = 1 while (not good_enough(guess,x)): guess = improve(guess,x) return guess
e77861cc46c9b1407a84ff2c8414df2ba284911e
cgazeredo/cursopython
/mundo02/aula-12_exercicios-044-gerenciador-de-pagamentos.py
801
3.703125
4
preco = float(input('Qual o preço normal do produto? R$')) condicao = str(input('A condição de pagamento será à vista ou parcelado? ')) if condicao == 'à vista': condicao_vista = str(input('O pagamento será feito em dinheiro cheque ou cartão? ')) if condicao_vista == 'dinheiro' or condicao_vista == 'cheque': preco_final = preco*0.9 else: preco_final = preco * 0.95 else: condicao_parcelado = int(input('O pagamento pode ser feito em 2 e 3 vezes. Escolha uma das opçoes: ')) if condicao_parcelado == 2: preco_final = preco elif condicao_parcelado == 3: preco_final = preco*1.2 else: print('Condição escolhida invalida. ') print('O preço final do produto para o pagamento escolhido é de R${:.2f}'.format(preco_final))
20b8936e94733a3489ac4d22ec725983cd9cbc52
LenaSmb/geekbrains-python
/lesson08/ex05.py
2,157
3.71875
4
class Warehouse: equipment = {} quantity = {} transfered = {} def __init__(self): pass def status(self): for key in self.equipment.keys(): print(key, self.quantity[key], end='; ') print() def receive(self, item): if item.name not in self.equipment.keys(): self.equipment[item.name] = {} self.quantity[item.name] = 0 self.equipment[item.name][item.inventoryNumber] = item self.quantity[item.name] += 1 def transfer(self, equipment_type, quantity, unit): if equipment_type not in self.equipment.keys(): raise ValueError('no such item with given inventory number') if quantity > self.quantity[equipment_type]: raise ValueError('no such quantity of given equipment') if unit not in self.transfered.keys(): self.transfered[unit] = [] for _ in range(0, quantity): item = self.equipment[equipment_type].popitem() self.transfered[unit].append(item) self.quantity[equipment_type] -= 1 class Equipment: inventoryNumber: int @property def name(self): return self.__class__.__name__.lower() def __init__(self, inventoryNumber): self.inventoryNumber = inventoryNumber class Printer(Equipment): technology: str def __init__(self, inventoryNumber, technology): super().__init__(inventoryNumber) self.technology = technology class Scanner(Equipment): resolution: int def __init__(self, inventoryNumber, resolution): super().__init__(inventoryNumber) self.resolution = resolution class Xerox(Equipment): resize: bool def __init__(self, inventoryNumber, resize): super().__init__(inventoryNumber) self.resize = resize printer = Printer(2, 'laser') print(printer.name) warehouse = Warehouse() warehouse.receive(Printer(1, 'laser')) warehouse.receive(Scanner(2, 8000)) warehouse.receive(Xerox(3, True)) warehouse.status() warehouse.transfer('printer', 1, 'accounting') warehouse.status()
0c2322df5a728f12f4b855bccb96e8e8e33b2c44
shishengjia/PythonDemos
/数据结构和算法/切片命名_P18.py
209
3.796875
4
""" 代码中如果有很多硬编码的索引值,可读性会很差. """ record = '20 15.5' COUNT = slice(0, 2) PRICE = slice(3, 7) total_cost = int(record[COUNT]) * float(record[PRICE]) print(total_cost)
d81855f5982e2b2ffb70c58c9da437620247fe80
chaoboliu/Aircraft-Wars_pygame
/2018.1.8/8555.py
607
3.515625
4
''' s = "欢迎进入个人信息管理系统" print(s.center(65,'*')) list = [] while True: gongneng = int(input("请您选择功能:① 新增 ② 查询 ③ 修改 ④ 删除 请您进行选择:")) if gongneng == 1: name = input("请输入姓名") years =int(input("请输入年龄")) sex = input("请输入性别") work = input("请输入工作") list.append(name) list.append(years) list.append(sex) list.append(work) print(list) elif gongneng == 2: g = int(input("请输入查询内容")) print(list[g]) ''' a = [["a","c"],["w","d"]] for i in a: for j in i: print(j)
fdc8f815d418a7b60d22c19a9e15d65825b6de3e
GitHubUPB/PreInformeConAcum
/Problema 3.py
173
3.90625
4
primer=0 for x in range (0,5): num=int(input("ingrese un numero")) if x==0: mayor=num else: if num>mayor: mayor=num print(mayor)
759bf4df23c2701d534f6890db1e44751c7c7f84
droogadulce/HackerRank
/math/handshake.py
1,154
4.09375
4
#!/bin/python3 """ Handshake Problem: At the annual meeting of Board of Directors of Acme Inc, every one starts shaking hands with everyone else in the room. Given the fact that any two persons shake hand exactly once, Can you tell the total count of handshakes? Input Format The first line contains the number of test cases T, T lines follow. Each line then contains an integer N, the total number of Board of Directors of Acme. Output Format Print the number of handshakes for each test-case in a new line. Constraints 1 <= T <= 1000 0 < N < 10e6 Sample Input 2 1 2 Sample Output 0 1 Explanation Case 1: The lonely board member shakes no hands, hence 0. Case 2: There are 2 board members, 1 handshake takes place. """ import os import sys # # Complete the handshake function below. # def handshake(n): # # Write your code here. # if n == 1: return 0 return int((n*(n-1))/2) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) result = handshake(n) fptr.write(str(result) + '\n') fptr.close()
23e311f68a82acb0187c860a412e0c217b88dd9e
wulfebw/algorithms
/scripts/elementary_data_structures/revisit/m_stack.py
443
3.96875
4
class Stack(object): def __init__(self): self.s = [] def pop(self): return self.s.pop() def push(self, v): self.s.append(v) def top(self): if len(self.s) == 0: return None else: return self.s[-1] if __name__ == '__main__': s = Stack() s.push(1) s.push(2) s.push(3) print(s.pop()) print(s.pop()) print(s.pop()) print(s.top())
f5e83e6abc365f78607c993c56ef1946e4cbb842
coldhair/Conda
/Try047.py
202
4.125
4
""" 输出乘法口诀表(九九表) Version: 0.1 Author: 吕艳朋 """ for i in range(1, 10): for j in range(1, i + 1): print('{1}×{0}={2: <2d}'.format(i, j, i * j), end=' ') print()
9dcfc14fb244dd00df951d34ec431527a180572b
tombiasz/exercism-python
/robot-simulator/robot_simulator.py
1,002
3.6875
4
NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 class Robot(object): INSTRUCTION_TO_FUNCTION_MAP = { 'A': 'advance', 'L': 'turn_left', 'R': 'turn_right', } def __init__(self, bearing=NORTH, pos_x=0, pos_y=0): self.bearing = bearing self.pos_x = pos_x self.pos_y = pos_y @property def coordinates(self): return self.pos_x, self.pos_y def turn_left(self): self.bearing = (self.bearing - 1) % 4 def turn_right(self): self.bearing = (self.bearing + 1) % 4 def advance(self): if self.bearing == NORTH: self.pos_y += 1 elif self.bearing == EAST: self.pos_x += 1 elif self.bearing == SOUTH: self.pos_y -= 1 elif self.bearing == WEST: self.pos_x -= 1 def simulate(self, sequence): for instruction in sequence: fn_name = self.INSTRUCTION_TO_FUNCTION_MAP[instruction] getattr(self, fn_name)()
66e312103f3e0c95c4930e17257cfba881735b28
wpy-111/python
/month01/day08/exercise03.py
195
3.859375
4
""" 定义函数,根据时分秒计算总秒数 """ def calculation_all_second(hour=0,minutes=0,second=0): return hour*3600+minutes*60+second re=calculation_all_second(2,60) print(re)
3776df6b8f60fee67218565d5e3b1eb2b1c64f86
Chris-Isherwood/Python-Game-Pile
/Chris' Python Game-Pile.py
26,293
3.578125
4
from tkinter import * from random import randint import time import tkinter.messagebox #Formats and sets the overarching game window Game_Window = Tk() Game_Window.title("Chris' Python Game-Pile") HEIGHT = 500 WIDTH = 800 x = (Game_Window.winfo_screenwidth() // 2) - (WIDTH // 2) y = (Game_Window.winfo_screenheight() // 2) - (9*HEIGHT // 16) Game_Window.geometry('{}x{}+{}+{}'.format(WIDTH, HEIGHT, x, y)) class Players: #initialises scores and names for the players involved in the game Player_1 = StringVar(value = "Player 1") Player_2 = StringVar(value = "Player 2") Player_3 = StringVar(value = "Player 3") #sets the remaining lives of each player to 100 Player_1_mpscore = IntVar(value = 100) Player_2_mpscore = IntVar(value = 100) Player_3_mpscore = IntVar(value = 100) #sets the rounds survived highscores for multiplayer mode Player_1_mpHHscore = IntVar(value = 0) Player_2_mpHHscore = IntVar(value = 0) Player_3_mpHHscore = IntVar(value = 0) #sets the current scores for rounds survived in multiplayer mode Player_1_mpHscore = IntVar(value = 0) Player_2_mpHscore = IntVar(value = 0) Player_3_mpHscore = IntVar(value = 0) #sets the current score for rounds survived in singleplayer mode Player_1_spscore = IntVar(value = 0) #sets the rounds survived highscores for singleplayer mode Player_1_spHighscore = IntVar(value = 0) class GameFunctions: #set some required textvariables for multiple of the game features Countdown = IntVar(value = 3) targetNumber = IntVar(value = 100) Player1_guess = StringVar(value = "None") Player2_guess = StringVar(value = "None") Player3_guess = StringVar(value = "None") class Windows: def MainMenu(): #contains all the frames and widgets responsible for the main menu #begin by defining all of the necessary functions for the main menu def MainMenuClose(): #this function closes all of the labels and frames from the main menu bg_frame.grid_forget() sb_frame.grid_forget() title_label.grid_forget() word_game_button.grid_forget() second_game_button.grid_forget() third_game_button.grid_forget() edit_players_button.grid_forget() scoreboard_label.grid_forget() p1_label.grid_forget() p1_mpscore_label.grid_forget() p1_spHighscore_label.grid_forget() p2_label.grid_forget() p2_mpscore_label.grid_forget() p3_label.grid_forget() p3_mpscore_label.grid_forget() def wg_open(): #a shortcut function to close the main menu and open the word game menu MainMenuClose() Windows.wg_Menu() def SecondGameInstructions(): #displays the pop-up note for the second game button tkinter.messagebox.showinfo("The Second Game", "Space here for a future second game") def ThirdGameInstructions(): #displays the pop-up note for the third game button tkinter.messagebox.showinfo("The Third Game", "Space here for a future third game") #defines the necessary frames for the main menu #first of which is the background frame bg_frame = Frame(Game_Window, bg = "Dark Green", width = 800, height = 500) bg_frame.grid(rowspan = 10, columnspan = 3) #then we have the scoreboard frame sb_frame = Frame(Game_Window, bg = "#0055cc", width = 800, height = 150) sb_frame.grid(row = 8, rowspan = 2, columnspan = 3) #following this is the necessary labels and buttons for the main menu functionality #the title label title_label = Label(Game_Window, text = "Python Game-Pile", bg = "Dark Green", fg = "Black", bd = 1, font = ("Times New Roman", 75, "underline")) title_label.grid(row = 0, column = 1, sticky = S) #the word game button word_game_button = Button(Game_Window, text = "Word Game", bg = "Dark Green", font = ("Helvetica", 15), command = wg_open) word_game_button.grid(row = 2, column = 1) #the second game button second_game_button = Button(Game_Window, text = "Second Game", command = SecondGameInstructions, bg = "Dark Green", font = ("Helvetica", 15)) second_game_button.grid(row = 3, column = 1) #the third game button third_game_button = Button(Game_Window, text = "Third Game", bg = "Dark Green", command = ThirdGameInstructions, font = ("Helvetica", 15)) third_game_button.grid(row = 4, column = 1) #the edit players button edit_players_button = Button(Game_Window, text = "Edit Players", bg = "Dark Green", font = ("Helvetica", 15), command = Windows.editPlayerWindow) edit_players_button.grid(row = 5, column = 1) #the scoreboard labels scoreboard_label = Label(Game_Window, text = "Scoreboard:", bg = "#0055cc", font = ("Helvetica", 25, "underline")) scoreboard_label.grid(row = 8, column = 1, sticky = N) #player 1 name label p1_label = Label(Game_Window, textvariable = Players.Player_1, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p1_label.grid(row = 8, column = 1, sticky = S) #player 1 multiplayer highscore label p1_mpscore_label = Label(Game_Window, textvariable = Players.Player_1_mpHHscore, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p1_mpscore_label.grid(row = 9, column = 1, sticky = N) #player 1 singleplayer highscore label p1_spHighscore_label = Label(Game_Window, textvariable = Players.Player_1_spHighscore, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p1_spHighscore_label.grid(row = 9, column = 1, sticky = S) #player 2 name label p2_label = Label(Game_Window, textvariable = Players.Player_2, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p2_label.grid(row = 8, column = 1, sticky = SW) #player 2 multiplayer highscore label p2_mpscore_label = Label(Game_Window, textvariable = Players.Player_2_mpHHscore, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p2_mpscore_label.grid(row = 9, column = 1, sticky = NW) #player 3 name label p3_label = Label(Game_Window, textvariable = Players.Player_3, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p3_label.grid(row = 8, column = 1, sticky = SE) #player 3 multiplayer highscore label p3_mpscore_label = Label(Game_Window, textvariable = Players.Player_3_mpHHscore, bg = "#0055cc", font = ("Helvetica", 15, "bold")) p3_mpscore_label.grid(row = 9, column = 1, sticky = NE) def editPlayerWindow(): #creates the window used to add/remove players optionsWindow = Tk() optionsWindow.title("Edit Players") WIDTH = 120 HEIGHT = 110 x = (Game_Window.winfo_screenwidth() // 2) - (WIDTH // 2) y = (Game_Window.winfo_screenheight() // 2) - (2*HEIGHT // 2) optionsWindow.geometry('{}x{}+{}+{}'.format(WIDTH, HEIGHT, x, y)) #adds a user input line playerEntry = Entry(optionsWindow) playerEntry.grid(row = 1) def addPlayer(): #defines the function used to take the input entry and define it as the first/second/third player if Players.Player_1.get() == "Player 1": Players.Player_1.set(playerEntry.get()) elif Players.Player_2.get() == "Player 2": Players.Player_2.set(playerEntry.get()) elif Players.Player_3.get() == "Player 3": Players.Player_3.set(playerEntry.get()) def removePlayer(): #defines the function used to take the input entry and remove this player from the game if Players.Player_1.get() == playerEntry.get(): Players.Player_1.set("Player 1") if Players.Player_2.get() == playerEntry.get(): Players.Player_2.set("Player 2") if Players.Player_3.get() == playerEntry.get(): Players.Player_3.set("Player 3") if Players.Player_1.get() == "Player 1" and Players.Player_2.get() != "Player 2": Players.Player_1.set(Players.Player_2.get()) Players.Player_2.set("Player 2") if Players.Player_2.get() == "Player 2" and Players.Player_3.get() != "Player 3": Players.Player_2.set(Players.Player_3.get()) Players.Player_3.set("Player 3") #adds the relevant buttons for adding players, removing players and closing the options window Adder = Button(optionsWindow, text = "Add Player", command = addPlayer).grid(row = 2) Remover = Button(optionsWindow, text = "Remove Player", command = removePlayer).grid(row = 3) Canceller = Button(optionsWindow, text = "Cancel", command = optionsWindow.destroy).grid(row = 4) def wg_Menu(): #contains all the frames and widgets responsible for the word game menu #begins by defining the necessary functions for the word game menu def wgMenuClose(): #this function closes all of the frames and labels associated with the word game menu bg_frame.grid_forget() title_label.grid_forget() instructions_button.grid_forget() singleplayer_button.grid_forget() multiplayer_button.grid_forget() edit_players_button.grid_forget() return_button.grid_forget() def MainMenuReturn(): #this function closes the word game window and returns the user to the main menu wgMenuClose() Windows.MainMenu() def SinglePlayGame(): #this function closes the word game menu and opens a singleplayer game wgMenuClose() Windows.wg_single() def MultiPlayGame(): #this function closes the word game menu and opens a multiplayer game wgMenuClose() Windows.wg_multi() def Instructions(): #this brings up a messagebox showing the instructions for the singleplayer and multiplayer word game tkinter.messagebox.showinfo("Singleplayer Instructions", "Singleplayer: \nGuess as many words as possible with scores which add up to the target number shown, where a = 1, b = 2 etc... Survive as long as you can: you start with 100 lives and lose one for each point value away from the target score.\n\nMultiplayer: \nRemaining lives are no longer visible. Play continues until all players have 0 lives; can you survive longer than the rest?") #defines all the necessary frames for the word game menu #first of which is the background frame bg_frame = Frame(Game_Window, bg = "Dark Green", width = 800, height = 500) bg_frame.grid(rowspan = 10, columnspan = 3) #following this is the necessary labels and buttons for the main menu functionality #the title label title_label = Label(Game_Window, text = "Word Game", bg = "Dark Green", font = ("Helvetica", 75, "underline")) title_label.grid(row = 0, column = 1, sticky = S) #the instructions button instructions_button = Button(Game_Window, text = "Instructions", bg = "Dark Green", font = ("Helvetica", 15), command = Instructions) instructions_button.grid(row = 2, column = 1) #the singleplayer button singleplayer_button = Button(Game_Window, text = "Singleplayer", bg = "Dark Green", font = ("Helvetica", 15), command = SinglePlayGame) singleplayer_button.grid(row = 3, column = 1) #the multiplayer button multiplayer_button = Button(Game_Window, text = "Multiplayer", bg = "Dark Green", font = ("Helvetica", 15), command = MultiPlayGame) multiplayer_button.grid(row = 4, column = 1) #the edit players button edit_players_button = Button(Game_Window, text = "Edit Players", bg = "Dark Green", font = ("Helvetica", 15), command = Windows.editPlayerWindow) edit_players_button.grid(row = 5, column = 1) #the return to main menu button return_button = Button(Game_Window, text = "Return to Main Menu", bg = "Dark Green", font = ("Helvetica", 15), command = MainMenuReturn) return_button.grid(row = 5, column = 1) def wg_single(): #contains all the frames and widgets responsible for the word game singleplayer game #begins by defining the necessary functions for the singleplayer word game def wg_singleClose(): #this function closes all of the frames and labels associated with the word game menu bg_frame.grid_forget() title_label.grid_forget() return_button.grid_forget() count_label.grid_forget() count_start_button.grid_forget() countdown_reset() def MainMenuReturn(): #this function closes the word game window and returns the user to the main menu wg_singleClose() Windows.MainMenu() def mpScoreReset(): #this function resets the number of lives remaining Players.Player_1_mpscore.set(100) def spScoreReset(): #this function sets the singleplayer current score back to 0 Players.Player_1_spscore.set(0) def startTimer(): #this function reduces the value of the countdown timer and updates the screen to show it t = GameFunctions.Countdown.get() while t >= 0: Game_Window.after(1000, GameFunctions.Countdown.set(t)) Game_Window.update() t -= 1 spScoreReset() beginGame() def countdown_reset(): #this function resets the countdown clock integer variable to 3 seconds GameFunctions.Countdown.set(3) def beginGame(): #start by defining the functions needed to play the singleplayer word game def wg_singleCloseGame(): #this function closes all the frames and labels associated with the game bg_frame.grid_forget() target_label.grid_forget() return_button_game.grid_forget() word_entry.grid_forget() target_explain_label.grid_forget() lives_explaining_label.grid_forget() lives_remaining_label.grid_forget() countdown_reset() def MMRet_game(): #this function closes the word game window from within the game, and returns the user to the main menu wg_singleCloseGame() mpScoreReset() Windows.MainMenu() def CalculateScore(): #starts off by clearing whats on the screen target_label.grid_forget() return_button_game.grid_forget() word_entry.grid_forget() target_explain_label.grid_forget() lives_explaining_label.grid_forget() lives_remaining_label.grid_forget() #then calculates the score achieved word = GameFunctions.Player1_guess.get() Letters = list(word.lower()) total_score = 0 for L in Letters: letter_score = ord(L) - ord("a") + 1 total_score = total_score + letter_score Players.Player_1_mpscore.set(Players.Player_1_mpscore.get() - (abs(total_score - GameFunctions.targetNumber.get()))) if Players.Player_1_mpscore.get() <= 0: if Players.Player_1_spscore.get() > Players.Player_1_spHighscore.get(): Players.Player_1_spHighscore.set(Players.Player_1_spscore.get()) MMRet_game() else: Players.Player_1_spscore.set(Players.Player_1_spscore.get() + 1) beginGame() def submitted(event): #this is what happens when the return key is pressed GameFunctions.Player1_guess.set(word_entry.get()) CalculateScore() #this is the function that once again clears the screen, ready for the game to be played title_label.grid_forget() count_label.grid_forget() count_start_button.grid_forget() return_button.grid_forget() #next, the target number is randomised GameFunctions.targetNumber.set(randint(25, 150)) #this random number is then displayed on the screen with an explanation label target_explain_label = Label(Game_Window, text = "Your target number is:", bg = "Dark Green", font = ("Helvetica", 50)) target_explain_label.grid(row = 1, column = 1) target_label = Label(Game_Window, textvariable = GameFunctions.targetNumber, bg = "Dark Green", font = ("Helvetica", 75, "bold")) target_label.grid(row = 2, column = 1) #the input window is added to the screen word_entry = Entry(Game_Window) word_entry.grid(row = 3, column = 0, columnspan = 3, sticky = S) Game_Window.bind('<Return>', submitted) #the remaining lives label is added to the screen lives_explaining_label = Label(Game_Window, text = "Lives remaining: ", bg = "Dark Green", font = ("Helvetica", 20)) lives_explaining_label.grid(row = 6, column = 1, sticky = S) lives_remaining_label = Label(Game_Window, textvariable = Players.Player_1_mpscore, bg = "Dark Green", font = ("Helvetica", 20)) lives_remaining_label.grid(row = 7, column = 1, sticky = N) #the return button is added to the screen return_button_game = Button(Game_Window, text = "Return to Main Menu", bg = "Dark Green", font = ("Helvetica", 10), command = MMRet_game) return_button_game.grid(row = 9, column = 1, sticky = S) #begin by defining all the necessary frames for the word game menu #first of which is the background frame bg_frame = Frame(Game_Window, bg = "Dark Green", width = 800, height = 500) bg_frame.grid(rowspan = 10, columnspan = 3) #following this is the necessary labels and buttons for the main menu functionality #the title label title_label = Label(Game_Window, text = "Singleplayer", bg = "Dark Green", font = ("Helvetica", 50, "underline")) title_label.grid(row = 0, column = 1) #the countdown timer count_label = Label(Game_Window, textvariable = GameFunctions.Countdown, bg = "Dark Green", font = ("Helvetica", 25)) count_label.grid(row = 4, column = 1) #the countdown starter button count_start_button = Button(Game_Window, text = "Start!", bg = "Dark Green", font = ("Helvetica", 20), command = startTimer) count_start_button.grid(row = 6, column = 1) #the return to main menu button return_button = Button(Game_Window, text = "Return to Main Menu", bg = "Dark Green", font = ("Helvetica", 10), command = MainMenuReturn) return_button.grid(row = 9, column = 1, sticky = S) def wg_multi(): #contains all the frames and widgets responsible for the word game singleplayer game #begins by defining the necessary functions for the multiplayer word game def wg_multiClose(): #this function closes all of the frames and labels associated with the word game menu bg_frame.grid_forget() title_label.grid_forget() return_button.grid_forget() count_label.grid_forget() count_start_button.grid_forget() countdown_reset() def MainMenuReturn(): #this function closes the word game window and returns the user to the main menu wg_multiClose() Windows.MainMenu() def mpScoreReset(): #sets the remaining lives of all of the players back to 100 Players.Player_1_mpscore.set(100) Players.Player_2_mpscore.set(100) Players.Player_3_mpscore.set(100) def mpHScoreReset(): #sets the survived rounds scores of all players back to 0 Players.Player_1_mpHscore.set(0) Players.Player_2_mpHscore.set(0) Players.Player_3_mpHscore.set(0) def startTimer(): #this function reduces the value of the countdown timer and updates the screen to show it t = GameFunctions.Countdown.get() while t >= 0: Game_Window.after(1000, GameFunctions.Countdown.set(t)) Game_Window.update() t -= 1 mpHScoreReset() beginGame() def countdown_reset(): #resets the countdown timer to 3 seconds GameFunctions.Countdown.set(3) def beginGame(): #defines the necessary functions to run the multiplayer word game def wg_multiCloseGame(): #this function closes all the frames and labels associated with the game bg_frame.grid_forget() target_label.grid_forget() return_button_game.grid_forget() word_entry1.grid_forget() word_entry2.grid_forget() word_entry3.grid_forget() p1_label.grid_forget() p2_label.grid_forget() p3_label.grid_forget() target_explain_label.grid_forget() countdown_reset() def MMRet_game(): #this function closes the word game window from within the game, and returns the user to the main menu wg_multiCloseGame() mpScoreReset() Windows.MainMenu() def CalculateScore1(): #calculates the score achieved for player 1 word1 = GameFunctions.Player1_guess.get() Letters1 = list(word1.lower()) total_score_1 = 0 for L in Letters1: letter_score_1 = ord(L) - ord("a") + 1 total_score_1 = total_score_1 + letter_score_1 Players.Player_1_mpscore.set(Players.Player_1_mpscore.get() - (abs(total_score_1 - GameFunctions.targetNumber.get()))) if Players.Player_1_mpscore.get() > 0: Players.Player_1_mpHscore.set(Players.Player_1_mpHscore.get() + 1) if Players.Player_1_mpscore.get() <= 0: Players.Player_1_mpscore.set(0) def CalculateScore2(): #calculation for the score achieved by player 2 word2 = GameFunctions.Player2_guess.get() Letters2 = list(word2.lower()) total_score_2 = 0 for L in Letters2: letter_score_2 = ord(L) - ord("a") + 1 total_score_2 = total_score_2 + letter_score_2 Players.Player_2_mpscore.set(Players.Player_2_mpscore.get() - (abs(total_score_2 - GameFunctions.targetNumber.get()))) if Players.Player_2_mpscore.get() > 0: Players.Player_2_mpHscore.set(Players.Player_2_mpHscore.get() + 1) if Players.Player_2_mpscore.get() <= 0: Players.Player_2_mpscore.set(0) def CalculateScore3(): #calculation for the score achieved by player 3 word3 = GameFunctions.Player3_guess.get() Letters3 = list(word3.lower()) total_score_3 = 0 for L in Letters3: letter_score_3 = ord(L) - ord("a") + 1 total_score_3 = total_score_3 + letter_score_3 Players.Player_3_mpscore.set(Players.Player_3_mpscore.get() - (abs(total_score_3 - GameFunctions.targetNumber.get()))) if Players.Player_3_mpscore.get() > 0: Players.Player_3_mpHscore.set(Players.Player_3_mpHscore.get() + 1) if Players.Player_3_mpscore.get() <= 0: Players.Player_3_mpscore.set(0) def CalculateScores(): #shortcut function to calculate the scores for all of the players in multiplayer mode CalculateScore1() CalculateScore2() CalculateScore3() #determines whether or not to exit to the main menu for gameover if Players.Player_1_mpscore.get() > 0 or Players.Player_2_mpscore.get() > 0 or Players.Player_3_mpscore.get() > 0: target_explain_label.grid_forget() target_label.grid_forget() word_entry1.grid_forget() word_entry2.grid_forget() word_entry3.grid_forget() p1_label.grid_forget() p2_label.grid_forget() p3_label.grid_forget() return_button_game.grid_forget() beginGame() else: title_label.grid_forget() count_label.grid_forget() count_start_button.grid_forget() return_button.grid_forget() if Players.Player_1_mpHscore.get() > Players.Player_1_mpHHscore.get(): Players.Player_1_mpHHscore.set(Players.Player_1_mpHscore.get()) if Players.Player_2_mpHscore.get() > Players.Player_2_mpHHscore.get(): Players.Player_2_mpHHscore.set(Players.Player_2_mpHscore.get()) if Players.Player_3_mpHscore.get() > Players.Player_3_mpHHscore.get(): Players.Player_3_mpHHscore.set(Players.Player_3_mpHscore.get()) MMRet_game() def submitted(event): #defines what happens when the return button is pressed GameFunctions.Player1_guess.set(word_entry1.get()) GameFunctions.Player2_guess.set(word_entry2.get()) GameFunctions.Player3_guess.set(word_entry3.get()) CalculateScores() #this is the function that once again clears the screen, ready for the game to be played title_label.grid_forget() count_label.grid_forget() count_start_button.grid_forget() return_button.grid_forget() #next, the target number is randomised GameFunctions.targetNumber.set(randint(25, 150)) #this random number is then displayed on the screen with an explanation label target_explain_label = Label(Game_Window, text = "Your target number is:", bg = "Dark Green", font = ("Helvetica", 50)) target_explain_label.grid(row = 1, column = 1) target_label = Label(Game_Window, textvariable = GameFunctions.targetNumber, bg = "Dark Green", font = ("Helvetica", 75, "bold")) target_label.grid(row = 2, column = 1) #the input window is added to the screen word_entry1 = Entry(Game_Window) word_entry1.grid(row = 5, column = 1, sticky = W) word_entry2 = Entry(Game_Window) word_entry2.grid(row = 5, column = 1) word_entry3 = Entry(Game_Window) word_entry3.grid(row = 5, column = 1, sticky = E) #binds the return key to the submitted function Game_Window.bind('<Return>', submitted) #the return button is added to the screen return_button_game = Button(Game_Window, text = "Return to Main Menu", bg = "Dark Green", font = ("Helvetica", 10), command = MMRet_game) return_button_game.grid(row = 9, column = 1, sticky = S) #shows the player names for clarification in the multiplayer game p1_label = Label(Game_Window, textvariable = Players.Player_1, bg = "Dark Green", font = ("Helvetica", 25)) p1_label.grid(row = 4, column = 1, sticky = W) p2_label = Label(Game_Window, textvariable = Players.Player_2, bg = "Dark Green", font = ("Helvetica", 25)) p2_label.grid(row = 4, column = 1) p3_label = Label(Game_Window, textvariable = Players.Player_3, bg = "Dark Green", font = ("Helvetica", 25)) p3_label.grid(row = 4, column = 1, sticky = E) #begin by defining all the necessary frames for the word game menu #first of which is the background frame bg_frame = Frame(Game_Window, bg = "Dark Green", width = 800, height = 500) bg_frame.grid(rowspan = 10, columnspan = 3) #following this is the necessary labels and buttons for the main menu functionality #the title label title_label = Label(Game_Window, text = "Multiplayer", bg = "Dark Green", font = ("Helvetica", 50, "underline")) title_label.grid(row = 0, column = 1) #the countdown timer count_label = Label(Game_Window, textvariable = GameFunctions.Countdown, bg = "Dark Green", font = ("Helvetica", 25)) count_label.grid(row = 4, column = 1) #the countdown starter button count_start_button = Button(Game_Window, text = "Start!", bg = "Dark Green", font = ("Helvetica", 20), command = startTimer) count_start_button.grid(row = 6, column = 1) #the return to main menu button return_button = Button(Game_Window, text = "Return to Main Menu", bg = "Dark Green", font = ("Helvetica", 10), command = MainMenuReturn) return_button.grid(row = 9, column = 1, sticky = S) #begins the game by opening the main menu Windows.MainMenu() Game_Window.mainloop()
2afe3054fe636aa8620c035ba5210c21a60d8a31
lemonshark12/Portfolio
/Division without division.py
2,677
3.96875
4
def divide(): """Divides any positive number by another positive number without using the build-in floor division or modulus operator.""" n = float (input ("please enter a positive integer you wish to divide >> ")) m = float (input ("please enter a positive inter you wish to divide by >> ")) solution = [] if m == 0: print ("Cannot divide by zero! Please choose a non-zero number.") divide() while n != 0: temp_list = [] ans = m b = 1 dig = 0 while (ans < n): ans += m di = temp_list.append(ans) dig = len(temp_list) digit = (n - dig*m)*10 solution.append(str(dig)) n = digit if len(solution) == 1: solution.append(".") elif len(solution) > 17: break if (len(solution) > 5) & (int(solution[2]) == int(solution[3]) == int(solution[4]) == 9): print (int(solution[0])+1) else: print ("".join(solution)) divide() # PREVIOUS ATTEMPTS AND CODE SNIPPETS FOR TESTING BELOW: # print (int("".join(solution))+6.000000001) # # if remainder < rem: # except (OverflowError): # print ("MAX_INT") #except(ZeroDivisionError): # print ("Cannot divide by zero!") def solution(): """divide two integers without using multiplication, division, or mod operator; if overflow, return MAX_INT""" digits_and_remainder = calculate_digits(n, m) print (digits_and_remainder) calculate_remainder(digits_and_remainder) def calculate_digits(n, m): r = list(range(n)) ans = m rem = m division_list = [] while ans < n: ans += m division_list.append(ans) # print (division_list) digits = len(division_list) last = division_list[-1] remainder = (n - digits*m)*10 return (digits, remainder) def calculate_remainder(digits_and_remainder): remainders_list = [] remainder_list = [] digits, rem = int(digits_and_remainder[0]), digits_and_remainder[1] # print (digits, rem) # digits = 3, rem = 30 remainder = m # remainder = 7 while rem != 0: while remainder < rem: # while 7 < 30 remainder += m # add 7 to the remainder variable remainder_list.append(remainder) # attach the remainder variable to the remainder_list # print (n, m, remainder, rem) print (remainder_list) remainders = len(remainder_list) last = remainder_list[-1] rem = (rem - remainders*m)*10 decimals = remainders_list.append(remainders) remainder_list = [] print (last) print (remainder) print (decimals) #print (new_remainder) #while remainders != 0: # print (decimals) #return (remainders) # print (str(digits) + "." + str(remainders_list.join())) balls = 24/7 print (balls) #print (short) # except (overflowError): # print ("MAX_INT") #solution()
555d94df09534bcd431d0e3a9ef391e5362d81df
DanaMC18/advent_of_code
/2020/day_12/navigate.py
3,130
3.890625
4
"""Navigate module.""" import os DIRS = ['N', 'E', 'S', 'W'] OPPS = {'N': 'S', 'S': 'N', 'W': 'E', 'E': 'W'} INSTRUCTIONS_TXT = 'instructions.txt' def manhattan_dist(): """Get manhattan distance.""" instructions = _load_instructions() curr_dir = 'E' east_west = 0 north_south = 0 for ins in instructions: direction = ins[:1] val = int(ins[1:]) pos_neg = -1 if direction in ['S', 'W'] or \ (direction == 'F' and curr_dir in ['S', 'W']) else 1 if direction in ['N', 'S'] or (direction == 'F' and curr_dir in ['N', 'S']): north_south += (val * pos_neg) elif direction in ['W', 'E'] or (direction == 'F' and curr_dir in ['W', 'E']): east_west += (val * pos_neg) elif direction in ['R', 'L']: index = DIRS.index(curr_dir) rotation = int(val / 90) if direction == 'R' else int((360 - val) / 90) new_index = (index + rotation) % len(DIRS) curr_dir = DIRS[new_index] manhattan_distance = abs(east_west) + abs(north_south) print(f'abs({east_west}) + abs({north_south}) = {manhattan_distance}') return manhattan_distance def waypoint_manhattan(): """Get waypoint manhattan distance.""" instructions = _load_instructions() curr_dirs = ['E', 'N'] east_west = 0 north_south = 0 waypoint = {'N': 1, 'E': 10, 'S': 0, 'W': 0} for ins in instructions: direction = ins[:1] val = int(ins[1:]) if direction in DIRS and direction in curr_dirs: waypoint[direction] += val elif direction in DIRS and direction not in curr_dirs: opp_dir = OPPS[direction] waypoint[opp_dir] -= val elif direction == 'F': for key in waypoint.keys(): pos_neg = -1 if key in ['S', 'W'] else 1 if key in ['N', 'S']: north_south += (val * waypoint[key] * pos_neg) elif key in ['W', 'E']: east_west += (val * waypoint[key] * pos_neg) elif direction in ['R', 'L']: new_dirs = [] new_waypoint = {x: 0 for x in DIRS} for d in curr_dirs: index = DIRS.index(d) rotation = int(val / 90) if direction == 'R' else int((360 - val) / 90) new_index = (index + rotation) % len(DIRS) new_dir = DIRS[new_index] new_dirs.append(new_dir) new_waypoint[new_dir] = waypoint[d] curr_dirs = new_dirs waypoint = new_waypoint manhattan_distance = abs(east_west) + abs(north_south) print(f'abs({east_west}) + abs({north_south}) = {manhattan_distance}') return manhattan_distance def _load_instructions(): """Load instructions from text file.""" filepath = os.path.join(os.getcwd(), os.path.dirname(__file__), INSTRUCTIONS_TXT) f = open(filepath, 'r') instructions = f.read() f.close() return instructions.strip().split('\n') # SOLUTION 1 | 508 # manhattan_dist() # SOLUTION 2 | 30761 # waypoint_manhattan()
178ca465befb03d29b7a8404efab3b9b0fe1214e
bovarysme/advent
/2017/day04.py
1,254
3.78125
4
def duplicates(passphrase): words = set() for word in passphrase.split(): if word in words: return False words.add(word) return True def anagrams(passphrase): words = set() for word in passphrase.split(): word = ''.join(sorted(word)) if word in words: return False words.add(word) return True def solve(validator, passphrases): return sum(validator(passphrase) for passphrase in passphrases) def part_one(passphrases): return solve(duplicates, passphrases) def part_two(passphrases): return solve(anagrams, passphrases) if __name__ == '__main__': assert part_one(['aa bb cc dd ee']) == 1 assert part_one(['aa bb cc dd aa']) == 0 assert part_one(['aa bb cc dd aaa']) == 1 assert part_two(['abcde fghij']) == 1 assert part_two(['abcde xyz ecdab']) == 0 assert part_two(['a ab abc abd abf abj']) == 1 assert part_two(['iiii oiii ooii oooi oooo']) == 1 assert part_two(['oiii ioii iioi iiio']) == 0 with open('inputs/day4.txt', 'r') as f: passphrases = [line.rstrip() for line in f] print('Answer for part one:', part_one(passphrases)) print('Answer for part two:', part_two(passphrases))
d8ce865ec0ffd3f50f33679d5e2c27f0d0749607
akotwicka/Learning_Python_Udemy
/dziedziczenie.py
1,825
3.6875
4
class Cake: bakery_offer = [] def __init__(self, name, kind, taste, additives, filling): self.name = name self.kind = kind self.taste = taste self.additives = additives.copy() self.filling = filling self.bakery_offer.append(self) def show_info(self): print("{}".format(self.name.upper())) print("Kind: {}".format(self.kind)) print("Taste: {}".format(self.taste)) if len(self.additives) > 0: print("Additives:") for a in self.additives: print("\t\t{}".format(a)) if len(self.filling) > 0: print("Filling: {}".format(self.filling)) print('-' * 20) @property def full_name(self): return "--== {} - {} ==--".format(self.name.upper(), self.kind) class SpecialCake(Cake): def __init__(self, name, kind, taste, additives, filling, occasion, shape, ornaments, text): super().__init__(name, kind, taste, additives, filling) self.occasion = occasion self.shape = shape self.ornaments = ornaments self.text = text def show_info(self): super().show_info() print("Occasion: {}".format(self.occasion)) print("Shape: {}".format(self.shape)) print("Ornaments: {}".format(self.ornaments)) print("Text: {}".format(self.text)) birthday = SpecialCake('birthday cake', 'cake', 'chocolate', ['chocolate', 'coconut','cherries'], 'chocolate cream', 'birthday', 'round', 'flores', 'Happy Birthday') wedding = SpecialCake('wedding cake', 'cake', 'vanilla', ['raspberries', 'strawberries'], 'vanilla cream', 'wedding', 'round', '-', 'Mrs & Mr') birthday.show_info() wedding.show_info() for i in SpecialCake.bakery_offer: print(i.full_name) i.show_info()
905ace7073124c7d9d330e333e8adfdf2ecad943
nicolasfcpazos/Python-Basic-Exercises
/Aula15_Ex067.py
509
4.125
4
# Faça um programa que leia a tabuada de vários números, um de cada vez, # para cada valor digitado pelo usuário. O programa será interrompido # quando o número solicitado for negativo. print('------- TABUADA -------') cont = 0 while True: num = int(input('Digite um número para ver sua tabuada: ')) print('-' * 30) if num < 0: break for cont in range(1, 11): print(f'{num} x {cont} = {(num * cont)}') print('-' * 30) print('Programa encerrado. Volte sempre !!')
0077a2503c2db5b90d323bc4e79356352db31a67
McNultyPT/Algorithms
/recipe_batches/recipe_batches.py
1,489
3.90625
4
#!/usr/bin/python pizza = { 'dough': 1, 'cheese': 12, 'sauce': 5 } ingredients = { 'dough': 1, 'cheese': 7, 'sauce': 5 } import math def recipe_batches(recipe, ingredients): batches = [] recipe_values = [i for i in recipe.values()] ingredient_values = [j for j in ingredients.values()] for i in range(len(recipe_values)): for j in range(len(ingredient_values)): if i == j: if ingredient_values[j] > recipe_values[i]: print(ingredient_values) print(recipe_values) num = recipe_values[i] % ingredient_values[j] print(num) batch = int(ingredient_values[j] // num) print(batch) batches.append(batch) elif ingredient_values[j] == recipe_values[i]: batches.append(1) else: batches.append(0) if len(recipe_values) > len(batches): return 0 else: print(batches) return min(batches) if __name__ == '__main__': # Change the entries of these dictionaries to test # your implementation with different inputs recipe = { 'milk': 100, 'butter': 50, 'flour': 5 } ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 } print("{batches} batches can be made from the available ingredients: {ingredients}.".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))
ad51e4d5ab11a292911904aa9af86f0f717e8062
nasir-001/Core-Python-Exercise
/UpperToLower.py
230
3.796875
4
def main(): def getName(): user_input = input() for a in user_input: lower = user_input.lower() if a == a.lower(): print(a.upper()) else: print(a.lower()) getName() if __name__ == "__main__": main()
0272aa772c17862826a80460b68039e252403cb5
edgarduart23/poloMisiones
/estructuras.py
1,588
4.125
4
nombre = "Harry" print(nombre[0]) #LISTAS nombres = ["Harry", "Ron", "hermione"] print(nombres) #agregar un elemento a la lista nombres.append("Draco") print(nombres) #ordenar la lista nombres.sort() print(nombres) #borar la lista nombres.clear() print(nombres) #SET: no agrega elementos repetidos conjunto = set() #add: agrega elemento al conjunto conjunto.add(1.0) conjunto.add(2.0) conjunto.add(1.0) print(conjunto) #remove: elimina elemento del conjunto conjunto.remove(2.0) #len: la longitud del conjunto print(f"El conjunto {conjunto} tiene {len(conjunto)} elemento") #DICCIONARIO casas = {"Harry" : "Gryffindor", "Draco" : "Slytherin"} print(casas["Harry"]) print(casas["Draco"]) #agregar un nuevo elemento casas["Hermione"] = "Gryffindor" print(casas["Hermione"]) #EVALUACION 3 ejemploSet = {"Amarillo", "Naranja", "Negro"} ejemploList = ["Azul", "Verde", "Rojo"] ejemploSet = ejemploSet.add(ejemploList ) print(ejemploSet) conjunto1 = {10, 20, 30, 40, 50} conjunto2 = {30, 40, 50, 60, 70} print(conjunto1.intersection(conjunto2)) conjunto1 = {10, 20, 30} conjunto2 = {20, 40, 50} conjunto1.difference_update(conjunto2) print(conjunto1) ejemploDiccionario = { "clase":{ "estudiante":{ "nombre":"Marcos", "examenes":{ "matematica":70, "geografia":80 } } } } print(ejemploDiccionario['clase']['estudiante']['examenes']['matematica']) from datetime import datetime, timedelta fecha_dada = datetime(2020, 3, 22, 10, 00, 00) fecha_limite = fecha_dada + timedelta(days=7, hours=12) print(fecha_limite)
d0f2b62ae013886bac65f1492be1e17351cf192b
kranthikumar27/demo
/cspp1-practice/m5/p3/square_root_bisection.py
645
4.15625
4
'''# Write a python program to find the square root of the given number # using approximation method # testcase 1 # input: 25 # output: 4.999999999999998 # testcase 2 # input: 49 # output: 6.999999999999991 ''' def main(): ''' this program is used to print the squareroot value of the given number using bi-section method''' num_val = int(input()) epsilon = 0.01 low = 0 high = num_val avg = (low+high)/2 while abs(avg**2-num_val) >= epsilon: if avg**2 < num_val: low = avg else: high = avg avg = (low+high)/2 print(avg) if __name__ == "__main__": main()
21961c0cd137233b4a9c5f4ab3233bab1252ba05
ShivaBansfore-JGEC/DataStructureAndAlgo-Python
/dynamic_programming/knapsackAtcoderbu.py
722
3.515625
4
import sys sys.stdout = open('dynamic_programming/output.txt', 'w') sys.stdin = open('dynamic_programming/input.txt', 'r') def knapsackBottomUp(wt,price,c,n): dp=[[0 for x in range(c+1)] for y in range(n+1)] for i in range(n+1): for w in range(c+1): if i==0 or w==0: dp[i][w]=0 else: inc=exc=0 if wt[i-1]<=w: inc=price[i-1]+dp[i-1][w-wt[i-1]] exc=dp[i-1][w] dp[i][w]=max(inc,exc) return dp[n][c] n,c=map(int,input().split()) wt=[] price=[] for _ in range(n): w,v=map(int,input().split()) wt.append(w) price.append(v) print(knapsackBottomUp(wt,price,c,n))
8d2413570038115e7a052062ea074a4ade535fa8
danslavov/Programming-Basics-Python-2017-MAY
/06_DrawingWithLoops/P08_Sunglasses.py
364
3.984375
4
n = int(input()) halfBorder = "*" * 2 * n halfMiddle = "*" + "/" * (2 * n - 2) + "*" border = halfBorder + " " * n + halfBorder middle = halfMiddle + " " * n + halfMiddle center = halfMiddle + "|" * n + halfMiddle print(border) for i in range(n - 2): if i == (n - 1) // 2 - 1: print(center) else: print(middle) print(border)
1e48160edc852d90bd1e71eda192d01d5b5a8546
PrakashPrabhu-M/pythonProgramsGuvi
/oddFactorsOfaNumber.py
229
4.03125
4
""" Given a number N, print the odd factors of the number. Input Size : 1 <= N <= 1000 Sample Testcase : INPUT 9 OUTPUT 1 3 9 """ n=int(input()) l=[] for i in range(1,n+1): if n%i==0 and i%2==1: l.append(i) print(*l)
b5c55868c0f801b4818e56c8a5964cfca904063c
SevenHanXu/python---learn
/list.py
1,377
3.921875
4
#!/usr/bin/env python # coding=utf-8 list_a = [1, 2.2, "hello world", [1, 2, 3]] list_b = () print "list_a = %s" % str(list_a) print "list_b = %s" % str(list_b) range_a = range(0, 100) print "rang_a = %s" % str(range_a) print type(range_a) list_c = range(0, 5) list_d = range(5, 10) print "list_c = %s" % str(list_c) print "list_d = %s" % str(list_d) list_c.append(2.3) print "list_c = %s" % str(list_c) list_c.insert(3, [1, 2, 3]) print "list_c = %s" % str(list_c) list_d.extend(list_c) print "list_d = %s" % str(list_d) del list_c[0] print "list_c = %s" % str(list_c) print "list_d = %s" % str(list_d) list_c.pop(3) print "list_c = %s" % str(list_c) print "list_d = %s" % str(list_d) list_e = range(0, 10, 2) print "list_e = %s" % str(list_e) list_f = range(0, 11) print "list_f [2~5] = %s" % str(list_f[2 : 6]) print "list_f [2~the last num] = %s" % str(list_f[2 : ]) print "list_f [2~倒数第二个元素] = %s" % str(list_f[2 : -1]) #下标为2 print "list_f [全部元素] = %s" % str(list_f[ : ]) print "list_f [全部元素:每隔两个取一个元素] = %s" % str(list_f[ : : 2]) import random list_g = [random.randint(0, 10) for x in xrange(0, 10)] print "list_g = %s" % str(list_g) sorted(list_g) print "list_g = %s" % str(list_g) list_h = sorted(list_g) print "list_h = %s" % str(list_h) list_g.sort(reverse = True) print "list_g = %s" % str(list_g)
825ffa977a5878827f757ae398e0823c0a18f4c3
w7374520/Coursepy
/L07/prepareCouse/opp_1.py
531
3.921875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:xp #blog_url: http://blog.csdn.net/wuxingpu5/article/details/71209731 std1 = { 'name': 'Michael', 'score': 98 } std2 = { 'name': 'Bob', 'score': 81 } std3={'name':'xp','score':111} def print_score(std): print('%s %s'%(std['name'],std['score'])) class Student(object): def __init__(self,name,score): self.name=name self.score=score def print_score(self): print('%s %s'%(self.name,self.score)) bart = Student('Bart simpsom',59) bart.print_score()
dceb26252c863c29044f8e98b41bf08b47526aad
winnertree/idk-htd
/1st/main.py
16,147
3.71875
4
#**은 ^ #//은 몫 #true false 10>3 # abs() 는 절댓값 # pow(4,2) 는 4^2 #max(a,b) , min(a,b) # round(3.13) 반올림 # from math import * # print(floor(4.99)) #내림 # print(ceil(3.14)) # 올림 # print(sqrt(16)) #제곱근 # from random import * # print(random()) #0.0 ~ 1.0 사이의 임의의 값 생성 # print(random()*10) #0.0~10.0 # print(int(random()*10)) # # print(int(random()*45)+1) # print(int(random()*45)+1) # print(int(random()*45)+1) # print(int(random()*45)+1) # print(int(random()*45)+1) # print(int(random()*45)+1) # # print(randrange(1,46)) # 1~46 미만의 임의의 값 생성 # print(randint(1,45)) #월 4회 3번 온라인 1번은 오프라인 # from random import * # date = randint(4,28) # print("오프라인 스터디 모임 날짜는 매월", date, "일로 선정되었습니다.") # sentence = '이건 뭘까요?' # sentence2 = "이건 뭘까요?" # sentence3 = """이건 뭘까요? 알아맞춰 보세요""" # print(sentence + "\n" + sentence2+ "\n" + sentence3) #슬라이싱 # jumin = "980654-1234567" # print("성별 : " + jumin[7]) # print("연 : " + jumin[0:2]) #0부터 2직전까지 # print("월 : " + jumin[2:4]) # print("뒤 7자리 (뒤에서부터) : " + jumin[-7:]) #맨 뒤에서 7부터 끝까지 # python = "Python is Amazing" # print(python.lower()) # print(python.upper()) # print(python[0].isupper()) # print(len(python)) # print(python.replace("Python", "Java")) # print(python) # # index = python.index("n") # print(index) # index = python.index("n", index + 1) # print(index) # # print(python.find("Java")) # 없으면 -1출력하고 계속 코드 돌아감 # print(python.index("Java")) # 없으면 에러남 # # print(python.count("n")) #문자열 포멧 # print("나는 %d살입니다" %20) # print("나는 %s을 좋아해요" %"파이썬") # print("Apple 은 %c로 시작해요" %"A") # print("나는 %s색과 %s색을 좋아해요" %("파란", "빨간")) # print("나는 {}살입니다".format(20)) # print("나는 {}색과 {}색을 좋아해요" .format("파란", "빨간")) # print("나는 {0}색과 {1}색을 좋아해요" .format("파란", "빨간")) #print("나는 {age}살이며, {color}색을 좋아해요".format(age = 20, color="빨간")) # age = 20 # color = "빨강" # print(f"나는 {age}살이며, {color}색을 좋아해요") #탈출문자 # print("백문이 불여일견 \n백견이 불여일타") # # print('저는 "이것저것"입니다') # print("저는 \"이것저것\"입니다") # # print("\\") # # print("Red Apple\rPine") #Pine Apple # # print("Redd\bApple") #한글자 삭제(백스페이스) # # print("Red\tApple") #사이트별로 비밀번호 만들어주는 프로그램 # url = "http://google.com" # my_str = url.replace("http://", "") # my_str=my_str[:my_str.index(".")] # password = my_str[:3] + str(len(my_str)) +str(my_str.count("e")) + "!" # print("{} 의 비밀번호는 {} 입니다.".format(url,password)) #리스트 [] # subway = ["유재석","조세호","박명수"] # print(subway.index("박명수")) # # subway.append("하하") #맨뒤에 삽입 # print(subway) # # subway.insert(1,"정형돈") #중간에 삽입 # print(subway) # # print(subway.pop()) #뒤에서부터 뻄 # print(subway) # subway = ["유재석","조세호","박명수"] # subway.append("유재석") # print(subway) # print(subway.count("유재석")) #리스트 정렬 # num_list=[5,3,4,1,2] # num_list.sort() #정렬 # print(num_list) # # num_list.reverse() #뒤집기 # print(num_list) # # num_list.clear() # print(num_list) #다양한 자료형과 함께 사용 가능 # list=["조세호", 200 , True] # num_list=[5,3,4,1,2] # print(list) # # num_list.extend(list) # print(num_list) #사전 (key/value) # cabinet={3:"유재석", 100:"김태호"} #key = 3, value = 유재석 # print(cabinet[3]) # print(cabinet[100]) # print(cabinet.get(3)) # print(cabinet.get(5)) # print(cabinet[5]) # print(cabinet.get(5, "사용 가능")) # print(3 in cabinet) # print(5 in cabinet) # cabinet={"A-3":"유재석", "B-100":"김태호"} # print(cabinet["A-3"]) # print(cabinet["B-100"]) # # print(cabinet) # cabinet["C-20"] = "조세호" # print(cabinet) # # del cabinet["A-3"] # print(cabinet) # # print(cabinet.keys()) # # print(cabinet.values()) # # print(cabinet.items()) # # cabinet.clear() # print(cabinet) #리스트 [] // 사전 {:} // 튜플 () // 집합{} #튜플 // 변경되지 않는 값들들, 늘릴수없음 # menu=("돈까스", "치즈까스") # print(menu[0]) # print(menu[1]) # # name,age,hobby=("김종국",20,"코딩") # print(name,age,hobby) #집합 // 중복 안됨, 순서 없음 # my_set={1,2,3,3,3} # print(my_set) # # java={"A","B","C"} # python=set(["A","D"]) # # print(java&python) # 교집합 # print(java.intersection(python)) # 교집합 # # print(java | python) # print(java.union(python)) # 합집합 # # print(java-python) # print(java.difference(python)) # 차집합 # # python.add("B") # print(python) # # java.remove("B") # print(java) #자료구조의 변경 # menu={"커피", "우유", "주스"} # print(menu, type(menu)) # # menu=list(menu) # print(menu, type(menu)) #quiz # from random import * # a=range(1,21) # 1부터 20까지 숫자를 생성 // range타입 # a= list(a) # shuffle(a) # winners = sample(a, 4) # print("치킨 당첨자 : {0}".format(winners[0])) # print("커피 당첨자 : {0}".format(winners[1:])) #if # weather = input("오늘 날씨? ") # if weather == "비" or weather =="눈": # print("우산") # elif weather == "미세": # print("마스크") # else: # print("nothing") # temp = int(input("온도? ")) # if 30<= temp: # print("덥다") # elif 10<= temp: # print("good weather") # else: # print("cold") #for # for i in range(5): #0~4 # print("the number of waiting : {0}".format(i)) # for i in range(1,6): # 1~5 # print("the number of waiting : {0}".format(i)) # coffe = ["a","b","c"] # for i in coffe: # print("{0} ready!".format(i)) #while # customer="A" # index=5 # while index>=1: # print("{0}, ready!{1}left".format(customer, index)) # index-=1 # customer="A" # while True: # print("{0}, ready!left".format(customer)) # customer="A" # person = "unknown" # while person!=customer: # print("{0}, ready!left".format(customer)) # person = input("whats your name? ") #continue / break # absent = [2,5] # no_book=[7] # for student in range(1,11): # if student in absent: # continue #바로 다음 반복으로 # elif student in no_book: # print("you better run! {0} follow me".format(student)) # break #반복문 바로 탈출 # print("{0} read the book".format(student)) #한줄 for문 #출석번호 1,2,3,4 -> 앞에 100을 붙이기로함 ->101,102,103,104 # student =[1,2,3,4,5] # student = [i+100 for i in student] # print(student) # # #학생 이름을 길이로 변환 # student = ["apple", "banana", "coffee"] # student = [len(i) for i in student] # print(student) # # #학생 이름을 대문자로 변환 # student = ["apple", "banana", "coffee"] # student = [i.upper() for i in student] # print(student) #quiz # from random import * # cnt=0 # for i in range(5,51): # time = randint(1,50) # if(time>=5 and time <=15): # print("[0] {0}번째 손님 (소요시간 : {1}분)".format(i, time)) # cnt+=1 # else: # print("[] {0}번째 손님 (소요시간 : {1}분)".format(i, time)) # print("the sum of customers : {0}".format(cnt)) #함수 # def oepn_account(): # print("new account create") # # def deposit(balance, money): # print("입금 완료. 잔액 {0} 원".format(balance+money)) # return balance+money # # def withdraw(balance, money): # if(balance<money): # print("출금안되") # return balance # else: # print("잔액 {0}원 입니다".format(balance-money)) # return balance - money # # def withdraw_night(balance, money): # commission = 100 # return commission, balance-money-commission # balance=0 # balance = deposit(balance, 1000) # print(balance) # balance = withdraw(balance, 2000) # print(balance) # commission , balance = withdraw_night(balance, 500) # print("commission = {0}, balance = {1}".format(commission,balance)) #기본값 # def profile(name,age,main_lang): # print("name : {0}\tage : {1}\tlan : {2}".format(name,age,main_lang)) # profile("a",20,"A") # profile("b",25,"B") # def profile(name,age=17,main_lang="A"): # print("name : {0}\tage : {1}\tlan : {2}".format(name,age,main_lang)) # profile("A") # profile("B") #키워드값 # def profile(name,age,main_lang): # print(name,age,main_lang) # # profile(name = "A", main_lang="B", age=15) #순서 바껴도 상관없음 #가변인자 // *로 나타내는 인자 # def profile(name,age,lang1,lang2,lang3,lang4,lang5): # print("name : {0}\tage : {1}\t".format(name,age), end=" ")#end=" "쓰면 이어서 출력 # print(lang1,lang2,lang3,lang4,lang5) # # profile("A",20,"A","B","C","D","E") # profile("A",15,"A","B","C","","") # def profile(name,age,*lang): # print("name : {0}\tage : {1}\t".format(name,age), end=" ")#end=" "쓰면 이어서 출력 # for i in lang: # print(i, end=" ") # print() # profile("A",20,"A","B","C","D","E","F") # profile("A",15,"A","B","C") #지역변수와 전역변수 # gun = 10 # def checkpoint(soldiers): # global gun #전역 공간에 있는 gun 사용 # gun = gun - soldiers # print("the sum of guns : {0}".format(gun)) # checkpoint(2) # print("{}".format(gun)) #quiz # def std_weight(height, gender): # if gender == "man": # print("height {0}cm man's middle weight is {1}kg.".format(height,round((height*0.01)**2*22,2))) # else: # print("height {0}cm woman's middle weight is {1}kg.".format(height,(height*0.01)**2*21)) # std_weight(175, "man") #표준 입출력 # print("A","B","C", sep=" vs ") #sep로 사이에 뭐 넣을지 정함 # print("A"+"B") # print("A","B", sep=",", end="? ") #end로 문장의 끝부분을 정할수있음 # print("what is better?") # # import sys # print("A","B", file=sys.stdout) #표준 출력으로 처리 # print("A","B", file=sys.stderr) #표준 애러로 처리 # # score = {"A":0, "B":50, "C":100} #dictionary # for subject,scores in score.items(): # #print(subject, scores) # print(subject.ljust(8), str(scores).rjust(4), sep=":") #왼쪽으로 공백 8개 만들고 정렬 # # for num in range(1,21): # print("the num : "+str(num).zfill(3)) #3크기를 0으로 채워넣음 # answer = input("anything you want : ") #문자열로 입력받음 # print(type(answer)) # print(answer) # #다양한 출력포멧 # #빈자리는 빈공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보 # print("{0: >10}".format(500)) # #양수일 땐 + 음수일 땐 -로 표시 # print("{0: >+10}".format(500)) # #왼쪽 정렬하고, 빈칸으로 _로 채움 # print("{0:_<+10}".format(500)) # #3자리마다 콤마를 찍어주기 # print("{0:,}".format(5000000000)) # #3자리마다 콤마를 찍어주기 + 부호도 # print("{0:+,}".format(5000000000)) # #3자리마다 콤마를 찍어주기 + 부호도, 자리수도 확보, 빈 자리는 ^로 채우기, 왼쪽정렬 # print("{0:^<+30,}".format(5000000000)) # # #소수점 출력 # print("{0:f}".format(5/3)) # #소수점을 특정 자리수 까지만 표시 (소수점 3째 자리에서 반올림) # print("{0:.2f}".format(5/3)) #파일 입출력 # score_file=open("score.txt","w",encoding="utf8") #utf8로 한글 불러오는거 애러없이 # print("math : 0", file=score_file) # print("eng : 50", file=score_file) # score_file.close() # score_file=open("score.txt","a",encoding="utf8") #a는 파일 뒤에 계속 쓸때 # score_file.write("science : 80") # score_file.write("\ncoding : 100") # score_file.close() # score_file=open("score.txt", "r", encoding="utf8") #r로 읽기 w로 쓰기 # print(score_file.read()) # score_file.close() # score_file=open("score.txt", "r", encoding="utf8") # print(score_file.readline(), end="") # 줄별로 읽기, 한 줄 일고 커서는 다음 줄로 이동 # print(score_file.readline(), end="") # print(score_file.readline(), end="") # print(score_file.readline(), end="") # score_file.close() # score_file=open("score.txt", "r", encoding="utf8") # while True: #몇 줄인지 모를 때 # line = score_file.readline() # if not line: #읽어온 내용이 없으면 # break # print(line, end="") # score_file.close() # score_file=open("score.txt", "r", encoding="utf8") # lines = score_file.readlines() #list 형태로 저장 # for line in lines: # print(line,end="") # score_file.close() #pickle # import pickle # # profile_file = open("profile.pickle", "wb") #b는 바이너리고 피클쓸때 꼭 써야댐 # # profile = {"name":"A", "age":20, "hobby":["a","b","c"]} # # print(profile) # # pickle.dump(profile, profile_file) #profile에 있는 정보를 file에 저장 # # profile_file.close() # # profile_file = open("profile.pickle", "rb") # profile = pickle.load(profile_file) #file에 있는 정보를 profile에 불러오기 # print(profile) # profile_file.close() #with : 편하게 파일을 읽고 쓸 수 있음 close 필요 없음 # import pickle # # with open("profile.pickle","rb") as profile_file: # print(pickle.load(profile_file)) # # with open("study.txt", "w", encoding="utf8") as study_file: # study_file.write("studying python") # # with open("study.txt", "r", encoding="utf8") as study_file: # print(study_file.read()) #quiz # for i in range(1,51): # with open(str(i) + "주차.txt", "w", encoding="utf8") as report_file: # report_file.write("{0} 주차 주간보고 : ".format(i)) # report_file.write("\n부서 : ") # report_file.write("\nname : ") # report_file.write("\n요약 : ") #class ********* #마린 : 공격유닛, 군인, 총을 쏨 # name = "marin" # hp = 40 # damage = 5 # # #tank : 공격 유닛, 일반 모드 / 시즈 모드 # tank_name = "tank" # tank_hp = 150 # tank_damage = 30 # # def attack(name, location, damage): # print("{0} : {1} 방향으로 공격합니다. [공격력 {2}]".format(name,location,damage)) # # attack(name,"1시", damage) # attack(tank_name,"1시", tank_damage) # class Unit: # def __init__(self, name, hp, damage): # self.name=name # self.hp=hp # self.damage=damage # print("{0} unit create".format(self.name)) # print("hp {0}, damage {1}".format(self.hp,self.damage)) # # marine1 = Unit("marine",40,5) # marine2 = Unit("marine",40,5) # tank = Unit("tank",150,35) #맴버 변수 / 클래스 내에서 생성된 변수 # class Unit: # def __init__(self, name, hp, damage): # self.name=name # self.hp=hp # self.damage=damage # print("{0} unit create".format(self.name)) # print("hp {0}, damage {1}".format(self.hp,self.damage)) # # wraith1 = Unit("레이스", 80 ,5) # print("{0}, {1}".format(wraith1.name,wraith1.damage)) # # wraith2 = Unit("빼앗은 레이스",80,5) # wraith2.clocking = True #클래스 밖에서 변수를 만들어서 사용 가능 # # if wraith2.clocking==True: # print("{0} 는 현재 클로킹 상태입니다".format(wraith2.name)) #메소드 # class Unit: # def __init__(self, name, hp, damage): # self.name=name # self.hp=hp # self.damage=damage # print("{0} unit create".format(self.name)) # print("hp {0}, damage {1}".format(self.hp,self.damage)) # # class AttackUnit: # def __init__(self, name, hp, damage): # self.name=name # self.hp=hp # self.damage=damage # def attack(self, location): # print("{0} : {1}방향으로 공격 {2}damage".format(self.name, location, self.damage)) # # def damaged(self, damage): # print("{0} : {1} damaged".format(self.name,damage)) # self.hp-=damage # print("{0} : now hp {1}".format(self.name,self.hp)) # if self.hp<=0: # print("{0} destroyed".format(self.name)) # # firebat1 =AttackUnit("firebat", 50 ,16) # firebat1.attack("5시") # # firebat1.damaged(25) # firebat1.damaged(25)
0a3f15694a600dace6b6c71f5101d2d758883ee2
alexgarces98/Pythonprogramas
/extraEjercicios.py
1,951
4.25
4
#Escriba un subprograma en Python que determine si dos valores enteros dados son iguales o si su suma o diferencia es # 5 def igualdad_a_cinco(a,b): """int,int --> bool OBJ: Comprueba si dos enteros son iguales o suma o diferencia es 5""" import math return (a == b) or (abs(a-b) == 5) or (a+b == 5) #Programa que pide 5 mediciones de temperatura y un umbral y dice cuántas hay por encima de dicho umbral NUM_VALORES = 5 umbral = float(input('Introduzca el valor umbral de temperatura: ')) por_encima = 0 for i in range(NUM_VALORES): temp = float(input('Introduzca una medición de temperatura: ')) if temp > umbral: por_encima += 1 print('De las temperaturas dadas, ',por_encima, ' están sobre el umbral') #Escriba una función en Python que sume 3 números y retorne el resultado, excepto en el caso de que dos o más de ellos #sean iguales, en cuyo caso devolverá cero def igualdad_a_tres(a,b,c): """ float, float, float --> float OBJ: suma 3 números, si dos o más de ellos son iguales retorna cero """ if (a==b) or (a==c) or (b==c): return 0 else: return a+b+c #Escribir un programa que calcule el número de pares e impares de una serie de números que se introducen por teclado # (el usuario va introduciendo números hasta que con el centinela -999 indica que no quiere continuar) def es_par(n): """ int --> bool OBJ: Determina si un entero es par """ return n % 2 == 0 # Prueba CENTINELA = -1 print("Entre un número entero, para salir introduzca ", CENTINELA, ": ",end='') numero = int(input()) impares = 0 pares = 0 while (numero != CENTINELA): if es_par(numero): pares += 1 else: impares += 1 print("Entre un número entero, para salir introduzca ", CENTINELA, ": ",end='') numero = int(input()) if pares + impares > 0: print ("El número de pares encontrado es: " , pares) print ("El número de impares encontrado es: " , impares)
868d227a9d76640ca8745069de3c909a44adfa18
IBBD/IBBD.github.io
/machine-learning/yolov3-train-loss-show.py
1,430
3.609375
4
# -*- coding: utf-8 -*- # # yolov3训练误差可视化 # python3 machine-learning/yolov3-train-loss-show.py \ # --filename /tmp/yolov3-spp-loss.txt \ # --n 200 # Author: alex # Created Time: 2019年08月22日 星期四 10时32分44秒 import re import pandas as pd from matplotlib import pyplot as plt def read_data(filename): # 1: 3983.445801, 3983.445801 avg loss, 0.000000 rate, 8.518392 seconds, 128 images pattern = re.compile("^\\s*(\\d+):.*?, (.*?) avg loss") lines = None with open(filename) as r: lines = r.readlines() data = [pattern.findall(line)[0] for line in lines] data = [(int(row[0]), float(row[1])) for row in data] return pd.DataFrame(data, columns=['epoch', 'loss']) def show(filename, n=1): """ 可视化yolov3训练loss :param filename 文件名 :param n 设置若干个epoch的loss合并到一起,在相同区间内取最小值 """ df = read_data(filename) loss_min = min(df.loss) print("Loss最小值:", loss_min) print("对应epoch:", list(df.epoch[df.loss == loss_min])) epochs = max(df.epoch) y = [min(df.loss[(i*n < df.epoch) & (df.epoch <= (i+1)*n)]) for i in range(epochs//n)] plt.title("Yolov3 train loss") plt.xlabel("Epoch") plt.ylabel("loss") plt.plot([(i+1)*n for i in range(epochs//n)], y) plt.show() if __name__ == '__main__': import fire fire.Fire(show)
05829e05765d45d0933c8c894ee60d693e9b47a6
TauqeerAhmad5201/Python-OOPS
/args and kwargs1.py
214
3.75
4
def adder(*num): #a tuple is given otherwise converted but yes tuple sum = 0 for n in num: sum = sum + n print("Sum: ",sum) adder(5,7,4) adder(5,7,4,6.7) adder(5,7,4.5,76,34.454)
a477e6593d16e73218ce184e06c481bf6b7e2454
Shreyas018/launchpad-assignments
/practise5.py
151
3.9375
4
num1=int(input("enter the number a:-")) num2=int(input("enter the number b:-")) temp=int() temp=num1 num1=num2 num2=temp print(num1) print(num2)
2975fcbfee0a9d980d1420275c5527dd36b3e6fa
complicatedlee/About_algorithm
/dataStru.py
1,797
4.15625
4
#--coding:utf-8 #linked list class Node(object): """ node initialization A node consists of data and next pointer """ def __init__(self, data): self.data = data self.next = None class ListNode(object): def __init__(self): self.head = None def length(self): length = 0 p = self.head while p: length += 1 p = p.next return length def add(self, data): node = Node(data) if self.head is None: self.head = node else: p = self.head while p.next: p = p.next p.next = node def print_ListNode(self): if self.length() == 0: print("Empty ListNode") else: node = self.head while node: print(node.data) node = node.next #stack class stack(object): def __init__(self): self.top = None def isTop(self): if self.top == None: return None else: return self.top.data def push(self, item): node = Node(item) node.next = self.top self.top = node def pop(self): if self.isTop() == None: return None else: pdata = self.top.data self.top = self.top.next return pdata def print_stack(self): if self.isTop() == None: print("Empty Stack") else: while(self.isTop()): print(self.pop()) # if __name__ == '__main__': # L = ListNode() # for i in [1, 3, 8]: # L.add(i) # L.print_ListNode() # s = stack() # s.push(1) # s.push('23') # s.print_stack()
b0563726ef9de9e05d6c8c323e93de7b45281df3
osmarsalesjr/SolucoesUriOnlineJudgeEmPython3
/colecao_pokemon.py
1,321
3.53125
4
def main(): n = int(input()) jgs = ["pedra", "papel", "tesoura", "lagarto", "spock"] pls = ["rajesh", "sheldon"] for i in range(n): ps = [i for i in input().split()] if ps[0] == jgs[0] and (ps[1] == jgs[2] or ps[1] == jgs[3]): print(pls[0]) elif ps[1] == jgs[0] and (ps[0] == jgs[2] or ps[0] == jgs[3]): print(pls[1]) elif ps[0] == jgs[1] and (ps[1] == jgs[0] or ps[1] == jgs[4]): print(pls[0]) elif ps[1] == jgs[1] and (ps[0] == jgs[0] or ps[0] == jgs[4]): print(pls[1]) elif ps[0] == jgs[2] and (ps[1] == jgs[1] or ps[1] == jgs[3]): print(pls[0]) elif ps[1] == jgs[2] and (ps[0] == jgs[1] or ps[0] == jgs[3]): print(pls[1]) elif ps[0] == jgs[3] and (ps[1] == jgs[1] or ps[1] == jgs[4]): print(pls[0]) elif ps[1] == jgs[3] and (ps[0] == jgs[1] or ps[0] == jgs[4]): print(pls[1]) elif ps[0] == jgs[4] and (ps[1] == jgs[0] or ps[1] == jgs[2]): print(pls[0]) elif ps[1] == jgs[4] and (ps[0] == jgs[0] or ps[0] == jgs[2]): print(pls[1]) else: print("empate") if __name__ == "__main__": main()
19387eba9e667955c01c4fe19571af19b890c1d8
clowe88/Code_practicePy
/simple_cipher.py
277
4.15625
4
phrase = input("Enter a word or phrase to be encrypted: ") phrase_arr = [] finished_phrase = "" for i in phrase: phrase_arr.append(i) for x in phrase_arr: num = ord(x) cipher = chr(num + 12) finished_phrase += cipher print (finished_phrase)
ade4be28e983a3183c4bbfdece18411068a7ee1b
qbarrier/Python
/D01/ex02/groceries.py
252
3.765625
4
f = open("groceries.txt", "a") print("Qu'ajouter a la liste de course ?") add = input() f.write("%s\n" % add) add = "" while (add != "no") : print("Anything else ?") add = input() if (add != "no") : f.write("%s\n" % add) f.close()
d74d2263ce67e723a1fb073761932d4e5d01faf7
deepakmhr/tensorflow
/polynomial-regression/polynomial-regression.py
1,089
3.8125
4
# Multiple Linear Regression from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression import numpy as np import matplotlib.pyplot as plt import pandas as pd def show(): # Importing the datasets datasets = pd.read_csv('Position_Salaries.csv') X = datasets.iloc[:, 1:2].values Y = datasets.iloc[:, 2].values # Fitting Polynomial Regression to the dataset poly_reg = PolynomialFeatures(degree=4) X_Poly = poly_reg.fit_transform(X) lin_reg_2 = LinearRegression() lin_reg_2.fit(X_Poly, Y) # Visualising the Polynomial Regression results X_Grid = np.arange(min(X), max(X), 0.1) X_Grid = X_Grid.reshape((len(X_Grid), 1)) plt.scatter(X, Y, color='red') plt.plot(X_Grid, lin_reg_2.predict( poly_reg.fit_transform(X_Grid)), color='blue') plt.title('Polynomial Regression results') plt.xlabel('Position level') plt.ylabel('Salary') plt.show() # Predicting a new result with the Polynomial Regression lin_reg_2.predict(poly_reg.fit_transform(6.5)) show()
e937069f475e950ac24c371222f744555f81f1ac
owowww/python-
/0812/untitled2.py
459
4.125
4
# -*- coding: utf-8 -*- """ 請設計一個 function TRI(a,b,c),輸入三個邊長,此 function 可以判斷, 此三邊長能否組成三角形。三角形必要條件,最小兩邊加總大於第三邊。 """ def TRI(a,b,c): if (a + b) > c and (a + c) > b and (b + c) > a: print("可以") else: print("不可以") return a=int(input("輸入a:")) b=int(input("輸入b:")) c=int(input("輸入c:")) TRI(a,b,c)
5eec022b393680405e7d153729ff668715d1fa4e
agrawalalisha/CS1110-Python
/programming assignments/dating.py
377
4.09375
4
# Alisha Agrawal (aa3se) """ This program prompts the user for their age and returns the age range for people they can date according to an old folk rule. """ # ask the user for their age age = input("How old are you? ") age = int(age) # print the age range of people they can date min = int(age/2)+7 max = age*2-13 print("You can date people between", min, "and", max, "years old")
d55c62253b3bb47e5e1b7f993958bc324db2d616
AbdullahAlsalihi/python-projects
/student_test_score.py
843
4.46875
4
# student grades_average # this program will ask the user to enter the number of students and # how many test scores each one gets according to specific number of test # the user will enter both (student numbers and test scores) the program # then will dispaly the average score for each specific student according # to their test scores. students = int(input('Please enter how many students: ')) test_score = int(input('how many test for each one: ')) for student in range(students): print('student num ', student + 1, ' : ') print('==============') total = 0 for num_score in range(test_score): print('score num ', num_score + 1, end= " ") score = float(input(' : ')) total += score average = total / test_score print('student number ', student + 1 , ' : ', average , ' average score.')
2da9dee5892a19ef9d81f6de799056522625a3a5
voxoblivion/Code_Wars
/List Filtering.py
350
3.515625
4
# https://www.codewars.com/kata/list-filtering/train/javascript def filter_list(l): e = [] for i in l: if isinstance(i, str): e.append(i) [l.pop(l.index(i)) for i in e] return l def filter_list_V2(l): return [i for i in l if not isinstance(i, str)] print(filter_list([1,2,'a','b']))
bde5d3c4a9c4f10f33f419f2971fd9cf3767bad4
teaganryley/leetcode
/src/helpers/trie_node.py
1,264
3.96875
4
class TrieNode(): """ Simple prefix tree (trie) implementation. """ def __init__(self, value: str): self.value = value self.children = [] #gives multiplicity of current character self.counter = 1 def insert(root, word: str): """ Maps word to trie structure. """ current = root for char in word: found_in_child = False for child in current.children: if child.value == char: child.counter += 1 current = child found_in_child = True break if not found_in_child: new_node = TrieNode(char) current.children.append(new_node) current = new_node def find_lcp(root, list_length: int): """ Locates the longest common prefix in a trie. """ lcp = "" current = root common_char_exists = True while common_char_exists: common_char_exists = False for child in current.children: if child.counter == list_length: lcp += child.value current = child common_char_exists = True break return lcp
18add43db8abfd228f95bd0fa10a47d9f03cf24a
angersa/bitesofpy
/71/record.py
328
3.75
4
class RecordScore(): """Class to track a game's maximum score""" def __init__(self): self._score = float('-inf') def __call__(self, score): self._score = max(self._score, score) return self._score record = RecordScore() print(record(10)) print(record(3)) print(record(12))
7bd5f320620cf9b2c94b8b9708b121cd2b643886
Tenzin-sama/LabExercisesPYTHON
/Lab Exercises/Lab Exercise 2/q6.py
176
4.125
4
# Lab Exercise 2, Question 6 """Given an integer number, print its last digit""" num = input("Enter a number: ") print(f"The last digit is {num[-1]}") print() input()
610bd09a565d77007ec81ad77e922b119b1bd251
L0ST-bit/Programming
/Practice/07/Python/module7.py
1,475
3.640625
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: User # # Created: 28.10.2020 # Copyright: (c) User 2020 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if __name__ == '__main__': main() import math print("Чтобы считать через стороны треугольника введите: 1\nЧтобы считать через координпты вершин введите: 2\n"); k = int (input()) if (k == 1): print("Введите стороны треугольника:") a, b, c = map(float, input().split()) p = float; p = (a+b+c)/2 if (a < 0 or b < 0 or c < 0): print("Длинна не может быть отрицательной") elif ((a + b) < c or (a + c) < b or (c + b) < a): print("Такого треугольника не существует") else: print("S = " , math.sqrt(p * (p - a) * (p - b) * (p - c))); if(k==2): print("Введите координаты:\n") x1, y1 = map(float, input().split()) x2, y2 = map(float, input().split()) x3, y3 = map(float, input().split()) if(((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) == 0): print("Треугольник вырожденный") print("S = " , (math.fabs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1))/2));
e06c8dc685efe8ac8878f2a5b54ee456edb9c882
phu-n-tran/LeetCode
/monthlyChallenge/2020-06(juneChallenge)/6_28_ReconstructItinerary.py
3,742
4.3125
4
# -------------------------------------------------------------------------- # Name: Reconstruct Itinerary # Author(s): Phu Tran # -------------------------------------------------------------------------- """ Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK. Note: 1. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. 2. All airports are represented by three capital letters (IATA code). 3. You may assume all tickets form at least one valid itinerary. 4. One must use all the tickets once and only once. Example 1: Input: [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]] Output: ["JFK", "MUC", "LHR", "SFO", "SJC"] Example 2: Input: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] Output: ["JFK","ATL","JFK","SFO","ATL","SFO"] Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order. """ class Solution(object): def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ def dfs(cur_airport, adjList, path): while adjList.get(cur_airport, []): # remove the last element since it is sort in descending and it is to ensure the result contains the smallest lexical order next_des = adjList[cur_airport].pop() dfs(next_des, adjList, path) path.append(cur_airport) adjList = dict() path = [] for src, des in tickets: adjList[src] = adjList.get(src, []) + [des] # sort by descending order, since the last des is recorded first for key in adjList: adjList[key].sort(reverse=True) dfs("JFK", adjList, path) # reverse the list return path[::-1] '''other faster methods (from other submissions) ################################################## def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ from collections import defaultdict d = defaultdict(list) for i in sorted(tickets): d[i[0]].append(i[1]) res = [] def dfs(airport): while(d[airport]): v = d[airport].pop(0) dfs(v) res.append(v) dfs('JFK') res.append('JFK') print(res) return res[::-1] ################################################## def findItinerary(self, tickets): """ :type tickets: List[List[str]] :rtype: List[str] """ airports={} for dep,arr in tickets: if dep not in airports: airports[dep]=[arr] else: heappush(airports[dep],arr) if arr not in airports: airports[arr]=[] return self.dfs(airports,"JFK",[])[::-1] def dfs(self,airports,departure,res): while airports[departure]: self.dfs(airports,heappop(airports[departure]),res) res.append(departure) return res '''
b2c3b693eaf2309308e09023310690e27306cfbd
mjrich/trimming-twitter-friends
/trimming-twitter-friends.py
3,569
3.765625
4
# coding: utf-8 # In[1]: print("Hello World") # In[7]: import tweepy import pandas as pd #Then create new twitter app: https://apps.twitter.com/ #Then set up Oauth below (filling in the empty double quotes) # In[5]: # == OAuth Authentication == # # This mode of authentication is the new preferred way # of authenticating with Twitter. # Source: https://github.com/tweepy/tweepy/blob/master/examples/oauth.py # The consumer keys can be found on your application's Details # page located at https://dev.twitter.com/apps (under "OAuth settings") consumer_key="" consumer_secret="" # The access tokens can be found on your applications's Details # page located at https://dev.twitter.com/apps (located # under "Your access token") access_token="" access_token_secret="" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.secure = True auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) # If the authentication was successful, you should # see the name of the account print out print(api.me().name) # In[6]: #If you set up to write as well as read, you can send this message api.update_status(status='This tweet just came from my local Jupyter notebook. Thanks project Jupyter and Tweepy for the helpful docs!') # In[17]: #put your twitter handle below instead of mine to get list of who you follow friend_ids_all = api.friends_ids("richmanmax") len(friend_ids_all) # In[104]: #put your twitter handle below instead of mine to get list of who follows you followers_ids_all = api.followers_ids("richmanmax") len(followers_ids_all) # In[72]: #choose how many friends (people who follow you) you want to analyze #note: in the next section you will hit rate limit of 180 calls #so pick a number under 180 or be prepared to wait friend_ids_some = friend_ids_all[0:10] friend_ids_some # In[78]: #check how many user API calls we have left api.rate_limit_status()['resources']['users'] # In[79]: user_json = [] for i in friend_ids_some: user_json += [api.get_user(i).__getstate__()['_json']] len(user_json) # In[80]: #check how many user API calls we have left api.rate_limit_status()['resources']['users'] # In[81]: user_json # In[111]: from pandas.io.json import json_normalize df_user_data = json_normalize(user_json) df_user_data # In[112]: df_user_data.columns # In[113]: #example frequency of a variable df_user_data['time_zone'].value_counts(dropna=False) # In[120]: #merge in information if they follow you followback = [] for x in range(len(followers_ids_all)): followback.append("TRUE") user_data_followback = zip(followers_ids_all,followback) df_user_data_followback = pd.DataFrame(user_data_followback) df_user_data_followback.columns = ["id","follow_back"] df_user_data_followback df_user_data_merge = pd.DataFrame.merge(df_user_data,df_user_data_followback, how='left', on='id') df_user_data_merge # In[126]: #simplify data frame to just the key variables of interest #then sort by those following with most tweets and fewest followers (likely for me to still follow) df_user_simple = df_user_data_merge[['id','name','screen_name','follow_back','statuses_count','followers_count','friends_count']] df_user_simple.sort_values(["follow_back","statuses_count","followers_count"],ascending=[False,False,True]) # In[127]: #DANGER WILL ROBINSON: This is the write command that will unfollow people #it is appropriately called "destroy friendship" so use with care. #designed currently for using one ID from above at a time for ##### api.destroy_friendship(######) # In[ ]:
c4c76b35c9a7d30035483e93d76c5ab78d2a6014
madeibao/PythonAlgorithm
/PartA/PyMap与Lambda匿名函数相互的结合.py
1,251
4.5
4
map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence). function 为None 的情况 map(None, [1,2,3]) #[1, 2, 3] map(None, [1,2,3], [4,5,6]) #[(1, 4), (2, 5), (3, 6)] map(None, [1,2,3], [4,5]) #[(1, 4), (2, 5), (3, None)] 考虑function为lambda表达式的情形。 此时lambda表达式:的左边的参数的个数与map函数sequence的个数相等, :右边的表达式是左边一个或者多个参数的函数。 map(lambda x: x+1, [1,2,3]) #[2, 3, 4] map(lambda x, y:x+y, [1,2,3], [4,5,6]) #[5, 7, 9] map(lambda x, y:x == y, [1,2,3], [4,5,6]) #[False, False, False] def f(x): return True if x==1 else Fasle map(lambda x: f(x), [1,2,3]) #[True, False, False] 当lambda 为外部定义的函数的时候 def f(x): return True if x==1 else Fasle map(f, [1,2,3]) #[True, False, False]
c7502e4c07ab0af9e83033636ddacc4441e389a0
LorenzoVaralo/ExerciciosCursoEmVideo
/Mundo 2/Ex041.py
735
3.875
4
# a confederação Nacional de natação precisa de um programa q leia o ano ne nascimento de um atleta e mostre sua categoria, de acordo com a idade: # Até 9 anos: MIRIM # Ate 14 anos: INFANTIL # Ate 19 anos: JUNIOR # Ate 20 anos : SENIOR # ACIMA: MASTER from datetime import date presente = date.today().year nasc = int(input('Digite o ano de nascença do aluno: ')) idade = presente - nasc if idade <= 9: modalidade = 'MIRIM' elif idade <= 14: modalidade = 'INFANTIL' elif idade <= 19: modalidade = 'JUNIOR' elif idade <= 20: modalidade = 'SENIOR' else: modalidade = 'MASTER' print('O aluno nascido em {}, com {} anos, pertencerá a modalidade {}.'.format(nasc, idade, modalidade))
94a18874d8273858644f6b4366e7a4f6a52678c7
alvinrach/28-Linear-Regression-From-Scratch
/Single-Variable Demo of LinearRegression Imitation .py
2,654
3.84375
4
#!/usr/bin/env python # coding: utf-8 # **Here is the demo for the imitation model of the scikit-learn's LinearRegression** # **This notebook presents you single-variable linear regression** # In[1]: from LinearReg import LinReg # In[2]: help(LinReg) # In[3]: import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, mean_absolute_error # In[4]: # Load the diabetes dataset diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True) # Use only one feature diabetes_X = diabetes_X[:, np.newaxis, 2] # In[5]: # Split the data into training/testing sets diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] # Split the targets into training/testing sets diabetes_y_train = diabetes_y[:-20] diabetes_y_test = diabetes_y[-20:] # In[6]: ## Comparation of built model and sklearn's LinearRegression model # Create linear regression object regr = linear_model.LinearRegression() myReg = LinReg(lr=1.9, percent_diff=0.000001) # Train the model using the training sets regr.fit(diabetes_X_train, diabetes_y_train) myReg.fit(diabetes_X_train, diabetes_y_train) # Make predictions using the testing set diabetes_y_pred = regr.predict(diabetes_X_test) diabetes_y_pred # In[7]: my_pred = myReg.predict(diabetes_X_test) my_pred.flatten() # In[8]: # The coefficients print('Coefficients: ', regr.coef_) print('Built Module Coefficients: ', myReg.coefs) # In[9]: #The intercept print('Intercept: ', regr.intercept_) print('Built Module Intercept: ', myReg.const) # In[10]: # The mean squared error print('Mean squared error: %.2f' % mean_squared_error(diabetes_y_test, diabetes_y_pred)) print('Built Module Mean squared error: %.2f' % myReg.rmse(diabetes_y_test, my_pred.flatten(), unroot=True)) # In[11]: # The mean absolute error print('Mean absolute error: %.2f' % mean_absolute_error(diabetes_y_test, diabetes_y_pred)) print('Built Module Mean absolute error: %.2f' % myReg.mae(diabetes_y_test, my_pred.flatten())) # In[12]: # Plot outputs plt.scatter(diabetes_X_test, diabetes_y_test, color='black') plt.plot(diabetes_X_test, diabetes_y_pred, color='r', linewidth=3) plt.show() # In[13]: # Built module plot plt.scatter(diabetes_X_test, diabetes_y_test, color='black') plt.plot(diabetes_X_test, my_pred, color='b', linewidth=3) plt.show() # In[14]: fig = plt.figure(figsize=(15,4)) plt.plot([i for i in range(len(myReg.losses))], myReg.losses, 'b-') plt.xlabel('Epoch/Iterations') plt.ylabel('Cost Value') # In[15]: # Print epochs/iteration has done myReg.epochs
b9ca311e7752045e33d31ce55d51bb91d88aaa01
burakhanaksoy/PythonOOP
/corey_schafer/dictionaries.py
208
3.96875
4
# key : value pairs student = {'name': 'Burak', 'age': 25, 'course': ['Math', 'CS']} for k in student: print(f"{k}:{student.get(k)}") print(student.keys()) print(student.values()) print(student.items())
1508486b8b2044f997ced5c58278dbdea2ec952c
SudoBobo/data_structures
/multi_thread.py
1,170
3.53125
4
from queue import PriorityQueue procN, taskN = map(int, input().split(' ')) tasks_times = [int(task_time) for task_time in input().split(' ')] # to store processing tasks in format [time_when_proccessing_ends, proc_idx] pq = PriorityQueue() # to store answer in format [proc_idx, time_when_proccessing_started] proc_log = [] curr_time = 0 # handle border cases if procN == 1: for task_idx in range(taskN): print(0, curr_time) curr_time = curr_time + tasks_times[task_idx] elif procN >= taskN: for task_idx in range(taskN): print(task_idx, 0) else: # fill queue with first m tasks for proc_idx in range(procN): pq.put([curr_time + tasks_times[proc_idx], proc_idx]) proc_log.append([proc_idx, curr_time]) for task_idx in range(procN, taskN): # extract finished task and process number it's been handled. Change time free_proc = pq.get() curr_time = free_proc[0] # log proc_log.append([free_proc[1], curr_time]) # add new task free_proc[0] = curr_time + tasks_times[task_idx] pq.put(free_proc) for elem in proc_log: print(*elem)
f20083301ebb7c64a6eaa53400cc8126291568ef
gmavrova/python-retrospective
/task3/solution.py
1,056
3.609375
4
class Person: def __init__(self, name, birth_year, gender, mother=None, father=None): self.name = name self.birth_year = birth_year self.gender = gender self.mother = mother self.father = father self.list_of_children = [] for parent in [self.father, self.mother]: if parent: parent.list_of_children.append(self) def children(self, gender=None): if gender: return list(filter(lambda child: child.gender == gender, self.list_of_children)) else: return self.list_of_children def get_siblings(self, gender): siblings = set(self.mother.children(gender) + self.father.children(gender)) return list(siblings - {self}) def get_brothers(self): return self.get_siblings('M') def get_sisters(self): return self.get_siblings('F') def is_direct_successor(self, other_person): return other_person in self.list_of_children
201820abfdd248c92ce999875e03b243d4e2870c
ersanirem/gaih-students-repo-example
/Homeworks/HW1.py
5,393
3.59375
4
#Question 1; How would you define Machine Learning The system learns its past experiences with the model it has developed using its data. Ability to use this knowledge on new data without the need for reprogramming for future tasks. #Question 2; What are the differences between Supervised and Unsupervised Learning? Specify example 3 algorithms for each of these. Supervised Learnig is a approach that here the program is given labeled input data and the expected output results.But in unsupervised learning, we have unlabeled training data. For example; 1- Image classification. We can use supervised learning to check if it is a dog or a cat in the picture. 2- Predicting next year's sales volume 3- Checking an email if it is spam or not spam For unsupervised learning examples; 1-Clustering DNA patterns to analyze evolutionary biology. 2-Recommender systems - giving better Amazon purchase suggestions or Netflix movie matches 3-Medical imaging - for distinguishing between different kinds of tissues #Question 3; What are the test and validation set, and why would you want to use them? – Training set: A set of examples used for learning, that is to fit the parameters of the classifier. – Validation set: A set of examples used to tune the parameters of a classifier, for example to choose the number of hidden units in a neural network. It is usually used for parameter selection and to avoid overfitting – Test set: The sample of data used to provide an unbiased evaluation of a final model fit on the training dataset. In order to reach a good and effective algorithm, to make accurate and true predictions we should use validation and test test. Because we can avoid overfitting with use of validation test.And with test set we can see the accuracy of our model and see how good it works. #Question 4; What are the main preprocessing steps? Explain them in detail. Why we need to prepare our data? #Why we need to prepare our data? In Data preparation, we load our data into a suitable place and prepare it for use in our machine learning training. It is important because we can see if there are any relevant relationships between different variables you can take advantage of, as well as if there are any data imbalances. It is essential to identify these outliers, duplicated values etc. Because it will affect our algorithm in a negative way. #What are the main preprocessing steps? 1. Acquire the dataset; To build and develop Machine Learning models, we must first acquire the relevant dataset. This dataset will be comprised of data gathered from multiple and disparate sources which are then combined in a proper format to form a dataset. 2. Import all the crucial libraries; like NumPy, MatPlobLib, Pandas. These are very beneficial for importing, managing datasets. 3. Import the dataset; In this step, we need to import the dataset/s that we have gathered for the ML project at hand 4. Identifying and handling the missing values; We can eleminate missing values or fill them with mean or median. If we dont handle missing values, we can get inaccurate values. 5. Encoding the categorical data; Categorical data refers to the information that has specific categories within the dataset. Machine Learning models are primarily based on mathematical equations. Thus, we can intuitively understand that keeping the categorical data in the equation will cause certain issues since we would only need numbers in the equations. 6. Splitting the dataset; Every dataset for Machine Learning model must be split into two separate sets – training set and test set. Usually, the dataset is split into 70:30 ratio or 80:20 ratio. 7. Feature scaling; Feature scaling marks the end of the data preprocessing in Machine Learning. It is a method to standardize the independent variables of a dataset within a specific range. In other words, feature scaling limits the range of variables so that we can compare them on common grounds. We can perform feature scaling in Machine Learning in two ways; Standardization and Normalization. #Question 5;How you can explore and analyse countionus and discrete variables? Discrete data involves round, concrete numbers that are determined by counting. Continuous data involves complex numbers that are measured across a specific time interval. A simple way to describe the difference between the two is to visualize a scatter plot graph vs. a line graph. We can explore and analyse them by drawing a scatter plot and line graph. We can see more clearly by visualizing. #Question 6; Analyse the plot given below. (What is the plot and variable type, check the distribution and make comment about how you can preproccess it.) This is a MatPlobLib histogram. Continuous variable. We use histogram to analyse continuous variable. If the graph is approximately bell-shaped and symmetric about the mean, we can usually assume normality. But we dont see this shape, so it is not normal distribution. Our ditribution is really asymmetric. It is not also right skewed right or left. We can say it has a random distribution.It has no apparent pattern. We can check if there is a outlier around 0-1 petal width. Because there is a anormal value compared to others.
78e0dfe569c21db022dc4a3d9178edfdccc2c2ff
zhyErick/fengkuang_python
/11/11.2/extend_frame.py
1,168
3.578125
4
from tkinter import * # 定义继承Frame的Application类 class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() # 调用initWidgets()方法初始化界面 self.initWidgets() def initWidgets(self): # 创建label对象,第一个参数只当将改Label放入root内 w = Label(self) # 创建一个位图 bm = PhotoImage(file='images/serial.png') # 必须用一个不会被释放的变量引用该图片,否则图片会被收回 w.x = bm # 设置显示的图片是bm w['image'] = bm w.pack() # 创建button对象,第一个参数指定将该Button放入root内 okButton = Button(self, text="确定") okButton['background'] = "yellow" #okButton.configure(background='yellow') # 与上面代码的作用相同 okButton.pack() # 创建app对象 app = Application() # Frame有一个默认的master属性,该属性值是Tk对象(窗口) print(type(app.master)) # 通过master属性来设置窗口标题 app.master.title('窗口标题') # 启动主窗口消息循环 app.mainloop()
efb0e2d6ebac141d0aa0abcc467cf8e4d538b13f
mgbo/My_Exercise
/2018/My_students/6_объект_класс/0_primel.py
667
3.71875
4
import random greetings = ["'How can I help you?'", "'...'", "'Next!'"] MOODS = ('bad', 'average', 'good') RANKS = ('low', 'medium', 'high') class Bureaucrat: '''A government employee who works in the Institution.''' def __init__(self): self.rank = random.choice(RANKS) self.mood = random.choice(MOODS) def greet(self): '''A random greeting from the government employee.''' print(random.choice(greetings)) print('The bureaucrat is of a {} rank.'.format(self.rank)) # bureaucrat.rank print("The bureaucrat's mood seems to be {}.".format(bureaucrat.mood)) bureaucrat = Bureaucrat() bureaucrat.greet()
09a421f964258ff2723339369e20fe3e17426a2b
Trsak/Python-sorting-algorithms
/insertion_sort.py
464
4.125
4
def insertion_sort(numbers_list): list_length = len(numbers_list) for i in range(0, list_length - 1): j = i + 1 temp = numbers_list[j] while j > 0 and temp < numbers_list[j - 1]: numbers_list[j] = numbers_list[j - 1] j -= 1 numbers_list[j] = temp return numbers_list if __name__ == "__main__": print(insertion_sort([10, 58, 12, 0, 55, 57, 88, 11, 5, 56, 2, 18, 22, -51, -20, 574, -154]))
76d4153ccf165a8934586156038f239e72204b3a
TianhaoFu/Web-crawler
/初步接触汇总/匹配电子邮件地址.py
290
3.515625
4
inport re pattern = "\w+([.+-]\w+)*@\w+([.-]\w+)*\.\w+([.-]\w+)" #字母,任意的字符 字母 出现多次 @ 字母 任意的字符 字母出现多次 任意字符 出现多次 任意的字符字母出现多次 string = "fdewfewfewfe" result = re.research(pattern.string) print(result)
30c5c90f5d9b24263c1fc6ffa82a7446f72ef5cf
entirelymagic/Link_Academy
/fundamentals/ppf-ex07/knight.py
333
3.625
4
start = [-1, -1] # Your code here letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] for y in range(8): print(y + 1, end=" ") for x in range(8): chr = "O" if [x + 1, y + 1] == start: chr = "S" print(chr, end="") print() print(end=" ") for l in letters: print(l, end="") print()
6091da469453c2708499a6b356d3a5baac7bb94b
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4501/codes/1764_2390.py
290
3.65625
4
from numpy import * pre = array(eval(input("Digite o numero de presentes a cada mes: "))) falt = array(eval(input("Digite o numero de faltantes a cada mes: "))) freq = pre - falt mes = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) i = 0 while(freq[i] != max(freq)): i = i+1 print(mes[i])
bb26aa1621d711740cf122cb76ef64ee0fed52d6
dvolk20/PythonScripts
/webscraping.py
590
3.578125
4
import requests import csv from bs4 import BeautifulSoup url = "http://dataquestio.github.io/web-scraping-pages/ids_and_classes.html" page = requests.get(url) #print(page) #this will print the status page_html = page.content #gets all of the page html soup = BeautifulSoup(page_html, 'html.parser') a = soup.prettify() #this is the 'pretty' version of the html b = soup.find_all('p') #this finds all items in the p tag c = soup.find_all(class_="outer-text") #finds based on class d = soup.find_all(id="first") #finds based on id for item in b: print(item.get_text()) #print(b)
97ef49d9f5491ccd94c320a8ef7628fb73ce74dd
theTrio11/python-docs
/const.py
254
3.65625
4
class emp: c=0 def _init_(s,name,role,salary): s.name=name s.role=role s.salary=salary emp.c+=1 def display(s): print("%s,%s,%d"%(s.name,s.role,s.salary)) e1=emp("naman","ceo",99999999999) e1.display()
535d0a2152703b96697441dc5651cde5f97dc2c8
HITOfficial/College
/ASD/Sorts/selection_sort_linked_list.py
1,865
4.15625
4
# insertion sort algorithm on linked list # complexity: # - time O(n^2) # - space O(1) class Node(): def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def array_to_linded_list(array): n = len(array) # condition if array is not empty if n == 0: return None else: head = Node(array[0]) p = head for i in range(1, n): actual = Node(array[i]) p.next_node = actual p = actual return head def print_linked_list(node): while node is not None: print(node.value, end="->") node = node.next_node def selection_sort_linked_list(head): sentinel = Node() # sorted linked list p = sentinel q = head pivot = q while q is not None: s_prev, s = q, q.next_node prev_pivot, pivot = Node(), q while s is not None: if s.value < pivot.value: prev_pivot, pivot = s_prev, s s_prev, s = s, s.next_node # node with lowest value is a first element in linked list if prev_pivot.value is None: q = pivot.next_node p.next_node = pivot pivot.next_node = None # lowest value node is not a first node in linked list to sort else: prev_pivot.next_node = pivot.next_node p.next_node = pivot pivot.next_node = None # moving to tail in sorted linked list p = p.next_node # taking off sentinel head = sentinel.next_node # taking off sentinel and returning head of sorted linked list return head array = [9, 1, 8, 7, 5, 3, 4, 5, 17, 2] node = array_to_linded_list(array) print_linked_list(selection_sort_linked_list(node))
94750a543d63cfb04eacda77860c5a8bdcd348ef
amandakwong898/cs110-project1
/day_of_week.py
474
3.546875
4
import stdio import sys # Get m month (int) from the command line. m = int(sys.argv[1]) # Get d day (int) from the command line. d = int(sys.argv[2]) # Get y year (int) from the command line. y = int(sys.argv[3]) # Calculate and write the value of day of the week D. y0 = y - (14 - m) // 12 x0 = y0 + y0 // 4 - y0 // 100 + y0 // 400 m0 = m + 12 * ((14 - m) // 12) - 2 d = (d + x0 + 31 * m0 // 12) % 7 # Use // (floored division) for / and % for mod. stdio.writeln(d)
c63f0953dae6ba734cad29397ca20d61f45c9904
astefano/project-Euler_leetCode_acm
/longestPref.py
818
3.6875
4
class Solution: # @return a string def longestCommonPrefix(self, strs): ns = len(strs) if ns == 0: return "" lens = [len(s) for s in strs] minl = min(lens) if minl == 0: return "" i = 0 last = strs[0][0] pref = "" print minl while i < minl and strs[0][i] == last: print ("i = %i last = %s"%(i,last)) for j in range(1, ns): if strs[j][i] != last: return pref pref += last i += 1 if (i < minl): last = strs[0][i] else: return pref return pref s = Solution() #strs = ["abab","aba","abc"] strs = ["a"] print s.longestCommonPrefix(strs)
298db5630651e8655526f54053928ea67472aa5f
prbh695a/MyPrograms
/Practice/DataStructure/Queue/Circular.py
967
3.765625
4
class Circular: def __init__(self): self.items=[None]* 10 self.count=0 self.front=0 def add(self,value): position=(self.front+self.count)%10 self.items[position]=value self.count=self.count+1 def delete(self): temp=self.items[self.front] self.items[self.front]=None self.front=(self.front+1)%10 self.count=self.count-1 return temp def displayQueue(self): print(self.items) q=Circular() q.add(1) q.add(2) q.add(3) q.add(4) q.add(5) q.add(6) q.add(7) q.add(8) q.add(9) q.add(10) print("The queue is") q.displayQueue() print("After deleting",q.delete()) q.displayQueue() print("After deleting",q.delete()) q.displayQueue() print("After deleting",q.delete()) q.displayQueue() print("After deleting",q.delete()) q.displayQueue() print("After deleting",q.delete()) q.displayQueue() q.add(1) q.add(2) q.add(3) q.add(4) print("The queue is") q.displayQueue()
921b9835212ae29b00ba5b92b7b674cbcf23e770
pulkitmathur10/FSBC2019
/Day 01/string.py
117
3.828125
4
#String Handling str1 = input("Enter the input string") list1 = str1.split() print(list1[1] + " " + list1[0])
cb41a985cedae18cad136aeff8152716a9c52413
ClaytonStudent/leetcode-
/OfferPython/15_bit.py
742
4.0625
4
# 题目:二进制中1的个数 # 原来Python2的int类型有32位和64位一说,但到了Python3,当长度超过32位或64位之后,Python3会自动将其转为长整型,长整型理论上没有长度限制。 def bit_calculate(n): count = 0 while n & 0xffffffff != 0: # 需要注意处理负数 count += 1 n = (n-1) & n # 减去1,再与本身做与操作,就可以去掉最右边的1 return count def bit_(n): if n < 0: n = n & 0xffffffff # 对于负数,将最高位的符号位取反就可以获得补码,通常我们采用和0x7FFFFFFF相与来得到。 count = 0 while n: count += 1 n = (n-1) & n return count print(bit_calculate(3)) print(bit_(1))
1f11ef4f3b71c5ed4251cdf815da21e759e4bf29
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/lnsjoh002/mymath.py
553
3.890625
4
# calculate number of k-permutations of n items # bhavana harrilal # 10 april 2014 def get_integer (x): print("Enter", x, end="") print(":") n=input() while not n.isdigit (): print("Enter", x, end="") print(":") n=input() n = eval (n) return n def calc_factorial (n): fact = 1 for i in range(2,n+1): fact*= i return fact def calc_factorial (z): fact=1 for i in range(2, (z) +1): fact *=i return fact
2c7eb657eb6f3732e87cc8a10b49f69528dccf3d
abhisheksahu92/Programming
/Solutions/31-Smallest subarray with sum greater than x.py
1,216
4
4
# Smallest subarray with sum greater than x # Given an array of integers (A[]) and a number x, find the smallest subarray with sum greater than the given value. # Note: The answer always exists. It is guaranteed that x doesn't exceed the summation of a[i] (from 1 to N). # Example 1: # Input: # A[] = {1, 4, 45, 6, 0, 19} # x = 51 # Output: 3 # Explanation: # Minimum length subarray is # {4, 45, 6} def smallestSubarray(nums,element): d = {} print(nums,element) x,y = 0,0 while True: if x < len(nums): if y < len(nums): sum1 = sum(nums[x:y+1]) if sum1 > element: if sum1 not in d: d[sum1] = nums[x:y+1] else: if len(d[sum1]) > len(nums[x:y+1]): d[sum1] = nums[x:y+1] y = y + 1 else: x = x + 1 y = x else: break print(d[sorted(d)[0]]) if __name__ == '__main__': li = [[[1, 4, 45, 6, 0, 19],51],[[1, 10, 5, 2, 7],9]] for input in li: print(f'Input is {input[0]} and element is {input[1]}') smallestSubarray(*input)
122ba4bab71017dd0fd32625e4a7d14ae088d63b
yosho-18/LeetCode
/Basic_60/Group_Anagrams.py
658
3.5625
4
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: two_strs = [[] for _ in range(len(strs))] for two_part, part in zip(two_strs, strs): two_part.append(part) sort_part = sorted(part) two_part.append(sort_part) two_strs = sorted(two_strs, key=lambda x: x[1]) anagram = two_strs[0][1] ans = [[]] for origin, sorting in two_strs: if sorting == anagram: ans[-1].append(origin) else: anagram = sorting ans.append([]) ans[-1].append(origin) return ans
0e4f2bdda598db25075fe4d585a10147e2488412
charan2108/pythonprojectsNew
/Tuples/reassigningtuple.py
142
3.578125
4
click = (1,2,3, [6,7,8]) click[3][0] = 9 print(click) print(type(click)) click =('H','e', 'l', 'l', 'o', 'w', 'o', 'r','l','d') print(click)
0b20585b0cb88ec084442f9237f2fd993d641155
suhaila98/basic-python-b6-b
/Tugas-1/Soal-1.py
221
4.09375
4
nama = input("Masukkan nama kamu :") umur = input("Masukkan umur kamu :") tinggi = input("Masukkan tinggi kamu :") text = "Halo nama saya {}, umur saya {} tahun, tinggi saya {} cm".format(nama,umur,tinggi[:5]) print(text)
a9d4b6d6975797dbc1488c04609990c28e562095
yashcholera3074/python-practical
/exp9_iteration.py
168
3.75
4
abc=input("enter a string") abc=abc.replace(" ","") lis=list(abc) lis2=set(lis) for i in lis2: if i in lis: count=abc.count(i) print(i,":",count)
a6a11b707399aafdc05c49daef624e52ff9c1deb
UJHa/Codeit-Study
/(11) 알고리즘 기초 - Dynamic Programming/01) 1003 피보나치 함수/jinhwan.py
773
3.8125
4
# (1003) 피보나치 함수 fibo_dict = {} def fibonacci(n): if n == 0: if fibo_dict.get(n) is None: fibo_dict[n] = 0 return fibo_dict[n] elif n == 1: if fibo_dict.get(n) is None: fibo_dict[n] = 1 return fibo_dict[n] else: if fibo_dict.get(n) is None: fibo_dict[n] = fibonacci(n - 1) + fibonacci(n - 2) return fibo_dict[n] # 입력에 대한 처리 n = int(input()) test_cases = [] for i in range(n): test_cases.append(int(input())) for test_num in test_cases: if test_num == 0: print('1 0') elif test_num == 1: print('0 1') else: fibo_number = fibonacci(test_num) print(f'{fibonacci(test_num - 1)} {fibonacci(test_num)}')