blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
fb56b8ce1d1987049f9cc36b48efaf0a445d7ecf
seblogapps/coursera_python
/Part 2 - Week 1/MemoryCardGame.py
3,403
3.625
4
# "Memory Card Game" mini-project # Sebastiano Tognacci import simplegui import random # Define constants (can resize canvas if needed) CANVAS_WIDTH = 800 CANVAS_HEIGHT = 100 CARD_WIDTH = CANVAS_WIDTH / 16.0 CARD_HEIGHT = CANVAS_HEIGHT FONT_SIZE = CARD_WIDTH LINE_WIDTH = CARD_WIDTH - 1 # Define global variables deck...
a9bc7c1de42cf3bc67125581a6c8d402faa70ea9
rfolk/Project-Euler
/problem92.py
1,523
3.8125
4
#! /usr/bin/env python3.3 # Russell Folk # July 9, 2013 # Project Euler #92 # A number chain is created by continuously adding the square of the digits in # a number to form a new number until it has been seen before. # # For example, # 44 → 32 → 13 → 10 → 1 → 1 # 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 # The...
e773f8fe3492f330395e0d2c44900b9b96f75b63
rfolk/Project-Euler
/problem65.py
1,050
3.796875
4
#! /usr/bin/env python3.3 # Russell Folk # December 3, 2012 # Project Euler #65 # http://projecteuler.net/problem=65 import time limit = 100 def digitSum ( n ) : """ Adds the sum of the digits in a given number 'n' """ return sum ( map ( int , str ( n ) ) ) def calceNumerator ( term , numeratorN1 , nume...
7994be2f3282be98f6ff2ad6f63a8e18f39a5833
siukwan/python-programming
/network/chapter1/1_13a_echo_server.py
1,111
3.671875
4
import socket import sys import argparse host = 'localhost' data_payload = 2048 backlog = 5 def echo_server(port): """A simple echo server """ #Create a TCP socket sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Enable reuse address/port sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) #Bind...
49893875d1c65cf248f45912a31f9552042b0bd3
sudhasr/Competitive_Coding_2
/TwoSum.py
401
3.625
4
#One pass solution. Accepted on Leetcode #Time complexity - O(n) #space complexity - O(n) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dict1 = {} for i in range(0,len(nums)): if (target - nums[i]) in dict1: return [i,dict1[target-nu...
989514af8deb8d7d68c51f0a1a0983cf04629656
cwormsl2-zz/2PlayerPongGame
/cwormsl2Pong.py
4,268
3.625
4
from Ball import Ball from Paddle import Paddle from graphics import * from time import sleep """ Caitlin Wormsley 12/14/12 This prgorams runs the game Pong while calling a Ball class and a Paddle class. Along with the minimum requirements, this game has a background and is a two player version. """ class Pong: ...
7b4c2a9f79f8876ab091a03d83e10918d7cf358a
chinaglia-rafa/sorting
/classes/QuickSort.py
906
3.578125
4
from Sorter import * from random import randint def partition(lst, start, end, pivot): lst[pivot], lst[end] = lst[end], lst[pivot] store_index = start for i in range(start, end): if lst[i] < lst[end]: lst[i], lst[store_index] = lst[store_index], lst[i] store_index += 1 l...
b2427bd9bf568696217c5e0dd1db531d8472cb5e
kamadforge/ranking
/algorithms/breadth_first_search.py
441
3.9375
4
BFS(v): Q = Queue() Q.add(v) visited = set() visted.add(v) #Include v in the set of elements already visited while (not IsEmpty(Q)): w = Q.dequeue() #Remove a single element from Q and store it in w for u in w.vertices(): #Go through every node w is adjacent to. if (not u...
26cf949e46bd2bb958eca1241fe25beef76bbb1d
kamadforge/ranking
/algorithms/binary_tree.py
1,273
4.25
4
class Tree: def __init__(self): self.root=None def insert(self, data): if not self.root: self.root=Node(data) else: self.root.insert(data) class Node: def __init__(self, data): self.left = None self.right = None self.data = data ...
a64c513cd683163b5596310bf0c15c39b83e2e3d
remnestal/eppu
/keyboard.py
1,007
4.09375
4
import curses class Keyboard(object): """ Simple keyboard handler """ __key_literals = ['q', 'w', 'e', 'f', 'j', 'i', 'o', 'p'] __panic_button = ' ' def __init__(self, stdscr): self.stdscr = stdscr def next_ascii(self): """ Returns the next ascii code submitted by the user """ ...
2185999943f7891d33a7519159d3d08feba8e14d
tim-jackson/euler-python
/Problem1/multiples.py
356
4.125
4
"""multiples.py: Exercise 1 of project Euler. Calculates the sum of the multiples of 3 or 5, below 1000. """ if __name__ == "__main__": TOTAL = 0 for num in xrange(0, 1000): if num % 5 == 0 or num % 3 == 0: TOTAL += num print "The sum of the multiples between 3 and 5, " \ ...
7588f35f10bea6d457e9058d21b41d8fff329fe9
karthik137/tensorflow
/housing_prices_byprice.py
787
3.75
4
import tensorflow as tensor import numpy as np from tensorflow import keras ''' Housing Price Condition One house cost --> 50K + 50K per bedroom 2 bedroom cost --> 50K + 50 * 2 = 150K 3 bedroom cost --> 50K + 50 * 3 = 200K . . . 7 bedroom cost --> 50K + 50 * 4 = 400K ''' ''' Training set to be given xs = [100,...
ac4244195cf8ecf1330621bd31773f3b211f4d5c
HaNuNa42/pythonDersleri
/python dersleri/tipDonusumleri.py
1,286
4.1875
4
#string to int x = input("1.sayı: ") y = input("2 sayı: ") print(type(x)) print(type(y)) toplam = x + y print(toplam) # ekrana yazdirirken string ifade olarak algiladigindan dolayı sayilari toplamadi yanyana yazdi bu yuzden sonuc yanlis oldu. bu durumu duzeltmek için string'ten int' ve...
74d037e74d7f602d96e5c07931ac5f561eab0359
mehoil1/Lesson-10
/News_json.py
726
3.5625
4
import json def ten_popular_words(): from collections import Counter with open('newsafr.json', encoding='utf-8') as f: data = json.load(f) words = data['rss']['channel']['items'] descriptions = [] for i in words: descriptions.append(i['description'].spli...
c62c8cac3dd6d0f918755eea1d4a28c025a4afac
masterfabela/Estudios
/FRMCode/DI/Exame Python/romaymendezfrancisco/MetodosDB.py
2,337
3.53125
4
import sqlite3 try: """datos conexion""" bbdd = 'frm' conex = sqlite3.connect(bbdd) cur = conex.cursor() print("Base de datos conectada.") except sqlite3.OperationalError as e: print(e) def pechar_conexion(): try: conex.close() print("Pechando conexi...
2afdae0bc871c7651934dedb5a6a72e696fef54f
liuyzGIt/python_datastructure_algorithms
/data_structure_algorithms/code/queue_prio_list.py
1,157
3.8125
4
class PrioQueueError(ValueError): pass class PrioQueue: """小的元素优先""" def __init__(self, elems): self.elems = list(elems) self.elems.sort(reverse=True) def is_empty(self): return not self.elems def enqueue(self, item): i = len(self.elems) -1 ...
68372dfabb4a768815176fd77acbab0dca4cfd68
AngelLiang/python3-stduy-notes-book-one
/ch02/memory.py
635
4.28125
4
"""内存 对于常用的小数字,解释器会在初始化时进行预缓存。 以Python36为例,其预缓存范围是[-5,256]。 >>> a = -5 >>> b = -5 >>> a is b True >>> a = 256 >>> b = 256 >>> a is b True # 如果超出缓存范围,那么每次都要新建对象。 >>> a = -6 >>> b = -6 >>> a is b False >>> a = 257 >>> b = 257 >>> a is b False >>> import psutil >>> def res(): ... m = psutil.Process().memory_info() ...
b83d307111992d4dae35a3769afa7e3a26e7d6a4
Man-lu/100DaysOfCodingMorseCode
/MorseCode/main.py
2,110
3.515625
4
from colorama import Fore from data import morse_dict continue_to_encode_or_decode = True print(f"{Fore.MAGENTA}############## MORSE CODE | ENCODE AND DECODE MESSAGES ##############{Fore.MAGENTA}") def encode_message(): """"Encodes Normal Text, Numbers and Some Punctuation into Morse Code""" message = input...
56dd440b18d46fb27786c94f6ba663d8fd29f284
tomjay1/auth
/authcontproject.py
2,546
4.09375
4
#register #-first name, last name, password, email #-generate useraccount #login #-account number and password #bank operation #initialization process import random database = {} #dictonary def init(): print ('welcome to bankphp') haveaccount = int(input('do you have an accou...
2334036ddc243ed0d3befd33a69d030a0d82c215
klq/euler_project
/euler26.py
1,124
3.84375
4
def euler26(): """ Reciprocal cycles: A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given: Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle. Find th...
017df190a9e6ad31ef89fb5dc929f5c58551c2b7
klq/euler_project
/euler5.py
660
3.859375
4
def least_common_multiple(numbers): lcm = 1 for i in range(len(numbers)): factor = numbers[i] if factor != 1: lcm = lcm * factor for j in range(len(numbers)): if numbers[j] % factor == 0 : numbers[j] = numbers[j] / facto...
3b7fce6dfa1739f58a0a5a451f0dc8c14425ac9b
klq/euler_project
/euler20.py
412
4.0625
4
import math def euler20(): """ n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ number = math.factorial(100) ...
c0bbbecf90a0e6128b03981b56a3c8a175f82a0b
klq/euler_project
/euler32.py
1,272
3.796875
4
def euler32(): """ Pandigital products: We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing multipl...
78b2dadaa067264258ed93da5a4e13ebf692ec6a
klq/euler_project
/euler41.py
2,391
4.25
4
import itertools import math def is_prime(n): """returns True if n is a prime number""" if n < 2: return False if n in [2,3]: return True if n % 2 == 0: return False for factor in range(3, int(math.sqrt(n))+1, 2): if n % factor == 0: return False ret...
43e039d8f937cbdad0da0a04204611436eb10ba2
jjfiv/mm2019
/mm10534.py
643
3.734375
4
import time name=input("What's your name?\n") time.sleep(1) print("HELLO", name) time.sleep(1) print("I'm Anisha.") time.sleep(1) feel=input("How are you today?\n") time.sleep(1) print("Glad to hear you're feeling", feel, "today!") time.sleep(1) print("Anyway in a rush g2g nice meeting you!") # import sys # from typi...
37c3dcf02898d3d6f510814948f0a4c4de72d2d9
geekbaba/happy_python
/square.py
345
3.703125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #类4边形 import turtle colors=['red','blue','green','orange'] t=turtle.Pen() turtle.bgcolor('black') for x in range(360): t.pencolor(colors[x%4]) #设置画笔的颜色 t.width(x/100+1) #笔尖的宽度 t.forward(x) #笔向前移动多少 t.left(90) #笔的角度调整 90度
d838b971f537f51123defb0358633a9041fd2732
Haribabu1433/gitpython
/test.py
176
4.03125
4
print("Hello World") print("Hello from Hari") list1 = [x*2 for x in [1,2,3]] print(list1) dict1 = {'x':1,'y':2} print(dict1['x']) set1 = set([1,2,3,4,4,3,2,4]) print(set1)
5ddf987c72fed9f1576ddd4fc236693c0cab0101
hsnbskn/sqlite-python
/sqlAuthDemo.py
1,069
3.515625
4
#!/usr/bin/python3 import sqlite3 dbConnect = sqlite3.connect('userAuthData.db') #Veritabanina baglan. dbCursor = dbConnect.cursor() #imlec olustur. dbCursor.execute("""CREATE TABLE IF NOT EXISTS users (username,password)""") #Kullanici adi ve parola tutan bir tablo ekle. datas = [('admin','12...
085357eaa91ec17fcad387c048b18b4858eb6c6b
schumanzhang/python
/pandas_demo.py
1,068
3.953125
4
import pandas as pd import matplotlib.pyplot as plt from matplotlib import style import numpy as np style.use('ggplot') #dataframe is like a python dictonary web_stats = {'Day' : [1, 2, 3, 4, 5, 6], 'Visitors' : [34, 56, 34, 56, 23, 56], 'Bounce_Rate' : [65, 74, 23, 88, 93, 67]} #how to conve...
199e8640a08e85102ba40a418487ce262137ac22
jkarwacki/Mosh-s-Python-course
/Examples and excercises/secret_number.py
410
3.921875
4
secretNumber = 9 noOfGuesses = 0 maxGuesses = 3 while noOfGuesses < maxGuesses: guess = int(input('Guess: ')) noOfGuesses += 1 if guess == secretNumber: print("You won!") break else: # else statement to the while loop; if the condition is not longer fulfi...
9981ba51c093c04e7458a5ce0394d2736c6647e3
bgagan911/Python_edX
/test.py
545
4
4
# [ ] review and run example student_name = "Joana" # get last letter end_letter = student_name[-1] print(student_name,"ends with", "'" + end_letter + "'") # [ ] review and run example # get second to last letter second_last_letter = student_name[-2] print(student_name,"has 2nd to last letter of", "'" + second_last_le...
f6ae082ababd05373fa7170573662f83c6686a00
sososeng/DigitalCrafts_Exercises
/function_exercises/degree_conversion.py
242
3.671875
4
import matplotlib.pyplot as plot import math def f(x): # put your code here return x +1 c = int(input("Celsius? ")) xs = list(range(c, int(c *(9/5)+ 32))) ys = [] for x in xs: ys.append(f(x)) plot.plot(xs, ys) plot.show()
55016de6c8eb6bfd69668f561b4686f0d23a9f9a
sososeng/DigitalCrafts_Exercises
/python_exercises_2/loop/multiplication_table.py
89
3.578125
4
for i in range(1,11): for j in range(1,11): print("{0} X {1} = {2}".format(i,j,(i*j)))
0fbd1ecb479efa0ab654ae686d8ecc3acdab53b4
sososeng/DigitalCrafts_Exercises
/python_exercises_2/list/matrix_addition.py
196
4.03125
4
one = [ [1, 3], [2, 4]] two = [ [5, 2], [1, 0]] three=[ [0,0], [0,0]] for i in range (0, len(one)): for j in range(0,len(one)): three [i][j] = (one[i][j] + two[i][j]) print(three)
11e4e6ec3b1d406dc98967eebbe6f040e28a5704
sososeng/DigitalCrafts_Exercises
/python_exercises_1/tip_calc.py
374
3.84375
4
bill = input("Total bill amount? ") level = input("Level of service? ") tip = 0.0 if(level == "good"): tip = "{:.2f}".format(float(bill) * .20) if(level == "fair"): tip = "{:.2f}".format(float(bill) * .15) if(level == "bad"): tip = "{:.2f}".format(float(bill) * .1) print ("Tip amount:", tip) print ("Total bill ...
e6f4754b851d4f078593a7dc5c4976f0dd43b3be
A-ZHANG1/CS61ACS88
/part1.py
12,227
3.640625
4
#CS61A,CS88 #Textbook from http://composingprograms.com/ """ #######Local state,Recursion Text book############################# """ # def outer(f,x): # def inner(): # return f(x) # return inner # g=outer(min,[5,6]) # print(g()) # def outer(f,x): # return inner # def inner(): # ...
492736dac8fb52067c21b4561ba9731337f8b84c
merveky/BASKENT-TBY414-Bahar2020
/3 Mart 2020/beden kutle indeksi.py
1,244
3.84375
4
# Beden kütle indeksi - Sağlık göstergesi hesaplama # TBY414 03.03.2020 # ADIM 1 - Kullanıcı girdilerinden indeksi hesaplamak # ağırlık (kg) boy (metre) olacak şekilde bki = a/(b*b) agirlik = float( input("Lütfen ağırlığınızı giriniz (kg): ") ) # ^ bir sayı olması gereken bir girdi alıyoruz. boy = float...
9c030cd12cc6af8ecde57f52ed0063e5acc4bf5e
artraya/scrapeDB
/Template Scripts/FlixmetricScrape.py
2,205
3.625
4
import requests import http.client from bs4 import BeautifulSoup MetaUrl = 'https://flickmetrix.com/watchlist' MetaHeaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} # result = requests.get(MetaUrl, headers=MetaHeaders...
684ed7e9ab5c2bce663e47c8791f4e23465dd0c6
Romihime/Algo3.2.tp1
/aed3-tp3-master/cargar.py
1,242
3.875
4
#!/usr/bin/python import sys def leer_datos(path): xs = [] ys = [] ds = [] with open(path, 'r') as f: #Ignoro las primeras 3 lineas nombre_archivo_salida = str(f.readline().split()[2]) nombre_archivo_salida = nombre_archivo_salida + ".in" for i in range(2): f.readline() #Leo la cantidad de nodos ...
7f311d686d93dd4894dfac265c66eea3e8ae7f38
senzuo/tryleetcode
/leetcode5Bruce.py
1,747
3.90625
4
# 自己写的暴力求解 def longestPalindrome(s): """ :type s: str :rtype: str """ imax = len(s) longest = s[0] for k in range(imax - 1): # 两种情况考虑 1. xxxaaxxx 2.xxaxx # 但是 xxxaaaxxx GG # 只能乖乖都执行了…… if s[k] == s[k + 1]: i, j = k, k + 1 # while i > ...
969dcb391cd130eb1f02357eac75c53c0c4427ac
wonnacry/hw
/task_generator_password.py
164
3.5
4
import random import string def password_generator(n): while 1: a = [] for i in range(n): a.append(random.choice(string.ascii_letters)) yield ''.join(a)
ba0392de63e38ed23e776be5de7c09ed61510360
JinnieJJ/leetcode
/67-Add Binary.py
571
3.5
4
class Solution: def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ result = "" value = 0 carry = 0 if len(a) < len(b): return self.addBinary(b, a) for i in range(len(a)): val = carry ...
a6fe9e17e19a70fc6b383af53ccbe645469a7a39
JinnieJJ/leetcode
/430-Flatten a Multilevel Doubly Linked List.py
944
3.84375
4
""" # Definition for a Node. class Node(object): def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child """ class Solution(object): def flatten(self, head): """ :type head: Node :rtype: Node ...
363aed625a6b0236330372b0355d6d3c4a032020
JinnieJJ/leetcode
/437-Path Sum III.py
698
3.6875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def pathSum(self, root, target): """ :type root: TreeNode :type sum:...
862bf3f795351c97753078b73cd9992b89b24d50
JinnieJJ/leetcode
/680-Valid Palindrome II.py
467
3.515625
4
class Solution(object): def validPalindrome(self, s): """ :type s: str :rtype: bool """ left = 0 right = len(s) - 1 while left < right: if s[left] == s[right]: left += 1 right -= 1 else: r...
c7b2c1ef58c980fa43b866a1c81ab6c5e79069bc
JinnieJJ/leetcode
/269-Alien Dictionary.py
1,768
3.78125
4
from collections import deque class Solution: def alienOrder(self, words): """ :type words: List[str] :rtype: str """ self.visited = {} self.graph = {} self.results = deque() characters = set() for word in words: for char ...
741b914a0720c6637a7c7a39b6e744e6ec873fd3
JinnieJJ/leetcode
/298-Binary Tree Longest Consecutive Sequence.py
956
3.609375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestConsecutive(self, root): """ :type root: TreeNode :rtype: int """ if not root: ...
40ace747a74a8261a90b44a01292e40a9ff56877
Rakeshgsekhar/DataStructure
/QCodes/swapNodesInPair.py
492
3.5625
4
class Solution: def swapPairs(self, head: ListNode): if head is None or head.next is None: return head tempx = ListNode(0) tempx.next = head temp2 = tempx while tempx.next is not None and tempx.next.next is not None: first = tempx.next sec...
2b92afe371f111e0353ac1276c33d79a17f2c6e1
Rakeshgsekhar/DataStructure
/QCodes/printMiddleNodeofList.py
628
3.75
4
class Node: def __init__(self,data): self.data = data self.next = None def printMiddleElement(head): temp = head temp1 = head if temp is None: print ('No Elements Found') count = 0 while temp is not None: count += 1 temp = temp.next mid = count//...
ea7bccb74b723915301aa7328f7c1baaeadaffa1
Nesters/python-workshop
/intro/solutions/animals/cat.py
169
3.5
4
from animals.animal import Animal class Cat(Animal): def __init__(self, name): super(Animal,self).__init__() def meow(self): print('meow')
734c2933e3fc24ecb3efc7ca1e468d5264d53ea3
hrldcpr/cryptopals
/set2/challenge9.py
418
3.765625
4
import utilities def pad(text, n): m = n - len(text) return text + bytes([m] * m) def unpad(text, n): if text: m = text[-1] if m < n and text.endswith(bytes([m] * m)): return text[:-m] return text @utilities.main def main(): x = b'YELLOW SUBMARINE' y = pad(x, 2...
c18a67801410dab787e4cbe3e2915074a040377e
lidannili/IIPP-Part1
/stopwatch.py
1,992
3.59375
4
# template for "Stopwatch: The Game" import simplegui # define global variables width = 150 height = 150 interval=100 # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D # t is in 0.1 seconds # A:BC.D A=0 B=0 C=0 D=0 win = 0 trial = 0 #time = str(...
a084d4b1a3a99cd2b6dcfc996af18aa6514245f1
QaisZainon/Learning-Coding
/Automate the Boring Stuff/Ch.13 - Working with Excel Spreadsheets/TextFilestoSpreadsheet.py
952
3.96875
4
#! python3 # Reads text files, put them into lists and then input into an excel file import openpyxl, os def TextToExcel(folder): wb = openpyxl.Workbook() sheet = wb.active num_column = 0 # Going through the file for foldername, subfolders, filenames in os.walk(folder): for fl_int i...
cb24203b039fe1ad617c34c1c14b920c8ca3a8fc
QaisZainon/Learning-Coding
/Statistics for Financial Analysis/Week 3/Population&Sample.py
1,219
4.03125
4
import pandas as pd import numpy as np #Create a Population DataFrame with 10 data data = pd.DataFrame() data['Population'] = [47, 48, 85, 20, 19, 13, 72, 16, 50, 60] #Draw sample with replacement, size=5 from Population a_sample_with_replacement = data['Population'].sample(5, replace=True) print(a_sample_with...
0f8ded0901ca84c9b277aaba67b9578f799d75de
QaisZainon/Learning-Coding
/Practice Python/Exercise_24.py
249
3.890625
4
#Returns a board based on user input def board(width, height): top_bot = ' ---' vertical = '| ' for i in range(height): print(top_bot*(width)) print(vertical*(width + 1)) print(top_bot*(width)) board(3, 3)
e077c341cf3f4dc0825b712a24ffd1ad2378dac0
QaisZainon/Learning-Coding
/Practice Python/Exercise_31.py
482
4.03125
4
# make a hangman game?-ish random_word = 'BALLISTOSPORES' def hangman(): print('Welcome to Hangman!') missing = ['_ ' for i in range(len(random_word))] while '_ ' in missing: print(''.join(missing)) guess = input('Guess your letter: ').upper() # word checker and updater ...
1ba8cda2d2376bd93a169031caa473825b3912da
QaisZainon/Learning-Coding
/Practice Python/Exercise_02.py
795
4.375
4
''' Ask the user for a number Check for even or odd Print out a message for the user Extras: 1. If number is a multiple of 4, print a different message. 2. Ask the users for two numbers, check if it is divisible, then print message according to the answer. ''' def even_odd(): num = int(input('Enter a n...
297253a153c50c6a2c4c64a1242584fe98801ae7
QaisZainon/Learning-Coding
/Automate the Boring Stuff/Ch.10 - Organizing Files/DeletingUnneededFiles.py
561
3.59375
4
from pathlib import Path import os p = Path.cwd() #Walk through a folder tree for foldername, subfolders, filename in os.walk(p): print(f'checking folders {foldername}...') for filenames in filename: try: #searches for large files, > 100MB size = os.path.getsize(os.pat...
3ce261f1cc1721461582343902df008991a61382
Rain-Sun/ABCA
/ABCA_topK.py
13,643
3.984375
4
""" A Python Class A simple Python graph class, demonstrating the essential facts and functionalities of graphs. """ #import queue import math from random import choice #import copy import sys import time from collections import deque #from numba import jit class Graph(object): def __init__(s...
29bc7b008f6dfe00a089dafda4b1a606408bd68d
ErikZornWallentin/Fun_Challenges
/Python/Length_Converter/length_converter.py
3,447
4.1875
4
#!/usr/bin/python ''' Author: Erik Zorn - Wallentin Created: May. 10 / 2016 This program was created to polish and improve my Python programming skills during my spare time. This was created in several languages in my repository of code to show the differences in each language with the same functionality. ...
6426ac00f17c7d1c5879ddf994938cfa0a412e62
ChienSien1990/Python_collection
/Ecryption/Encrpytion(applycoder).py
655
4.375
4
def buildCoder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation, numbers, and spaces. shift: 0 <= int < 26 returns: dict """ ### TODO myDict={} for i in string.as...
7dddf0cba7cb5f97137282a09323a090931f31f2
xingchenwan/NeuAcademy
/initialisation.py
2,893
3.9375
4
# Initialisation routine for first time login of an user import pandas as pd import numpy as np from settings import * from utils import * def init_user(udata: pd.DataFrame) -> pd.DataFrame: """ Initialise a new user in the system :param udata: the user data df :return: the updated user data df conta...
1105fd4cb3e9b95294e5e918b0017e7f109d1aac
sujit4/problems
/interviewQs/InterviewCake/ReverseChars.py
1,023
4.25
4
# Write a function that takes a list of characters and reverses the letters in place. import unittest def reverse(list_of_chars): left_index = 0 right_index = len(list_of_chars) - 1 while left_index < right_index: list_of_chars[left_index], list_of_chars[right_index] = list_of_chars[right_index]...
a88d70f775bc70026cb338561fecd88be94058fb
michaelstreyle/CS160
/Exercises/Exercise8B.py
1,263
4.03125
4
""" Tree building exercise Michael Streyle LIST IMPLEMENTATION """ def BinaryTree(r): return [r, [], []] def insert_child_left(root, new_branch): t = root.pop(1) if len(t) > 1: root.insert(1, [new_branch, t, []]) else: root.insert(1, [new_branch, [], []]) return root def i...
2003afa4046346dda230a99effaebb4f337413a6
fanwangwang/fww_study
/doc/py_example/femknowledge/change.py
558
3.53125
4
#给定一个$5×4$ 的矩阵,把它变成 $4×5$ $2*10$ 的列向量,并且每隔 $4$ 行取一个元素 import numpy as np A = np.array([[1,2,3,3],[1,2,3,4],[1,1,2,3],[2,0,0,2],[0,0,1,2]]) print(A) a = np.reshape(A,(4,5)) print(a) B = np.reshape(A,(4,5),order = 'F') C = np.reshape(A,(4,5),order = 'C') print(B) print(C) # 变换的时候默认是‘C’,如果加‘order = 'F'’,则是按列排列,例如变换成 ...
eb93656378a977bac3503804f3a8ad7123d41385
fanwangwang/fww_study
/doc/py_example/femknowledge/matrixmutivec.py
289
3.546875
4
# 给定一个 $5×n5$ 的矩阵,$5×1$ 的向量,对矩阵与向量作乘积,以及对向量与数作乘积 import numpy as np A = np.array([[4,-1,0,0,0],[-1,4,-1,0,0],[0,-1,4,-1,0],[0,0,-1,4,-1],[0,0,0,-1,4]]) b = [1,1,1,1,1] x = A*b y = A@b y = y.reshape(5,1) print(x) print(y)
d97afa0117f3088d653e118423252078f9b1982c
gcarrara97/projeto_semantix
/projeto_semantix_6_balanco.py
2,548
3.53125
4
arquivo_parcial = open("bank.csv", "r") arquivo_completo = open("bank-full.csv", "r") #Questo 6 #BALANO linhas = arquivo_completo.readlines() fl = False emprestimo_imobiliario = 0 balanco = [] for i in linhas: linha = i.split(';') if fl == True: if linha[6] == "\"yes\"": empr...
6a28d887ba8bf192a48254a460922cbadd0b0074
jasonzhixian/PythonForOffer
/Python_exercise/5_print_linked_list_for_end_to_start/exercise_reverse.py
664
3.90625
4
class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def printLinkedListFromHeadToTail(self, listNode): if listNode is None: return None result = [] cur = listNode while cur: result.append(cu...
dfb0505e3afbc8e12cf9f22f0e65d14cce9cda17
jasonzhixian/PythonForOffer
/Python_exercise/19_Mirror_of_binary_tree/exercise.py
691
3.609375
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None #change the exist tree def mirrorBinaryTree(self, root): if root == None: return None root.left, root.right = root.right, root.left self.mirrorBinaryTre...
9fe23b1af531610a538a71a5a2e19986cb992506
jasonzhixian/PythonForOffer
/exercise_for_tree.py
4,999
3.625
4
#6 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): #reconstructbinarytree def reConstructBinaryTree(self, preorder, inorder): if not preorder and not inorder: return None root = TreeNo...
73db8a09cd5009c1c9cdca7ffdc92a3f7fc34fab
12389285/meps
/code/constraints/distribution.py
7,548
3.84375
4
from itertools import permutations, repeat import numpy def distribution(schedule, courses): """ This function calculates the malus points regarding the spread of course activities over the week. This function takes as input arguments: - the schedule - list of courses This functio...
e8ccaa13937f18d9f09a3484df5915e0506f1cc2
12389285/meps
/code/constraints/overlap_simulated.py
1,275
4.0625
4
def overlapping(activity, timelock, overlap_dict, roomlock): """ This function returns True if the is no overlap with courses given in the overlap matrix. Otherwise, it returns False. This function takes as input arguments: - activity - time lock and room lock - overlap matrix ...
ecc6ade6a296c0f1d2b4f6567eba9a4d13951e00
michaelsong93/python-prac
/sep4-2.py
598
3.75
4
lst1 = [('a',1),('b',2),('c','hi')] lst2 = ['x','a',6] d = {k:v for k,v in lst1} s = {x for x in lst2} print(d) print(s) def f(n): yield n yield n+1 yield n*n print([i for i in f(3)]) def merge(l,r): llen = len(l) rlen = len(r) i = 0 j = 0 while i < llen or j < rlen: if j ==...
93f460a4b712f9b45b30382d5ffa6213db38d226
lemacm/python
/loan.py
2,819
4.03125
4
name = input ("Name: ") def takeincome(num): if num < 500: return 'payscale1' elif num < 1000: return 'payscale2' else: return 'payscale3' def criteria1 (): print('''Are you employed?) - No - Part time''') employment = input ('Please choose...
4c1e3608010a0b5c306c5fbd10bc00b07fc0e771
sishu7/common-interview-questions
/ZeroDuplicates.py
575
3.625
4
#zeroes duplicates in a list, after first instance def zero_duplicates(l): dict1 = {} for i in range(0, len(l)): if l[i] in dict1: l[i] = 0 else: dict1[l[i]] = 1 return l print zero_duplicates([1, 2, 2, 3, 4, 4, 5, 5, 6, 6]) #zeroes all duplicates in a list def zero_duplicates2(l): d...
b73eef9b47783fca87f8bb1201a46bebd0cc1e3e
sishu7/common-interview-questions
/StringComparison.py
388
3.84375
4
#compares strings character by characters def compare(str1, str2): if len(str1) == len(str2): for i in range(0, len(str1)): if str1[i] != str2[i]: return False else: return False return True print compare('abc', 'abc') print compare('abd', 'abc') print compare('...
6c3c5507ecf07b53bf40a1353ba04447ea80d882
ErikWeisz5/chapter_work
/3/6.py
149
3.765625
4
d = int(input("your day")) m = int(input("your month")) y = int(input("your year")) if d * m == y : print("magic") else : print("not magic")
84006abd27c93fcb1fd6fe813161f34ab0177e9f
ErikWeisz5/chapter_work
/4/3.py
300
3.765625
4
l = int(input("number of laps: ")) r = set() a = 0 b = 0 while a < l: seconds = int(input("Lap time: ")) r.add(seconds) a += 1 r = list(r) r.sort() while b < l: b += r[b] average = b/l print("fastest lap : ", r[0]) print("Slowest Lap : ", r[a-1]) print("average lap : ", average)
1946e3e82bc870dc367c8d3b9b9c19536bb2aed4
jruizvar/jogos-data
/aula/variable.py
495
3.515625
4
""" Variables in tensorflow """ import tensorflow as tf """ RANK 0 """ a = tf.Variable(4, name='a') b = tf.Variable(3, name='b') c = tf.add(a, b, name='c') print("Variables in TF\n") print(a) print(b) print(c) print() with tf.Session() as sess: sess.run(a.initializer) sess.run(b.initializer) a_va...
5a748bacb223ad9de8620dd4ebcad3c457525ef8
JuanSebastianOG/Analisis-Numerico
/Talleres/PrimerCorte/PrimerTaller/CuadraticaMejorada.py
670
3.953125
4
#Implementacion de una ecuación que mejora la ecuación cuadratica original import math def calculoOriginal( a, b, c ): x0 = (-b - math.sqrt( b**2 - 4*a*c )) / (2*a) x1 = (-b + math.sqrt( b**2 - 4*a*c )) / (2*a) print("Los valores de las raices con la formula original son: Xo -> ", x0, " X1 -> ", ...
934bdc157134659f5fc834ea4bce96bd6df629a2
JuanSebastianOG/Analisis-Numerico
/Talleres/PrimerCorte/PrimerTaller/Algoritmos/Metodo_Newton.py
1,285
4.25
4
#Implementación del método de Newton para encontrar las raices de una función dada from matplotlib import pyplot import numpy import math def f( x ): return math.e ** x - math.pi * x def fd( x ): return math.e ** x - math.pi def newton( a, b ): x = (a + b) / 2 it = 0 tol = 10e-8 errorX = [] ...
72f12e63fbac4561a74211964ab031f5ffb29212
derick-droid/pythonbasics
/files.py
905
4.125
4
# checking files in python open("employee.txt", "r") # to read the existing file open("employee.txt", "a") # to append information into a file employee = open("employee.txt", "r") # employee.close() # after opening a file we close the file print(employee.readable()) # this is to check if the file is readable prin...
8cf687f5d815f6fc2b0940d55d30e46cd1c7355a
derick-droid/pythonbasics
/exponent functions.py
184
3.765625
4
def large_number(base_number, power_number): result = 1 for index in range(power_number): result = result * base_number return result print(large_number(3, 2))
16086860e6bf740354f6cdb0537fbbe3f39e85ae
derick-droid/pythonbasics
/nest2dic.py
404
4.09375
4
# creating nested dictionary with for loop aliens = [] for alien_number in range (30): new_alien = { "color" : "green", "point" : 7, "speed" : "high" } aliens.append(new_alien) print(aliens) for alien in aliens[:5]: if alien["color"] == "green": alien["color"] == "red"...
ea96c07f9845aca38a5011f1009a7dc4b8de30e9
derick-droid/pythonbasics
/dictionary.py
686
3.53125
4
# returning dictionary in functionn def user_dictionary (first_name, last_name): full = { "first_name" : first_name, "last_name" : last_name } return full musician = user_dictionary("ford", "dancan") print(musician) # using optinal values in dictionary def dev_person(occupation, age, ...
95a9f725607b5acc0f023b0a0af2551bec253afd
derick-droid/pythonbasics
/dictexer.py
677
4.90625
5
# 6-5. Rivers: Make a dictionary containing three major rivers and the country # each river runs through. One key-value pair might be 'nile': 'egypt'. # • Use a loop to print a sentence about each river, such as The Nile runs # through Egypt. # • Use a loop to print the name of each river included in the dictionary. # ...
dcf2b3140557d00145cdcbc2cddddedc08e6095d
derick-droid/pythonbasics
/listfunctions.py
248
3.828125
4
lucky_numbers = [1, 2, 3, 4, 5, 6, 7] friends = ["derrick", "jim", "jim", "trump", "majani" ] friends.extend(lucky_numbers) # to add another list on another list print(friends) print(friends.count("jim")) # to count repetitive objects in a list
6da039c504277c5a23ca5a744faa1f2341c58105
derick-droid/pythonbasics
/persona.py
446
3.78125
4
class Robots: def __init__(self, name, color, weight): self.name = name self.color = color self.weight = weight def introduce_yourself(self): print("my name is " + self.name ) print("I am " + self.color ) print("I weigh " + self.weight) r1 = Robots("Tom", "bl...
448b01b0daa1f1cb13ac286d3f4c600318cf8a30
derick-droid/pythonbasics
/module.py
262
3.890625
4
# from largest_number import largest_number # biggest_number = largest_number(numbers) # print(biggest_number) from largest_number import find_biggest_number numbers = [2, 3, 73, 83, 27, 7, ] biggest_number = find_biggest_number(numbers) print(biggest_number)
935e0579d7cbb2da005c6c6b1ab7f548a6694a86
derick-droid/pythonbasics
/slicelst.py
2,312
4.875
5
# 4-10. Slices: Using one of the programs you wrote in this chapter, add several # lines to the end of the program that do the following: # • Print the message, The first three items in the list are:. Then use a slice to # print the first three items from that program’s list. # • Print the message, Three items from the...
5a827e2d5036414682f468fac5915502a784f486
derick-droid/pythonbasics
/exerdic.py
2,972
4.5
4
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the # name of a pet. In each dictionary, include the kind of animal and the owner’s # name. Store these dictionaries in a list called pets . Next, loop through your list # and as you do print everything you know about each print it rex = { ...
d65f32a065cc87e5de526a718aeea6d601e1ac06
derick-droid/pythonbasics
/iflsttry.py
2,930
4.5
4
# 5-8. Hello Admin: Make a list of five or more usernames, including the name # 'admin' . Imagine you are writing code that will print a greeting to each user # after they log in to a website. Loop through the list, and print a greeting to # each user: # • If the username is 'admin' , print a special greeting, such as ...
80bb7af9cb2b49a297419ccdd8d6ae2d486f244a
leticiasayuri/introducao-pandas
/introducao/dataframe.py
1,541
3.75
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({'Aluno': ["Wilfred", "Abbie", "Harry", "Julia", "Carrie"], 'Faltas': [3, 4, 2, 1, 4], 'Prova': [2, 7, 5, 10, 6], 'Seminário': [8.5, 7.5, 9.0, 7.5, 8.0]}) print("DataFrame\n...
dec5f53cc6965129b4eeea95ac949cd8fa2fa3ba
781-Algorithm/JeonPanGeun
/Algo_python/[BOJ] 10773.py
1,287
3.75
4
# 백준 10773 제로 # 첫 번째 줄에 정수 K가 주어진다. (1 ≤ K ≤ 100,000) # # 이후 K개의 줄에 정수가 1개씩 주어진다. # 정수는 0에서 1,000,000 사이의 값을 가지며, # 정수가 "0" 일 경우에는 가장 최근에 쓴 수를 지우고, 아닐 경우 해당 수를 쓴다. # # 정수가 "0"일 경우에 지울 수 있는 수가 있음을 보장할 수 있다. class Stack: def __init__(self): self.top = [] self.cnt = 0 def push(self, item): ...
0ed70af907f37229379d7b38b7aaae938a7fc31a
adamkozuch/scratches
/scratch_4.py
584
4.15625
4
def get_longest_sequence(arr): if len(arr) < 3: return len(arr) first = 0 second = None length = 0 for i in range(1, len(arr)): if arr[first] == arr[i] or (second and arr[second]== arr[i]): continue if not second: second = i continue ...
286fe8a0f431330f9fc43b430646ff942254a602
jiz148/blueprint_editor
/model/operation/implement/multiply.py
732
3.828125
4
""" Operation: Multiply """ def generate_code(json_dict, lang='python'): result = '' multiply_1, multiply_2, output = parse_json(json_dict) if lang == 'python': result = "{} = {} * {}".format(output, multiply_1, multiply_2) return result def parse_json(json_dict): """ @param json_dic...
1bbb879b68e07c8c9b20612ef956ed3fdfd4da51
FatherZosima/CLV-Wishing-Well
/sim.py
5,108
3.546875
4
import random import matplotlib.pyplot as plt import numpy as np import enum class GambleOutcomes(enum.Enum): Won = 1 Lost = 2 NoPlay = 3 class Player: def __init__(self, startingHoldings, playerID): self.currentHoldings = startingHoldings self.holdingHistory = [startingHoldings] ...
4c9029512a3446a50058a0d7099b71cfb3ad2574
kKunov/Haskel_exam
/03-NameMatching.py
1,786
3.90625
4
def get_known_m_f(): known_m_f = [0, 0] known_m_f[0] = input("Males names: ") known_m_f[1] = input("females names: ") known_m_f[0] = int(known_m_f[0]) # Tuk gi preobrazuvam za da moga known_m_f[1] = int(known_m_f[1]) # sled tova da gi polzvam bez da go pravq return known_m_f def helper_ge...
e06f5970d225977b18877e7c40cbc04cc748aa09
cvtorrisi93/cp1404practicals
/prac_04/list_exercises.py
1,181
3.9375
4
""" CP1404/CP5632 Practical - Christian Torrisi List exercises """ USERNAMES = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob'] def main(): numbers = ...
c5812e210bf7b92a7f46b90edab07feef8cc9fa1
cvtorrisi93/cp1404practicals
/prac_03/scores.py
1,118
4.0625
4
""" CP1404/CP5632 - Practical Scores program to determine what the score is based on value """ import random MIN_SCORE = 0 MAX_SCORE = 100 def main(): output_file = open("results.txt", 'w') number_of_scores = get_valid_integer("Enter a number of scores to generate: ") for i in range(number_of_scores)...