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
49111dd001ed2decbc5d6ae4d9c9ec88d7ae378e
PotatoMemeInvestor107/Ice-Serpent
/rpgbattle.py
6,570
4.1875
4
import random print ("An Ice Serpent appears!") print ("Press 1 to hit it with a sword.") print ("Press 2 to hit it with Fire") print ("Press 3 to hit it with Electricity") move = int(input("What do you want to hit it with?")) #First turn enemyhp = 100 sworddamage = 25 criticalsword = 100 fire = 60 chance =...
05a0a56993c931366b440bf118a3b8aeb93a8017
23kimh/Learning-Python
/Python Basic Grammar/2019-06-25-Lesson-Python-For-While.py
9,410
3.984375
4
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>> #!= - false >>> #== - true >>> num = input('enter number') enter number 5 >>> num = input('enter number') enter number5 >>> num '5' >>> if int(num)...
fa8b2f12b38257a7111d00aca216f0251c8238b4
juso40/ALDA_SS2019
/sheet1/sieve.py
861
4.125
4
from math import sqrt def sieve(sieve_up_to): sieve_up_to=int(sieve_up_to) is_prime = [True] * sieve_up_to #jede zahl ist eine potentielle primzahl is_prime[0],is_prime[1]=False,False #0 und 1 sind keine Primzahlen for n in range(2, int(sqrt(sieve_up_to)+1)): #bei 2(der erstenprimzahl) fängt man an ...
00bc777c430a11af023e41079920fa6651a7873a
JimBroughton/PythonProgrammingBook
/Chapter 9/Alien_Blaster.py
409
3.671875
4
# Alien Blaster # Demonstrates object interaction class Player(object): """A player in a shooter game.""" def blast(self, enemy): print("The player blasts an enemy.\n") enemy.die() class Alien(object): """An alien in a shooter game.""" def die(self): print("I died.") # main ...
c85d0740935a33bfb7bf8c7e4b082741926cf989
JimBroughton/PythonProgrammingBook
/Chapter 5/Challenge 3.py
3,244
4.59375
5
# Chapter 5, Challenge 3 # Write a Who's Your Daddy? program that lets the user enter the name of a male # and produces the name of his father. Allow the user to add, replace, and # delete son-father pairs. sf = {'tom cruise':'antony hopkins', 'boris becker':'tin tin'} son = '' father = '' choice = None while choice...
f9e378202dc35b6968904b27a86cee7212738664
JimBroughton/PythonProgrammingBook
/Chapter 7/Challenge 3.py
3,606
4.3125
4
# Chapter 7, Challenge 3 # Trivia game that reads a plain text file import sys def open_file(file_name, mode): """Open a file.""" try: the_file = open(file_name, mode) except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the ente...
aab3e5c87641eff27345dc59bfb4da521d85a6ff
timothyburd/teaching
/collection_h19_q10.py
611
3.859375
4
import numpy as np import matplotlib.pyplot as plt def main(): """Find stationary points of x^3+y^3 on the ellipse x^2+2y^2=3""" # Generate ellipse polar coordinates theta=np.linspace(-np.pi,np.pi,1000) r=np.sqrt(3.0/(np.cos(theta)**2+2.0*np.sin(theta)**2)) # Convert to cartesian x=r*np.cos(t...
dabb83de9f5195d8e8adbbddee60d45d7ada980e
acoconut/adventOfCode2016
/dec04/room2.py
686
3.734375
4
#!/usr/bin/python3 # Advent of code # Day 4 - Part 2 from collections import Counter alphabet =('a','b','c','d','e','f','g','h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z') alphabetLength = 26 # Read and parse input fo = open("input.txt", "r+") for line in fo: roomName = "...
c5a1b28a33540444e601d2859864a6e75fd46d82
acoconut/adventOfCode2016
/dec02/keypad.py
1,646
3.828125
4
#!/usr/bin/python3 # Advent of Code # Day 2 - Part 1 from enum import Enum class Direction (Enum): up = 'U' down = 'D' left = 'L' right = 'R' class Keypad (): def __init__ (self): self.keys = [[1,2,3],[4,5,6],[7,8,9]] self.position = [1,1] def isMovable(self, direction): ...
cd86f416a7f87b74733732e7ba811a392fdb249d
thakran14/Python-Practice
/game.py
567
3.984375
4
# guess the dice number game import random import sys if __name__ == "__main__": print("This is a dice number guessing program\n") while True : val = input("Press y to continue, n to exit\n") if val=='y': num = int(random.choice([1,2,3,4,5,6])) #print(num) #print(type(num)) n = int(in...
b80cb0d8e3d127c6f859b761403cce0f9a9fcc0e
g423221138/chebei
/bs4_study.py
1,766
4.21875
4
#bs4官方文档学习 #例子文档 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http:/...
cac5c6340e5e594f9fca7d5b6e59703b059380e4
jabibenito/pynet_course
/class1/exercise8.py
997
3.8125
4
# Write a Python program using ciscoconfparse that parses this config file. # Note, this config file is not fully valid (i.e. parts of the configuration are missing). # The script should find all of the crypto map entries in the file (lines that begin with 'crypto map CRYPTO') and for each crypto map entry print out it...
c1279076e019dd32f1e2fd30c52d1831b9ffe504
NicsonMartinez/The-Tech-Academy-Basic-Python-Projects
/For and while loop statements test code.py
2,469
4.46875
4
mySentence = 'loves the color' color_list = ['red','blue','green','pink','teal','black'] def color_function(name): lst = [] for i in color_list: msg = "{0} {1} {2}".format(name,mySentence,i) lst.append(msg) return lst def get_name(): go = True while go: name = input('What...
bc62c712563f95dbe18de0e646d6963670cece02
smcshan97/python
/Python inclass day 2/Python class 1 lists.py
545
3.96875
4
fruits = ["apple", "mango", "banana", "kiwi", "peach"] print(fruits) mixed_list = ["Hello", 30, [1,2,3], None] print(mixed_list) print(fruits[0]) print(fruits[-2]) print(fruits[0:3]) print(fruits[1:-1]) fruits_copy = fruits.copy() print(fruits_copy) fruits.append("orange") fruits.append("mango") fruits[2] = "bananas...
ce6184e2a461ca09ecedae3f7804b2144bdb3222
smcshan97/python
/Python inclass day 2/Python class 1 tuples.py
251
4
4
fruits = ("apple","mango","banana","kiwi","mango" ) print(fruits) print(fruits[1]) print(fruits[1:-2]) # fruits[3] = durian more_fruits = fruits + ("durian",) print(more_fruits) print(fruits) print(fruits.count("mango")) print(fruits(empty_list))
c149e8e75aa615201a30f30684483e50a53dd513
aivischer/Project-to-show-Professor-Young
/display.py
596
3.53125
4
from colorama import * class Map(object): """ Matrix is a list of rows of a rectangle. Each value in each row should be a string that will be diplayed in a merged R x C matrix. Maps also have borders. """ def __init__(self, matrix): self.matrix = matrix def _...
0c1de4834cfd91e7ab017f9d6b6fa0907027d31f
Eric2D/movie_list
/entertainment_center.py
1,458
3.546875
4
# Use the file here to make your favorite movie lists through media import media import fresh_tomatoes # In the three variables below they all call the class movie (in media). # There are three arguments in the class which are title, image url, and # youtube video url. oblivion = media.movie('Oblivion', ...
99a653e97b87f856e54644554480ffb2150c5bfa
dnvnxg/cse107-lab4
/statistics107.py
4,732
4.4375
4
""" A program that contains a lot of list functions and tests them file: statistics107.py author: Donovan Griego Date: 9-15-2021 assignment: Lab 4 """ # Fill in a correct implementation for each function. # Define other functions if you think they make the # assigned function easier to write or easier to read. d...
5a186a8bf354dc1c572b4ff777e637c447b5a781
kkomissarchik/polyglot
/hello/python/greeter.py
228
3.75
4
import sys def hello( name = None ): return "Hello!" if name is None else "Hello, " + name + "!" def main( argv ): print( hello( argv[ 1 ] if len( argv ) == 2 else None ) ) if __name__ == "__main__": main( sys.argv )
29a6b170d89f9a6ccad0f77cf10a9f58aefa89a8
advil64/probabilistic-sensing
/src/gridworld.py
2,042
3.796875
4
from random import choices, randint, random class Gridworld: # NOTE: 1 -> blocked, 2 -> flat, 3 -> hilly, 4 -> forest def __init__(self, dim, start=(0,0), target=(0,0), prob=0, empty=True): # gridworld is an object attribute self.gridworld = [] # start filling in grids by rows and co...
2a7fae35e0cdcbd7c39a3ff49c6aa32a5271ca88
carasolomon/python-socket
/server.py
661
3.6875
4
# Python server import socket s = socket.socket() print("Socket successfully created") # identify port port = 9500 s.bind(('', port)) print("socket binded to %s" %(port)) # socket is listening for connection s.listen(5) print("socket is listening") while True: (c, addr) = s.accept() # show established conne...
4f4b4945580eb538ce9a32bd053a99b837d19497
oktaviacitra/nimgame-minimax
/Game.py
4,585
3.828125
4
from Tree2 import Tree2 class Game: def __init__(self): self.number_of_sticks = None self.is_play_first = None self.tree = None self.current_player = None self.play() def play(self): self.menu() current_node = self.tree.tree[0] while not current...
987f00212a4965e0fe900b1abdf6a2cdd595944b
lufe089/lfrincon
/material/IntroProg/Notas/ResultadosParcial2/Soluciones/6. Juan Daniel Lopez Niño.py
975
3.71875
4
#Juan Daniel Lopez Niño def sondeo(): conjuntos=int(input(" ingrese el numero de conjuntos: ")) cont=1 Xmascotas=0 Smascotas=0 mascotasporapto=0 while cont<=conjuntos: Xmascotas=0 cont=0 apartamentos=int(input(" ingrese los aptos por conjunto: ")) while cont<=apartam...
1d57804d9639d48b774aac3e36bc4e7d9aef8ffc
lufe089/lfrincon
/material/IntroProg/Notas/ResultadosParcial2/Soluciones/13. César Manuel Samboni.py
4,404
3.9375
4
#César Manuel Samboni Rojas #ejercicio 1 def Sondeo(): conjuntos= int (input("ingrese cuantos conujntos realizaran la encuesta: ")) apartamentos= int (input("ingrese cuantos apartamentos tiene cada conjunto: ")) mascotasT=0 SinMascotas=0 cont3= 1 while conjuntos > 0: mascotas1=0 ...
6b42b0ca8302c2642bf2becbacf273c22f9281d2
lufe089/lfrincon
/material/IntroProg/Ejercicios/6. Diccionarios/Nivel0- ejemploLLenarDiccionario.py
1,586
4.3125
4
# Escriba un programa en Python que le solicite al usuario por pantalla un listado de números (para finalizar debe ingresar 0). Cree un diccionario en donde se almacene la siguiente información a partir de los números ingresados: # Cantidad de números pares # Cantidad de números impares # Número mayor # Número menor # ...
7d1220e47c0c95ac23a0a811b1e0780c72af84d0
lufe089/lfrincon
/material/IntroProg/Notas/ResultadosParcial2/Soluciones/10.SimonPedroGranada.py
3,347
3.75
4
def ejercicio1(): conjunto=int(input("ingrese el numero de conjuntos residenciales")) apto=int(input("ingrese el numero de apartamentos")) contApto=0 contConjunto=0 aptosCon2Mascotas=0 mascotasConjunto=0 while contConjunto<conjunto: while contApto< apto: mascostas=int(in...
c1b6589bfd35869f975ae35f1f4b642339bbac64
lufe089/lfrincon
/material/IntroProg/Notas/ResultadosParcial2/Soluciones/28.Juan Pablo Garcia V.py
2,168
3.828125
4
#Juan Pablo Garcia Vicuña def ejercicio1(): conjuntos=int(input("ingrrese el # de conjuntos residenciales")) conj=1 suma11=0 while conj<=conjuntos : aptos=int(input("ingrese el # de apartamentos ")) cona=0 suma1=0 sumaMascotas=0 while cona<aptos: mascotas=int(input("¿cuantas mascot...
c5a8e89a64fa4f4b90840e82d0d9d0ae1cc3e5cd
PaolaCNacif/Juego
/proyecto/Snake.py
3,190
3.78125
4
#Encoding:UTF-8 #Autor:Paola Castillo Nacif #Proyecto final: Juego "Snake" from Graphics import* from Myro import* from random import randint v=Window("Snake",800,600) v.setBackground(Color("black")) listaCuerpo=[] snake=makePicture("greencircle.png") snake.x=400 snake.y=300 snake.border=0 listaCuerpo.append(snake...
357acc76fff55a50bcf5efa4db6c41971480d46c
Mag1cPanda/MyPython
/ErrorAndDebug.py
874
3.671875
4
from functools import reduce def str2num(s): try: return int(s) except: return float(s) def calc(exp): ss = exp.split('+') ns = map(str2num, ss) return reduce(lambda acc, x: acc + x, ns) def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('9...
6b4b9779d408534a3f171df82a5e99c41cef421e
Mag1cPanda/MyPython
/Threading.py
3,089
4.15625
4
# 多线程(线程是操作系统直接支持的执行单元) # 多任务可以由多进程完成,也可以由一个进程内的多线程完成。 # 进程是由若干线程组成的,一个进程至少有一个线程。 import time, threading # 新线程执行的代码: def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n += 1 print('thread %s >>> %s' % (threading.current_thread().name, n)) ...
44a91cbbb4e45ac0e3a8cabe67fd49d61d0fb524
harini9804/social_networks
/op.py
150
3.8125
4
my_dict = dict() my_dict['Social'] = {'Social': 6, 'Networks' : 8} my_dict['Networks'] = {6,8} for (key, values ) in my_dict.items(): print values
a8c6b3a45decaab39815ec260d549285b264889c
veterinarian-5300/Genious-Python-Code-Generator
/Py_lab/Lab 1,2/plotting_sin.py
503
4.03125
4
# importing the required modules import matplotlib.pyplot as plt import numpy as np # setting the x - coordinates x = np.arange(0, 2*(np.pi)*5, 0.1) # setting the corresponding y - coordinates y = np.sin(x) # potting the points plt.plot(x, y, label ='sin(x)') # naming the x axis # naming the y axis plt.yla...
2e7f1e2ce23ff72517f2e310f5c27c74b7f26717
veterinarian-5300/Genious-Python-Code-Generator
/Py_lab/Lab 1,2/postlab2_1.py
700
3.75
4
import matplotlib.pyplot as plt import numpy as np # setting the x - coordinates x = np.linspace(0,5,500) # setting the corresponding y - coordinates plt.figure() plt.subplot(311) y = np.sin(20*x) plt.plot(x, y, label ='sin(x)',color='blue',linewidth=4) plt.legend() plt.subplot(312) y = np.exp(-x) plt.plot(...
a59a8a3825c2b2d1c790e24f3fd2e7738b7b999d
veterinarian-5300/Genious-Python-Code-Generator
/Py_lab/Lab 1,2/plotting_a_line.py
345
4.375
4
# importing the module import matplotlib.pyplot as plt # x axis values x = [1,2,3,4,5] # corresponding y axis values y = [2,4,1,3,5] # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('x - axis') # naming the y axis plt.ylabel('y - axis') # Title to plot plt.title('Plot') # function to ...
a0c81588e6d61d486a4ba5e678df7a2af283be79
veterinarian-5300/Genious-Python-Code-Generator
/hackerrank/gridtraveller.py
450
3.609375
4
def gridtraveller(x,y,memo): if x==0 or y==0: return 0 if x==1 and y==1: return 1 if (memo[x][y]!=0): return memo[x][y] memo[x][y]=(memo[x-1][y]+memo[x][y-1]); return memo[x][y]; if __name__ == '__main__': x=int(input()) y=int(input()) arr=[] for i in range(y+1): ...
a4c2a76ab564fbb82594d8747c70be1c06ce3642
AP-MI-2021/lab-3-ale-stanciu
/main.py
5,010
3.890625
4
def printMenu(): print ("1. Citire date") print ("2. Determinare cea mai lungă subsecvență in care toate numerele sunt pare") print ("3. Determinare cea mai lungă subsecvență in care media numerelor nu depășește o valoare citită") print ("4. Determinare cea mai lunga subsecventa in care toate numerele s...
a4a56a565ddbe74759ee4ededce24719c9b7cde2
SUMAN147/PROJECT
/Practice/CNN/Transfer_Learning_Model/convnet_Trained_From_Scratch.py
3,349
3.671875
4
'''This script goes along the blog post "Building powerful image classification models using very little data" from blog.keras.io. It uses data that can be downloaded at: https://www.kaggle.com/c/dogs-vs-cats/data In our setup, we: - created a data/ folder - created train/ and validation/ subfolders inside data/ - crea...
8d8ef3015ed56ce5dacd9247960a938beb9e2322
SUMAN147/PROJECT
/Practice/Tensorflow/1_Introduction/eager_BasicOperation.py
1,625
3.796875
4
''' Basic Introduction to tensorflow's Eager API What is Eager API? " Eager execution is an imperative, define-by-run interface where operations are executed immediately as they are called from Python. This makes it easier to get started with TensorFlow, and can make research and development more intuitive. A vast maj...
d80e6c3ecd29dc1224683246489e4ee8a4905818
rest2437/intro_to_python
/dictionary.py
480
3.890625
4
# Dict = {} # # print(Dict) # Dict[0] = 'hello' # Dict[2] = 'world' # Dict[3] = 1 # # print(Dict) # Dict['value_set'] = 2, 3, 4 # # print(Dict) # # ==================================================================================================== # Dict[2] = 'nerd' # # print(Dict) # # ===========================...
db696158fe8ea3f1ed138e0ba20ec9d150db8b26
gayathriprashant/pythonscripts
/files.py
588
3.546875
4
#Files will be overwritten if already exists #fo=open('newfile.txt','w') ''' print(fo.mode) print(fo.readable()) print(fo.writable()) ''' ''' fo.write("This is the testing of file\n This is the second line \n This is the third line\n") content=["Testfile1\n Testfile2\n Testfile3"] fo.writelines(content) ''' my_content...
367de0555298bdb5e0368da7fe8b977a1e1c6123
MrDNA2018/data_structure_and_algorithm
/select_common.py
5,341
4.03125
4
# -*- coding: utf-8 -*- # 简单的插入排序 def insert_sort(arr,low,high,step): for i in range(low+step,high+1,step): temp = arr[i] j = i while arr[j-step] > temp and j >low: arr[j] = arr[j-step] j -=step arr[j] = temp def group_sort_size_5...
1517a84a700ec7beb25e9e73510777e5330f89ff
MrDNA2018/data_structure_and_algorithm
/common_select_k.py
5,171
3.640625
4
# -*- coding: utf-8 -*- # 简单的插入排序 def insert_sort(arr,low,high): for i in range(low+1,high+1): temp = arr[i] j = i while arr[j-1] > temp and j >low: arr[j] = arr[j-1] j -=1 arr[j] = temp def group_sort_size_5(arr...
de7f8171132e2dc0e423664fd434d649d5a95090
MrDNA2018/data_structure_and_algorithm
/check_().py
1,331
3.90625
4
# -*- coding: utf-8 -*- # 用于右括号和左括号匹配 def left(a): if a == '}': return '{' if a == ']': return '[' if a == ')': return '(' # 验证括号 def checkNotation(arr): num = len(arr) # 特殊case处理 if num == 0: return False # 用于存放左括号 stack =[] # 遍...
cd4b2e45f1247b7b3f0d66bd1d271800593da2e9
MrDNA2018/data_structure_and_algorithm
/pruning.py
2,789
3.640625
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 30 09:38:02 2018 分支限界法 @author: geng """ import numpy as np import heapq class dijkstra: def __init__(self,graph,start): # 邻接表 self.graph = graph # 顶点个数 self.num = len(graph) #源点 self.start = start ...
52d50782992f0f9c6b03b3149c2fa82926a78d16
marklevi/thirty_day_challenge
/chapter3_exercises.py
769
3.71875
4
# Exercises for chapter 3: Problems 3.1, 3.2, 3.3, and 3.4 in Think Python Mark Levi ex3.1 NameError: name 'repeat_lyrics' is not defined ex3.2 Because you do not call the function repeat_lyrics() until after you define it, it does not cause any errors. The program runs smoothly. ex3.3 def right_justify(x): rj...
e1cf583a208039a7b855063a4a8d4ff27caf6402
alexisflores99/Repo-for-Python
/sentenciaWhile.py
418
3.859375
4
# i = 0 # while i <= 10 : # print("HOla mundo", i) # i+=1 # else: # print("Finalizó el programa") # edad = int(input("Ingresa tu edad: ")) # while edad < 0 : # print("Eres idiota?") # edad = int(input("Vuelva a ingresar su edad: ")) # else: # print("Finalizó, ya te puedes ir") i = 0 while ...
c39f131e6b867f6c06ed566b02215920ac4b8456
alexisflores99/Repo-for-Python
/Interfaces Graficas/labelpy.py
618
3.625
4
from tkinter import * root = Tk() imagen = PhotoImage(file = "jeje.gif") label = Label(root, image = imagen) label.pack() """ texto_nuevo = StringVar() texto_nuevo.set("Python") root.title("Bienvenidos") root.config(width=400,height=300) label = Label(root,text = "Hola mundo") label.place(x = 100, y = 50) ...
e5bd139030bc28ca24d0df944d14c526f1698da1
alexisflores99/Repo-for-Python
/entrada_argumentos.py
218
3.765625
4
import sys if len(sys.argv)==3: texto=sys.argv[1] repeticiones = int(sys.argv[2]) for i in range(repeticiones): print(texto) else: print("Error, introdujo uno (1) o más de dos (2) argumentos")
6e1a18ac4d28b6c8d89f5b9b8e89363935267513
alexisflores99/Repo-for-Python
/vamos.py
328
3.9375
4
# a = int(input("Ingrese un número para \'a\': ")) # b = int(input("Ingrese otro número \'b\': ")) # if a==b : # print("Los numeros son iguales") # if a>b : # print("a es mayor que b") # else : # print("b es mayor que a") # 10 # print(not True) # print(True and True) # print(not False) # print(False or T...
41da6593087fa6ce2e17fff89aa8179832563cfb
prmkbr/misc
/python/fizz_buzz.py
536
4.125
4
#!/usr/local/bin/python """ Prints the numbers from 1 to 100. But for multiples of three print 'Fizz' instead of the number and for the multiples of five print 'Buzz'. For numbers which are multiples of both three and five print 'FizzBuzz'. """ def main(): """ Main body of the script. """ for i in xra...
790f5ac5154a1d85b3ab1e7df065b6014436b316
8cho8888/PracticasPython
/Ejerciocio1_Mod4.py
1,066
3.859375
4
def Opcion(): global opcion opcion=int(input("Elige una opción \n1.Tupla\n2.-Lista ")) def EntradaLista(): global lista,op op=3 lista=[] if(opcion==1): for i in range(0,4,1): nom=input("Introduce 10 nombres ") lista.append(nom) def EntradaTupla(): global miTupla,opi opi=0 miTupla=('') ...
5865f6608cffa64872fd2f2c75f4f9c34350eb59
hunterirving/roshambo
/roshambo_tournament/opponent6.py
674
3.8125
4
import random class opponent6(): #Replace these fields creatorName = "Hunter" programName = "Randall" #This function is called each round to determine your move for that round. #This function recieves as input a string containing your opponent's move from the last round. #In the first rou...
69936d76f0ecd2b3f640c6015389fbcbe8d14821
yodifm/Hacktoberfest2020
/round.py
705
4.1875
4
import turtle print("1. Draw circle") print("2. Draw Tangent Circles in Python Turtle") print("3. Draw Spiral Circles in Python Turtle") print("4. Draw Concentric Circles in Python Turtle") num = int(input("Enter a number: ")) if num == 0: t = turtle.Turtle() t.circle(100) print(num) elif ...
6751cf033efd3dd69f64d417d78e57f10cdc1060
bonjonson/course-67
/week 2/3367-7.py
662
3.765625
4
gen = input() #вводим строку gen2 = "" #результирующая пустая строка i=1 while i <= len(gen): #пока i не выходит за длину строки count = 1 #счетчик по умолчанию while (i<=len(gen)-1) and (gen[i] == gen[i-1]): #пока i <= длины gen-1 и индекс gen == индекс-1 gen count = count + 1 #увеличиваем cnt ...
addc9be4499650a0c1e56ef2da5df60917092f21
bonjonson/course-67
/week 1/5047-7.py
249
3.84375
4
abcdef = str(input()) qwerty = list(str(abcdef)) half1 = int(qwerty[0]) + int(qwerty[1]) + int(qwerty[2]) half2 = int(qwerty[3]) + int(qwerty[4]) + int(qwerty[5]) if half1 == half2: print('Счастливый') else: print('Обычный')
6ee455f9c5394e19a0ba057a2181248a67c3305c
alisamatisse/PythonCourse
/hw_B4.py
586
3.578125
4
# coding: utf-8 # In[ ]: import random rnumber = random.randint(1, 100) def guessing_game(): number = int(input('Введите число от 1 до 100, может быть Вы угадаете? ')) if number == rnumber: print('Вы угадали, классно!') elif number > rnumber: print('Загаданное число меньше, пробуйте ещё!...
d957e03f9022ffe35ccf422af20e5516f9c5dfe2
eprendergast/CS50
/pset6/bleep.py
815
3.578125
4
from cs50 import get_string import sys test = "HELLO" print(test.casefold()) def main(): #Take a command line argument of the name/path of a dictionary of banned words if len(sys.argv) < 2 or len(sys.argv) > 2: print("Usage: python bleep.py dictionary") sys.exit(1) dictionary = sys.argv[1]...
2cec349abb516611940390c215304bfb56daafd7
docoleman/csv-to-db-table
/csv_to_db_table.py
5,152
3.984375
4
from argparse import ArgumentParser,FileType as ArgParseFileType from sys import stdin, stderr, exit as sysexit import csv import re class CsvToDbTable: ''' Generate a create table statement based off of a CSV file. The header names \ will be the contents of the columns in the first row of the file...
4d2b231d0aa63d3e27ad591fedd9fb683b764cfe
scf1984/Sanctuary
/location.py
758
3.65625
4
import math from helper import Vector class Velocity(Vector): pass class Location(Vector): def bbox(self, size): return ( self.coords[0] - size, self.coords[1] + size, self.coords[0] + size, self.coords[1] - size ) def go_to(self, destina...
6dd0c430149a3c8a8aa77f4c07971a76659bbf37
andrewrgarcia/hello-world-python
/plot2.py
332
3.625
4
'''loads numpy (numerical python) package; makes vector operations (line 9) and other numerical features possible ''' import numpy as np import matplotlib.pyplot as plt #create a vector with the following numbers in sequence x=np.array([-5,2,3,4,5]) #y returns vector of operated x vector (operation y = x^2) y=x**2 p...
5782fa59d65af071e8fb004f42c8321f17fb6fd3
mljarman/Sorting
/src/iterative_sorting/iterative_sorting.py
1,383
4.25
4
# TO-DO: Complete the selection_sort() function below arr = [5, 2, 1, 6, 8, 10] def selection_sort(arr): # loop through n-1 elements for i in range(len(arr)-1): cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) # iterat...
3e391a0667f79d502d9d8cef066e51d06083050b
LuckyShawn/python-study
/demo/DictTest.py
252
3.9375
4
# dict 全称dictionary,相当于 JAVA 中的 map user = {'shawn': 123456, 'jack': 654321} print(user) user['jack'] = 123 print(user) del user['jack'] print(user) person = {'person1': 'man', 'person2': 'women'} user['shawn'] = person; print(user)
3fc7b27962cea06580a90ba8ffb44fab206a9413
siuols/intern-python
/louis/Sum.py
199
4.09375
4
list1 = [45, 8, 15, 14, 23, 42] # = 147 # print("The total of all the integers in the list is:",list1[len(list1) - 1]) Total = sum(list1) print("The total of all the integers in the list is: ",Total)
7a139ce5bc239c59339f16561c9196ceea6a1876
LucaLukas0126/SPL2
/Strings.py
208
3.71875
4
eingabe = input("Hallo: wer bist du?") print(eingabe) for i in range(0,len(eingabe)): print(eingabe[i], end=".") print() for i in range(len(eingabe) -1, -1, -1 ): print(eingabe[i], end=".") print()
de2c80883264b731c748c09d2a20c8c27995d03e
bjucps/cps110scope
/Lesson 2-3 String Processing/greeter.py
481
4.21875
4
# Demonstrates string processing full_name = input('Enter your first and last name:') if full_name == '': print('You did not enter a name!') else: space_pos = full_name.find(' ') if space_pos == -1: print('You did not enter your first and last name!') else: first_name = full_name[0:spa...
3d9018bea5f64544cb6abc8c06a27385262d73c3
bjucps/cps110scope
/Lesson 2-4 Unit Testing/addnums.py
409
4.1875
4
def addNums(num: str) -> int: """Adds up all digits in `num` Preconditions: `num` contains only digits Postconditions: returns sum of digits in `num` """ sum = 0 for digit in num: sum += int(digit) return sum def test_addNums(): assert addNums('123') == 6 if __name__ == "__ma...
3609acffc7a47af9953f2802bfc2ad9f626e1311
bjucps/cps110scope
/Lesson 1-6 Software Development/chickenfeed.py
608
4
4
# The Chicken Feed Calculator current_temp = int(input('Enter the temperature in degrees fahrenheit: ')) total_weight = int(input('Enter total chicken weight in pounds:')) if current_temp < 60: print("It's cold! temperature =", current_temp) # for debugging total_feed = total_weight * .12 elif current_temp ...
c51067c268bd1ccd651a0ad4823f4848195a3032
NGTS/hardware-changes-python-srw
/hardware_changes/form_types.py
420
3.515625
4
class Type(object): def __eq__(self, other): try: return self.value == other.value except AttributeError: return self.value == other def __str__(self): return "<Type {0}>".format(self.value) class Boolean(Type): def __init__(self, value): self.value ...
84f66970542de9f86cad4528f0f1fc697f9d9a84
zohairhashmi17/Programming-Fundamentals-Detailed-Assignment
/3.1(b).py
269
3.5
4
print('zohair hashmi - 18b-127-cs - Section A') print('Practice Problem - 3.1(b)') x = ['Musial', 'Aaraon', 'Williams', 'Gehrig', 'Ruth'] a = input('enter a name:') if a in x: print('One of the top 5 baseball players,ever!') else: print('Thank you')
a8c21400a5b5713d266e84ab352fe6cc59cfc3b4
tacotoemeck/cs50
/sql/houses/import.py
795
3.6875
4
from cs50 import SQL from csv import reader from sys import argv db = SQL("sqlite:///students.db") if len(argv) != 2: print("usage error, import.py characters.csv") exit() with open(argv[1]) as student_file: file_reader = reader(student_file) for row in file_reader: if row[0] != 'name': ...
4238dd2e2fdc3c2951c13ddf35489df95527e12b
thanhnguyentang/pib
/pib/data_utils.py
1,979
3.625
4
import numpy as np import keras import keras.backend as K from keras.datasets import mnist # Data class Data(object): """Abstract data class. """ def __init__(self, feature_rank=1, width = 28, height =28, channels = 1, name='MNIST'): self.name = name self.feature_rank = feat...
6119d5e8e714298b12d4206b317850ddea812210
koziscool/embankment_4
/e35.py
1,478
3.6875
4
import time def build_primes_up_to(n): primes = [2] current_counter = 3 while primes[-1] < n: is_prime = True for p in primes: if p*p > current_counter: break if current_counter % p == 0: is_prime = False break...
8469a5fb9f1a780f8b18ebb09b06a1df45fdeeb8
koziscool/embankment_4
/e128.py
2,334
3.75
4
import time def binary_search(alist, item): first = 0 last = len(alist)-1 found = False while first<=last and not found: midpoint = (first + last)//2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: las...
1713999fd16a0a57349c8019558401eb068c7f3c
koziscool/embankment_4
/e2.py
449
3.59375
4
import time def e2(): total = 0 previous_f, current_f = 1, 2 while current_f < 4 * 10 ** 6: if current_f % 2 == 0: total += current_f previous_f, current_f = current_f, current_f + previous_f return total if __name__ == "__main__": start = time.time() print pr...
bb32070de97c9354d7061ce8b3c9e3b43aa752d7
tmzeder/P-Y-T-H-O-N-Na-Faculdade
/Lista de Exercícios - Para P1/Lista 2 - (Função SEM retorno COM parâmetro)/Exercício_1.py
435
4.0625
4
#1. (Função sem retorno com parâmetro) Faça um programa contendo uma função/método que leia um número e o multiplique por 2, apresente o resultado. def mult (num): #Variavel nomeada com parametro, num = qualquer resposta = num * 2 print(f'O resultado da multiplicação do valor informado é: {resposta}') ...
c30c2c5f308ee3437c1d5b64ec5706728b56ff9e
tmzeder/P-Y-T-H-O-N-Na-Faculdade
/Lista de Exercícios - Para P1/Lista 1 - (Função SEM retorno SEM parâmetro)/Exercício_4 Personalizado.py
2,946
4.09375
4
#4. (Função COM retorno COM parâmetro) Faça uma função/método que leia um único valor representado em segundos, converta-o e apresente o resultado em horas, minutos e segundos. #h = segundos / 3600 #r = resto(segundos / 3600) #m = r / 60 #s = resto(r / 60) #Observação 1: resto de uma divisão em Python %. #Observa...
b669c858a719c719ed4a5da447f0f980965596d4
tmzeder/P-Y-T-H-O-N-Na-Faculdade
/Lista de Exercícios - Para P1/Lista 1 - (Função SEM retorno SEM parâmetro)/Exercício_1.py
309
4.09375
4
#1. (Função sem retorno sem parâmetro) Faça um programa contendo uma função/método que apresente o valor 1 se o número digitado for positivo e 0 se for negativo. def função(): num = int(input('Informe um numero: ')) if num > 0: print(1) else: print(0) função()
6f531b7ea32058e73fc9c772796988d127ac18ef
tmzeder/P-Y-T-H-O-N-Na-Faculdade
/Lista de Exercícios - Para P1/Lista 1 - (Função SEM retorno SEM parâmetro)/Exercício_9.py
714
4.0625
4
# 9. (Função sem retorno sem parâmetro) Faça uma função/método que leia cinco valores inteiros, determine e mostre o maior e o menor deles. Não pode usar vetor e função pronta da linguagem Python. def numerais(): for c in range(1, 6): valor = int(input(f'Informe o {c}º valor: ')) if c == 1: ...
1b3afce364cf9a213823c39c945d1833eb7ebd26
tmzeder/P-Y-T-H-O-N-Na-Faculdade
/Lista de Exercícios - Para P1/Lista 4 - (Função COM retorno COM parâmetro)/Exercício_4.py
682
4.0625
4
#4. (Função com retorno com parâmetro) Faça um programa contendo uma função/método que receba duas notas (P1, P2) calcule a média, chame outra função na main que avalie se este aluno esta aprovado ou reprovado retornando a str/string 'Aprovado' ou 'Reprovado'. def media(a, b): media_prova = (a + b) / 2 ret...
17e6a30f740858de25185b1949b022aa16950f10
MarkovCredit/python-decorators
/3-examples/5-class/task.py
678
3.5
4
__author__ = 'Michael' class Task(object): def __init__(self, func): self.__func = func self.__next = [] def next(self, task): if not isinstance(task, Task): task = Task(task) self.__next.append(task) return task def __call__(self, *args, **kwargs): ...
85c985d14475b2c35ea7c634a93c239fcc0b0ae5
fnov/learn_python3
/specialist/work/labs/04-unique-words-from-file.py
1,176
3.609375
4
# labs/list-of-unique-words.py def read_file(filename): '''Return list of unique words from given filename''' def clean(s): result = '' for char in s: if char.isalpha(): result += char.lower() return result with open(filename, 'r', encoding='utf...
ed170810dcf9a973a804ccd7d605627fc17a25ae
fnov/learn_python3
/stepik/stepic-02.py
1,617
3.84375
4
#!/usr/bin/python3 """Выведите таблицу размером n×n, заполненную числами от 1 до n2 по спирали, выходящей из левого верхнего угла и закрученной по часовой стрелке, как показано в примере (здесь n=5): Sample Input: 5 Sample Output: 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9""" side = int(inpu...
afc6bd6fb50ee00ed4b9752655beeed9bda8f943
fnov/learn_python3
/specialist/work/demo/super/funcs.py
583
3.84375
4
# demo/funcs.py def add(a, b): return a+b def area_of_disk(radius): '''Help on user-defined function area_of_disk: area_of_disk(radius) Return the area of disk with current radius ''' return 3.14 * radius ** 2 def area_of_ring(outer, inner): return area_of_disk(outer...
68e1c0f6297a73edf2f4a45004ae85c7f5dc003b
fnov/learn_python3
/specialist/homework/home1-06.py
772
3.84375
4
#!/usr/bin/python #Дано число N - количество секунд прошедших после полуночи. Сколько полных часов и полных минут #прошло после полуночи? #Код должен напечатать два числа: количество часов (между 0 и 23) и количество минут (между 0 и #1339). #На пример, если N = 3900, то 3900 после полуночи - это 1:05 на часах. Резуль...
8241ae0cefc0f5a0d98c4bb5102b1c1752d12d72
fnov/learn_python3
/specialist/homework/home5-08.py
765
3.671875
4
#!/usr/bin/python #Дана последовательность неотрицательных целых чисел, где каждое число записывается в отдельной #строке. Последовательность заканчивается на 0. #Напечатайте длину самого широкого фрагмента последовательности, где все элементы равны друг #другу. array = [] n = 1 while n !=0 : n = int(input()) ...
0248ca71ea896ac298b7540fd4238ac20087f913
fnov/learn_python3
/specialist/homework/home2-07.py
381
3.921875
4
#!/usr/bin/python #Дан год в виде целого положительного числа. #Напечатайте число соответствующее веку. Обратите внимание, что 20 век начинается в 1901 году. number = int(input()) if number % 100 > 0: s = number // 100 + 1 else: s = (number // 100) print(s)
620d5ee5dfb5a018fc4d7f4c48873f3d967e741f
arlandism/tic_tac_toe
/game/test/test_minimax.py
2,409
3.65625
4
import unittest from game.minimax import Minimax from game.base_board import BaseBoard class MinimaxNextMoveTests(unittest.TestCase): def setUp(self): self.x_minimax = Minimax("x",20) self.o_minimax = Minimax("o",20) self.board = BaseBoard(3) def tearDown(self): self.board.boa...
07809f440b6eed38276cbc771f97a4152727f761
brianhoang7/7a
/square_list.py
526
4.09375
4
# Author: Brian Hoang # Date: 11/13/2019 # Description: Function that takes list and modifies each object to its squared value #takes mylist and modifies each object to be its squared value def square_list(mylist): #to tally through the length of mylist tally = 0 #multiplies each object by itself and repla...
1730efc73c8d2eb43475ec03f0c7cdfb7d4bf0c0
bandita19/imad-app-v2
/italian_database.py
1,160
3.84375
4
import sqlite3 import recipe1 def name(): name = "Creamcake" return name con = sqlite3.connect('recipes.db') c = con.cursor() c.execute('''drop table if exists italian''') con.commit() c.execute('''create table italian (recipe_name text not null primary key,category text)''') c.execute...
3a96ea9f64f09b7a1c382e8e2ec5a937912c036f
bandita19/imad-app-v2
/login.py
5,128
3.65625
4
import sqlite3 from tkinter import * from tkinter import messagebox import signup import project1 con = sqlite3.connect('recipes.db') p = con.cursor() #print("inside") def request(a,h,v): p.execute("insert into request_table(user,status) values (?,?);",(a,'pending' )) con.commit() messagebox.showi...
76158ad8f20bd09922340609e44d14b2a577c2ab
lauren0914/baekjoon
/09.07(대회 자리).py
336
3.546875
4
N = int(input()) for _ in range(N): # 3 preference_list = [] people, _ = map(int, input().split()) # 4 4 for _ in range(people): preference = input() # 1 4 1 4 preference_list.append(preference) # [1, 4, 1, 4] preference_set = set(preference_list) # [1, 4] print(people - len(p...
7a05ebfd7287435f0ccf92a2334e9b33e5973e03
lauren0914/baekjoon
/(31)1181.단어정렬.py
198
3.59375
4
str_list = ['but', 'i', 'wont', 'hesitate', 'no', 'more', 'no', 'more', 'it', 'cannot', 'wait', 'im', 'yours'] print(str_list) str_list = sorted(str_list, key = lambda x : len(x)) print(str_list)
f7a22e03437db6aed8e55b1b425eecdd7cee4589
hemankithreddy/hacktoberfest2k19
/Prime Factors/primefactorization.py
102
3.859375
4
import sympy n=int(input('Enter a number:')) for i in range(1,n): print(sympy.isprime(i),end=" ")
1180797f286a842189f9b9171590f493b35d4090
lega4e/flask-films
/filling/parse/nvxiex.py
1,680
3.6875
4
import time from threading import Thread, Lock class IntervalExecutor(Thread): ''' IntervalExecutor — это класс, который предназначен для интервального повторения какого-либо действия Уязвимость: время выполнения функции никак не измеряется, поэтому, если эта функция будет выполняться значительное время, ...
fd107de13e9d54a41c3b2cefc2a709c44b65460c
Mellohugoo/BatalhaPython
/classes/game.py
459
3.53125
4
from random import randint def rolar_dados(size): """retornar um valor aleatorio entre 1 e o size""" return randint(1,size) def values_for_enemy(difficult): """retornar random strenght, ability and constitution""" #difficult = forca + habilidade + constituicao forca = randint(1,difficult-2) ha...
6abb352534194f7ed99d7ad3be15eeb02192d3cf
kanisque/Programming
/binarySearch.py
1,373
4.03125
4
class Solution: def searchInsert(self, nums, target): # Recursive Approach # def binarySearch(nums,target,start,end): # if target > nums[-1]: # return len(nums) # if target < nums[0]: # return 0 # mid = (start+end) // 2 # ...
5f7808ab34dca4e792a4e62de175e7fac36b99d6
kanisque/Programming
/findCeilingFloor.py
1,120
3.828125
4
# Given an integer k and a binary search tree, find the floor (less than or equal to) of k, # and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None. class Node: def __init__(self, value): self.left = None self.right = None self.value = value def ...
ac5fe9b569d9c342d3e6f284f4671f46a5772832
kanisque/Programming
/knapsack.py
1,173
3.96875
4
from collections import namedtuple from functools import lru_cache import timeit items = [] def main(): #inputs costs = [1,2,3,1,2,3,5,2,7,1] weights = [2,1,4,5,2,6,1,3,6,3] capacity = 10 #Named Tuples for readability itemTuple = namedtuple('itemTuple',['cost','weight']) for cost,weig...
25d71f955e65b7fd8bd67850c5cc694e8eb5b2ba
meera-ramesh19/sololearn-python
/displaycalenderofthemonth.py
1,511
4.25
4
# input from the user the month and the year of the calendar and displaythe #calendar for the month or the year yearuser=int(input("Enter the year:")) print(yearuser) #monthuser=int(input("\nEnter the month : ")) #print(monthuser) startday=input("Enter the day of the week:") print(startday) calendar=[('January',range...
93a322154bac9981fa1c8b07d830660e5ddc1d2c
meera-ramesh19/sololearn-python
/learninglambda,map&filter.py
339
3.546875
4
# Declare a list x = [2, 3, 4, 5, 6] y = map(lambda v : v * 5, filter(lambda u : u % 2, x)) print y def cube(x): return x**2 cubes = map(cube, range(10)) print cubes print (lambda x: x**2)(5) print (lambda x, y: x*y)(3, 4) special_cubes = filter(lambda x: x > 9 and x < 60, cubes) pr...