blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
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)...
228c27b3406c45f10f3df2588de29e1d4ad5bfcb
AjayHao/helloPy
/demos/basic/list.py
684
4.21875
4
#!/usr/bin/python3 # 元祖 list1 = ['Google', 'Runoob', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7, 8] # 随机读取 print ("list1[0]: ", list1[0]) print ("list1[-2]: ", list1[-2]) print ("list2[1:3]: ", list2[1:3]) print ("list2[2:]: ", list2[2:]) # 更新 list1[2] = '123' print ("[update] list1: ", list1) # 删除 d...
a97267baf084e7e54bc75706b82fe02fcbe7f519
AjayHao/helloPy
/demos/designpatterns/creational/singleton_pattern.py
301
3.59375
4
class Singleton: def __init__(self): pass def __new__(cls): if not hasattr(Singleton, "__instance"): Singleton.__instance = super(Singleton, cls).__new__(cls) return Singleton.__instance obj1 = Singleton() obj2 = Singleton() print(obj1, obj2)
3551929bd1814c20eca69cbb80290d2ff8de8372
chaksamu/python
/venv/binarysearch.py
442
3.609375
4
pos=-1 def search(list,s): l=0 u=len(list)-1 print(l,u) while l<=u: mid=(l+u) // 2 print(mid) if list[mid]==s: globals()['pos']=mid return True else: if list[mid] < s: l=mid+1 else: u=mid-1 ...
7a5473750801417f14ab6605e911b5d5765d04b7
chaksamu/python
/venv/multithreads.py
486
3.90625
4
from time import sleep from threading import * class Hello(Thread): def run(self): #run is default method for i in range(5): print("Hello") sleep(1) t1=Hello() #t1.run() t1.start() sleep(0.5) class Hi(Thread): def run(self): for i in range(5): prin...
477250d187e782933186cb9bf8b3b4e6a9ece45c
chaksamu/python
/venv/calendar.py
595
3.90625
4
import calendar for month in calendar.month_name: print(month) for month in calendar.day_name: print(month) for month in calendar.day_name: print(month) c=calendar.TextCalendar(calendar.SUNDAY) str=c.formatmonth(2025,12) print(str) c = calendar.TextCalendar(calendar.TUESDAY) str = c.formatmonth(2025, 2) pri...
b8ad231bf1e687ee05105ea6440ed20c9f263f6f
chaksamu/python
/venv/classinsideclass.py
711
3.8125
4
class Student: def __init__(self,name,rollno): self.N = name self.R = rollno self.L = self.Laptop() def show(self): print(self.N,self.R) self.L.show() class Laptop: def __init__(self): self.brand = 'hp' self.cpu = 'i8' sel...
35d4105326e91ac51680a7a0d7e50d17a87c79d9
chaksamu/python
/venv/loops.py
594
3.921875
4
#While def main(): x=0 while (x<=5): print(x) x=x+1 #print(x) main() #For def main(): x=0 for x in range(2,7): print("The ",x) main() def main(): Months={"Jan", "Feb", "Mar"} for i in Months: print(i) main() #break def main(): y={1,2,3,4,5,6,7,8,9,1...
227ace258237b03dd4bb000ad3b4abec216c656b
chaksamu/python
/venv/bubblesort.py
305
3.828125
4
def sort(nums): print(nums) for i in range(len(nums)-1,0,-1): for j in range(i): if nums[j]>nums[j+1]: t=nums[j] nums[j]=nums[j+1] nums[j+1]=t print(nums) #print(nums) nums=[6,5,4,3,2,1] sort(nums) #print(nums)
a547e08af1445d7aa9f2ff0d95fc66d9f2a8c9db
chaksamu/python
/venv/steps/liststeps3.py
271
3.609375
4
name=str(input("Enter the Filename: ")) f=open(name,'r') #ff=f.read() #print(ff) #gg=(ff.split()) #print(gg) for line in f: if not line.startswith('From'): continue tt=line.split() print(tt[1]) yy=tt[1] zz=yy.split('@') print(zz) #4:13:00
e99b2ad952745f289c6e8e19ac756e975092606c
Akshay1997a/Python-Datastructure
/LinkedList.py
1,841
4
4
from os import system def cls(): system('clear') class Node: def __init__(self, val): self.data = val self.next = None class LinkedList: def __init__(self): self.head = None def addNode(self, list): for i in list: if self.head == None: s...
faf4ef2dab7840dfe0c778377e4998fa951ab988
quynhhgoogoo/Artificial-Intelligence
/lectures/n-grams/ngrams.py
1,105
3.625
4
from collections import Counter import math import nltk import os import sys nltk.download('punkt') def main(): '''Calculate top term frequencies for a corpus of documents''' if len(sys.argv) != 3: sys.exit("Usage: python ngrams.py n corpus") print("Loading data...") # Loading input n =...
1d2d81b28514c9d02774bab739dff207a7e619f0
nixeagle/euler
/2/flare183.py
265
3.53125
4
def fib(): x,y = 0,1 while True: yield x x,y = y, x+y def even(seq): for number in seq: if not number % 2: yield number def problem(seq): for number in seq: if number > 4000000: break yield number print sum(even(problem(fib())))
4646413619e71320a217116999fa2ba6fc4e7992
ZanderBE/Fill-in-the-Blank-Quiz
/Final-Version-Fill-In-The-Blank-Quiz.py
7,241
3.71875
4
guessCounter = 5 guessIndex = 0 outOfLives = 0 blankList = ["BLANK1", "BLANK2", "BLANK3", "BLANK4"] promptList = ['What do you think fills "BLANK1"? ', 'What do you think fills "BLANK2"? ', 'What do you think fills "BLANK3"? ', 'What do you think fills "BLANK4"? '] easyMod...
0d113719859b6ff06717d69e0bd4aee5150985ee
wrf22805656/Web-Crawler
/Scraping data - example one
555
3.640625
4
#! /user/bin/env python import re import urllib2 def download(url): print ('downloading:' "\n", url) try: html = urllib2.urlopen(url).read() except urllib2.URLError as e: print 'Downloading error:', e.reason html = None return html url =...
aeed9a1fecdf64c15fed3310d68fc54cfb839475
trallorc/Steev
/Moshe Sharat/hexmap/Render.py
7,712
3.640625
4
from abc import ABCMeta, abstractmethod import pygame import math from Map import Grid SQRT3 = math.sqrt(3) class Render(pygame.Surface): __metaclass__ = ABCMeta def __init__(self, map, radius=16, *args, **keywords): self.map = map self.radius = radius # Colors for the map s...
7c3a1cf25c041f0212a7764e4aad57abecf7f9bf
kanglicheng/GoogleCodeJam
/2019/Qualification/B/b.py
263
3.59375
4
def solve(): N = int(input()) S = input() ans = "" for c in S: ans += "E" if c == "S" else "S" return ans if __name__ == "__main__": T = int(input()) for t in range(1, T + 1): print("Case #{}: {}".format(t, solve()))
7dbb6ceb733fa90b5f1cc5ab5521cffaf24d7c0f
ryanmcfarland/file-tk-downloader
/classes/reqdl.py
937
3.5625
4
import requests import os import sys import urllib3 class RequestFile: def __init__(self, dir="", filename="", url=""): self.dir = dir self.filename = filename self.url = url ## --> check if the directory exists def check_dir_exists(self): if not os.path.exists(self.fil...
a66405eeea9904f8c4967a7789bc6a4841713f24
anumulaphani/nodejs-application
/sales enhancement.py
255
3.796875
4
sales = float(input("Enter sales: $")) while sales <= 0: print("Invalid option") sales = float(input("Enter sales: $")) if sales < 1000: bonus = sales * 0.1 print(bonus) else: bonus = sales * 0.15 print(bonus) print("good bye")
fcf2d76ad0f3015988ae7b445870405ac0e2e668
anumulaphani/nodejs-application
/practicals 2/practicals_3/value_error.py
436
4.0625
4
def get_num(lower, upper): while (True): try: user_input = int(input("Enter a number ({}-{}):".format(lower, upper))) if user_input < lower: print("Number too low.") elif user_input > upper: print("please enter a valid number") ...
977529bdb4da2c8b6a0a7d5749b57dca59ece90c
Wormandrade/Trabajo01
/eje02.py
358
4.03125
4
#Calcular el perímetro y área de un círculo dado su radio. print("========================") print("\tEJERCICIO 02") print("========================") print("Cálculo de périmetro y área de un círculo\n") radio = float(input("Ingrese el radio: \n")) pi=3.1416 print("El perímetro es: ",round(radio*pi,2)) print("El área e...