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
cd70f63a295a2d71fe9a4be59b906626e84ea668
benzheren/python-playground
/project-euler/p015.py
507
3.6875
4
''' Starting in the top left corner of a 2x2 grid, there are 6 routes (without backtracking) to the bottom right corner. How many routes are there through a 20x20 grid? ''' def route(max): result = [[0] * (max+1) for x in xrange(max+1)] result[0][0] = 1 for i in range(max+1): for j in range(max+1)...
793ca0dd99a7d70bc36c13040748d8e510b668b0
benzheren/python-playground
/project-euler/p004.py
507
3.90625
4
''' A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91*99. Find the largest palindrome made from the product of two 3-digit numbers. ''' from time import time start = time() n = 0 for i in xrange(999, 100, -1): if i * i < n: break...
978f82ca4a28bbdc7ad3ab2d23c9cd4ada89e4db
jholstein/python-examples
/neural-network/neural-network-countdown.py
3,776
3.53125
4
##First Neural Network import numpy as np # X = (hours sleeping, hours studying), y = score on test X = np.array(([2, 5], [1, 5], [3, 5]), dtype=float) y = np.array(([10], [5], [15]), dtype=float) predictTest = np.array(([3,5]), dtype=float) predictTest = predictTest/np.amax(predictTest, axis=0) # scale units X = X/...
42c4c030d496bec361077236f7b388b45e3761c8
AnuradhaIyer/Python-Code
/walrus_demo.py
1,201
3.984375
4
''' Walrus operator is := official name : PEP 572 Assignment Expressions. Problem being solved: A regular "=" assignments is a statement and statements cant be used inside statement Rules: 1) The assignment expression must be in paranthesis 2) The return value is wjatever was assigning. ...
4b5dea2d3c170ede818842a9b5a8e9d9a0e30ea2
webmalc/challenges
/data_structures/max_sliding_window.py
1,332
4.03125
4
# python3 from collections import deque def max_sliding_window(sequence, window_size): """ Given a sequence a 1 , . . . , a n of integers and an integer m ≤ n, find the maximum among {a i , . . . , a i+m−1 } for every 1 ≤ i ≤ n − m + 1. A naive O(nm) algorithm for solving this problem scans each w...
8b7133196f3e274e2df6dab18ba45c2508dc71fd
forkcodeaiyc/codelab
/server/engines/python/defaults/defaults.py
2,035
3.9375
4
# Flatten a nested list structure a_list = [0, 1, [2, 3], 4, 5, [6, 7]] def flatten(nestedList): result = [] if not nestedList: return result stack = [list(nestedList)] while stack: current = stack.pop() next = current.pop() if current: stack.append(current) if isinstanc...
77ffe561d8ff2e08ce5aa7550b81091387ed4981
WellingtonTorres/Pythonteste
/aula10a.py
206
4.125
4
nome = str(input('Qual é o seu nome? ')) if nome == 'Wellington': print('Alem do nome ser bonito é nome da capital da NZ!') else: print('Seu nome é tão normal') print('Bom dia {}!'.format(nome))
a74c53f7de8307a42104fa1d4972e55dc97b2e29
WellingtonTorres/Pythonteste
/aula12a.py
327
3.953125
4
nome = str(input('Qual é o seu nome? ')) if nome == 'Wellington': print('Que nome bonito!') elif nome == 'Lucas' or nome == 'Ana' or nome == 'Victor': print('Seu nome é bem comum no Brazil!') elif nome in 'Barbara Eduarda Claudia Gabriela Jaqueline': print('Um belo nome feminino!') print('Tenha um bom dia, ...
ab0c1381c31007d12bcdafcf3ec0f8c3a9ad814d
bicipeng/python_crash_course_pj1
/alien.py
677
3.53125
4
'''a class to mange aliens''' import pygame from pygame.sprite import Sprite class Alien(Sprite): """docstring for Alien""" def __init__(self, ai_settings,screen): super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings #create an alien an place it on the top left corner self.im...
833172bd630823bf9e035fd443f43098bc0c10b7
wansiLiangg/CISC471
/Assignment2/main.py
4,268
3.671875
4
''' CISC 471 HW2 ''' #Part1 -- Programming #Question 1.1 Find an Eulerian Cycle in a Graph class LinkedList: def __init__(self, node): self.node = node self.next = self def insert(self, link): link.next = self.next self.next = link return link def eulerianCycle(graph):...
c3e4d19ad6b650bd400a75799c512bb8eecad4c9
ldswaby/CMEECourseWork
/Week3/Code/get_TreeHeight.py
2,274
4.5
4
#!/usr/bin/env python3 """Calculate tree heights using Python and writes to csv. Accepts Two optional arguments: file name, and output directory path.""" ## Variables ## __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imp...
6f5863262df12da64f2b130ac485b4a76ae282b6
ldswaby/CMEECourseWork
/Week3/Code/Vectorize1.py
1,057
4.0625
4
#!/usr/bin/env python3 """Groupwork: to do vectorize1 using Python""" ## Variables ## __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imperial.ac.uk), ' \ 'Dengku Tang (dengkui.tang20@imperial.ac.uk)' __versi...
bdf5cc71e2046f299a0327fc71bf903043428130
Minimaximize/IFN680_A1
/IFN 680 - Assessment 1 - Current Best Answer/population_search.py
4,877
4.25
4
''' This module defines an abstract class 'Population' for particle filter search. ''' import numpy as np #----------------------------------------------------------------------------- class Population(object): ''' An abstract container class for a collection of individuals to be used in a 'partic...
4e44ee0c832595b4e5bca4e3fd185bf95ca74b9a
wangruicsu/LeetCode_practice-python
/25-Reverse_Nodes_in_k-Group.py
2,421
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseKGroup(self, head, k): """ :type head: ListNode :type k: int :rtype: ListN...
10801e723093b8d6965312f8546ac7fec37aac17
amitgadhave17/Python_Training
/Day4/Classes.py
920
3.6875
4
from datetime import date class Person: def __init__(self, name, surname, birthdate, email, address, mob, tel): self.name = name self.surname = surname self.birthdate = birthdate self.email = email self.address = address self.mob = mob self.tel = tel ...
eef274367f9d57f490459286d4e4dc6622fa2581
cmesiasd/CC3101-Matematicas-Discretas
/Tarea1/T1.py
3,489
3.71875
4
# Run the file as "python SAT.py -v" # Add further needed modules import unittest # To implement the functions below, you are allowed # to define auxiliary functions, if convenient. def SetLiteral(formula, lit): new = formula[:] #Crea una lista copia de formula, donde se iran eliminando literales for i in f...
0b93e8f102c95fae9189001148325937dcb520f9
davide990/IRSW-lab
/PythonApplication1/nltk_ex1.py
3,791
3.8125
4
'''from nltk.book import *''' import nltk import math import numpy def main(): print("hi") ''' Open a text file, tokenize and return an nltk.Text object ''' def open_textfile(fname): f = open(fname, 'r') raw_text = f.read() tokens = nltk.word_tokenize(raw_text) text = nltk.Text(tokens) re...
350abd340322e564c4ff24b4431d14715ac54708
JacksonOsvaldo/bc_calcado-vendas
/fixtures/manager_db.py
8,303
3.859375
4
# -*- coding: utf-8 -*- """ Este App gerencia um banco de dados sqlite3. Pode-se usar o modo interativo com python2. Popula as tabelas do banco de dados com valores randômicos. Banco de dados: 'db.sqlite3' Tabelas: 'vendas_brand', 'vendas_customer', 'vendas_product', ...
3d2f444f1d240b071793b1ffaa99109fa5089a8e
josedesoto/s3-upload
/get_s3_file.py
3,523
3.5
4
#! /usr/bin/env python """Download logs or files from S3 Usage: python get_s3_file.py [options] Options: -f ..., --log=... Name of the log to download -D ..., --datelog=... Date to thelog to donwload -l, --list List all lthe content on the storage -h, --help Show this help ...
6f230e46e7f3cdbd542f97613853b825f76273fd
pringlized/phraseware
/python/Phraseware/phraseware.py
1,489
3.5625
4
import sys import csv import random import constants # init vars numWords = 0 wordDict = {} wordKeys = [] thePhrase = "" print "\nLet's make a Diceware inspired password..." print "------------------------------------------" # ask for how many words to use and validate while True: try: numWords = int(raw...
d9a442c886eb178e2fab6422e8a1ef44e7e9ab07
bizhan/pythontest3
/chapter_1/range_vs_enumerate.py
1,040
4.1875
4
#print("Hello world") def fizz_buzz(numbers): ''' Given a list of integers: 1. Replace all integers that are evenly divisible by 3 with "fizz" 2. Replace all integers divisble by 5 with "buzz" 3. Replace all integers divisible by both 3 and 5 with "fizzbuzz" >>> numbers = [45, 22,14,65, 97, 72] >>> ...
026b22cd4e0ff011b244dfb6308f3b2d44353d3b
osmanuss/prog
/testi/10test/10test.py
625
4
4
##1 # a = 5 # b = 15 # if True and False: # print(a) # else: # print(b) ##2 # a = 5 # b = 6 # print(a, 1 if a < b else "<=", b) ##3 # a = 5 # b = 15 # if True and True: # print(a) # else: # print(b) ##4 # a = 6 # b = 7 # c = 1 + b if a > b else a # print(c) ##5 # a = 5 # b = 15 # if True or False: #...
08f10c107886ccd9b6f93bfd72e7287a47b29d2e
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_twenty_one.py
806
3.765625
4
""" 程式設計練習題 2.2-2.10 2.21 財務金融應用程式:複利值. 利息公式: 100 * (1 + 0.00417) = 100.417 (100 + 100.417) * (1 + 0.00417) = 201.252 (100 + 201.252) * (1 + 0.00417) = 302.507 以下是輸出樣本: ``` Enter the monthly saving amount:100 After the sixth month, the account value is 608.81 ``` """ import ast amount = ast.literal_eval(input("Ent...
954c952dba2e72d6b70c9d345b96090b0a43b732
timmy61109/Introduction-to-Programming-Using-Python
/examples/TestSet.py
549
4.3125
4
from Set import Set set = Set() # Create an empty set set.add(45) set.add(13) set.add(43) set.add(43) set.add(1) set.add(2) print("Elements in set: " + str(set)) print("Number of elements in set: " + str(set.getSize())) print("Is 1 in set? " + str(set.contains(1))) print("Is 11 in set? " + str(set.contains(11)))...
f20df9950890ea3b43729837524065283366aa60
timmy61109/Introduction-to-Programming-Using-Python
/examples/ComputeFactorialTailRecursion.py
322
4.15625
4
# Return the factorial for a specified number def factorial(n): return factorialHelper(n, 1) # Call auxiliary function # Auxiliary tail-recursive function for factorial def factorialHelper(n, result): if n == 0: return result else: return factorialHelper(n - 1, n * result) # Recursive cal...
43a372bacd7092285e07b4600bfdcdcc8731027d
timmy61109/Introduction-to-Programming-Using-Python
/examples/SimpleIfDemo.py
126
3.96875
4
number = eval(input("Enter an integer: ")) if number % 5 == 0 : print("HiFive"); if number % 2 == 0 : print("HiEven");
0ad23dca684097914370ac9f35a385b80ed74cc4
timmy61109/Introduction-to-Programming-Using-Python
/examples/ComputeLoan.py
687
4.21875
4
# Enter yearly interest rate annualInterestRate = eval(input( "Enter annual interest rate, e.g., 8.25: ")) monthlyInterestRate = annualInterestRate / 1200 # Enter number of years numberOfYears = eval(input( "Enter number of years as an integer, e.g., 5: ")) # Enter loan amount loanAmount = eval(input("Enter l...
d582d636fd87f6d370a85e3d3632cbfb66e9de25
timmy61109/Introduction-to-Programming-Using-Python
/examples/UseCustomTurtleFunctions.py
431
4
4
import turtle from UsefulTurtleFunctions import * # Draw a line from (-50, -50) to (50, 50) drawLine(-50, -50, 50, 50) # Write a text at (-50, -60) writeText("Testing useful Turtle functions", -50, -60) # Draw a point at (0, 0) drawPoint(0, 0) # Draw a circle at (0, 0) with radius 80 drawCircle(0, 0, 80) # Draw a ...
77fc93e8454ea34d6d78599e47fd8739d791d4e6
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_fourteen.py
780
3.984375
4
u""" 程式設計練習題 2.2-2.10 2.14 幾何:計算三角形的面積. 請撰寫一程式,提示使用者輸入三角形的三點座標(x1, y1)、(x2, y2)以及(x3, y3),然後顯示期面積。 s = (side1 + side2 + side3) / 2 area = (s * (s - side1)(s - side2)(s - side3)) ** 0.5 以下是輸出樣本: ``` Enter three points for a triangle:1.5, -3.4, 4.6, 5, 9.5, -3.4 The area of the triangle is 33.6 ``` """ import ast x1...
4a2cb417075f45bd0f2691c6e06e4328e54653ad
timmy61109/Introduction-to-Programming-Using-Python
/examples/MatchDemo.py
370
3.921875
4
import re regex = "\d{3}-\d{2}-\d{4}" ssn = input("Enter SSN: ") match1 = re.match(regex, ssn) if match1 != None: print(ssn, " is a valid SSN") print("start position of the matched text is " + str(match1.start())) print("start and end position of the matched text is " + str(match1.span())...
cc6e632af3bba895d4e05d457f17049c20f8b4e1
timmy61109/Introduction-to-Programming-Using-Python
/examples/SubtractionQuizLoop.py
1,158
4.03125
4
import random import time correctCount = 0 # Count the number of correct answers count = 0 # Count the number of questions NUMBER_OF_QUESTIONS = 5 # Constant startTime = time.time() # Get start time while count < NUMBER_OF_QUESTIONS: # 1. Generate two random single-digit integers number1 = random.randint(0, ...
5939d5daba1f8b7ef4fd2803b3363ebe140c66e9
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_eight.py
919
3.78125
4
""" 程式設計練習題 2.2-2.10 2.8 計算能量. 請撰寫一程式,計算從起始溫度到最後溫度時熱水所需的能量。程式提示使用者數入多少公斤的水、起始溫度 及最後溫度。計算能量的公式如下: Q = M * (finalTemperature - initialTemperature) * 4184 此處的M逝水的公斤數,溫度是攝氏溫度,而Q是以焦耳(joules)來衡量的能量。 以下是範例輸出的樣本: ``` Enter the amount of water in kilograms: 55.5 Enter the initial temperature: 3.5 Enter the final Temperature...
81637bd0a27f1ebc4d3606549dc9bfc6e78277a6
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/two_one.py
395
4.03125
4
u""" 程式設計練習題 2.2-2.10 2.1 將攝氏溫度轉換成華氏溫度. 請撰寫一程式,從控制臺讀取攝氏溫度,接著將其轉換為華氏溫度,並顯示結果。轉換的公式如下: fahrenheit = (9 / 5) * celsius + 32 """ CELSIUS = int(input("Enter a degree in Celsius:")) FAHRENHEIT = (9 / 5) * CELSIUS + 32 print(CELSIUS, "Celsius is", FAHRENHEIT, "Fahrenheit")
97a050e009a2c1e53a1842a6c7de60a6d6148b90
timmy61109/Introduction-to-Programming-Using-Python
/examples/QuickSort.py
1,267
4.21875
4
def quickSort(list): quickSortHelper(list, 0, len(list) - 1) def quickSortHelper(list, first, last): if last > first: pivotIndex = partition(list, first, last) quickSortHelper(list, first, pivotIndex - 1) quickSortHelper(list, pivotIndex + 1, last) # Partition list[first..last] def pa...
2b6c63f938d13dc8103f3cb8d5f7261f04c4676c
timmy61109/Introduction-to-Programming-Using-Python
/examples/Decimal2HexConversion.py
745
4.375
4
# Convert a decimal to a hex as a string def decimalToHex(decimalValue): hex = "" while decimalValue != 0: hexValue = decimalValue % 16 hex = toHexChar(hexValue) + hex decimalValue = decimalValue // 16 return hex # Convert an integer to a single hex digit in a character ...
324bb0fd6f126c77d953ba9dc1096f8bdb0d9a50
timmy61109/Introduction-to-Programming-Using-Python
/examples/SierpinskiTriangle.py
2,218
4.25
4
from tkinter import * # Import tkinter class SierpinskiTriangle: def __init__(self): window = Tk() # Create a window window.title("Sierpinski Triangle") # Set a title self.width = 200 self.height = 200 self.canvas = Canvas(window, width = self.width...
d658665811319f345a62ca59cfce5fbec059a735
timmy61109/Introduction-to-Programming-Using-Python
/examples/DefaultListArgument.py
275
4
4
def add(x, lst = []): if x not in lst: lst.append(x) return lst def main(): list1 = add(1) print(list1) list2 = add(2) print(list2) list3 = add(3, [11, 12, 13, 14]) print(list3) list4 = add(4) print(list4) main()
10eda90db24a3fcf34881935a01327d229bc484f
timmy61109/Introduction-to-Programming-Using-Python
/examples/CircleWithPrivateRadius.py
333
3.765625
4
import math class Circle: # Construct a circle object def __init__(self, radius = 1): self.__radius = radius def getRadius(self): return self.__radius def getPerimeter(self): return 2 * self.__radius * math.pi def getArea(self): return self.__radius * self.__rad...
bf8d3d46a74e9da8fe560231ceb161cd57a3316d
timmy61109/Introduction-to-Programming-Using-Python
/examples/MergeSort.py
1,246
4.21875
4
def mergeSort(list): if len(list) > 1: # Merge sort the first half firstHalf = list[ : len(list) // 2] mergeSort(firstHalf) # Merge sort the second half secondHalf = list[len(list) // 2 : ] mergeSort(secondHalf) # Merge firstHalf with secondHalf into list ...
6f72ca0fb36414b3656d118a3d32ecd2b001af71
timmy61109/Introduction-to-Programming-Using-Python
/examples/ControlAnimation.py
2,360
4.0625
4
from tkinter import * # Import tkinter class ControlAnimation: def __init__(self): window = Tk() # Create a window window.title("Control Animation Demo") # Set a title self.width = 250 # Width of the self.canvas self.canvas = Canvas(window, bg = "white", width ...
674a0def98a2f37c3dae8cf1ce070c767431b66a
timmy61109/Introduction-to-Programming-Using-Python
/examples/EfficientPrimeNumbers.py
1,451
4.15625
4
def main(): n = eval(input("Find all prime numbers <= n, enter n: ")) # A list to hold prime numbers list = [] NUMBER_PER_LINE = 10 # Display 10 per line count = 0 # Count the number of prime numbers number = 2 # A number to be tested for primeness squareRoot = 1 # Check whether numbe...
d5c03365561b6847a3d30d9bf15476235319df44
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/three_eight.py
1,278
3.65625
4
""" 程式設計練習題 2.2-2.10 3.8 財務應用:貨幣單位. 請解決範例程式3.4 ComputeChange.py的float轉成int導致的精確度遺失,以輸入「分」(cents)方式 解決。 """ from ast import literal_eval # Receive the amount amount = literal_eval(input("Enter an amount in cents, e.g., 1156: ")) # Convert the amount to cents remainingAmount = int(amount) # Find the number of one do...
f077e375871aed2d815b8c0d15babdd3f2a54414
timmy61109/Introduction-to-Programming-Using-Python
/examples/TestPassMutableObject.py
544
4.09375
4
from Circle import Circle def main(): # Create a Circle object with radius 1 myCircle = Circle() # Print areas for radius 1, 2, 3, 4, and 5. n = 5 printAreas(myCircle, n) # Display myCircle.radius and times print("\nRadius is", myCircle.radius) print("n is", n) # Print a table of ...
3f340f323e9932e48ebbe5212fcef638772ccb13
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/homework1_1.py
129
3.953125
4
"""作業一 Loop, List.""" list1 = [1] for value in range(1, 11): print(list1) list1.append(value + list1[value - 1])
3eea73798a4ddc9043f2123d5ba6f919ca239929
timmy61109/Introduction-to-Programming-Using-Python
/examples/DataAnalysis.py
496
4.15625
4
NUMBER_OF_ELEMENTS = 5 # For simplicity, use 5 instead of 100 numbers = [] # Create an empty list sum = 0 for i in range(NUMBER_OF_ELEMENTS): value = eval(input("Enter a new number: ")) numbers.append(value) sum += value average = sum / NUMBER_OF_ELEMENTS count = 0 # The number of elements above ave...
4bf722a50c7e125cfcc433539edc546b47a0e4b6
timmy61109/Introduction-to-Programming-Using-Python
/examples/CountEachLetter.py
736
3.84375
4
def main(): filename = input("Enter a filename: ").strip() infile = open(filename, "r") # Open the file counts = 26 * [0] # Create and initialize counts for line in infile: # Invoke the countLetters function to count each letter countLetters(line.lower(), counts) # Display resu...
255e39ff64323b2afa0102ac92302511229317d6
timmy61109/Introduction-to-Programming-Using-Python
/examples/TwoChessBoard.py
1,263
4.15625
4
import turtle def main(): drawChessboard(-260, -20, -120, 120) # Draw first chess board drawChessboard(20, 260, -120, 120) # Draw second chess board turtle.hideturtle() turtle.done() # Draw one chess board def drawChessboard(startx, endx, starty, endy): # Draw chess board borders turtle.pens...
1759318a2937df482d020000af5d574311dc572d
timmy61109/Introduction-to-Programming-Using-Python
/examples/RandomCharacter.py
662
3.78125
4
from random import randint # import randint def getRandomCharacter(ch1, ch2): """Generate a random character between ch1 and ch2.""" return chr(randint(ord(ch1), ord(ch2))) def getRandomLowerCaseLetter(): """Generate a random lowercase letter.""" return getRandomCharacter('a', 'z') def getRandomU...
3e2002d56082c63e9880ef0f2a9b2012b89a6e6c
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/three_two.py
1,003
4.03125
4
""" 程式設計練習題 2.2-2.10 3.2 幾何:大圓距離. 撰寫一程式提示使用者輸入球面上兩點,並計算出這兩點間在圓表面的最短距離。 地球半徑平均6371.01km。 d = RADIUS * acos(sin(x1) * sin(x2) + cos(x1) * cos(x2) * cos(y1 - y2)) 以下是程式的執行結果: ``` Enter point 1 (latitude and longitude) in degrees: 39.55, -116.25 Enter point 2 (latitude and longitude) in degrees: 41.5, 87.37 The distance...
705f0333cd9c94331f8963d40270a1bebb6ab135
timmy61109/Introduction-to-Programming-Using-Python
/own_practice/one_twenty.py
764
3.703125
4
""" 程式設計練習題 1-6 1-20 Turtle:畫一矩形體. 撰寫一程式,顯示矩形體。 """ import time from turtle import Turtle TURTLE = Turtle() TURTLE.showturtle() TURTLE.goto(50, 0) TURTLE.goto(50, -40) TURTLE.goto(0, -40) TURTLE.goto(0, 0) TURTLE.penup() TURTLE.goto(10, 20) TURTLE.pendown() TURTLE.goto(50 + 10, 0 + 20) TURTLE.goto(50 + 10, -40 + ...
2b1e7281a5c4fdb8bdfa12301ddba38a9f953f94
oskarblo02/exercises
/022list_name.py
164
3.546875
4
name_list = [] def addlist(name): for i in range(50): name_list.append(name) return print(name_list) print(addlist(input('ditt namn: ')))
c8acc009f326bba9ec6a4a5a2d31c317077b0113
marksameh19/mancala
/functions/main.py
3,361
4.03125
4
import global_settings from game import game while(True): mode = 0 print("1. human against human") print("2. human against ai") print("3. exit") while(True): userinput = input("choose which mode to play: ") if(userinput == "1"): mode = 1 break elif(us...
ec569b9b7975319724f3cc613fe4c45587fda197
peteasy/estrutura-de-dados
/AC 10 - Estrutura de dados - Merge sort.py
1,798
4.34375
4
# Estrutura de dados # Atividade Contínua 10 # Alunos: # André Niimi RA 1600736 # Caique Tuan RA 1600707 # Gustavo Andreotti RA 1600044 #Linguagem de programação utilizada: Python # inicio da função recursiva def mergeSort(lista): # Dividindo a lista em duas pa...
770102a24bd87f633645599dc126511fef189dd8
raghavatgithub/Hello-World
/Project_Final - Copy.py
27,467
3.859375
4
from tkinter import * import sqlite3 from tkMessageBox import * con=sqlite3.Connection("Project database") cur=con.cursor() cur.execute("create table if not exists member(EmailU varchar2(20) primary key,First name varchar2(9),Last name varchar2(9),Mobile number(11),address varchar2(30),Password varchar2(15))") cu...
b371194186fe7f5de4958638626a731701c4a22b
Aquassaut/Serpentide
/Segment.py
1,211
3.96875
4
from constants import * from math import sin, cos, pi class Segment: """ Defines a segment with a length of 1 according to its starting point and its direction """ def __init__(self, x, y, dct): assert dct <= 3 and dct >= 0 self.x = x self.y = y self.dct = dct def mov...
43bc9e6f5d5d844cda2887a0c55fd88ea24497da
wjr0102/Leetcode
/Medium/Trie_Tree.py
1,806
4.0625
4
class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self, word: str) -> None: """ Inserts a word into the trie. """ # print("Insert %s"%word) node = self.root for c in word: ...
d6fa40520eed414c30c468bcd27765412ffa19f5
wjr0102/Leetcode
/Easy/Middle_Node.py
344
3.765625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head: ListNode) -> ListNode: fp = head sp = head while fp and fp.next: sp = sp.next fp = fp.next...
0ff9c9b0aeefe4b689b10d718addaf4b34635a92
wjr0102/Leetcode
/Easy/Majority.py
1,175
3.71875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-03-29 21:10:12 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-03-29 21:22:10 def majorityElement(nums): """ :type nums: List[int] :rtype: int """ dic = {} for num in nums: if dic.__contains__(...
363d786add9a3507ab2808c76363eb6fd3adbbd7
wjr0102/Leetcode
/Medium/Integer to Roman.py
2,227
3.671875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2018-12-17 00:06:23 # @Last Modified by: Jingrou Wu # @Last Modified time: 2018-12-17 00:38:15 # Input range: [1,3999] def intToRoman2(num): # divide the number thousand = num // 1000 hundred = (num // 100) % 10 ten = (num //...
cf12b1f7b9196c8b8a431746aac4636d1062f029
wjr0102/Leetcode
/Medium/Swap_Pairs.py
839
3.84375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head: return None node1 = head node2 = head.next if not node2: ...
39be6f6875de70abe7e3613d526adc7298b8acd4
wjr0102/Leetcode
/Medium/Gray_code.py
1,351
3.671875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-04-04 13:24:21 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-04-04 19:23:56 ''' G(i) = i ^ (i/2); 如 n = 3: G(0) = 000, G(1) = 1 ^ 0 = 001 ^ 000 = 001 G(2) = 2 ^ 1 = 010 ^ 001 = 011 ...
6bfb64ca94d7670bada63dfcd9229cba6baa3d25
wjr0102/Leetcode
/Easy/MinCostClimb.py
1,094
4.21875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-05-07 01:46:49 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-05-07 01:53:03 ''' On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two s...
690421a4a89a926506c86dda2e7b03a7a846c343
wjr0102/Leetcode
/Easy/addBinary.py
1,158
3.75
4
''' 67. 二进制求和 tips: list转string要求元素都为字符串 ''' class Solution: ''' 高精度加法——二进制版 ''' def addBinary(self, a: str, b: str) -> str: la = len(a) lb = len(b) def add(s1,s2): """ 要求s1的长度小于等于s2时的二进制高精度加法 Args: s1...
9a5d17afe593e265bda23221eadff2b9d83fb86c
Ash515/hacktoberfest2021-1
/Python/equal_subarrays.py
526
3.65625
4
# Find the index of the element in the array such that the sum of all the elements left to the index is equal to the sum of all the elements right to the index. print("enter list elements: ") sample = list(map(int, input().split())) sumi = 0 sum_left=[] for val in sample: sumi += val sum_left.append(sumi) ...
849e57081867107d996ccb2459f06fb89d257ebc
Ash515/hacktoberfest2021-1
/Python/sum_of_two_numbers.py
108
4.03125
4
num1=float(input('Write the first number:')) num2=float(input('Write the second number:')) print(num1+num2)
4ddb1334805625f56a0c04a57ce80a2165796f54
Ash515/hacktoberfest2021-1
/Python/GUI_sorting.py
4,567
3.5625
4
import tkinter as tk import random #Function to swap two bars that will be animated def swap(pos_0, pos_1): bar11, _, bar12, _ = canvas.coords(pos_0) bar21, _, bar22, _ = canvas.coords(pos_1) canvas.move(pos_0, bar21-bar11, 0) #canvas.itemconfig(pos_0, bar21-bar11, fill='yellow') canvas.move(pos_1,...
e7827a558cdeda6943d8c67f8ab234e13618db6d
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex22_Morphological Transformations.py
1,584
3.65625
4
# Morphological Transformations """ Opening is just another name of erosion followed by dilation. It is useful in removing noise, as we explained above. Here we use the function, cv2.morphologyEx() Closing is reverse of Opening, Dilation followed by Erosion. It is useful in closing small holes inside the fore...
c4dd541b364d0a493af3810f8580f045098d2dd4
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex17_ImageRotation.py
374
3.5625
4
# Program for rotatin of an image # rotates the image by degree with respect to center without any scaling import cv2 import numpy as np img = cv2.imread('messi5.jpg',0) rows,cols = img.shape M = cv2.getRotationMatrix2D((cols/2,rows/2),27,1) dst = cv2.warpAffine(img,M,(cols,rows)) cv2.imshow('Rotated Imag...
f7a5fe592f5c42ffa1b5d8f6d63d11d588403556
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex22_StructuringElementForMorphological Transformations.py
697
4.15625
4
# Structuring element """ We manually created a structuring elements in the previous examples with help of Numpy. It is rectangular shape. But in some cases, you may need elliptical/ circular shaped kernels. So for this purpose, OpenCV has a function, cv2.getStructuringElement(). You just pass the shape and size...
4d777c7fe80e213e8c01615b69750ab20732c583
MattCrutchley/python_excersises
/applications/functions.py
370
4.0625
4
def hello(name,age): greeting = "hello " + str(name) + " you are " + str(age) +" years old" return greeting def age (dob): age = 2020 - dob return age dob = int(input("enter the year you where born")) name = input("enter your name") print(hello(name,age(dob)) def pletters(greeting): for char in greeting print...
19c87e27a36f1547b692b45a901ce06d8b5dc60e
njsdias/automated_sw_test_python
/1_refresh_python/10_passing_functions.py
586
3.890625
4
import os os.system("clear") def methodception(another): return another() def add_two_numbers(): return 35 + 77 # print(methodception(add_two_numbers)) ## lambda function # print(methodception(lambda: 35 + 77)) # declarative or functional programming # usefull when we are working with data my_list = [13, ...
6b0b4068cb73f0b37189703f8e0046f203259d94
njsdias/automated_sw_test_python
/1_refresh_python/7_classes_objects_advance.py
1,094
3.84375
4
# classmethod and staticmethod ## Student Class class Student(object): """docstring for Student.""" def __init__(self, name, school): super(Student, self).__init__() self.name = name self.school = school self.marks = [] def average(self): return sum(self.marks) / l...
af0aa9ae06659cd275bb93ffd98f2bee27ead545
Tozman99/JeuDeCombatPartieTir
/projectiles.py
599
3.5625
4
import pygame class Projectile(pygame.sprite.Sprite): def __init__(self, x, y, taille, direction, image): self.x = x self.y = y self.taille = taille self.direction = direction self.image = image self.rect = pygame.Rect(self.x, self.y, self.taille[0], self.taille[1]) def afficher(self, surface): py...
da60d5b35c0c7be1a238dd303ce6ce1f07d9ae80
Max-Fu/MNISTPractice
/Digits_With_Neural_Network.py
1,035
4.21875
4
#!/usr/bin/python #Import data and functions from scikit-learn packets, import plotting function from matplotlib from sklearn.neural_network import MLPClassifier import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm #load the digits and asign it to digits digits = datasets.load_digits...
afaeeaacdd727241728cd009634681c70153699f
ramushetty/CSPP1
/day_5/GuessMyNumber/GuessMyNumber/guess_my_number.py
430
3.765625
4
#Guess My Number Exercise def main(): #s = raw_input() #your code here m_m = 50 l_l = 0 h_h = 100 i_i = 'l' g_g = 0 while (i_i != 'c'): print(m_m) i_i = input("enter h to guess the number is too high,'l' if number is low 'c' indicate number is correct") if(i_i=='h'): h_h=m_m m_m=(h_h+l_l)//2 elif...
c4bbdc40782b90e3bef4373e3a384df5b5bda57b
ramushetty/CSPP1
/day_5/p3 (2)/p3/square_root_bisection.py
692
4.0625
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(): ''' bisection ''' s_s = int(input()) # epsilon and step are initialized ...
c2e859effb367bbd7ddf72285b5f7ee240deb8d2
ramushetty/CSPP1
/day_3/iterate_even_reverse.py
51
3.8125
4
a=10 print("hello!") while a>0: print(a) a=a-2
2fd44882878ff55c7128ff2e6ce243e323dcee40
sdjunaidali/dice
/interface.py
726
3.59375
4
import d6 import d20 import sys while True: try: type = input("Please enter the type of die you want to roll\n(d6 or d20): ") num = int(input("Enter the number of die you want to roll: ")) myResult = [] if type == "d6": pri...
19115600647d00d9acebfb4ce1f6f41d74b67924
Ing-salcedo/Exercism_Python
/sum-of-multiples/sum_of_multiples.py
299
3.65625
4
def sum_of_multiples(limit, multiples): sum = 0 lowest_multiply = sorted(multiples)[0] if len(multiples) != 0 else 0 for i in range(lowest_multiply, limit): for j in multiples: if j != 0 and i % j == 0: sum += i break return sum
ff467efbfd95363b36e2e88a5543c7d59c09cdbf
timo-bronseth/student-record-manager
/src/ExceptionHandling.py
4,231
3.765625
4
# ------------------------------------------------------------------------------------- # Timo Brønseth, January 2020. # ------------------------------------------------------------------------------------- class ExceptionHandlingClass: """All input queries to the user are handled via this class. First, inpu...
c42e9e31a2ffd2d59b576aabef22283c4a7ed0ee
Kunika28/positive-numbers-in-a-list
/list.py
184
3.8125
4
list1=[12,-7,5,64,-14] for num in list1: if num>=0: print(num,end=",") list2=[12,14,-95,3] for num2 in list2: if num2>=0: print(num2,end=",")
5058b9265da455110f041cc25e2b1a1842fb34d8
ozgurfiratcelebi/UdacityWeatherTrends
/WeatherTrends.py
958
3.546875
4
""" istanbul verilerini al Dünyanın sıcaklık değerlerini al csv leri python ile açgrafiği dök Şehriniz, küresel ortalamaya kıyasla ortalama olarak daha sıcak mı yoksa daha soğuk mu? Fark zaman içinde tutarlı oldu mu? Şehrinizin sıcaklıklarındaki zaman içindeki değişimler, küresel ortalamadaki değişikliklerle karşıla...
6da441db203174f2ba781c98d26eaf7149745598
tainenko/Data-Structure-and-Algorithmic
/Course1 Algorithmic Toolbox/Week5/primitive_calculator.py
1,335
3.984375
4
# Uses python3 import sys def optimal_sequence(n): sequence = [] while n >= 1: sequence.append(n) if n % 3 == 0: n = n // 3 elif n % 2 == 0: n = n // 2 else: n = n - 1 return reversed(sequence) def dynamic_sequence(n): sequence=[] ...
9fdfd978d2c141649aa3d16892c97c9d09e47893
tainenko/Data-Structure-and-Algorithmic
/Course1 Algorithmic Toolbox/Week2/lcm.py
395
3.75
4
# Uses python3 import sys def gcd_naive(a, b): while b!=0: a=a%b if a==0: break b=b%a current_gcd =a if a!=0 else b return current_gcd def lcm_naive(a, b): gcd=(gcd_naive(a,b)) lcm=gcd*(a//gcd)*(b//gcd) return lcm if __name__ == '__main__': input = sys.s...
cfcf599e3264dabc0b063edf6e4a3a554a22830e
tainenko/Data-Structure-and-Algorithmic
/Course3 Algorithms on Graphs/Week2/acyclicity.py
894
3.53125
4
#Uses python3 import sys def acyclic(adj): visited=[] path=[] for u in range(len(adj)): if u not in visited and explore(u,adj,path,visited): return 1 return 0 def explore(u,adj,path,visited): if u in path: return True #add the vertex u to visited and path list ...
afe93a41c67a025389c0101436fb05079f664a7a
kakashi-wells/python-basics
/for.py
87
3.578125
4
numbers = [1,2,3,4,5,20] nombre = "Arthur Wells" for elemento in nombre: print(elemento)
6ea67fe9633ceb8c5d0c7bf8afb067dcf9ad06f7
pedromesmer/python-speech-recognition
/src/db.py
5,282
3.609375
4
import sqlite3 import os def realPath(): return os.path.dirname(os.path.realpath(__file__)) def wait(text = '\nTecle Enter para continuar'): input(text) def create(): # o python não assume o caminho do arquivo como raiz, essa função faz esse 'ajuste técnico' filePath = realPath() conn = sqlite3....
7dbab4080831e5bbc9cee498cd3436d9e61cea39
Jaisinghani/AutomataFromRNN
/generator.py
353
3.828125
4
import random chars = 'etaoinsmpru' #num = int(input('How long do you want the string to be? ')) #How long do you want the string to be? 10 word_list=[] number=[3,4,5,6,7] for num in number: for i in range(50): str = [] for k in range(1, num+1): str.append(random.choice(chars)) str = "".join(str) word_l...
e7931aaecf8b518c31002176ef1f49f02bafe296
bronzeRaf/ai-models
/Netflix/main.py
5,108
3.5
4
import numpy as np import kmeans import common import naive_em import em # Read toy data X = np.loadtxt("toy_data.txt") X_netflix_incomplete = np.loadtxt("netflix_incomplete.txt") X_netflix_complete = np.loadtxt("netflix_complete.txt") # Parameters K = 1 seed = 1 # Testing the Kmeans along K (number of clusters) and...
028692a752e6b44f2aa073dc03c760846c2281a7
Mezheneva/ITMO-Python
/lesson 2/birthday.py
266
3.921875
4
nowDay = 4 nowMonth = 10 nowYear = 2019 day = int(input('Enter day>')) month = int(input('Enter month>')) year = int(input('Enter year>')) if (month > nowMonth) or (month == nowMonth and day > nowDay): print (nowYear - year - 1) else: print(nowYear - year)
475e9cfb8b043e59c74717b57aaec3b5d01e1532
Gabrihalls/Estudos-de-python
/desafios/dsf016.py
253
3.640625
4
import math print('-'*20,'DECIMO-SEXTO DESAFIO','-'*20) nome = input('Olá , digite seu nome:') num = float(input('{},por favor escolha um número:'.format(nome))) ni = (math.trunc(num)) print('O seu número de uma forma inteira é: {}'.format(ni))
e070f5c318c6b44e4d5661509b855ff82f2621d7
Gabrihalls/Estudos-de-python
/desafios/dsf003.py
244
4.125
4
print('-----------------------TERCEIRO DESAFIO-----------------------') primeiro = int(input('Qual primeiro número de sua soma?')) segundo = int(input('Qual segundo número de sua soma?')) print('O resulta de sua soma é:',primeiro+segundo)
dbd2d7f4af28f43a5b3ef927627abb706c181eb7
Mohanbarman/hackerrank-problems
/DayOfProgrammer/main.py
760
4.09375
4
""" Hackerrank - Day Of Programmer. 1. Calculate day of the year in Russia. 2. Years -> 1700 - 2700 3. From 1700 to 1917 : Julian calender. 4. From 1919 : Gregorian calender. 5. 1918 of 31st jan : Julian calender. ***After 31st jan 14th feb came in 1918*** 6. 1918 of 14th feb : Gregorian calender. * In both calend...
0e71cb0ac7dd5ccadf9142fffff83b37403cbd52
linkpark/study
/pythonProgram/pythonForDataBase/SQLiteHandler.py
1,039
3.53125
4
#!/usr/bin/python # Filename: SQLiteHandler.py from BaseHandler import*; import sqlite3; class SQLiteHandler(BaseHandler): def __init__(self): BaseHandler.__init__(self); print "SQLiteHandler created successful!"; def connectDataBase(self,baseName): self.conn = sqlite3.connect(baseName); self.cursor...
9614b6922dcfbb9ed5a1184543ce999da5cf0238
linkpark/study
/pythonProgram/pythonForProcess/thread_2.py
591
3.765625
4
#!/usr/bin/python # Filename: thread_2.py import threading; import time; class ThreadDemo(threading.Thread): def __init__(self,index,create_time): threading.Thread.__init__(self); self.index = index; self.create_time = create_time; def run(self): time.sleep(1); print(time.time() - self.create_time),"\t"...
d24d68173565aefbd768a8378c9d9ada9d9e4bb0
blackhen/Python
/gradex.py
416
3.859375
4
'''Grade''' def grade(med, mid): '''grade''' if med <= 100 and mid <= 100: med2 = med*30/100 mid2 = mid*70/100 grad = med2+mid2 if grad >= 80: print 'A' elif grad >= 70: print 'B' elif grad >= 60: print 'C' elif grad >= ...
bbb2bfad8385c47b1e0f39508806995fbecd31a5
blackhen/Python
/patland.py
796
3.53125
4
'''patland''' def pat(num): '''check''' num = int(num) while num >= 0: fff = ['a king.', 'a queen.', 'nobody.'] for i in range(num): word = raw_input() bbb = 0 while word[-1] == 'a': bbb = 1 break while word[-1] ...
8eec237f290ebf572b469d67fe8b1a0a7042d6ad
blackhen/Python
/center.py
223
3.796875
4
'''center''' def center(): '''cen''' wwww = input() letter = raw_input() lengh = len(letter) space = wwww - lengh space2 = space/2 space3 = ' '*space2 print space3 + letter + space3 center()
40968f50bbd929cde9f0f5777c810e3b64ed7300
blackhen/Python
/primetest.py
910
3.921875
4
'''primes''' def prime(number, loop, check): '''primes''' if number >= 0: if loop > number: pass elif loop % 2 == 0 and loop != 2: prime(number, loop+1, check) elif loop % 3 == 0 and loop != 3: prime(number, loop+1, check) elif loop % 4 == 0 an...
ac92d16f89772e50084e5f5d4c4dcb8a9d75476e
blackhen/Python
/classroom.py
363
3.515625
4
'''classroom''' def classroom(aaa): '''classroom''' colum = aaa row = aaa lis = [] for i in range(colum): lid = [] for i in range(row): num = input() lid.append(num) lis.append(lid) for i in range(aaa): lis[i].sort() lis.sort(reverse=Tr...