blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4ed8f28feb103132beb8f29880a4542e773ed329 | Duaard/ProgrammingProblems | /HackerRank/Easy/StrongPassword/solution.py | 1,024 | 3.890625 | 4 | #!/bin/python3
import os
def elementPresent(password, db_string):
# Return wether list a and b have a common element
# Make the lists argument set
return set(password) & set(db_string)
def minimumNumber(n, password):
# Return the minimum number of characters to make the password strong
# Thes... |
0912bd457340dd025aa88673ab4a8bd298046317 | Duaard/ProgrammingProblems | /HackerRank/Easy/FairRations/solution.py | 985 | 3.796875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def fairRations(B):
odd_bread = []
# Check the number of odd loaves
# and add their index to index liste
for i in range(len(B)):
if B[i] % 2 != 0:
odd_bread.append(i)
# If the number of odd is odd return ... |
7136b39fbd9133c1c2ae742dce0b84665d8ecf86 | Duaard/ProgrammingProblems | /HackerRank/Easy/BetweenTwoSets/solution.py | 1,299 | 3.546875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def findLCM(num1, num2):
if num1 > num2:
num = num1
den = num2
else:
num = num2
den = num1
rem = num % den
while rem != 0:
num = den
den = rem
rem = num % den
gcd = den
... |
548afe5ad44003c042061a3c15fcca9c21f3efbb | Duaard/ProgrammingProblems | /HackerRank/Easy/BigSorting/solution.py | 1,048 | 3.984375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def bigSorting(unsorted):
# Store the len per each elem
len_dict = {}
sorted_list = []
# Loop through each element to store their len
for val in unsorted:
if len(val) not in len_dict:
# Create a new entr... |
f79524fc299c8ad8a4f062f3ee4d980b2edac8c8 | Duaard/ProgrammingProblems | /HackerRank/Easy/FlatlandSpaceStation/solution.py | 1,667 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def flatlandSpaceStations(n, c):
# There is only 1 space station
if len(c) == 1:
# Check most left and most right city
return max(c[0], (n - 1) - c[0])
# There is a space station for each city
# if len(c) == n:
... |
e2457b1eb6c5c5a0b9a2cc6be2aafd9cd8344296 | georules/MCModel | /MCModel2/Data1D.py | 201 | 3.515625 | 4 | #!/usr/bin/python
class Data1D:
dataX = []
dataY = []
def __init__(self, dataX = [], dataY = []):
self.dataX = dataX
self.dataY = dataY
def show(self):
print self.dataX
print self.dataY
|
b597809c23f9cde0b57dcab1d66817dea5fc97ee | phoebepx/Algorithm | /LeetCode/Word Ladder II.py | 2,641 | 3.703125 | 4 | # coding:utf-8
# created by Phoebe_px on 2017/3/16
'''
Description:
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. ... |
9a7ba381cc7f1a8b2f4ce6538843316d352a8ad5 | abhishekchhibber/Parsing-and-Query-Scripts | /circle.py | 293 | 3.5625 | 4 | rad = int(input("radius : "))
dia = (rad*2)+1
h = rad
k = rad
x = 1
y = 1
for cord in range(0,dia):
for rows in range (0,dia):
if (((x-h)**2)+((y-k)**2)) == rad**2:
print('x')
else:
print (' ')
x = x+1
y = y+1
|
2602afa3f33ce9a53c55c6c5c4559173ef863d73 | abhishekchhibber/Parsing-and-Query-Scripts | /google news recusrive - backup.py | 2,154 | 3.75 | 4 | import urllib.request
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
#get and read the URL
url = ("https://www.google.co.in/search?q=banking&num=100&espv=2&biw=1366&bih=653&tbs=cdr:1,cd_min:01/04/2016,cd_max:15/04/2016,sbd:1&tbm=nws&source=lnt&sa=X&ved=0ahUKEwjp2ICE15DMAhVBJ5QKHWoXDS... |
545da9756f951eb8e8a1ad007d02378eccf25178 | XuanC6/Data-Structures-and-Algorithms | /course 2 Data Structure/week 1 Basic Data Structures/tree-height_try.py | 2,245 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 4 21:07:10 2018
@author: CX
"""
class Node(object):
def __init__(self,parent_index = -1,children_index_list=[]):
self.parent_index = parent_index
self.children_index_list = children_index_list
def add_child(self,new_child_i... |
53eb63150ed819a08d8142fb536212724eb01447 | XuanC6/Data-Structures-and-Algorithms | /course 2 Data Structure/week 1 Basic Data Structures/tree-height_2.py | 1,816 | 3.515625 | 4 | # python3
import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class Node(object):
def __init__(self,parent_index = -1,children_index_list=[]):
self.parent_index = parent_index
self.children... |
f1049ce8db57eb081ad02c682f3060cc0a3cd042 | XuanC6/Data-Structures-and-Algorithms | /course 1 Algorithmic Toolbox/week 2 Introduction/fibonacci_sum_last_digit.py | 225 | 3.9375 | 4 | # Uses python3
def fibonacci_sum_last_digit(n):
n = n%60
a,b = 0,1
m = 0
for i in range(n):
a,b = b,(a+b)%10
m = (m+a)%10
return m
n = int(input())
print(fibonacci_sum_last_digit(n)) |
e98cf12646f84ec8d5a388266b566ecb088dfbc0 | anamariadem/University | /Semester 1/FP/past work/S#2 8.10.2019.PY | 2,690 | 3.859375 | 4 | '''
procedural programming
functions= subprograms subroutines procedures
functions:
have human readable names
each function does one thing
talk using parameters and/or returns
specification
'''
# simple feature-driven development
#id = 114, name = "Anna", grade = 10
s = {"id":114, "name":"Anna",... |
a31b864e1dcba5a00c57035a76937d0bc2321f47 | anamariadem/University | /Semester 1/FP/past work/S#3 15.10.2019.PY | 3,271 | 3.640625 | 4 | # add <student id>, <name>, <grade>
# delete student <student id>
# list
# exit
# help
# command_word param1,param2
def get_id (student):
return student[0]
def get_name (student):
return student[1]
def get_grade (student):
return student[2]
def create_student (sid,name,grade): #non ui
'''
Creat... |
b5bb11cfefdaf9e7ae1076d1399c7362873c1bab | anamariadem/University | /Semester 1/FP/past work/L#2 9.10.2019.PY | 6,608 | 4.46875 | 4 | def create_number (real,imaginary):
return [real,imaginary]
def empty ():
'''
Returns an empty list
'''
empty = []
return empty
def get_first_element (numberList):
return numberList[0]
def get_real(number):
return number[0]
def get_imaginary(number):
return number[1]
def set_rea... |
70acaad5c424a456a079e1d7d0b9c2612242d711 | anamariadem/University | /Semester 3/Computer Networks/python/Lab2/problem6/server_6.py | 3,226 | 3.734375 | 4 | """
The server chooses a random integer number. Each client generates a random integer number and send it to the server.
The server answers with the message “larger” if the client has sent a smaller number than the server’s choice,
or with message “smaller” if the client has send a larger number than the server’s choic... |
d0c9bb1989c12ee541fe6cc435de1be3dcb88b82 | anamariadem/University | /Semester 1/FP/past work/animals/ui.py | 2,481 | 3.59375 | 4 | from service import *
def menu ():
menu = '''
1. Add animal
2. Change type of an animal
3. Change type of a species
4. Show all animals with a given type sorted by name
5. Exit
'''
print(menu)
def list_animals (animals):
count = 0
for i in animals:
count += 1
print(str(count) + ". " ... |
f405175ba38efcb799269a8820063472412c5fd5 | dtekluva/zero-to-ML | /datatypes.py | 5,900 | 4.34375 | 4 | # # DATATYPES
# # INTEGERS
# # FLOAT
# # STRINGS
# # BOOLEANS
# # COMPLEX NUMBER
# # + plus
# # - minus
# # / division
# # * multiplication
# #triangle side_a = 5, side_b = 4 find side_c - (PYTHAGORAS)
# # side_a = input("Please enter side A : ")
# # side_b = input("Please enter side B : ")
# # side_a = int(side_a... |
fd729119aa79c3b89e4ee7966ac55260234ac2b6 | CyanBrown/PhysicsCalculator | /src/kinematics.py | 4,365 | 3.6875 | 4 | import math
from src.errors import *
class kinematics:
def __init__(self, kinvalues):
"""
:param kinvalues: dictionary of known values, used keys = ['X','X0','V','V0','A','T']
"""
self.values = kinvalues
self.solved = False
# calls calculate attributes to start th... |
bcf11a5da208a87272d1e864db22e5f5b946aa76 | neerajbardia/dh-key-exchange | /dh_key_exchange.py | 2,216 | 3.78125 | 4 | #diffie hellman key exchange
#this is a single file with the sender and the reciever functions, this file can be split into two separate files and made to communicate through socket programming to enable
#transfer of data. Socket programming and diffie hellman key exchange algorithm together can be very helpful to unde... |
81ee23a737cd0b6b2bd3e5ffa303581c2c72c884 | joelivey/PFAB | /Homework.python | 766 | 3.921875 | 4 | #!/usr/bin/env python
import math
first = "Joel"
last = "Ivey"
age = 70
print first + " " + last + " " + str(age)
print
sideA = 12.55
sideB = 17.85
sideC = math.sqrt((sideA*sideA)+(sideB*sideB))
print "length of side C = " + str(sideC)
print
operand1 = 95
operand2 = 64.5
string1 = str(operand1)
string2 = str(operand2)
... |
37e984963aa10ef3a73d39fd19405c750729b51c | biggstd/teaching36 | /gillespie/gillespie_algorithm.py | 2,928 | 3.546875 | 4 | import numpy as np
class gillespie:
def __init__(self, X_values, c_values, X_change, h_form, max_time, max_count):
self.X_values = X_values
self.c_values = c_values
self.X_change = X_change
self.h_form = h_form
# some stopper variables so the simulation does not go on fo... |
b547b4815a241ef79b9b5bad7c26ed11892bd610 | Miloloaf/Automate-The-Boring-Stuff | /chapter_12/txt2excel.py | 666 | 3.53125 | 4 | #! python 3
# Reads in the contents of a text file and inserts those contents into a spreadsheet,
# with one line of text per row. The lines of the first text file will be in the cells of column A,
# TODO Lines of the second text file will be in the cells of column B.
import openpyxl
text_file = r"C:\Users\User\.P... |
e0e4d705156e2897d38994feb5407604f1502c09 | Seowyongtao/Snake_Game | /snake.py | 1,617 | 3.765625 | 4 | from turtle import Turtle
STARTING_POSITION = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
RIGHT = 0
LEFT = 180
class Snake:
def __init__(self):
self.snake_body = []
self.create_snake()
def create_snake(self):
for position in STARTING_POSITION:
self.... |
662118b6d213215725262300f3fdb94eeb508bdc | kapeed54/python-exercises | /Functions/4. reverse_a_string.py | 107 | 4.1875 | 4 | #python program to reverse a string
def rev(x):
return x[::-1]
string = rev("1234abcd")
print (string) |
54cc30035a08a05123f76d06811c3bdc22cac087 | kapeed54/python-exercises | /Functions/2. sumofallonlist.py | 167 | 4.09375 | 4 | #python function to sum all the number in the list
def sum(num):
count = 0
for x in num:
count += x
return count
print (sum((8,2,3,0,7)))
|
c784c3ebc68cf0ad3801ab65a53bcc7e8f0f10e8 | kapeed54/python-exercises | /Data Types/46. length_of_tuple.py | 108 | 3.953125 | 4 | # python program to find the length of a tuple
tuple1 = tuple("workshop")
print (tuple1)
print(len(tuple1)) |
b20e47ee3cc7718215fbfc409c589137f08c5a14 | kapeed54/python-exercises | /Data Types/32. print_dict.py | 225 | 4.3125 | 4 | # python program to generate and print a dictionary that contain a number
# (between 1 and n) in the form (x,x*x)
num = int(input("Enter a number : "))
dict1 = dict()
for a in range(1, num+1):
dict1[a]=a*a
print(dict1) |
bffbe649ef12a1685864c35d3b993269330fd4c2 | kapeed54/python-exercises | /Data Types/44. slice_tuple.py | 113 | 3.828125 | 4 | # python program to slice a tuple
tuple1 = ('w','o','r','k','s','h','o','p')
slice1 = tuple1[2:4]
print(slice1)
|
74ea0084d277df2f2c2a4e4aac63d88ba7b6d92c | kapeed54/python-exercises | /Data Types/42. convert_L_T.py | 135 | 4.25 | 4 | # python program to convert a list to a tuple
list1 = ['i','n','s','i','g','h','t']
print(list1)
tuple1 = tuple(list1)
print (tuple1)
|
b077d9fef7a17290f12dd806704e5ddba02a23dd | kapeed54/python-exercises | /Functions/16. sqandcube.py | 341 | 4.4375 | 4 | # python program to square and cube every number in a given list of integer using lambda
list1 = [1,2,3,4,5,6,7,8,9]
print("List of integers: ",list1)
square = list(map(lambda x:x**2, list1))
cube = list(map(lambda x:x**3, list1))
print("the square of numbers in the list is: ", square)
print("the cube of numbers in th... |
3ad88b6badec5de8abdb09ba4243cc9d65cf3d0a | kapeed54/python-exercises | /Data Types/4. swap.py | 277 | 3.984375 | 4 | #python program to get a single string from two
#given strings, separated by a space and swap the
#first two characters of each string.
def swap(a,b):
a_update = b[:2] + a[2:]
b_update = a[:2] + b[2:]
return a_update + ' ' + b_update
print(swap('abc','xyz'))
|
7d1aea77096445b3ef07a77016f8f1032062ba4b | plfsantos/Bootcamp | /main.py | 1,967 | 3.625 | 4 | import numpy as np
import pandas as pd
df = pd.read_csv("https://pycourse.s3.amazonaws.com/bike-sharing.csv")
print('Qual o tamanho desse dataset?')
print(df.info())
print('Qual a média da coluna windspeed?')
print(df['windspeed'].mean())
print('Qual a média da coluna temp?')
print(df['temp'].describe())
print('Qua... |
bc798958bacd8f377ec50af5b4db273cc66b6b20 | palindungan/2021_skripsi | /OpencvTutorial/TutorialMurtaza/Src/5JoiningMultipleImages.py | 1,349 | 3.546875 | 4 | # start of import library
import cv2
import numpy as np
from TutorialMurtaza.Util import BaseFunction
# read image
img = cv2.imread("../Resources/lena.jpg")
# convert color img from BGR to GRAY
imgGrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Blur (src, kernel_size, sigma)
kernelSize = (7, 7) # odd number : rise t... |
c66c06090249c08c0cb0e36276b46ab6769fa622 | dicompyler/dicompyler-core | /dicompylercore/util.py | 5,286 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# util.py
"""Several utility functions that don't really belong anywhere."""
# Copyright (c) 2009-2016 Aditya Panchal
# This file is part of dicompyler, released under a BSD license.
# See the file license.txt included with this distribution, also
# available at http:... |
722c8c853f637857b8abcebbb4a79a8ddcb0bacc | Matthew-P-Lee/Python | /keyboard_row.py | 1,048 | 4.0625 | 4 | import time
#Keyboard row
def findLetterInRows(letter,rows):
for row in rows:
print "<<------------------>>"
if findLetterInRow(letter,row):
return row
#if a letter is found in a row, search only that row, and advance to the next letter
def findLetterInRow(letter,row):
print "Letter:{0}".... |
0095ba787644179167e19e863352a283583d0b06 | vignesh0794/codekata | /printntime.py | 93 | 3.90625 | 4 | a=input("enter the string to be printed")
n=int(input("no of times to repeat:"))
print(a*n) |
8b8e3d27750ccae59eec355b4761e628bbe43fa3 | vignesh0794/codekata | /allarmstrong.py | 251 | 3.96875 | 4 | a=int(input("enter the starting number"))
b=int(input("enter the ending number"))
for num in range(a,b+1):
sum=0
tmp=num
while tmp>0:
digit=tmp%10
sum+=digit**3
tmp//=10
if num==sum:
print(num) |
ba570244b183bea956e010137c1a2dbde3f63392 | thiaagodev/Curso_Python_Mundo_3 | /PythonExercicios/ex079.py | 542 | 3.984375 | 4 | valores = []
while True:
num = int(input('Digite um valor: '))
if num in valores:
print('Valor duplicado! Tente novamente.')
else:
valores.append(num)
print('Valor adicionado com sucesso!')
resposta = input('Quer continuar? [S / N]: ').strip().upper()[0]
while resposta ... |
54db84b28884b647a9b182f2a2dcb6866986e750 | thiaagodev/Curso_Python_Mundo_3 | /PythonExercicios/ex091.py | 564 | 3.546875 | 4 | from random import randint
from time import sleep
from operator import itemgetter
jogo = {
'jogador1': randint(1, 6),
'jogador2': randint(1, 6),
'jogador3': randint(1, 6),
'jogador4': randint(1, 6)
}
ranking = {}
print('Valores sorteados: ')
for key, value in jogo.items():
print(f'{key} tirou {va... |
f6268940406e69b1bc8df0ede8cdaacad07c8d6b | thiaagodev/Curso_Python_Mundo_3 | /pythonteste/aula17a.py | 525 | 4 | 4 | num = [2, 5, 9, 1]
num[2] = 3
num.append(7)
num.sort(reverse = True)
num.insert(2, 0)
num.pop(2)
num.insert(2, 2)
num.remove(2)
print(num)
print(f'Essa lista tem {len(num)} elementos')
valores = []
for count in range(0, 5):
valores.append(int(input('Digite um valor: ')))
for pos, valor in enumerate(valores):
... |
99098b529ce859e8a426ea2785a4e7b41b1fb1ca | thiaagodev/Curso_Python_Mundo_3 | /PythonExercicios/ex106.py | 201 | 3.8125 | 4 | print('SISTEMA DE AJUDA PyHELP')
print('-='*30)
while True:
resp = input('Função ou Biblioteca > ')
if resp.upper() == 'FIM':
print('Até Logo!')
break
print(help(resp))
|
c36d13eb07f511c03cdfa5e8250f24f4175109fc | thiaagodev/Curso_Python_Mundo_3 | /PythonExercicios/ex082.py | 538 | 3.890625 | 4 | valores = []
pares = []
impares = []
while True:
valores.append(int(input('Digite um número: ')))
resposta = input('Deseja continuar? [S / N]: ').strip().upper()[0]
while resposta not in 'SN':
resposta = input('Resposta inválida! Deseja continuar? [S / N]: ').strip().upper()[0]
if resposta == ... |
50c1e02f0d86f068e122ba6ad28bbe1fc992464f | thiaagodev/Curso_Python_Mundo_3 | /PythonExercicios/ex078.py | 672 | 3.796875 | 4 | valores = []
for i in range(0, 5):
valores.append(int(input(f'Digite o valor da posição {i}: ')))
print(f'O maior valor foi {max(valores)} e está nas posições ', end='')
if valores.count(max(valores)) > 1:
for pos, valor in enumerate(valores):
if valor == max(valores):
print(pos, end='...... |
98aed917d37c2d73c2038028caa78e8c8c8d541a | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/EncryptionAlgo_Py/HillCipher.py | 2,899 | 3.984375 | 4 | def generateKey(x):
import string
import numpy as np
import sympy
import random
key=""
if x>10:
randomlist = random.sample(range(0, 100), 10)
else:
randomlist=random.sample(range(0,100),x-1)
rand_prime=sympy.randprime(0,9999)
key_array=np.identity(x)
key_array=key... |
5c107792152e749c84e75e4635917ad81727a43e | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/email validation.py | 226 | 4.03125 | 4 | import re
Input = input("Please enter an email: ")
x = re.search("[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+", Input)
if x == None:
print("This is not a valid email format")
else:
print("This is a valid email format")
|
e230a9c78817a70f021187a8b842aec9b8379f0a | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/Triangle_Py/number.py | 205 | 3.65625 | 4 | #number triangle using bahasa
def ayam():
a = 1
c = int(input("Masukkan berapa banyak : ")) #input number
d = c
while(a<=c):
print(' '*d,f' {a}'*a)
a+=1
d-=1
ayam() |
79e7bceaaf2828250f84549616d80f05d54a3078 | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/EncryptionAlgo_Py/XorCipher.py | 850 | 3.703125 | 4 | def encrypt(text,key):
from itertools import cycle
import base64
encrypted_text=''
for i,j in zip(text,cycle(key)):
encrypted_text= encrypted_text+chr(ord(i)^ord(j))
encrypted_text_bytes= encrypted_text.encode("ascii")
encrypted_text_bytes= base64.b64encode(encrypted_text_bytes)
... |
f89986c19d7f2ac5f29be2d407d1003a899004a0 | starkblaze01/Algorithms-Cheatsheet-Resources | /Python/RecursivePalindrome.py | 552 | 4.09375 | 4 | def isPalindrome(s):
s = s.lower().replace(' ', '') # this allows working on sentences as well
if s == '' or len(s) == 1:
return True
else:
if s[0] != s[-1]:
return False
s = s[1:-1]
return isPalindrome(s) # note: we might delete s = s[1:-1] and write directly r... |
71999167c68950713b3f0a1c784c183f2af2f0e6 | Zantiki/PyScripts | /turtlecircle.py | 4,040 | 4.09375 | 4 | # Sebastian Ikin, 23/09-19
import turtle
import math
from _tkinter import TclError
# Method to reset the screen, write the drawing-type and prep the turtle
def set_up(r, main_func):
# Reset the window for a new drawing
wnd.resetscreen()
trt.penup()
trt.goto(-250, 250)
trt.pendown()
# Write w... |
09e90d368c61908ac81683f4738b5c949c100e44 | Zantiki/PyScripts | /GCD.py | 259 | 3.96875 | 4 | def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
run = True
while run:
a = input("A: ")
b = input("B: ")
print(gcd(int(a), int(b)))
y_n = input("Finished? y/n: ")
if y_n == "y":
run = False
|
a2f933774c468e1a4508c92e977ec118a724bf48 | ekohilas/rubber-snek | /other/test.py | 601 | 3.59375 | 4 | def send_string(string):
char, string = string[0], string[1:]
while char:
if char == "\\":
escape = ""
char, string = string[0], string[1:]
while char != "\\":
escape += char
char, string = string[0], string[1:]
if escap... |
e033da6d987aa12559398985afe44649036890f6 | al11588/WordSplitter | /wordsplitter.py | 164 | 4.03125 | 4 |
words = open('new.txt') #opens the pre existing text file
for word in words.read().split(): # the function that splits the words from the text file.
print word |
c834903f7e3ee19fe6d3a9306825f129bcada849 | SivaprakashAnand/python-basics | /game_inventory.py | 2,547 | 4.1875 | 4 | # game_inventory.py
# We demonstrate some ways to display, add and remove items from a
# player's inventory in a fantasy game.
def display_inventory(inventory={}):
print('\n- - - - - - - - - -')
print('INVENTORY: \n')
# Initialize counter variable
count = 0
# CASE: Nonempty Inventory
if (inv... |
341742816327f100585187bcdc3defc167eb5a7e | Audio/SPOJ | /ONP/solution.py | 618 | 3.59375 | 4 | def solve(expr):
global i
arg1 = arg2 = op = None
while i < len(expr):
c = expr[i]
i += 1
if c == '(':
subexpr = solve(expr)
if i >= len(expr):
return subexpr
elif arg1 == None:
arg1 = subexpr
else:
... |
519ad8ead2b98ad419677dbdac981ab54f201186 | DuyDucNguyen/Fenics_rotating_disk | /comp_stress_disk/Functions/memorize.py | 544 | 3.828125 | 4 | from functools import wraps
def memorize(func):
"""Store the results of the decorated function for fast lookup
"""
# Store results in a dict that maps arguments to results
cache = {}
# Define the wrapper function to return.
@wraps(func)
def wrapper(*args, **kwargs):
# If these argum... |
950ac9b14657a88e0ac10e5c782c055f9a90253a | ProgrammingWithPranav/Paint-Program | /main.py | 2,477 | 3.8125 | 4 | import pygame
import random
print("This is a paint program I wrote using Python and Pygame")
print("There are nine colours in this program. Red is the default colour.")
print("Press the following keys for the spesific colours:")
print("Red = r")
print("Green = g")
print("Yellow = y")
print("Blue = b")
print("Black = l... |
3e8903d8e0fbceaebbcf3fe9930cf2701df15eb6 | vnagaraj/nand2tetris | /projects/project7/VMTranslator.py | 15,461 | 3.59375 | 4 | import sys
import re
import os
class Parser:
"""
Handles the parsing of a single .vm file and encapsulates access to the input code
Reads VM commands, parses them and provides convenient access to the components.
In addition it removes all white spaces and comments
"""
# command types
C_AR... |
176bffc8ed134ccb5425c8f9c647b62eaeb06e3c | ruot-nyak/Lists-and-Loops | /list_loops.py | 404 | 3.84375 | 4 | songs = ["ROCKSTAR", "Do It", "For The Night"]
print(songs[0:3])
print(songs[1:3])
songs[0] = "Dynamite"
print(songs)
songs.append("Something Special")
songs.append("To The Top")
songs.append("Already")
songs.remove("Do It")
print(songs)
animals = ['snakes','dogs','cats',]
animals.append('fish')
print(animals... |
2b45416f06505888ef6aa1ad50e467449dbce57a | slayerwalt/LeetCode | /OJ/leet421/leet421.py | 1,012 | 3.5 | 4 | # leet421
from typing import List
class Solution:
def findMaximumXOR1(self, nums: List[int]) -> int:
# 哈希法,
# 要点 x ^ a = b => x ^ b = a, a ^ b = x;
L = max(len(bin(x)) for x in nums)
ans = 0
for i in range(L)[::-1]:
ans <<= 1
curXor ... |
da960665cf94e9fa4b792d694981c60048786bc0 | slayerwalt/LeetCode | /OJ/leet019/leet019.py | 2,079 | 3.625 | 4 | # from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def print(self):
next = self
while next:
print(f'{next.val} -> ', end='')
next = next.next
print(None)
class Solution:
def removeNthFr... |
0e0e88c25560304b3566d52bc899672d581e3366 | slayerwalt/LeetCode | /OJ/leet554/leet554.py | 718 | 3.6875 | 4 | # leet554
from typing import List
def init(dims, filled_value = 0):
if not dims: return filled_value
return [init(dims[1:]) for _ in range(dims[0])]
from collections import defaultdict
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
Counter = defaultdict(int)
for L i... |
f745464720dce6123cdd2b67e70acace3791c7b6 | slayerwalt/LeetCode | /OJ/leet395/leet395v2.py | 565 | 3.546875 | 4 | # leet395
from typing import List
from collections import Counter
class Solution:
def longestSubstring(self, s: str, k: int) -> int:
# 32ms, 递归
for si in set(s):
if s.count(si) < k:
return max(self.longestSubstring(sub, k) for sub in s.split(si))
re... |
95a0a8b08f14e64c70a5981fa39d3108e516b9bc | slayerwalt/LeetCode | /OJ/leet127/leet127.py | 512 | 3.640625 | 4 | # leet127
from typing import List
from collections import defaultdict
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
M = defaultdict(set)
for word in wordList:
edges = M[word]
for i in range(len(word)):
... |
8827ce662ab90602ec049925389001927a0b6c85 | bsyouness/CoffeeRecommender | /coffee.py | 2,693 | 3.78125 | 4 | """ This script allows to:
1) Parse names based on a certain structure:
```
$ python coffee.py parse "Organic Fair Trade Sweet and Sour Indian"
Decaf False
Organic True
Fair Trade True
Country India
Adjective Sweet And Sour
```
2) Summarize dat... |
43a52253df72362366d5a9e38f1433eeba79f445 | DAI-Lab/AnonML | /anonml/rsa_ring_signature.py | 4,698 | 3.75 | 4 | import os
import hashlib
import random
import Crypto.PublicKey.RSA
class PublicKey(object):
def __init__(self, e, n, size):
self.e = e
self.n = n
self.size = size
def to_json(self):
return {
'e': self.e,
'n': self.n,
'size': self.size
... |
fc511d1aa6aeef5de31cb20da16db647259274a8 | yuetlong/project-euler-solutions | /p020/p020.py | 206 | 3.703125 | 4 | #!/usr/bin/env python3
from scipy.misc import factorial
val = factorial(100, exact = True)
def sum_digits(n):
r = 0
while n:
r, n = r + n % 10, n//10
return r
print(sum_digits(val))
|
88169b16f17f537f92ea84e84a06d9e7d4f0fa6d | yitzyire/PythonCourse | /5.2.py | 822 | 4.1875 | 4 | #5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Ente... |
b28712aff7c2d77b3ec4ce58037befc142c3d137 | kaiser-matheus/python_classes | /primeiros ex python/ex11.py | 129 | 3.609375 | 4 | import math
graus = float(input("Quantos graus? "))
radianos = graus/180 * math.pi
#Agora é só adicionar o exercício 10
|
541a15b65df70d2dd4dd68711b03bd1c67d699a9 | kaiser-matheus/python_classes | /primeiros ex python/ex07.py | 320 | 3.984375 | 4 | x = int(input("Salario: "))
Maior = x
Menor = x
Soma = x
for i in range(11):
x = int(input("Salario: "))
Soma = Soma + x
if x > Maior:
Maior = x
elif x < Menor:
Menor = x
print("O maior salario:", Maior)
print("O menor salario:", Menor)
print("Total dos salarios:", Soma) |
f7aaac90b60c3ac6e20e2a30a4749e7fbf4daa7f | kaiser-matheus/python_classes | /primeiros ex python/ex01.py | 154 | 3.625 | 4 | ze = 1.10
chico = 1.50
count = 0
while (ze <= chico):
ze += 0.3
chico += 0.2
count += 1
else:
print("Serao necessarios", count, "anos.") |
ea2afff563ea962371a9d253c448689893f26c65 | irtiza7/String-Operations | /Find Two Intergers from Array that Multiplying to Certain Product/main.py | 641 | 3.984375 | 4 | # find two integers from an array which multiple to a certain product
# OPTIMIZED SOLUTION O(n)
def func(intList, product):
for i in intList:
temp = product/i
if temp in intList:
print(f"Numbers are {i} and {int(temp)}")
return None
# NON OPTIMIZED SOLUTION O(n^2)
... |
f6766dba9b5fbbab3db99f5677d577c2204e021a | irtiza7/String-Operations | /Recursive Method for Decimal to Binary Conversion/main.py | 511 | 4.46875 | 4 | # Program to convert a positive decimal number into binary number.
def decimalToBinary(num):
assert num >= 0, "Number is not a Positive Decimal Number"
# Binary of decimal 0 is also 0
if num == 0:
return 0
# Base Case: if num 1 then return 1 because 1 can not be divided by 2
i... |
c27f76a3c527184078f7ff1136c4b24b910a12e0 | mbonsma/merely-useful.github.io | /src/refactor/set_lookup_table.py | 582 | 4 | 4 | LETTERS = {
'A' : {'vowel', 'upper_case'},
'B' : {'consonant', 'upper_case'},
# ...other upper-case letters...
'a' : {'vowel', 'lower_case'},
'b' : {'consonant', 'lower_case'},
# ...other lower-case letters...
'+' : {'punctuation'},
'@' : {'punctuation'},
# ...other punctuation...
}
... |
70dd121a2712b8be7b405c465e25a79875ee2240 | mbonsma/merely-useful.github.io | /src/unit/stringio_example.py | 233 | 3.796875 | 4 | from io import StringIO
writer = StringIO()
for word in 'first second third'.split():
writer.write('{}\n'.format(word))
print(writer.getvalue())
DATA = '''first
second
third'''
for line in StringIO(DATA):
print(len(line))
|
c023b4e49ca6c365029bb08903277a1155bf06b2 | mbonsma/merely-useful.github.io | /src/docs/trim.py | 863 | 3.953125 | 4 | '''
Tools for trimming values to lie in a specified range.
'''
def trim(values, low, high, in_place=False):
'''
Ensure that all values in the result list lie in low...high (inclusive).
If 'in_place' is 'True', modifies the input instead of creating a new list.
Args:
values: List of values to b... |
2e6393f4cf4515150fc2221ce03f8a3d34349816 | smith-megan/pythonintro | /loan_calc.py | 880 | 4.25 | 4 | #Get teh loan details
money_owed=float(input("how much money do you owe, in dollars\n"))#50000
apr=float(input("What is the annual percentage rate?\n")) #3%
payment=float(input("what will your monthly payment be, in dollars\n")) # $1,000
months=int(input("How many months do you want to see results for?\n")) #24
#Divid... |
39899b9c136aed2cd80efcb961edeea2a5559abf | Jeff-Clapper/Coding_Dojo | /Python/fundamentals/for_loop_basic_1/for_loop_basics_1.py | 581 | 3.53125 | 4 | #Basic
for x in range(0,151):
print(x)
#Mulitples of Five
for x in range(5,1001,5):
print(x)
#Counting, the Dojo Way
for x in range(1,101):
if x % 10 == 0:
print("Coding Dojo")
elif x % 5 == 0:
print("Coding")
else:
print(x)
#Whoa. That sucker's huge (hehe)
total = 0
for x... |
1045a7e88405184e997b8837d6f8d2baf84c41fd | rjlardizabal/PythonCrashCourse | /Chapter 3/3-1_names.py | 238 | 4.5625 | 5 | """3-1. Names: Store the names of a few of your friends in a list called names
. Print each person’s name by accessing each element in the list, one at a time
"""
names = ['jen', 'grace', 'jonard']
for name in names:
print(name)
|
d7ad536c2ef85646d7b8ed4027c2c9f6b22e6040 | Gumbeat/test_tasks | /1/main.py | 994 | 3.6875 | 4 | import math
def multiply(x, y):
s_x = str(x)
s_y = str(y)
len_x = len(s_x)
len_y = len(s_y)
if len_x == 1 or len_y == 1:
r = int(x) * int(y)
return r
n = len_x
if len_x > len_y:
s_y = s_y.rjust(len_x, '0')
n = len_x
elif len_y > len_x:
s_x = s_x.... |
e35a15efabe83cf13fdef30da09130b3db2caeae | 82-petru/Loops_conditions | /For_loop_list_07.py | 442 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 19 15:49:06 2019
@author: petru
"""
r = [1, 2, 4, 5, 9] #variable with list of items
for hul in r: #this loop will run the code under the for x in r
print(hul) #dsiplay the hul not the 'r'
for item in [1, 3, 21]: #the variable between for and in can be set to ... |
32b33dedaf420b8b07443c4861d568ca1f16ff64 | billowy552/RPlab_python | /1주차 숙제/Example5.py | 883 | 3.703125 | 4 | def sort_tuple(input_dict):
list_temp = list(input_dict.values()) # input 딕셔너리의 value를 리스트로 저장한다.
list_temp2 = list(input_dict.items()) # input 딕셔너리의 key,value 튜플을 리스트로 저장한다.
list_temp.sort() # input의 value를 오름차순으로 정렬한다.
result = list(range(len(list_temp2))) ... |
45c69fab84cb88a589feee34f14691c88e47f953 | MomoeYoshida/do_this_now | /lecture03/square.py | 310 | 4.03125 | 4 | """
"Do This Now"
Write a function (with a good docstring) that takes in a number and returns
the number squared
"""
def main():
number = int(input("Enter number: "))
print("{}^2 = {}".format(number, square(number)))
def square(number):
"""Square the number."""
return number ** 2
main()
|
30591d331ae658e89c469220cef7a74b248d9962 | MomoeYoshida/do_this_now | /lecture02/average_age.py | 408 | 4.03125 | 4 | """
"Do This Now"
Write a program to calculate the average age of a group of people, of unknown
size. Use a negative number as the 'sentinel' (when to stop)
"""
total = 0
count = 0
age = int(input("Enter your age: "))
while age >= 0:
total += age
count += 1
age = int(input("Enter your age: "))
average_age ... |
4990a0f7b28e7d96e9899ba18eb1aa2db6ef37f6 | FeardaMeow/algo_struct_studyguide | /algorithms/sort/quick_sort.py | 2,248 | 3.609375 | 4 | '''
Description:
Quicksort is an efficient in-place sorting algorithm, which usually
performs about two to three times faster than merge sort and heapsort.
Performance:
Comparisons:
worst = O(n^2)
best = O(n log n)
average = O(n log n)
Swaps:
worst =
best =
... |
6fcee628ddf5691cc21bc1780cd9f8a609110ee7 | cyncynthiar/Python-PandasRefresher | /analysiscynRead.py | 4,705 | 4.5625 | 5 | """
Cynthia Rothschild
oct 29 2020
pandas project to study from
this covers reading and locating from panda daraframe and some helpful functions for
for accessing dataframe variables like culumn values and reseting index for value
"""
#variable df in main inspired from https://realpython.com/pandas-dataframe/ under cr... |
cc48c4bc6f419b16ec9c5eb8352760d98f6502a3 | ZeroMin-K/Doit_Algorithm_Review | /chapter01/triangle_lb.py | 260 | 3.921875 | 4 | # 왼족 아래가 직각인 이등변 삼각형으로 * 출력
print('왼쪽 아래가 직각인 이등변 삼각형 출력')
n = int(input('짧은 변의 길이 입력: '))
for i in range(n):
for j in range(i+1):
print('*', end='')
print()
|
2ce72b9572c6b4cb82e21964ed7ba2e4d2d72c45 | ZeroMin-K/Doit_Algorithm_Review | /chapter01/print_stars2.py | 233 | 3.734375 | 4 | # *를 n개 출력. w개마다 줄바꿈
print('* 출력 ')
n = int(input('몇 개를 출력?: '))
w = int(input('몇 개마다 줄바꿈?: '))
for _ in range(n //w):
print('*' * w)
rest = n % w
if rest:
print('*' * rest)
|
ac1072c4248a291c1044a1755604c9d29dc69c0c | ZeroMin-K/Doit_Algorithm_Review | /chapter01/alternative1.py | 215 | 3.796875 | 4 | # +와 -를 번갈아 출력.
print('+와 -를 번갈어 출력.')
n = int(input('몇 개를 출력?: '))
for i in range(n):
if i % 2:
print('-', end='')
else:
print('+', end='')
print()
|
b277cf3726a13370a5f32e9be70cbee841f9183d | zkarpinski/HackathonF2011 | /src/Actor.py | 1,532 | 3.640625 | 4 |
import pygame
import os
import util
from Vector2 import Vector2
from config import *
class Actor(pygame.sprite.Sprite):
"""
Sprite class for pygame library
Largely inspired by Chimp Tutorial
www.pygame.org/docs/tut/chimp/ChimpLineByLine.html
"""
def __init__(self, imageFile = None, colorKey = None):
"""... |
42755e75d8732dda3589fbcb1f289a7308eac680 | radam0/Python | /CS61002 Labs/Project1.py | 3,598 | 3.5625 | 4 |
#Nikhil Vemula
#cs61002
#March 29,2016
import os #importing required library files
from inspect import getsourcefile
import random
currdir = os.path.dirname(os.path.abspath(getsourcefile(lambda:0)))
class VocabularyQuiz(): #
def __init__(self,*args):
self.mainfunction()
def mainfunction(self,*args):
... |
de099f0c0bdfb7dc28ae4eacf090c28a65935a8b | bhuvaneshkumar1103/talentpy | /Add_gender.py | 1,113 | 4.03125 | 4 | '''
create a class student which as parameterised constructor and also has a function
with getter and setter using Decrators.
'''
class student:
def __init__(self,name,gender):
self.name = name
self.gender = gender
# this name_change function is a getter function using @property and ret... |
a368dae9ff78b1f11312f464c3b784ddd5eb43dd | bhuvaneshkumar1103/talentpy | /even _gen.py | 315 | 4.4375 | 4 | '''
generator which will give the output as even numbers from 1 to infinity.
'''
def all_even():
n = 0
# to create a infinity loop .
while True:
# it will yield only the even numbers
if n%2 == 0:
yield f'{n} is even'
n += 2
for i in all_even():
print(i)
|
749538127c596fd8b08c383ea5d971b923c72a65 | bhuvaneshkumar1103/talentpy | /oneoreightynine.py | 1,540 | 4.09375 | 4 | '''
Mr.Talentpy would like to create a func,on one_or_eight which takes an integer input (no) and
performs following opera,on.
1. Square the number if it is single digit. (Eg: 3, then 3 * 3 = 9)
2. If it is not single digit, square each digits and add. (Eg: 12, then (1*1) + (2*2) = 1+4 = 5
You have to repeat step ... |
695b983d88f6c51ddcf09ebb12b85f5184d59bba | luciozolezzi/Python-repo | /manejo-archivos/manejo-archivos-r.py | 805 | 3.640625 | 4 | from io import open
archivo_texto=open("data.txt","r") #Abro el archivo en modo lectura
#Para abrir un archivo como R y W, usamos "r+"
texto_lineas=archivo_texto.readlines() #Leo el contenido y genero una lista por lineas del archivo_texto
#Despues de hacer una primera lectura el cursor del archivo queda al final,
... |
9c78bb05604f689fcdad13abad3e5d824d547d9e | luciozolezzi/Python-repo | /expresiones-regulares/ejemplo-regex.py | 1,881 | 4.28125 | 4 | #Ejemplos de REGEX (REgular EXPression)
import re
cadena="Cadena de ejemplo para la práctica con expresiones regulares en Python 02/01/2019."
cadena+="En Python es sencillo hacer busquedas con expresiones regulares."
cadena+="21.10.12 19-11-2014 18|11|11."
lista_nombres=['Ana Gonzalez', 'Rodrigo Quispe','Gonzalo Bert... |
34b665f8a8aa1b0f9672fdd541200807d63febc1 | NhutNguyen236/Digital-Image-processing | /Labs_and_Lects/LABS/Lab01/Exercises/Exercise03.py | 785 | 3.8125 | 4 | """
Exercise 3: Write a program to crop a region of input image and save it to
another image file by:
"""
import cv2 as cv
import numpy
from PIL import Image
from pathlib import Path
from read_write import read_image
# crop function from pillow
def cropper(image, top, right, bottom, left):
"""
C... |
f8c16c15aa90c5530fcbc6aba45a8d8a336c1c69 | zhabatou/leetcode_solutions | /0303_Range_Sum_Query_-_Immutable/Solution1.py | 808 | 3.5625 | 4 | from typing import *
class NumArray:
def __init__(self, nums: List[int]):
if not nums:
return
self.presum = [nums[0]]
for n in nums[1:]:
self.presum.append(n + self.presum[-1])
def sumRange(self, i: int, j: int) -> int:
if i == 0:
return s... |
0a5b82ac7e3913ec674f965a7fe337c72d269d4e | ps-vivek/Python | /Movie_Recommendation/Movie_Recommendation.py | 3,052 | 4.375 | 4 | '''
This program does the following:
1) Reads "watchlist.csv" file and generates suggestions for viewing 5 random movies
2) Converts the contents of "watchlist.csv" into a unicode format and written those contents it into sqlite database
3) Displays all the movies whose rating is greater than 8.5
4) Dis... |
c25fb1cebb2e3de5a620c8fba068fa18dad9f72d | baselakasha/Mathsgame | /mathgame.py | 3,528 | 4.0625 | 4 | import sqlite3
import random
db = sqlite3.connect('database.db')
c=db.cursor()
c.execute("CREATE TABLE IF NOT EXISTS data(name TEXT , highscore REAL)")
db.commit()
def welcome(name,highscore): # Display the welcoming message
print(" Hello {} ! \n\n Welcome to Maths game \n\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.