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 |
|---|---|---|---|---|---|---|
87463e27c0896686c1556a791d28315e7ec82808 | deek11/practice_python | /Hangman.py | 443 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This script is used create the game of Hangman
"""
import PickAWord
import GuessLetters
def play_hangman():
word = PickAWord.pick_a_word()
print word
GuessLetters.guess_letters(word)
def main():
play = 'y'
while play == 'y':
play_hangman... |
0d27c9844e556d3ae480c4b33b5e20bab7f61164 | deek11/practice_python | /RockPaperScissors.py | 1,502 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This script is used to Make a two-player Rock-Paper-Scissors game.
"""
def main():
print "Rock Paper Scissors!"
print "Rules :- \n" \
"0 - Rock \n" \
"1 - Paper \n" \
"2 - Scissors"
continue_play = "y"
while continue_pla... |
01dd8d67ceaad408cb442d882cf3c4c08f3eb445 | eduardomrocha/dynamic_programming_problems | /tabulation/python/06_can_construct.py | 1,574 | 4.25 | 4 | """Can construct.
This script implements a solution to the can construct problem using tabulation.
Given a string 'target' and a list of strings 'word_bank', return a boolean indicating
whether or not the 'target' can be constructed by concatenating elements of 'word_bank'
list.
You may reuse elements of 'word_bank'... |
326a3bc0283e5864a9b7f1930410749884f3fdbc | eduardomrocha/dynamic_programming_problems | /tabulation/python/08_all_construct.py | 2,053 | 4.34375 | 4 | """All construct.
This script implements a solution to the all construct problem using tabulation.
Given a string 'target' and a list of strings 'word_bank', return a 2D list containing
all of the ways that 'target' can be constructed by concatenating elements of the
'word_bank' list. Each element of the 2D list shou... |
7f9a7bfea4bef71941a2ae9ca40f9c31290b96df | onurrkarasu/AdamAsmaca | /adamAsmaca.py | 520 | 4.03125 | 4 | name=input("Enter Name:")
print("Welcome"+ name +"Hadi Adam Asmaca Oynayalım")
tahmin_metni=""
can=10
gizliKelime="Türkiye"
while can>0:
char_left=0
for char in gizliKelime:
if char in tahmin_metni:
print(char)
else:
print("*")
char_left+=1
if char_left==0:
print("Kazandınız")
break
ta... |
f6d6484b84550580fe2941e92fee20054c66d468 | aakhedr/algo1_week2 | /part3/quickSort3.py | 2,470 | 4.21875 | 4 | def quickSort(A, fileName):
quickSortHelper(A, 0, len(A) - 1, fileName)
def quickSortHelper(A, first, last, fileName):
if first < last:
pivot_index = partition(A, first, last, fileName)
quickSortHelper(A, first, pivot_index - 1, fileName)
quickSortHelper(A, pivot_index + 1, las... |
09cf03248d9c147199db67c42fa7a7cb86d9e163 | acviana/advent-of-code-2019 | /day-3/day-3-code.py | 4,301 | 3.734375 | 4 | '''
https://adventofcode.com/2019/day/3#
'''
class Wire:
def __init__(self, instructions):
self.instructions = instructions.split(',')
self.wire_route = [(0,0)]
def distance_to_point(self, point):
for step in range(len(self.wire_route)):
if self.wire_route[step] == point:... |
f1a0071db11c10a175bdf28998709ba519ac7371 | liuweixin2014/CS-418-Project | /hw/reference_alignment/getFoodInspection.py | 2,452 | 3.515625 | 4 | import csv
import json
def convertDictToString(thisDict):
myString = ''
count = 0
for x in thisDict:
if count == 0:
myString = x
count += 1
elif',' in x:
myString = myString + ',' + '"' + x + '"'
else:
myString = myString + ',' + x
... |
306a94ff2098b1ad109481e00874cd6ea046e4f1 | jlin22/hacker-rank-python | /minimum_bribes.py | 526 | 3.5625 | 4 | def minimum_bribes(q):
'''Input:
q is an array of people, a permutation of 1-len(q)
People can bribe each other, swapping positions
People can only be bribed twice, so swapped twice
If a state is too chaotic, return 'Too chaotic'
'''
inversions = 0
for i in range(len(q)):
if q[i... |
8c14a65e5d96c5cfdcb0493e69173b2db6200175 | JeremyMorrison/Math4330 | /main.py | 2,564 | 3.765625 | 4 | def LeastSquares(x,y):
"""Solve for degree 4 interpolating polynomial
Build a degree 4 vandermonde matrix A, then use Mod G.S. to compute QR factorization of A, Next compute the inverse of Q, and use back substitution to solve Rb=Q^*y, and finally use b for coefficients of degree 4 interpolating polynomial.
Arg... |
3d90296802c026cb627b819186627327b6c8b367 | pakping/python-Data-type | /python.py | 1,546 | 3.65625 | 4 | def isEmpty (self):
return self.head == None
def add(self,item):
tmp = Node (item)
tmp.setNext(self.head)
self.head =tmp
def size(self):
cur =self.head
count = 0
while cur != Node:
count += 1
cur = cur.getNext()
return count
def search(self,time):
cur... |
0417492bf14cef4e0e68cc56f29977e3f3c50ad1 | ZGriffinLab/scripts | /renamer.py | 401 | 3.65625 | 4 | #----------------------------
# renamer.py
# Ariel Sibille 2015
# renames all the files in a
# folder. intended for when
# you mess up a ptcpt name
#----------------------------
import os
def renamer () :
for filename in os.listdir(".") :
if filename.startswith("wrong prefix here ex: c02") :
os.rename(filename,... |
20b2ee96ffe2969985b02dd57c89ca0a111c9e0d | dnr101/Neural-Net-Image-Proc | /NNetImageProc.py | 6,347 | 3.59375 | 4 | #!/usr/bin/python
'''
Example of Neural Net from AI App Prog
CSDP 638
Created on Jul 14, 2010
@author: David Raizen
'''
import random
import math
from PIL import Image
#Constants
INPUT_NEURS = 3
HIDDEN_NEURS = 3
OUTPUT_NEURS = 1
MAX_SAMPLES = 200
#ACTION_LABLES = ['Attack', 'Run', 'Wander', 'Hide']
LEARN_RATE = 0.2 ... |
eb26a933323a8aed9dd951eb60712038432aeff8 | YuSheng05631/CrackingInterview | /ch1/1.2.py | 193 | 3.875 | 4 | """
Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
"""
def reverse(string):
return string[::-1]
string = "abcde"
print(reverse(string))
|
f66e6d8773c886adb6c1932f8904ef545b2e2476 | YuSheng05631/CrackingInterview | /ch4/4.5.py | 1,184 | 4.15625 | 4 | """
Implement a function to check if a binary tree is a binary search tree.
"""
import Tree
def isBST(bt):
if bt.left is None and bt.right is None:
return True
if bt.left is not None and bt.left.data > bt.data:
return False
if bt.right is not None and bt.right.data < bt.data:
retur... |
f7e15b54b6c5c5fa1749e3cd6a3f1bf8737627a2 | YuSheng05631/CrackingInterview | /ch5/5.2.py | 582 | 4.09375 | 4 | """
Given a real number between 0 and 7 (e.g., 0.72) that is passed in as a double, print the binary representation.
If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR."
"""
def getBinary(num):
if num >= 1 or num <= 0:
return "ERROR"
b = ""
while num >... |
3f7c0cec28a9295cbbf27e0db862b0f1a8b16e32 | YuSheng05631/CrackingInterview | /ch5/5.7.py | 915 | 3.71875 | 4 | """
An array A contains all the integers from 0 through n, except for one number which is missing.
In this problem, we cannot access an entire integer in A with a single operation.
The elements of A are represented in binary, and the only operation we can use to access them is "fetch the jth bit of A[i]," which takes c... |
91582a67aea3db88f5b2de411ed596b65651564a | YuSheng05631/CrackingInterview | /ch4/4.4.py | 726 | 3.984375 | 4 | """
Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).
"""
import Tree
def createLinkedList(bt):
ls = list() # list的集合
ls.append([bt])
lt = list() # 臨時的list
lt.append(bt)
w... |
119da432f72da47b096285e11dc4d7cfcc4f0545 | krkimery/Netflix-Challenge | /NetflixCacheCreator.py | 14,121 | 3.53125 | 4 | import pickle
#from requests import get
#from array import array
#import numpy as np
def downloadTextFile():
for i in range(1, 18000):
fileName = "mv_" + str(i).zfill(7) + ".txt"
fileWrite = open(fileName, "w")
webAddress = "http://www.cs.utexas.edu/users/fares/netflix/training_data/" + fi... |
1c428f7cf06fa3b6113b2571221becade498a030 | fire-ferrets/cipy | /cipy/alphabet/alphabet.py | 1,452 | 4.46875 | 4 | """
The Alphabet class provides a general framework to embed alphabets
It takes a string of the chosen alphabet as attribute. This provides
the encryption and decryption functions for the ciphers with a performance
boost.
"""
class Alphabet():
def __init__(self, alphabet):
"""
Initialise an Alpha... |
c2ee818261c41b8a16efd5fb5d31e4de4d71aa9c | Kaue-Romero/Simulador-de-dado | /Simulador de Dado/Simulador_de_dado.py | 482 | 3.734375 | 4 | from random import randint
n1 = int(input('Quantos lados o dado tem ? '))
n2 = randint(1, n1)
while True:
n = str(input('Você que jogar o dado? ')).upper().strip()
while n not in 'SN':
n = str(input('Você que jogar o dado? [S/N] ')).upper().strip()
if n == 'S':
n2 = randint(1, n1)
... |
0c26e158842e1f3fcbd260a1115982c3a3303a6a | BenMarriott/1404 | /prac_02/exceptions.py | 1,036 | 4.28125 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur? When usings floating point numbers
2. When will a ZeroDivisionError occur? When attempting n/0
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
"""
"""""
try:
numerator = int(input("En... |
45cbb69ae304872ceee29f1cb720d2beb8541d4c | BenMarriott/1404 | /prac_02/lecture_03.py | 796 | 3.890625 | 4 | reg_days, fast_days = 4, 3
meat_normal = .850 * reg_days
meat_fast = .650 * fast_days
total_meat = meat_fast + meat_normal
steph_norm = .450 * 4
steph_fast = .300 * 3
steph_total = steph_fast + steph_norm
user = input("Ben or Steph?").capitalize()
while user == "Ben":
print("For 1 week of normal days Ben need {}kg'... |
48f2749c4d8843ecbc3d2c7fff9e7c26c81c89b2 | BenMarriott/1404 | /prac_01/number_sequence.py | 620 | 4.09375 | 4 | #x, y = int(input("Enter first number: ")), int(input("Enter second number: "))
#print(type(x), type(y))
#for x in range(y):
#menu_choice = "Q"
#while menu_choice != "Q":
menu_choice = input("Would you like to run the program?:" "\n" "(Y)es or (Q)uit")
while menu_choice != "Q":
y = int(input("Enter second number:... |
e5f992e04aff4f20a6b2b67e55b1f32ca60018b3 | ZackWhiteIT/pickem | /schedule_scraper.py | 3,299 | 3.625 | 4 | """
Scrapes an ESPN URL for schedule data
Returns an array of dictionaries containing game details
E.g. [game{away_team, home_team, away_rank, home_rank, away_abbr, home_abbr},...]
Displays dictionary as in a terminal as...
South Dakota State @ #13 TCU
Stephen F Austin @ Texas Te... |
8b32ac4e78714ad3ab3194c34804bddaf6a3ebd7 | Rcmaveric/Reloading-Press-Monitor | /Testing_and Examples_Section/Thread_EXT_Examples/Que_W_Lcok_Example.py | 730 | 3.515625 | 4 | import threading
import time, random
class Counter:
def __init__(self):
self.lock = threading.Lock()
self.value = 0
def increment(self):
self.lock.acquire() # critical section
self.value = value = self.value + 1
self.lock.release()
return value
counter = Counte... |
a1a6bf307369b7b8f98b2eaac41694bba690f961 | Rcmaveric/Reloading-Press-Monitor | /Testing_and Examples_Section/Gui_Examples/Dic2_test.py | 934 | 3.609375 | 4 | import csv
#Note to self: the way this works is the csv is turned into a class. The class name is the list ID which is Recipe[n],
#where N is the number of the recipe with 0 being the first line. After that the heading can be use as a dot atribut,
#IE Recipe[0].cartridge will give you the cartridge name of recipe 0.... |
25f92dd95eea6977334f334c91d38bf9f1dcffaf | liamvwood/Pi-Top-Repo | /math-game.py | 629 | 3.8125 | 4 | import random
number_of_tries = 0
while number_of_tries < 10:
first_number = random.randint(0,200)
second_number = random.randint(0,200)
answer = first_number + second_number
guess_correct = False
number_of_guesses = 0
while not guess_correct and number_of_guesses < 3:
guess = input... |
f2353c6b2304792e139ba927a9733759c67c4056 | sfrechou/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 853 | 3.890625 | 4 | #!/usr/bin/python3
"""Island Perimeter"""
def island_perimeter(grid):
"""Returns the perimeter of the island described in grid"""
per = 0
for row in range(0, len(grid)):
for cell in range(0, len(grid[row])):
if grid[row][cell] == 1:
if row <= 0:
per ... |
239d6a1cbcb96526c1e7127450b8e4cc0d64a859 | FR-heitor/python | /Python-exer-cond-break.py | 748 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 10 22:26:59 2020
@author: franc
"""
#forma 1
#contador numérico para cálculo
a = 0
#condicional
while a <= 20:
a += 1
#divisão para número inteiro
b = a % 2
if a == 15:
break
if b == 0:
print('Valor par:',a, 'resto da ... |
de21f505f5e02a3b5d7f2cd60aa67fb7cb8acdb3 | agarwaltanya06/DerivativeCalculator | /main.py | 13,957 | 4.28125 | 4 | #To get the required output, enter the function without spaces and with brackets in the input
#For example, (x+5), or (2/x), or (6*x), or (x*(2^x)), etc
class expr:
#assert: the class expr has an attribute 'expr'. This 'expr' attribute is represented in memory as a tree.
#Each node of that tree is an object of t... |
cf9ca4c3600e414faa01b80dcbc057ba62695cb9 | hardikvora200/Python | /Clustering/airline.py | 68,069 | 3.59375 | 4 | import pandas as pd
import numpy as np
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt
# reading a csv file using pandas library
airline=pd.read_excel("C:\\Users\\sanu\\Downloads\\Desktop\\Documents\\Excelr_1\\Python\\Clustering\\Assignments\\EastWestAirlines.xlsx")
###airline.rename({... |
115f3e4ab0f71068a21dbb2c1d72b872476742b8 | RodIba/NN | /BasicImageProcessor/simplepreprocessor.py | 809 | 3.609375 | 4 | import cv2 # imports required packages
class SimplePreprocessor:
#constructor requires two arguments, folowed by a third optional one.
#width: The target width after resizing
#height: The target height after resizing
#inter: an optional parameter used to control which interpolation algorithm is used when resizing
... |
595c2ad531d9f009aaf70f3ce9c6cde6aeee7a9e | koliadaKol/hw_2 | /11_spring.py | 558 | 3.890625 | 4 | import turtle
turtle.speed(1000)
def spring(n =1):
turtle.shape('turtle')
turtle.penup()
turtle.goto(-500,0)
turtle.pendown()
turtle.left(90)
for j in range(5):
for i in range(180):
turtle.right(1)
turtle.forward(3)
for i in range(90):
turtle.... |
e423486db398f338656a76911419658f940b898b | salmayasserahmed/Computer-Vision-Fundamentals | /Using Numpy/ColorSelection.py | 888 | 3.875 | 4 | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
#1. Read the Image
image = mpimg.imread("test.jpg")
#2. Print out some stats
print("This image is: ", type(image), "with dimensions", image.shape)
#3. Grab x and y of the image and make a copy to work on it
ysize = image.shape[0]
xsi... |
1f23b0479322beeeccbb72a7bca7f68b0b49fd4b | DOGANAY06/My-python-project- | /karakterbulmastring.py | 712 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 17 14:09:28 2019
@author: Doğan AY
"""
ad=input("Adını Giriniz=")
print("İlk Karakter",ad[0])
print("İkinci Karakter",ad[1])
print("Son karakter",ad[-1])
print("İlk üç karakter",ad[0:3])
print("İlk üç karakter",ad[:3])
print("Anne kızlık soyadı s... |
ca121fc655568e527847462262326e0348a6d290 | DOGANAY06/My-python-project- | /isimcevirme.py | 260 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 21:24:27 2019
@author: Doğan AY
"""
def terscevir(metin):
tershali=metin[::-1] #metni tam ters cevirir tek başına
return tershali
cumle=str(input("Metni giriniz="))
print(terscevir(cumle)) |
4adfccb1af74b2fb21d3b2a42acf2d530ec99263 | DOGANAY06/My-python-project- | /init.py | 1,185 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 15 13:22:19 2019
@author: Doğan AY
"""
sayi1=int(input("1.Sayıyı giriniz="))
sayi2=int(input("2.Sayıyı giriniz="))
class Islem4:
def __init__(self,sayi1,sayi2):
self.sayi1=sayi1
self.sayi2=sayi2
def topla(self):
return self.say... |
769ae2c27990e21214239a0e198eb6025e0b8508 | DOGANAY06/My-python-project- | /function.py | 1,712 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 20 11:22:52 2019
@author: Doğan AY
"""
import turtle
turtle.bgcolor("yellow")
turtle.pensize(5)
def heart():
for i in range(200):
turtle.right(1)
turtle.forward(1)
turtle.speed(0)
turtle.color("black","red")
turtle.begin_fill()
turtle.... |
e6439b914b276fbefa7e1dde95c38f4e60442835 | katlegoJKS/Animals-Part1-OOP-Basics | /cat.py | 270 | 3.6875 | 4 | from animal import Animal
class Cat(Animal):
def __init__(self,name,sound):
super().__init__(name,sound)
def eats(self):
return self.name
def sounds(self):
return "Meow"
cat1 = Cat('','')
#print(cat1.eats())
#print(cat1.sounds()) |
a4888285cfc1e8c4d3c7b098b149e72e4904eb35 | markymark5127/College-Ruled | /GUI.py | 7,259 | 3.765625 | 4 | from Tkinter import *
from tkFileDialog import *
filename = "Untitled"
docTitle = ""
lastName = ""
fullName = ""
teachName = ""
className = ""
dueDate = ""
def newFile():
global filename
filename = "Untitled"
text.delete(0.0, END)
def saveFile():
global filename
t = text.get(0.0, END)
f = op... |
7e5e56afb2acdeabf11e1a2f03926e0389b0a0eb | Alh1ra/First-Login | /Fifth.py | 2,330 | 3.90625 | 4 | # Python program to make first steps
''' Targets:
- Ask for user name:
- check in login.py (module) if name is correct
- if user name is not Alhira, increment counter in login.py
and give proper output.
- if user name is Alhira, a... |
2e00d3a9f5dc6d0f1c074113850ff7201ed7ecfa | prashantsahu99/tuple | /tuple4.py | 100 | 3.5 | 4 | t=eval(input("enter elements separated by comma in():"))
x,y=t[0:2]
print("x=%d"%x)
print("y=%d"%y)
|
219918fb26b89936acfa57d8b704e1eee040af53 | Pyk017/C | /DS/BFS.py | 1,304 | 3.984375 | 4 | from collections import defaultdict
class Graph:
def __init__(self, size):
self.size = size
self.graph = defaultdict(list)
self.visited = [False] * size
def add_edge(self, src, dest):
self.graph[src] = dest
self.graph[dest] = src
def bfs(self, start):
... |
2b0fa905ce030a8b3af48924a92371bfb768889f | liberbell/py15 | /csvope2.py | 693 | 3.5625 | 4 | import csv
# file = open("data_file/record.csv", "r")
# with file:
# read = csv.DictReader(file)
# for row in read:
# print(dict(row))
csv.register_dialect("tab", delimiter = "\t")
file = open("data_file/record_tab.csv", "r")
with file:
read = csv.reader(file, dialect="tab")
for row in read:
... |
5a530c11bf9ff825ace09f85299d8ac1419ce7a3 | nitishprabhu26/HackerRank | /Practice - Python/005_Loops.py | 760 | 4.46875 | 4 | if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i**2)
# The range() function
# The range function is a built in function that returns a series of numbers. At a minimum, it needs one integer parameter.
# Given one parameter, n, it returns integer values from 0 to n-1. For example... |
47e07549340524ff36d77c3e7ae130c3ac0dfbc6 | dineshgyawali/pythontasks3-7 | /Extra/Question6.py | 105 | 3.875 | 4 | text="Hello my name is abcde"
x=text.split()
for i in x:
if len(i)==5 or len(i)==2:
print(i)
|
b2693b64c7675189ed2e51183f68adde09998de1 | dineshgyawali/pythontasks3-7 | /Task6/Question1.py | 168 | 3.828125 | 4 | l1 = ["Apple", "Banana", "cherry", "avocado", "mango"]
l2=[]
for x in l1:
for a in x:
if a.isupper():
l2.append(x)
break
print(l2)
|
dbba9afad1492b58e5eb95b45023070284848565 | dineshgyawali/pythontasks3-7 | /Extra/LESSONS/polymorphism.py | 565 | 3.796875 | 4 | class Birds:
def __init__(self,type):
self.type=type
def show(self):
print("Bird type: ",self.type)
def display(self,color):
self.color=color
return self.color
class Snakes:
def __init__(self,name):
self.name=name
def show(self):
self.type="poisono... |
971743a7d752f5cbc4b0c77f1ba261713e69b4ab | asilvaferna/Boletin1-Python | /Domino/Domino.py | 317 | 3.5625 | 4 | def correctPieces(firstPiece, secondPiece):
aux = 0
for i in firstPiece:
for j in secondPiece:
if i == j:
aux = 1
if aux == 1:
return True
else:
return False
firstPiece = (3,4)
secondPiece = (5,6)
print(correctPieces(firstPiece, secondPiece))
|
6d20d166f6ddb74f2dbad0ad88202b1b64856833 | asilvaferna/Boletin1-Python | /MultiplicationTable/MultiplicationTable.py | 255 | 3.9375 | 4 | def generateTable(integerNumber):
for number in range(1, 10):
print(int(integerNumber) * number)
def generateTableWhile(integerNumber):
number = 1
while number <= 10:
print(number * int(integerNumber))
number += 1
|
583c789d1775673f864072a661b16fd909615a67 | mitrofanov-m/6_sem_labs | /4l_Hash_map/test.py | 1,437 | 3.703125 | 4 | from hash_map import HashMap
import random
title1 = \
'''
####################### Test of Map #########################
- creating
- len
- appending
- searching by key
- removing map
'''
print(title1)
print('1. Creating:')
mmap = HashMap()
print(f' mmap = {mmap}\n')
print('2. Appending:')
mmap[1] = "ooops"
mma... |
0c8b05910e9c48cd13ab7f7af48b5e9120fce7bd | GaurangX/ads | /P0/Task3.py | 3,875 | 4.375 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
import re
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area cod... |
219a8fe816e6bad703c55d6b75435fc761ace602 | supriya1110vuradi/Python-Tasks-Supriyav | /task4.py | 753 | 4.34375 | 4 | # Write a program to create a list of n integer values and do the following
# Add an item in to the list (using function)
# Delete (using function)
# Store the largest number from the list to a variable
# Store the Smallest number from the list to a variable
a = [1, 2, 3, 4, 5, 6]
hi = max(a)
lo = min(a)
print(hi)
pri... |
99d34ca90ca2351c5f881554e34c2a62ebd247fb | hvox/MIT-6.046J | /median-finding/test_finding.py | 915 | 3.515625 | 4 | import unittest
from finding import get_by_index
from random import randint
class TestScheduling(unittest.TestCase):
def test_median(self):
for _ in range(16):
arg = {randint(0, 2**10) for _ in range(2**randint(1, 11))}
expected_output = list(sorted(arg))[(len(arg) - 1) // 2]
... |
49de54a3b25450e39a9b3c4857c6754e854f4df8 | yaodecheng0217/Fengbian- | /练习/6-2.py | 940 | 3.8125 | 4 | '''
@Author: Yaodecheng
@Date: 2019-12-03 11:22:16
@LastEditors: Yaodecheng
'''
print('****************************')
movies = {
'妖猫传':['黄轩','染谷将太'],
'无问西东':['章子怡','王力宏','祖峰'],
'超时空同居':['雷佳音','佟丽娅'],
}
actor = input('你想查询哪个演员?')
#定义一个该演员所有出演电影的列表,初始化为空
include_list=[]
#遍历字典
for name in movies:
#如果演员出演了电影,则添加到出演电影列... |
8e72f211a28cc930c27297eb59225494bf44839c | kaparegime/Udemy-projects | /Milestone Project 1_ TicTacToe game.py | 3,756 | 4.0625 | 4 | from random import randint
board = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] # creat bord for collect cells from numlock which will use
position = []
print('Welcome to TIC TAC TOE game!!!')
game = input("Input 'Yes' for start game or 'No' if you don't want play: ").lower()
if game == 'yes':
player_1 = ''
... |
b7b188813f5f409fa1557633ad013982b6ef2296 | samhazemi/dascienceHM | /classactivity/week3/python/03-python/3/Activities/05-Stu_StoreManager/classhomework.py | 747 | 4.0625 | 4 | stor_dict={}
keep_going="Y"
while keep_going == "Y":
action_item=input("what you want me todo? (A),(R),(S)")
if action_item=="A":
item_to_be_added=input("what you want to be added")
number_of_item=input("how many do you want to added")
stor_dict[item_to_be_added]=number_of_item
elif action_item=="R... |
9430512297af2242566c250d147ff5573f89aaf0 | QuRyu/cs251 | /Project04/pca_cov.py | 9,770 | 3.546875 | 4 | '''pca_cov.py
Performs principal component analysis using the covariance matrix approach
Qingbo Liu
CS 251 Data Analysis Visualization, Spring 2020
'''
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
class PCA_COV:
'''
Perform and store principal component analysis results
'''
... |
9c518bf8db8e6f53c3624ae289d79b3674d82b99 | QuRyu/cs251 | /Project03/data.py | 15,836 | 3.6875 | 4 | '''data.py
Reads CSV files, stores data, access/filter data by variable name
Qingbo Liu
CS 251 Data Analysis and Visualization
Spring 2020
'''
import csv
import numpy as np
import os
import sys
import time
Types = ['numeric', 'string', 'enum', 'date']
class Data:
def __init__(self, filepath=None, headers=None... |
8e488771b4e8aa522e9246dc9f50aec625dbd872 | long2691/activities | /activity 5/comprehension.py | 1,521 | 4.15625 | 4 | prices = ["24", "13", "16000", "1400"]
price_nums = [int(price) for price in prices]
print(prices)
print(price_nums)
dog = "poodle"
letters = [letter for letter in dog]
print(letters)
print(f"we iterate over a string into al ist : {letters}")
capital_letters = [letter.upper() for letter in letters]
#long version of s... |
efbb12132eec613a1a580f9ad97262cf26f831c7 | luka319/portfelio_chemodanio | /config_parser/polygon_05.py | 1,291 | 3.984375 | 4 | import turtle
turtle.shape('turtle')
turtle.shapesize(2,2,1)
turtle.color('red', 'yellow')
turtle.width(5)
def side(long01, n01):
turtle.fd(long01)
turtle.lt(360/n01)
def polygon(long02, n02):
for z in range(n02):
side(long02, n02)
def poly_fill(long03, n03, color03, col3, fill):
tu... |
37b5ade35f1ca25487d6e6beaed7c0f532ebbfbb | irimina/trv_quiz_versions | /trivia_final.py | 4,190 | 3.9375 | 4 | import time
def intro():
print("Welcome to the Crimminal Justice Trivia game!")
name = input("What's your name?:")
print("Hello", name)
print(
"Today you will be quized on your knowlege about crime and the law by answering a few questions. Good Luck !"
)
print("-----------------------... |
685c843298695e8eb52cc52278958d31fd8dc711 | tommirrington/52167-Programming-and-Scripting-Final-Project | /05_iris_bfuncs_stats.py | 1,908 | 4 | 4 | #52167 Programming and Scripting
#Tom Mirrington 04/2018
#script combing scripts 01 - 04 to output max, min, mean and standard deviation using
#only python basic functions.
#define lists and input csv, write each line indec into a seperate list
petl = []
petw = []
sepl = []
sepw = []
y = 0
with open("data/iris.cs... |
4ea9e3580a7b1804d635a0c2a3945b3d60aa910a | Pashibo/course_Python | /HW_Python_001.py | 5,514 | 4.03125 | 4 | # Python. HW_1
# 1) Создать переменную типа String
str1 = "this_is_string"
print(str1)
# 2) Создать переменную типа Integer
# int целые числа
a = int(255)
print(a)
# 3) Создать переменную типа Float
b = (0.1+0.1+0.3)
print(b)
# 4) Создать переменную типа Bytes
message = "Hello world"
# string with encoding 'utf-... |
e86cd93b8e673fe4cc13b60778746e9631635f02 | lynochka/advent-of-code | /2020/day_18.py | 2,451 | 3.71875 | 4 | import re
# Part 1
def do_simple_math(expression):
expression = expression.replace("*", "@")
operator = "@"
total = 1
for value in re.findall("\d+|\+|@", expression):
if value.isnumeric():
if operator == "@":
total *= int(value)
elif operator == "+":
... |
ccd5218382ffe23b84fffc1e0d137feb35b0ea18 | andthenenteredalex/Allen-Downey-Think-Python | /thinkpy107.py | 404 | 4.125 | 4 | """ Allen Downey Think Python Exercise 10-7
This function checks if two words are anagrams and returns True if they are.
"""
def is_anagram(word_one, word_two):
one = sorted(list(word_one))
two = sorted(list(word_two))
if one == two:
return True
elif one != two:
return ... |
835d4da80ceb5652d9ea6b020814ba752daa73fb | vrcunha/db_sql_and_nosql | /sqlite/funcs/crud_sqlite.py | 2,966 | 3.53125 | 4 | import os
import sqlite3
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
def connect():
"""Connects to SQLite database."""
try:
connection = sqlite3.connect('sqlite_python.db')
# print('Connection Succefully')
return connection
except sqlite3.Error as e:
... |
d232f0751c754388ad340807e4e7adec5c50a5b8 | daviddlhz/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 288 | 3.6875 | 4 | #!/usr/bin/python3
def best_score(a_dictionary):
tmp = 0
empty = ""
if a_dictionary is None or a_dictionary == {}:
return None
for i in a_dictionary.keys():
if a_dictionary[i] > tmp:
tmp = a_dictionary[i]
empty = i
return empty
|
aa0616170bc2dbbd2dca519e550437bb0365ac12 | daviddlhz/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 403 | 4.25 | 4 | #!/usr/bin/python3
"""write to a text file"""
def write_file(filename="", text=""):
"""writes to a file
Keyword Arguments:
filename {str} -- name of file (default: {""})
text {str} -- text beingwritten (default: {""})
Returns:
int -- number of charaters
"""
with open(filena... |
ea20d0af98bd2d1cc16b6160dd644ad6274eeae0 | daviddlhz/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 272 | 3.65625 | 4 | #!/usr/bin/python3
"""Class with atributte private"""
class Square:
"""Square class with initialization
"""
def __init__(self, size):
"""Init
Arguments:
size {[private]} -- [size of square]
"""
self.__size = size
|
de05aa8c026cf4cdfc3f630ed88034645fd13563 | daviddlhz/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/1-last_digit.py | 338 | 3.890625 | 4 | #!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
n = (abs(number) % 10)
if number < 0:
n = n * -1
if n > 5:
messag = "and is greater than 5"
elif n < 6 and n != 0:
messag = "and is less than 6 and not 0"
else:
messag = "and is 0"
print("Last digit of {:d} is {:d} {:s}".format(nu... |
ef512cde834f205f9ad28ed5430e931a48bc911a | nunoi/euler | /old_python/p015.py | 267 | 3.953125 | 4 | #!/usr/bin/python
# see http://www.joaoff.com/2008/01/20/a-square-grid-path-problem/
def fac(n):
if n == 1:
return 1
else:
return n*fac(n-1)
n = 20
numerator = fac(2*n)
denominator = fac(n) * fac(n)
res = numerator/denominator
print res
|
3d927d5ca59e733841cee015da6d02e18682a0ab | nunoi/euler | /old_python/p003b.py | 661 | 3.921875 | 4 | #!/usr/bin/python
import sys
import random
import mutils
def Euclid(a, b):
while b != 0:
r = a % b
a = b
b = r
return a
def PollardRho(n):
i = 1
x = random.randint(0, n - 1)
y = x
k = 2
tried = set()
tried.add(x)
while True:
i = i + 1
x = (x ** 2 - 1) % n
if x in tried:
... |
6b7abf191517b6b49edd66e26f35640745d73cca | GaddipatiAsish/Natural-Language-Processing | /HW02/test.py | 366 | 3.875 | 4 | from collections import OrderedDict, Counter
"""
x = range(3)
y = ['a','b','c']
ziped = OrderedDict(zip(x, y))
for key, val in ziped.items():
print(key,val)
"""
"""
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1), reverse=True)
print(sorted_x)
"""
x = (('... |
28737fc08285b0796590d9e6ba734562367366c2 | XelorR/adventofcode_2015 | /day_01/second_part.py | 262 | 3.5625 | 4 | INPUT = open("input.txt").read()
current_floor = 0
for position, command in enumerate(INPUT):
if command == "(":
current_floor += 1
elif command == ")":
current_floor -= 1
if current_floor == -1:
print(position + 1)
|
3818bf7a270e6c8180a316d6b3d618bae3027939 | hirokishinoda/Interigence | /Perceptron/animeLine.py | 742 | 3.765625 | 4 | #
# アニメーション
# グラフをアニメーションで表示
#
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# 定義域を入力
xmin = -10.0
xmax = 5.0
num = 100 # 区間内の点の数
x = np.linspace(xmin, xmax, num) # xminからxmaxの区間で,num個のデータを等間隔に生成
# 表示したい関数を設定
def func(x, eps):
y = 1.0/(1+np.exp(-x*eps))
return y
... |
e0ad647d2a41399e05288821a3610fe10483b870 | q409640976/SiteDownloader | /main.py | 834 | 3.546875 | 4 | import file_functions as ff
def temp_ui(url=None):
"""Temporary UI for downloading websites."""
if not url:
url = input("Type in your url here: ")
exts = []
while True:
potential_ext = input("Type in your desired extensions (i.e. .pdf), or type \"done\" "
... |
428873ee1e05f908c2382ae0245e1b9f52ffca1b | CodingBullCom/Python | /comprehension_test_3.py | 154 | 4.0625 | 4 | #Demonstrate how to use Python's list comprehension syntax to produce the
#list [1, 2, 4, 8, 16, 32, 64, 128, 256].
print [pow(2, x) for x in range(9)] |
d1cfa11092b7f4232e3e9502a04bc805662615ca | martinlanabengut/Ejercitacion-Recursividad | /fibonacci_recursividad.py | 397 | 4.0625 | 4 | """
Ejercicio 1
Escriba una función recursiva que tenga un parámetro n de tipo entero y que devuelva el n-ésimo
número de Fibonacci. Los números de Fibonacci se definen de la siguiente manera:
F0 = 0
F1 = 1
Fi+2 = Fi + Fi+1
"""
# fibonacci = 0, 1, 1, 2, 3, 5, 8, ...
def fibonacciRecursivo(n):
if (n < 2):
return ... |
330654c09eb6cbb1f913f2734102f51b225c8bcd | oneyedananas/learning | /for Loops.py | 553 | 4.5 | 4 | # performs code on each item in a list i.e. iteration. loops are a construct which can iterate through a list.
# uses a while loop and a counter variable
words = ["milda", "petr", "karel", "pavel"]
counter = 0
max_index = len(words) - 1 # python starts counting from 0 so -1 is needed
# print(max_index) now returns 3... |
506fcdb39988603fef8062a7b55cba746cc43d1e | enriquemore587/FAM_python | /sesion2_4.py | 401 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''
El usuario elija el tamaño
de nuestra matriz
'''
tam = int(raw_input('Ingresa el Tamaño de la matriz: '))
matriz = [ ]
lon_matriz = range(tam)
for filas in lon_matriz:
fila = [ ]
for columna in lon_matriz:
if filas == columna:
fila.append('*')
else:
fila.append('1')
ma... |
2ec170d1c7be36f07975a3e48d57c3295215cb9e | supcomstudents/cv-parser | /cv-parser/resumeparser.py | 2,817 | 3.765625 | 4 | import argparse
import sys
from main.parser import *
def create_arg_parser():
""""Creates and returns the ArgumentParser object."""
parser = argparse.ArgumentParser(description='Extract skills and work experience from IT-resumes.')
parser.add_argument('inputDirectory',
help='Path... |
4aa7cf936c06a4ab159d52dbda604624e87f5e96 | extremums/the-simplest-programs | /Sodda dasturlar/O'ylangan sonni hohlagancha imkoniyatda topuvchi dastur.py | 440 | 3.71875 | 4 | #O'ylangan sonni hohlagancha imkoniyatda topuvchi dastur
son=23
yugur=True
while yugur :
taxmin=int(input("Butun son kiriting:"))
if taxmin==son :
print("Tabriklaymiz siz topdingiz ")
yugur=False
elif taxmin < son:
print("Yoq,o'ylangan son kiritilgan sondan kattaroq ")
else:
... |
6bfcfd8878ee8459f09d3961b979939fe8897ba3 | extremums/the-simplest-programs | /Sodda dasturlar/Berligan sonlarning yig'indisi va ko'paytmasinining oxirgi raqamini ko'paytirish.py | 211 | 3.59375 | 4 | a=int(input("Birinchi sonni kiriting = "))
b=int(input("Ikkinchi sonni kiriting = "))
c=a+b
d=a*b
S=(c%10)*(d%10)
print("Berilgan sonlarning yig'indisi va ko'paytmasining oxirgi raqamlarining ko'paytmasi = ",S)
|
1df628f7a2de240bc0c58349ece2093767f7aebd | extremums/the-simplest-programs | /Sodda dasturlar/Uchburchakning asosi va balandligi berilganda yuzini topish.py | 156 | 3.625 | 4 | c=input("Uchburchakning asosini kiriting = ")
h=input("Uchburchakning balandligini kiriting = ")
S=(float(h)*float(c))/2
print("Uchburchakning yuzi = ",S)
|
7c6d49a6acc090776ac84ce2cbb56196daaa441c | extremums/the-simplest-programs | /Murakkab dasturlar/Sonning raqamlari soni va yig'indisini topish dasturi.py | 428 | 3.578125 | 4 | # Kiritilgan sonning raqamlari yig'indisini va sonini topish dasturi
while True :
a =input("Natural son kiriting ")
if a.isdigit() :
a = int(a); b = 0; c = 0
while a >= 1 :
b+=a%10
a//=10
c+=1
print(f"Kiritilgan sonning raqamlari soni {c} ga teng")
... |
a1f7bd2b4e3861b3f4f2e6ee04f5a8a92e80bd10 | annamhuber/BDL1 | /SW_01_08/Pycharm/SW_01_08/demo/SQLiteTutorial/100-create-db-01.py | 836 | 3.75 | 4 | #!/usr/bin/env python3
# 2020-03, Bruno Grossniklaus, https://github.com/it-gro
# https://www.sqlitetutorial.net/sqlite-python/creating-database/
import sqlite3
import pathlib
# import os
# os.chdir(Path.home())
base_dir = str(pathlib.Path.home()) + "/bdl03-1/sqlite"
db_file = f"{base_dir}/pythonsqlite.db"
def crea... |
42c8ae3b693be4d2445d22678403d5949a02cfdc | AdamF42/MLSamples | /activationFunctions/relu.py | 268 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
def ReLU(x):
return x * (x > 0)
def dReLU(x):
return 1. * (x > 0)
def graph(formula, x_range):
x = np.array(x_range)
y = formula(x)
plt.plot(x, y)
plt.show()
graph(lambda x: ReLU(x), range(-6, 6))
|
713339eff20719b5dcfc0f39fe67deeb0d039440 | oshuienko/python-study | /english.py | 2,209 | 3.8125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import random
# окрытие файла с данными и преобразование их в словарь
put = '/home/norbert/Python_study/words_1.txt'
words = {}
for line in open(put):
line = line.split('\n') # избавляемся от последнего элемента (\n)
line = line[0] # из строки получаем с... |
bd1a9cba0eabc8ace30670d69b3753b25df47841 | lineva642/Work_3 | /ex.3.py | 266 | 3.59375 | 4 | import turtle as tr
tr.shape("turtle")
s = 50
a = 90
p = 30
n = int(input())
for i in range(n):
for i in range(4):
tr.forward(s)
tr.left(a)
tr.penup()
tr.backward(p/2)
tr.right(a)
tr.forward(p/2)
tr.left(90)
s+=p
tr.pendown()
|
eabe278987937d61cd067e91276c93b526d88a1a | nameNoMaterHere/tictoc | /ticttaktoe.py | 4,024 | 3.859375 | 4 | def whosturn(turn):#function help know who s turn x or o
'''
checks who'es turn is it. if turn is even return 'o' if odd return 'x'
:param turn: number of current turn
:return: 'x' or 'o'
'''
if turn % 2 == 0:
play = "o"
else:
play = "x"
return play
def placeprint(place):
... |
bbc9d6843c5d4b73a26ef31f08b4e8f882bf0fbc | AllanSilva156/projeto-dashboard-metodos-ordenacao | /dados.py | 2,099 | 3.53125 | 4 | import os
import insertionsort
import mergesort
import quicksort
import pandas as pd
# ================== Para obter/atualizar os dados de exemplo é necessário executar este programa ==================
# Dicionário das características de desempenho
METRICAS = {
'trocas': 0,
'comp': 1,
'tempo... |
0685f623b4f9cb897a13d09f537b410e4bf76868 | apranav19/FP_With_Python | /map_example.py | 499 | 4.40625 | 4 | """
Some simple examples that make use of the map function
"""
def get_name_lengths(names):
""" Returns a list of name lengths """
return list(map(len, names))
def get_hashed_names(names):
""" Returns a list of hashed names """
return list(map(hash, names))
if __name__ == '__main__':
people = ["Mary", "Isla", ... |
95322ed62a321bffd97cc40e9834e519173713e4 | DarrentLearn/Rpi20181223 | /Python/checkboxes.py | 1,054 | 3.859375 | 4 | # https://www.reddit.com/r/learnpython/comments/6dbhc7/array_of_checkboxes/
import tkinter as tk
from tkinter import ttk
class CheckBoxes(tk.Tk):
def __init__(self, rows=10, columns=10, **kwargs):
tk.Tk.__init__(self, **kwargs)
self.btns = []
self.selected = [False] * (rows * columns)
... |
0b68f680678cea7c94b812becf0f657ad8ad3701 | DarrentLearn/Rpi20181223 | /Python/Calculator.py | 1,560 | 4.09375 | 4 | #!/usr/bin/python
# 步驟一:匯入 tkinter 模組。
from tkinter import Tk, Label, Entry, Radiobutton, IntVar
# 步驟二:建立主視窗。
mainWin = Tk()
var = IntVar()
operation = [ '+', '-', '*', '/']
# 視窗標題
mainWin.title("Hello 雲林SONG")
# 視窗大小
mainWin.geometry("480x140")
# 步驟三:建立視窗控制項元件。
# 建立標籤
firstNumLabel = Label(mainWin, text="數字1")
sec... |
593c68988a1331101016ce98495135d6a1c82990 | DarrentLearn/Rpi20181223 | /Python/dict.py | 1,001 | 3.78125 | 4 | dictTest = {
"key1":"value1",
"key2":"value2",
}
print('dictTest=')
print(dictTest)
lol = [['a','b'],['c','d'],['e','f']]
print(dict(lol))
dict2={
'keyA':'valueA',
'keyB':'valueB',
}
print('value A=')
print(dict2.get('keyA','No keyA'))
print('value C=')
print(dict2.get('keyC','No keyC'))
dict... |
b87005a10aaaf4b240f087fd8581128b1dd56c64 | TearKnow/python | /demo/liaoxuefeng/03_6_dict_set.py | 84 | 3.890625 | 4 | d = {'jack':98, 'tom':67, 'mary':30}
print('The dict is:')
print(d)
print(d['tom'])
|
5e3a03300a4ac5765e0c0438834b3a9d64783897 | TearKnow/python | /demo/liaoxuefeng/06_1_1_map_reduce.py | 627 | 3.9375 | 4 | #map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
def f(x):
return x * x
f = map(f, [1, 2, 4, 5, 6])
for i in f:
print(i)
#reduce
#reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
#reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
from functools imp... |
e60df0efa350ba4aefc9d796562ce9f68aa0773b | TearKnow/python | /demo/functionManual/01produceConsumer.py | 805 | 3.921875 | 4 | import random,time
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[consumer] Consuming %s...' % n)
r = '200 OK'
def produce(c):
#调用c.send(None)启动生成器
c.send(None)
n = 0
while n < 5:
n = n + 1
print('[producer] producing %s...' % n)
#一旦生产了东西,通过c.send(n)切换到consumer执行
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.