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 |
|---|---|---|---|---|---|---|
d7fde37de96a578486d406415d28f46566c202ca | ethanjoyce14/autocross-v1.0 | /carpg_races.py | 4,814 | 3.765625 | 4 | import carpg
import carpgmenu
import carpg_autoshop
import random
class Race:
# A class that grants the race functionality
def __init__(self, totaltime):
self.totaltime = totaltime
def racestart(self):
# Start of the race
if carpg.current == '':
print("You ... |
8b9a31a1ffb56ff54780dfc22881286550ffb1d0 | orgh0/usr_csv_helper_tool | /csv_helper/row4.py | 556 | 3.59375 | 4 | import csv_helper
class row4:
def __init__(self, inp):
self.inp = inp
self.output = list()
def get_out(self):
tokens = self.inp.split(",")
tokens = tokens[:-1]
for token in tokens:
temp_token = token.split("_")
print("Is {} a mass or a def").for... |
5c9f3d7536081e47035308c8824605a45534773d | Adamthe1st/class-2016 | /reproducible workflows/palindrome example/tests/more_tests/test_2_palindrome.py | 573 | 3.796875 | 4 | from palindrome import is_palindrome
def test_single_character():
assert is_palindrome("a") == True
def test_two_same_character():
assert is_palindrome("bb")==True
def test_numbers_not_palindrome():
assert is_palindrome("ab3d")==False
def test_spacing_palindrome():
assert is_palindrome("... |
717e07ce6e76ff6606bf902af61dd31db3457ffb | vgswn/lab_codes | /SIX/COD/Lab/Q1.py | 959 | 4.125 | 4 | _end = '_end_'
def make_trie(*words):
root = dict()
for word in words:
current_dict = root
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict[_end] = _end
return root
def in_trie(trie, word):
current_dict = trie
for lette... |
cd981721d7f2515297c059baf9137d77cb9cf9f7 | jdg1837/MavSched | /Month.py | 1,588 | 3.75 | 4 | months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
def isMonth(month):
return month.title() in months
def countFile(month):
return month.lower() + '_count.csv'
def scheduleFile(month):
return month.lower() + '.csv'... |
92f98b090bd7c31f8c9f8f3980ef0f2a52e8ea83 | iron23butterfly/python | /helloWorld.py | 323 | 3.640625 | 4 | def main():
print ('\n')
print ('\nJaiShriRam')
user_name = input ('Wht is your name? ')
print ('RamRam ', user_name,"!!")
print ('\n' )
print ("\nGaneshaay Namaha!\n")
print ("\nhello world!\n")
if __name__ == "__main__":
main()
#OR
#def hello():
# print ('Sri Ramajayam')
#if __name__ == "__ma... |
857289d38210a6efb421780e8ad3fdfc95be36aa | iron23butterfly/python | /numbers.py | 259 | 3.875 | 4 | print(f'7/3 = {7/3}')
print(f'7//3 = {7//3}')
from decimal import *
a = Decimal('.10')
b = Decimal('.30')
result = a + a + a - b
print (result)
print (0.10 + 0.10 + 0.10 - 0.30)
# OUTPUT
# 7/3 = 2.3333333333333335
# 7//3 = 2
# 0.00
# 5.551115123125783e-17
|
321b7e57277446b9df3351a86770280ea6a1d287 | iron23butterfly/python | /FileOperation/filePath_Details.py | 1,557 | 3.734375 | 4 | # Example file for working with os.path module
#
import os
from os import path
import datetime
from datetime import date, time, timedelta
import time
def main():
# Print the name of the OS
print (os.name)
# Check for item existence and type
print ("Item exists: " + str(path.exists("textfile.txt")))
print... |
119329b585b254bcf60faacb6c79fca4ceebe123 | knight-wolf/Python | /python_tasks.py | 2,790 | 4.0625 | 4 | ##-------------tuple tasks
##--- 1 ---------
##x=(24,56,79.6,"hello","good",5,6,[4,5])
##print(type(x))
##print(x)
##--- 2 ----
##x=(24,56,79.6,"hello","good",5,6,[4,5])
##for i in x:
## print(x.index(i),i)
##--- 3 ----
##x=("hello","how","are", "you")
##if type(x)=='tuple':
##
##----------... |
7edfe39ddd94d7e8ec4e6ffd011797d8e693486d | prathyusha1/DSA | /week1/equilibrium_point.py | 333 | 3.53125 | 4 | def findEquilibriumPoint(arr,n):
sum = 0
leftSum = 0
for i in range(n):
sum = sum + arr[i]
for i in range(n):
sum = sum - arr[i]
if (sum == leftSum):
return i
leftSum=leftSum+arr[i]
eqIdx = findEquilibriumPoint([-7, 1, 5, 2, -4, 3, 0], 7)
print('equilibrium i... |
ab06f0a068e6729d011357ced93ef15956d07074 | asmi009/Web-Scraping-Project | /Beautiful soup/Beautiful Soup.py | 5,374 | 3.59375 | 4 | import timeit
start = timeit.default_timer()
from bs4 import BeautifulSoup #to scrape webpage
import requests #to get send request on website and get response
import pandas as pd #to make dataframe
import numpy as np
#Getting Website Response
get_website = requests.get("https://www.worldometers.info/coronavirus/")
#... |
5c66def8f899e10e0c8f746f502cec9f4d058f27 | lvhongyuan666/review | /10_sort.py | 5,112 | 3.8125 | 4 | # 打印横三竖五的星星
# a = 1
# while a <= 3:
# b = 1
# while b <= 5:
# print("*", end='')
# b += 1
# print()
# a += 1
# 打印竖五梯形
# c = 1
# while c <= 5:
# d = 0
# while d < c:
# print('*', end='')
# d += 1
# print()
# c += 1
# 九九乘法表
# i = 1
# while i <= 9:
# j ... |
9637757516aa5f2a19b9978b61fa88a2810b6a08 | Sayan450/IO | /test_songlist.py | 710 | 3.90625 | 4 | """
(incomplete) Tests for SongList class
"""
from songlist import SongList
from song import Song
# test empty SongList
song_list = SongList()
print(song_list)
assert len(song_list.songs) == 0
# test loading songs
song_list.load_songs('songs.csv')
print(song_list)
assert len(song_list.songs) > 0 # assuming CSV file ... |
1cd333335114761641cb20398da06de6051eb297 | chrisiou/wind-velocity-translator | /wind_timestamps_generator.py | 2,378 | 3.609375 | 4 | import sys
import random
from datetime import datetime, timedelta
TIME_FORMAT = '%Y-%m-%d %H:%M:%S'
'''
here you can change the time period of wind's velocities generation and the start time's wind velocity
'''
CURRENT_TIME = datetime.strptime('2021-05-23 00:30:00', TIME_FORMAT) # start time
END_TIME = datetime.strp... |
5f97503702d7aebbe9378452aa5bd5ab4d22f467 | evilsmile/python_programs | /thread/test.py | 636 | 3.640625 | 4 | #!/usr/bin/env python
__author__ = "anonymous"
import time
import threading
def func():
for i in range(800000):
print i,
print("func done.")
def main1():
start_time = time.time()
func()
func()
print("main1 done.");
end_time = time.time()
print("m1 time " + str(end_time - star... |
459b51c193898cf16c45fc82c5464c3aad3cb71f | SELC-ISU/pokemon | /pokemon.py | 1,151 | 3.59375 | 4 | from ElementalType import ElementalType
class Pokemon:
def __init__(self, name: str, personal_name: str, elemental_type: ElementalType):
self.name = name
self.personal_name = personal_name
self.elemental_type = elemental_type
# equivalent to javas toString kind of
def __str__(self... |
1f4c6875a6223d33d9a05ea9664aeb53aead2208 | praxitelisk/OpenCV_Image_Mining | /canny_edge.py | 918 | 3.890625 | 4 | #import Libraries
import cv2
import numpy as np
from matplotlib import pyplot as plt
import sys
import matplotlib.image as mpimg
##################################################
'''
This example illustrates how edges in an image
Usage:
canny_edge.py [<image_name>]
image argument defaults to fruits.jpg
'''
... |
180ec5503a0f29e6ba1db9b021c24842ad080d79 | areum514/pythonic | /generator/yield.py | 328 | 3.84375 | 4 | def gen():
value = 1
while True:
value = yield value #yield로 값을 반환하는 동시에 할당
def main():
print("=== print gen function ===")
g = gen()
print(next(g))
print(g.send(2))
print(g.send(10))
print(g.send(5))
print(next(g))
if __name__ == "__main__":
main()
|
9a802ce78f48b39abc293fbbacdf126e103b62ac | areum514/pythonic | /asynchronous/asyncio/async_comprehension.py | 543 | 3.5 | 4 | import asyncio
async def delay_range(to, delay=1):
for i in range(to):
yield i
await asyncio.sleep(delay)
async def run():
print("Async Comprehension")
return [i async for i in delay_range(3)]
async def run_multiple():
print("Async Await Comprehension")
func_list = [run, run]
... |
81d427b2c3891266e66a79239eb2f140a0a28454 | TrevorKitt/tkinter-painting | /tkinter_keyboard_binding.py | 1,051 | 3.53125 | 4 | from tkinter import *
window = Tk()
window.title('my gui')
canvas = Canvas(window, width=400, height=400)
canvas.pack()
circle = canvas.create_oval(100,200,130,230, fill='red')
blue_rect = canvas.create_rectangle(50,50,70,80,fill ='blue')
def move_circle(event):
key = event.keysym
if key == "Right":
... |
dea4ef42d5cf2fdb7422abad7104bbb80ce399a1 | Abdurrahmans/String-Problem-Solving | /String Practice/string _word_count2.py | 318 | 4.03125 | 4 | string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
print('The count is:', count)
s = 'bangladesh country is a beautiful is country country'
s1 = 'country'
s2 = s.split()
count = 0
for i in s2:
if i == s1:
count += 1
print('The substring count is:', count) |
594c2dfb43c870c326821e86fea92f22ea8b5151 | Abdurrahmans/String-Problem-Solving | /String Practice/CountDict.py | 132 | 4.03125 | 4 | str1 = "Apple"
countDict = dict()
for char in str1:
count = str1.count(char)
countDict[char] = count
print(countDict)
|
193e77f62dd588d9207e1f63de5555db0c07ac05 | sylee04/algo | /2009-Maximum Number of Balloons.py | 7,254 | 3.6875 | 4 | #1189. Maximum Number of Balloons
#text = "nlaebolko"
#text = "loonbalxballpoon"
text = "krhizmmgmcrecekgyljqkldocicziihtgpqwbticmvuyznragqoyrukzopfmjhjjxemsxmrsxuqmnkrzhgvtgdgtykhcglurvppvcwhrhrjoislonvvglhdciilduvuiebmffaagxerjeewmtcwmhmtwlxtvlbocczlrppmpjbpnifqtlninyzjtmazxdbzwxthpvrfulvrspycqcghuopjirzoeuqhetnbrcda... |
c2701a6ed610f5da00fc2f241d69f58a3015c765 | vs9390/flasksample | /parse_csv.py | 641 | 3.90625 | 4 | import csv
import pprint
# Function to convert a csv file to a list of dictionaries. Takes in one variable called "variables_file"
def csv_dict_list(variables_file):
# Open variable-based csv, iterate over the rows and map values to a list of dictionaries containing key/value pairs
reader = csv.D... |
82b1bccae67839e75f7c8bbe5b4ea6e4e2fdd0a0 | 1HommeAzerty/p3-MazeGyver | /gamet.py | 1,621 | 3.890625 | 4 | #! /usr/bin/env python3
# coding: utf-8
"""Makes the game run in text mode"""
from maze import Maze
from loot import Loot
from macg import Mac
class GameText:
"""Creates the instances for the main elements of the game.
Uses those element to run the game loop.
"""
def __init__(self):
maze1 ... |
df1ba417f6b9abc3cc7e44d582d2a831864613e5 | HSSON97/Secret-Society-1 | /CodeUp/ill_kwon/2653.py | 354 | 3.625 | 4 | #0 바로 뒤에는 1만 가능 1뒤에는 1,0 가능
# 시작이 0인경우와 1인 경우를 나누자
# n==1 일때 2
def f(a,b):
if(a==2 and b==1):
return 2
if(a==2 and b==0):
return 1
if(b==0):
return f(a-1,1)
else:
return f(a-1,0)+f(a-1,1)
n=int(input())
if(n!=1):
print(f(n,0)+f(n,1))
else:
print(2) |
1eaf4530ddd4661731a415b8ae9e384fa931dcfa | HSSON97/Secret-Society-1 | /CodeUp/hyung_seop/2632.py | 168 | 3.984375 | 4 | n = int(input())
def stairs(num):
if num <= 2:
return num
else:
return stairs(num-1)+stairs(num-2)
result = stairs(n)
print(result)
|
265489058e1b94d36f72ccd4c34972765859314f | gorgandiana/Proga | /hw_12/proga.py | 834 | 3.9375 | 4 | #Программа должна обходить всё дерево папок,
#начинающееся с той папки, где она находится,
#и сообщать следующую информацию (далее - по вариантам):
#в какой папке лежит больше всего файлов.
import os
start_path = '.'
max = 0
for root, dirs, files in os.walk(start_path):
print('Где мы сейчас', root)
pri... |
48517af908dc55b5f22cb2d6025a33cb8cde9aff | gorgandiana/Proga | /hw3/hw_03.py | 110 | 3.6875 | 4 | s = str(input("Enter word: "))
n = len(s)
i = 0
while (n>((2*i)-1)):
print(s[i:(n-i)])
i=i+1
|
c185546d5f10b2116edeb91a4b565ceac7c9d1dc | ronremets/Tasker | /tools/user.py | 765 | 3.765625 | 4 | # coding=ascii
"""
a user
"""
__author__ = "Ron Remets"
class User(object):
"""
a user class
"""
def __init__(self, username, password, info):
self._username = username
self._password = password
self._info = info
def __str__(self):
return """\
username = {}
passwo... |
701ec7da9bdc5dced435e3cf4cbda44079183178 | checor/python-clases | /sesion04/ejemplo02/archivo_csv.py | 414 | 3.6875 | 4 | import csv
with open("ejemplo.csv", 'w') as fcsv: # Creando archivo
writer = csv.writer(fcsv)
writer.writerow(["Nombre", "Apellido", "Genero"])
writer.writerow(["Nombre2", "Apellido2", "Genero2"])
writer.writerow(["Nombre3", "Apellido3", "Genero3"])
with open("ejemplo.csv", 'r') as fcsv: # Leer a... |
5ab33ca09272609067dd3a762ab31dd92411717a | checor/python-clases | /sesion01/ejemplo05/while_5.py | 64 | 3.75 | 4 | while n<5:
print("Numero {}".format(n))
n = n + 1
|
130ecc608aa73db6d1e4f827e80af2610f1eedfd | checor/python-clases | /sesion02/ejemplo01/lista-de-enteros.py | 174 | 3.734375 | 4 | n = input("Tamaño de la lista: ")
if not n.isdigit():
print("Número invalido")
else:
n = int(n)
lista = list(range(n))
for i in lista:
print(i)
|
700ab916b7c20caf167b9925466ef4352e79243b | checor/python-clases | /sesion01/reto05/tabla-multiplicar-for.py | 138 | 4 | 4 | n = 3
print("TABLA DE MULTIPLICAR")
print("-" * 20)
for i in range(1, 11):
print("{} x {} = {}".format(n, i, n * i))
print("-" * 20)
|
62466406cfd3be4d5692619595da7b2da7e94539 | checor/python-clases | /sesion05/ejemplo04/animales_tabla.py | 1,310 | 3.765625 | 4 | class Animal():
def __init__(self, nombre, especie, sonido):
self.nombre = nombre
self.especie = especie
self.sonido = sonido
def grito(self):
print("El {} hace {}".format(self.nombre, self.sonido))
def info(self):
print("Nombre: {} - Especie {}".format(self... |
f5ec6cd379fcfb8f2d6ce5b7b52403caea812769 | checor/python-clases | /sesion01/ejemplo05/par_non.py | 108 | 3.515625 | 4 | for i in range(11):
if i % 2 == 0:
print("Par")
else:
print("Non")
|
8d043832670f1f1f4a9fddc3dd58584084f5bcc9 | checor/python-clases | /sesion02/reto04/reservacion-con-diccionarios.py | 1,180 | 3.859375 | 4 | elementos = [
{
"nombre": "Habitación doble",
"precio": 150000.0,
"cantidad": 3
},
{
"nombre": "Transporte",
"precio": 3000.0,
"cantidad": 2
},
{
"nombre": "Tour en lancha",
"precio": 2170,
"cantidad": 1
},
{
"no... |
1630aca8d7a21851f80b32668a0434406e8bd123 | urziyath/GUI_Calculator | /Gui_Calculator.py | 2,500 | 3.84375 | 4 | from tkinter import *
root = Tk()
root.configure(background = "light blue")
root.title("Simple Calculator")
e = Entry(root,width = 35,borderwidth = 5)
e.grid(row=0,column=0,columnspan = 3,padx = 5,pady = 5)
def click(number):
num = e.get()
e.delete(0,END)
e.insert(0,str(num) + str(number))
... |
37bd25c1c9261bb2b98531fd6366cd4b67ab890a | ajmpunzalan/zigzag | /src/cut_palindrome.py | 2,376 | 3.65625 | 4 |
from longest_palindrome import get_longest_palindrome
from palindrome import time_decorator
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='input', help='Input String',
type=str, required=True)
return parser.parse_args()
de... |
8495f80a1293d51e0e53282d12bd4812a96d30cb | yuristefani/JOGO2 | /jogolegal.py | 8,713 | 4.09375 | 4 | from random import randint #spock 1 tesoura 2 papel 3 pedra 4 lagarto 5
tipo=int(input("1 para melhor de tres, 2 para jogador vs jogador, 3 para rodadas ilimitadas: "))
pcvit=0
usvit=0
if tipo==1:
pcvit=0
usvit=0
while (pcvit!=3 and usvit!=3):
usesc=int(input("faça a sua escolha (1 para ... |
b831639dd899859f8e12dba5d1ee4721762ce309 | martonMeszaros/python-battleship | /ship_placement.py | 9,315 | 4.34375 | 4 | """
A single ship placement cycle in ship_placement()
"""
from unicurses import *
from globals import *
from windows import *
def draw_ship(window, ship, character, color=WHITE):
""" Draws a ship onto a window. """
ship_origin_x = ship[0][1]
ship_origin_y = ship[0][0]
# Check ship orientation based o... |
fb04788459b04711b98ed17b9e099b4a96a69c97 | utrax/fromGit | /exploit01.py | 263 | 3.75 | 4 | ## GREETING FUNCTION STUFF
## DEFINING FUCNTIONS
def greeting(name):
print (f"Hello {name}, how you doing bro you have no idea how mach I missed you my Darling")
return
name = str(input("What is your name ? "))
## DEFINING MAIN FUNCTION
greeting(name) |
160eb81df7c6855753d6b18fe5f9b44df65b797e | FedorovMisha/PUL_LAB_7 | /main.py | 829 | 3.796875 | 4 | import re
text = "Baseball! Became@ popular in Japan after American soldiers introduced it during the occupation following World " \
"War II. In the 1990s a Japanese player, Hideo Nomo, became a star pitcher for the Los Angeles Dodgers. " \
"Baseball is also widely played in Cuba and other Caribbea... |
228d5d07ba7db3b9ddbdcd95c7746cea391ac68c | hbvj99/pybit-adder | /main.py | 1,152 | 3.734375 | 4 | import sys #sytem import
import iterator as m1 #import as m1
from inputNumber import BinaryConversion #import BinaryConversion
no3=[] #list
global n5 #global variables
def output(): #output function
for i in range (len(m1.sumF)): #length sum
no = str(m1.sumF[i]) #change to string
no3.append(... |
2957e5dbb73e444fc14a223b0ef85bbc2486e098 | spracle/python | /GUI/tk.py | 994 | 3.5 | 4 | #tk
#-*- encoding=UTF-8 -*-
__author__ = 'fyby'
from Tkinter import *
root = Tk()
def hello():
print('hello')
def about():
print('我是开发者')
menubar = Menu(root)
#创建下拉菜单File,然后将其加入到顶级的菜单栏中
filemenu = Menu(menubar,tearoff=0)
filemenu.add_command(label="Open", command=hello)
filemenu.add_command(label="Save", co... |
8949fd91df9d848465b03c7024e7516738e72c8e | jtew396/InterviewPrep | /linkedlist2.py | 1,651 | 4.21875 | 4 | # Linked List Data Structure
# HackerRank
#
#
# Node class
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# LinkedList class
class LinkedList:
# Function to initialize the LinkedList class
def __init__(self):
s... |
6518a3574bdd6a7c8d17457da76df351c80ace1f | jtew396/InterviewPrep | /minimum_swaps_2.py | 497 | 3.609375 | 4 | import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
arr = [i-1 for i in arr]
swaps = 0
for i in range(len(arr)):
if i != arr[i]:
for j in range(len(arr) - i):
if i == arr[j + i]:
... |
a624e3d14acd2154c5dc156cfaa092ab1767d6a5 | jtew396/InterviewPrep | /search1.py | 1,154 | 4.25 | 4 | # Cracking the Coding Interview - Search
# Depth-First Search (DFS)
def search(root):
if root == None:
return
print(root)
root.visited = True
for i in root.adjacent:
if i.visited == false:
search(i)
# Breadth-First Search (BFS) - Remember to use a Queue Data Structure
def ... |
78e04dee445264cd06b68053f1944def79f1746d | jtew396/InterviewPrep | /mergesort3.py | 1,617 | 4.15625 | 4 | # Python program for implementation of MergeSort
# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, left, middle, right):
n1 = middle - left + 1
n2 = right - middle
# create temp arrays
LeftArr = [0] * (n1)
RightArr = [0] * (n2)
# Copy data to temp ar... |
51f82114f94d4c45ed94a61113edd5a58245f9e9 | nickweseman/coderbyte | /timeconvert.py | 212 | 3.78125 | 4 | def TimeConvert(num):
hours = num // 60
minutes = num % 60
time = [str(hours), str(minutes)]
return ":".join(time)
# keep this function call here
print(TimeConvert(126))
print(TimeConvert(45)) |
e76ccac3b3d904481dd5022a6693dc67e36dc92a | louismillette/homeinvestment | /classes/Mortgage.py | 7,563 | 3.640625 | 4 | import statistics
import copy
import os
import itertools
import numpy as np
class Mortgage(object):
'''
Mortgage calculates the cash flows associated with home ownership, in NOMINAL dollars (ie literal amount taken out every period, unadjusted), accounting for taxes.
*** a note about cost of home ownership... |
03e57d9e6a2f4ecf3a47080536b9157981ee6859 | Khukhlaev/infa_2019_khukhlaev | /lab3/the_best_lab_3_task_3.py | 4,396 | 3.71875 | 4 | from graph import *
import math as m
# ________________________________________________________
# Sun Function
def sun(x_0, y_0, r):
"""(x_0, y_0) - coordinates of centre of the sun, r - radius of the sun, function returns list of reference to sun
object and (x_0, y_0)"""
penColor("yellow")
brushCol... |
8cb6204cb6023b934e9134f72e39c8ae624fbae2 | aniketjdv/mongodb | /mongodb_python.py | 5,021 | 3.671875 | 4 | import pymongo
#mongodb client
db=pymongo.MongoClient("mongodb://localhost:27017/")
studdb=db.school
studcol=studdb.student
c=1
while(c==1):
print("select the option")
print("1:insert data")
print("2:display data")
print("3:update data")
print("4:delete data")
i=int(input("Enter he... |
3e192d2fb29567b0a8121de25d604da39a482ea6 | viniciusparlatozaura/edutech-pr | /exercicio1.py | 151 | 3.84375 | 4 | n1 = int(input('digite um numero:'))
n2 = int(input('numero outro numero:'))
soma = (n1 + n2)
print("A soma {} + {} é = {}".format(n1,n2,soma))
|
42dc56d26d481c0929a5dabfd08846b4db73c3bd | ShroukMansour/2D-Fractals | /sierpinski.py | 2,008 | 3.546875 | 4 | import turtle
my_pen = turtle.Turtle()
def get_mid(p1, p2):
return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2 # find midpoint
def sierpinski_triangle(points, depth):
my_pen.up()
my_pen.goto(points[0][0], points[0][1])
my_pen.down()
my_pen.goto(points[1][0], points[1][1])
my_pen.goto(points[... |
b288d4d0bb10fe3fa47c578349f5070afcd1282c | maryb0r/geekbrains-python-hw | /lesson05/example01.py | 539 | 4.34375 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
with open("file01.txt", "w") as f_obj:
line = None
while line != '':
line = input("Type your text >>> ")
f_obj.write(f"{line... |
97f6072527b62706ad42be970f9e62280018d394 | maryb0r/geekbrains-python-hw | /lesson01/example04.py | 543 | 4.0625 | 4 | # 4. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
n = int(input("Введите целое положительное число >>> "))
max = n % 10
n = n // 10
while (n > 0):
temp = n % 10
if (temp > max):
max = temp
n = n... |
1e94eb4654f5f61e11fbc61a382904a4ab393828 | maryb0r/geekbrains-python-hw | /lesson04/example05.py | 828 | 4.125 | 4 | # Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from random import randint
from ... |
5e3189439b93a7ad057cbefc28c885fb8783efbd | maryb0r/geekbrains-python-hw | /lesson05/example05.py | 672 | 3.890625 | 4 | # Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
from random import randint
line = ''
with open("file05.txt", "w") as f_write:
for x in range(1, 10):
line += f"{randint(... |
9e9de6b4b29d7ea5ce6765fa0c2d508a44986c2c | wolfpackwolverine/python_urlshortener | /url_shortner.py | 1,794 | 3.53125 | 4 |
#we can use dictionary (key: original url, value: numeric id).
#when new url comes, we can simply give new id (latest id + 1) which always be unique.
#rather than returning id as shorten url, we apply base 62 encoding so we can compress base10 to base62
class URL_Shortener:
# suppose, we already have 10 billion ur... |
daadc78b6cbcc2480ef7ca229fc9673e45b8974d | Sayoden/JPI | /Exercice18.py | 542 | 3.75 | 4 | #!/usr/bin/python3
print("C'est le groupe A1")
print("Exercice 18 fait par Louis Iwinski")
n = 1
liste = []
l_2 = []
l_3 = []
while n != 0:
n = int(input("Entrer une valeur pour l'insérer dans une liste (0 pour arrêter):"))
liste.append(n)
for i in range (0,len(liste)-1) :
if liste[i]==2 or liste[i]==... |
a6ea628a9fed9d8e567e34258789ba7830745412 | Sayoden/JPI | /Exercice5.py | 299 | 3.90625 | 4 | #!/usr/bin/python3
print("C'est le groupe A1")
print("Exercice 5 fait par Louis Iwinski")
n = int(input("Entrer une valeur entière : "))
compteur = 0
liste=[]
v = ""
while compteur < n :
liste.append("*")
for i in range(len(liste)):
v += liste[i]
print(v)
v = ""
compteur +=1
|
c2da99735ee64b72b0271e5295a7bd8fbfad8eea | Sayoden/JPI | /Exercice15.py | 502 | 3.9375 | 4 | #!/usr/bin/python3
print("C'est le groupe A1")
print("Exercice 15 fait par Louis Iwinski")
n = int(input("Entrer un chiffre pour compléter le nombre à 4 chiffres"))
f = int(input("Entrer un chiffre pour compléter le nombre à 4 chiffres"))
z = int(input("Entrer un chiffre pour compléter le nombre à 4 chiffres"))
d = in... |
8e85f30061e61c9259b7a93d2f6876b2f2fc2534 | jameszhan/notes-ml | /01-mathematics/04-numerical-calculation/appendix-coding-practice/16_gradient_descent.py | 511 | 3.53125 | 4 | # -*- coding: utf-8 -*-
def derivative(g, epsilon=1e-8):
dx = epsilon
return lambda x: (g(x + dx) - g(x)) / dx
def gd(x_start, step, f, epsilon=1e-8):
x = x_start
for i in range(200):
grad = derivative(f, epsilon)(x)
x -= grad * step
print('[ Epoch {0} ] grad = {1}, x = {2}'.... |
cebdf759a3a1d8e054f60a17b16a89ab28f5aff1 | jameszhan/notes-ml | /06-programing-languages/01-pythons/01-lang-features/02-feature-codes/10_oop_mixin.py | 1,431 | 3.640625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'james'
class Chocolate(object):
def __init__(self):
super(Chocolate, self).__init__()
print('Chocolate initialized')
def color(self):
return 'black'
def taste(self):
return 'sweet'
class Peanuts(object):
def __init__(self):
... |
464db271eba286cf812547e57876c42f39df9942 | jameszhan/notes-ml | /01-mathematics/04-numerical-calculation/appendix-coding-practice/01_derivative.py | 475 | 4 | 4 | # -*- coding: utf-8 -*-
def derivative(g, dx=1e-8):
return lambda x: (g(x + dx) - g(x)) / dx
def cube(x):
return x ** 3
def parabola(a, b, c):
return lambda x: a * x ** 2 + b * x + c
print('((derivative cube) 5) = {0}'.format(derivative(cube)(5)))
squarex = parabola(1, 0, 0)
print('((derivative sq... |
3a6be4f800420414ad4637db2f48e9958739a841 | jameszhan/notes-ml | /06-programing-languages/01-pythons/01-lang-features/02-feature-codes/12_method_descriptor.py | 746 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# staticmethod and classmethod are build-in descriptor
class Class1(object):
def __del__(self):
print('del Class1')
def do_something(x):
print(x)
do_something = staticmethod(do_something)
def do_smth(self):
print(self, 'do it')
do_smth = c... |
8c7ad4b2c272da0f492d41e0b248c21fc4428965 | jameszhan/notes-ml | /02-swiss-army-knife/01-numpy/03_maths.py | 670 | 3.5 | 4 | # -*- coding: utf-8 -*-
import numpy as np
X = [1, 2, 3, 4, 5]
print('mean = {0}'.format(np.mean(X))) # 平均值
print('variance = {0}'.format(np.var(X))) # 方差
print('standard deviation = {0}'.format(np.std(X))) # 标准差
print('covariance = {0}'.format(np.cov(X))) ... |
c40cd7f90860810db6be3b85a104258c0da808dc | jameszhan/notes-ml | /06-programing-languages/01-pythons/02-boilerplate-codes/01-builtin-api/03_maths.py | 1,176 | 3.78125 | 4 | # -*- coding: utf-8 -*-
a = 3
b = 5
print('abs({0} - {1}) == abs({1}, {0}) => {2}'.format(a, b, abs(a - b) == abs(b - a)))
print('bin({0}) => {1}, bin(1023) => {2}'.format(b, bin(b), bin(1023)))
print('oct({0}) => {1}, oct(1023) => {2}'.format(b, oct(b), oct(1023)))
print('hex({0}) => {1}, hex(1023) => {2}'.format(b... |
20eab60ee140fa1ea6c55248083d8e113ca96b10 | jameszhan/notes-ml | /archived-files/obsoleted/py2/lang_features/nonlocal.py | 1,497 | 3.71875 | 4 | # -*- coding: utf-8 -*-
# python 2.x 不支持 nonlocal
def counter(init):
nonlocal = {'v': init}
def inc():
nonlocal['v'] += 1
print 'inc.locals: {0}'.format(locals())
return nonlocal['v']
print 'counter.locals: {0}'.format(locals())
return inc
c = counter(0)
c2 = counter(10)
f... |
e4d447dbd4423d74834fd7b0d03eaa234776c260 | jameszhan/notes-ml | /06-programing-languages/01-pythons/03-just-for-fun/02-algorithms/14_backtrack_rectangle.py | 1,621 | 3.640625 | 4 | # -*- coding: utf-8 -*-
def backtrack_recursive(a, k, check, handle):
n = len(a)
for i in range(n):
a[k] = i
if check(a, k):
if k == n - 1:
handle(a)
else:
backtrack_recursive(a, k + 1, check, handle)
def backtrack_iterative(n, m, check,... |
2e64022f3de1f4f422e95cc315dad67e7fa656ab | yassine2403/GOMYCODE | /4thcheckpoint_question1.py | 302 | 4.03125 | 4 | a=input("enter first number")
b=input("enter second number")
c=input("enter third number")
def abc_check (a,b,c):
if a>b and a>c:
print(a,"is the biggest")
elif b>a and b>c:
print(b,"is the biggest")
else:
print(c,"is the biggest")
abc_check(a,b,c)
|
d5d01c1c053754cee1cdb12ab639248fb9e6676b | yassine2403/GOMYCODE | /checkpoint3_5.py | 196 | 3.546875 | 4 | def takeSecond(elem):
return elem[1]
random = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
random.sort(key=takeSecond,reverse=True)
print('Sorted list:', random)
|
47345fe5a509759ec48a88b4c6dd5cf620a9d96e | yassine2403/GOMYCODE | /checkpoint8.py | 738 | 4.0625 | 4 | f =open("texte.txt",'r',encoding = 'utf-8')
def nth_line_reader(f,n):
for i in range (n):
print(f.readline())
n=input('enter number of lines you want to print counting from the top')
print('the first ' +n+' lines are')
nth_line_reader(f,int(n))
def lastnth_lines(f,n):
str1=''
... |
a3d06419fcd9fea07a35ba193f1b8ef8bf72a959 | JeanCarlosDS/ComedorDeRAM | /ComedorDeRAM.py | 618 | 3.5 | 4 | while True: # → Verifica-se sempre, logo o programa ficará preso neste loop.
argm = [] #
for w in range(48,123): #
for y in range(48, 123): #
for i in ran... |
0596bc6f07833e6bef052deee1ffd096caf0bd82 | mwidjaja1/WorldBankSQL | /growth.py | 728 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Example of loading SQL Database via Pandas and doing processing & calculations
in Python
"""
import math
import pandas as pd
import sqlite3
def final_population(row):
""" Calculates final population """
initial_pop = row['population']
pop_growth = row['population_growth']
... |
c43d98e28507b0e466228286ca0fa697be02f690 | ghzb/sockets | /client/main.py | 955 | 3.609375 | 4 | from sockets import SocketClient
def prompt():
print('> ', end='')
return input()
def output(data):
print("\r< " + data + "\n> ", end='')
client = SocketClient('localhost', 8888)
client.on("$MESSAGE", lambda data: output(data.message))
client.on("$CONNECT", lambda data: output("CONNECTED"))
client.on("... |
4ed580928366eac7db93e593b725bc86148410af | roblass/advent_of_code | /2020/12/distance_two.py | 1,671 | 3.515625 | 4 | # 990 is too high
import math
import sys
def update_coordinates(direction, distance, x, y):
if direction == 'N':
y += distance
elif direction == 'S':
y -= distance
elif direction == 'E':
x += distance
elif direction == 'W':
x -= distance
return x, y
def move_ship(... |
ffbd1535e7f9c25e817c10e31e0e6812a7645724 | knpatil/learning-python | /src/dictionaries.py | 686 | 4.25 | 4 | # dictionary is collection of key-value pairs
# students = { "key1":"value1", "key2": "value2", "key3": "value3" }
# color:point
alien = {} # empty dictionary
alien = {"green":100}
alien['red'] = 200
alien['black'] = 90
print(alien)
# access the value
print(alien['black'])
# modify the value
alien['red'] = 500
p... |
ed4bd4315289a312e5b9110b5229f70e3fe0fdd8 | knpatil/learning-python | /src/sets.py | 1,009 | 3.984375 | 4 | vowels = ['a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u']
set_of_vowels = {'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u'}
my_dict = {"k": "v", "k2": "v2"}
print("list: ", vowels)
print("set: ", set_of_vowels)
# properties : it holds only unique
print("length: ", len(set_of_vowels))
set... |
7b3f5e98d0ec4f94764e65e70a68c542f44ea966 | knpatil/learning-python | /src/lists2.py | 2,077 | 4.46875 | 4 |
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
# sort a list by alphabetical order
# cars.sort()
# print(cars)
#
# cars.sort(reverse=True) # reverse order sort
# print(cars)
print(sorted(cars)) # temporarily sort a list
print(cars)
cars.reverse()
print(cars)
print(len(cars))
# print(cars[4]) # exception... |
f0a72586b4a1603a7aa003bb258759019acc4c6f | knpatil/learning-python | /src/if_else_statements.py | 931 | 3.8125 | 4 |
cars = ['audi','bmw','lexus','ford']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
if 'bmw4' in cars:
print("I have BMW in list")
else:
print("no bmw")
# admission fee for a park
# age < 4: free
# 4 - 18: 25
# > 18: 40
age = 3
if age < 4:
print("... |
6da7f6b7b95b6360a98da1f217e77c71bf022d4a | knpatil/learning-python | /src/count_names.py | 582 | 3.875 | 4 |
names = []
while True:
username = input("Enter name:")
if username is None or username == "":
break
names.append(username)
print("List of names: ", names)
count_table = {}
for name in names:
if name in count_table:
cnt = count_table[name]
cnt += 1
count_table[name] = c... |
0b3d6e5cd67a4e7d9127ac1e677da11d6bf92c09 | jeffreybyrne/0401-reinforcement | /exercise.py | 965 | 3.78125 | 4 | from math import floor
string = "003111"
string2 = "813372"
string3 = "17935"
string4 = "56328116"
string5 = "234f"
string6 = "asdsd"
string7 = "1104932420839423804592340923429034"
def isInt(s):
try:
int(s)
return True
except ValueError:
return False
def luckCheck(string):
if st... |
0a8a186c3e9efb0f8b7effc801d63c1370739db7 | mdrajibkhan/PythonHacks | /PythonDeveloperHacks/GetNumberOfPossibleArraysOfCondition.py | 1,313 | 4.09375 | 4 | # Python program for implementation
# check criteria
def checkcriteria(arr):
w = 0
for i in range(0,len(arr),1):
if i%arr[i] == 0 or arr[i]%i == 0:
w=w+1
if w > 0:
return 1
else:
return 0
# Find combinations
def bubbleSort(arr):
matches = 1
n = len(arr)
# Tr... |
a87bf15fb1e4f742f5f31be7a1af84276ffe6fc2 | MaxAttax/maxattax.github.io | /resources/Day1/00 - Python Programming/task4.py | 808 | 4.40625 | 4 | # Task 4: Accept comma-separated input from user and put result into a list and into a tuple
# The program waits until the user inputs a String into the console
# For this task, the user should write some comma-separated integer values into the console and press "Enter"
values = input() # Use for Python 3
# After ... |
2823dce222d6d18b8e901786b78aa696d53effd4 | ek17042/ORS-PA-18-Homework02 | /task1.py | 872 | 4.25 | 4 | def can_string_be_float(user_value):
allowed_characters = ["0","1","2","3","4","5","6","7","8","9",".","-"]
for x in user_value:
if x not in allowed_characters:
return False
nr_of_dots = 0
for x in user_value:
if x == ".":
nr_of_dots = nr_of_dots + 1
if n... |
6e5cee6a44c16e8ab025a2f3345dcbddf3a58d15 | tmbolt/learning_python | /rand_fasta.py | 1,416 | 3.875 | 4 | #!/usr/bin/env python3
import gzip
import sys
import math
import random
# Write a program that finds creates random fasta files
# Create a function that makes random DNA sequences
# Parameters include length and frequencies for A, C, G, T
# Command line: python3 rand_fasta.py <count> <min> <max> <a> <c> <g> <t>
def ... |
e829a743405b49893446c705272db2f7323bb329 | Sharanhiremath02/C-98-File-Functions | /counting_words_from_file.py | 281 | 4.375 | 4 | def count_words_from_file():
fileName=input("Enter the File Name:")
file=open(fileName,"r")
num_words=0
for line in file:
words=line.split()
num_words=num_words+len(words)
print("number of words:",num_words)
count_words_from_file() |
5fd5364a389de92eb68cf5ab4c5eb7e194b9ecab | mtreml/project-euler | /011_020/12.py | 1,080 | 3.890625 | 4 | # The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Let us list the factors of the first seven triangle numbers:
#
# 1: 1
# 3: 1,3
# 6: 1,2,3,6
# ... |
9588a3e8ab91d3a2a028347c7ea37b2d091a508a | aubiao/leetcode-by-Python | /14.py | 363 | 3.625 | 4 | from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
prefixStr = ""
for i in zip(*strs):
if len(set(i)) == 1:
prefixStr += i[0]
else:
break
return prefixStr
x = Solution()
print(x.longestC... |
d77e11ed94149248b959263c575affb32350cf0a | hshine1226/currency-conversion | /main.py | 1,619 | 3.625 | 4 | import os
from country_code import get_country_code
from transfer_wise import get_converted
def input_num():
while True:
try:
num = int(input("#: "))
return num
except:
print("That wasn't a number")
def get_code(num):
return country_code[num]['code']
def... |
1362363a8c73b18c341ba694bfc27057542dffc8 | adriano-arce/Interview-Problems | /Advent-Of-Code-2015/03-Grid-Of-Houses/03-Grid-Of-Houses.py | 1,036 | 3.84375 | 4 | def this_year(directions):
curr = (0, 0)
delivered = {curr}
for direction in directions:
if direction == '^':
curr = curr[0], curr[1] + 1
elif direction == 'v':
curr = curr[0], curr[1] - 1
elif direction == '>':
curr = curr[0] + 1, curr[1]
... |
ba875fd5f7d924aa134a2c65bf627e37dc81db5b | adriano-arce/Interview-Problems | /Array-Problems/Missing-Ranges/Missing-Ranges.py | 611 | 3.578125 | 4 | def missing_ranges(nums):
LOW, HIGH = 0, 100
nums.append(HIGH)
ranges = []
low = LOW
for num in nums:
if num == low + 1:
ranges.append(str(num - 1))
elif num > low + 1:
ranges.append("{}->{}".format(low, num - 1))
low = num + 1
return ranges
if __... |
e8cd9e3b17f7178d3a6b5a1a85464112c3d7f1b4 | adriano-arce/Interview-Problems | /Advent-Of-Code-2015/12-Parse-JSON/12-Parse-JSON.py | 669 | 3.515625 | 4 | import json
def get_total(doc, ignore=None):
if isinstance(doc, list):
return sum(get_total(item, ignore) for item in doc)
if isinstance(doc, dict):
if ignore is not None and ignore in doc.values():
return 0
return sum(get_total(value, ignore) for _, value in doc.items())
... |
e8e164557742bc26dff153ecf8294727d0dcab2b | adriano-arce/Interview-Problems | /Advent-Of-Code-2015/09-Single-Night/09-Single-Night.py | 1,713 | 3.96875 | 4 | def all_routes(cities, i=0):
"""Return all possible routes, where cities[i:] have been permuted.
Args:
cities (list of string):
The cities that make up each route.
i (int, optional):
The starting index of the subarray of cities to be permuted.
Returns:
list... |
424eefb8560209897764465419a5de34a7627a85 | ParulProgrammingHub/assignment-1-Helly02 | /program11.py | 212 | 3.8125 | 4 | p=int(input("Enter the principle amount"))
t=int(input("Enter the time"))
r=int(input("Enter the interest rate"))
n=int(input("The number of values"))
ci=p+(1+r/n)**n*t
print("The compound interest is",ci)
|
355523a5ffd479fea877a011d18e60cfa876341e | ParulProgrammingHub/assignment-1-Helly02 | /program3.py | 198 | 4.28125 | 4 | centimeter=float(input("Enter the centimeter:"))
meter=centimeter/100
kilometer=centimeter/100000
print("The conversion of cm to m is:",meter)
print("The conversion of cm to km is:",kilometer)
|
64ca420c8c4c4df7a1db01326c74a263184db800 | chriswilkinsoncodes/hackerrank | /any_or_all.py | 144 | 3.609375 | 4 | #!/usr/bin/env python3
_, int_list = input(), input().split()
print(all(int(x) > 0 for x in int_list) and any(s == s[::-1] for s in int_list))
|
9491a09cc8966dc6ffcbf1b1c509a5f6c5156ef5 | chriswilkinsoncodes/hackerrank | /groupby_tuples.py | 185 | 3.71875 | 4 | #!/usr/bin/env python3
from itertools import groupby
s = input()
for k, g in groupby(s):
# print((sum(1 for _ in g), int(k)), end=' ')
print((len(list(g)), int(k)), end=' ')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.