blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5b1feda3932ac04c901b1d40f07c7f480883abac
saipardhu/Sample-Algorithms
/Python-Algorithms/perfect_sq_range.py
321
3.75
4
# Given two integers A and B, return the number of perfect square within the range(A,B) inclusive import math def solution(A, B): minV = math.sqrt(A) maxV = math.sqrt(B) low = int(math.ceil(minV)) high = int(math.floor(maxV)) return (high - low+1) if __name__ == '__main__': print(solution(1,9)...
e1636dc9da215c17cdad2cebe007e0736a717e0c
maridigiolo/python-exercises
/funcexe/fun1.py
181
3.921875
4
#!/usr/bin/env python3 import matplotlib.pyplot as plot def f(x): return x + 1 xs = list(range(-3, 3)) ys = [] for x in xs: ys.append(f(x)) plot.plot(xs, ys) plot.show()
dd900564abdba42dee7a5c440532e95ee36c5d48
JakobWyatt/loss-function-visualiser
/test.py
1,738
4.0625
4
import sys print(sys.path) """Thankyou so much for the help, after playing around with the function more this morning and looking at a tutorial on numpy broadcasting I think i mostly understand it. Turns out that each element in the X, Y, Z array corresponds with eachother to form one point (for example (X...
408c68cd9e754a185c24f995bacdadb6f73729d9
Sal-Nunez/python
/flask/fundamentals/hello_flask/server.py
1,889
3.75
4
from flask import Flask # Import Flask to allow us to create our app from flask import render_template # Create a new instance of the Flask class called "app" app = Flask(__name__) # The "@" decorator associates this route with the function immediately following @app.route('/') def hello_world(): # Return the s...
25d053aa8c31e99c7b69de70ef3b298f72dc82d1
ygorcanalli/documenthandler
/DocumentHandler/sandbox/sequential_levenshtein.py
1,717
3.5
4
import sys import getopt INS_COST = 1 DEL_COST = 1 EXC_COST = 1 def main(): s = '' t = '' dynamicProgramming = 0 #parse command line options try: opts, args = getopt.getopt(sys.argv[1:], 's:t:D') except getopt.GetoptError as err: print(str(err)) sys.exit(2) for o, a in opts: if o == '-s': s = a ...
7c8e970c72e2174b5e1cd4921aff82b95eea0da9
SSEBYOTO/practical_201297726
/animation ABM/model.py
2,894
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 19:18:23 2021 @author: gaming """ import random import operator import matplotlib.pyplot import agentframework import matplotlib.animation import csv num_of_agents = 100 num_of_iterations = 10 neighbourhood = 20 seed = 1 random.seed(seed) num_of_agents = 10 num_of...
616a54035562e10e6327d49ec2869d548d69b183
AVasilyev1998/Python_algorythms
/simpleTasks/7.py
869
4.03125
4
def is_year_leap(year): if year % 4 == 0 and year % 100 != 0: return True elif year % 400 == 0: return True else: return False def date(day, month, year): dict_month = dict() dict_month[1] = 31 if is_year_leap(year): dict_month[2] = 29 else: dict_mon...
af0c129c5e40b88a985bea0a789923e6f4d833dc
waithirakunene/code_snippets
/iterators.py
648
4.15625
4
# This program will reverse the string that is passed # to it from the main function class Reverse(object): def __init__(self, data): self.data = data self.index = len(data) #returns an obect thar can iterated def __iter__(self): return self #__next_gives the next value in th...
9b513dbdfd7d48f19901172250997aa592117a4b
RomanPenzov/python_lesson_2
/example.py
4,629
4.0625
4
# задача 1 вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована. print ('ЗАДАЧА # 1, вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.') for i in range(1,6): print(i, 0) print ('='*27) print ('='*27) # задача 2 пользователь в цикле в...
382632d73136023fc8ca345441671b85c283bf2d
Nizhat/d-z
/3 задача.py
143
3.84375
4
x = int(input('Enter the first number:')) y = int(input('Enter the second number:')) z = x%y if z==1: print("Uvedomlenie!!!") else: print(z)
474b84cf856fb6697a7313510e94aa009cf45ed9
Adricf28/Backup
/Python/Fundamentos/ClasesCurso/tienda-de-libros.py
523
3.78125
4
print('Proporcione los siguientes datos del libro:') nombre = input('Nombre: ') id = int(input('ID: ')) precio = float(input('Precio: ')) envioGratuito = input('Indica si el envio es gratuito (True/False): ') if envioGratuito == 'True': envioGratuito = True elif envioGratuito == 'False': envioGratuito = False e...
fe6c0393bbf0f1bc49d87cdccd54e2fff8e0dbbc
richardlynnchild/dealer
/main.py
578
3.59375
4
# This script will scrape reviews from a car dealership review # website. It will build an array of Reviews, assign each # Review a posivity rating, then sort the array by this # positivity rating. The top three "most positive" # reviews will be logged to the console. # # Author: Richard Child # Last updated: November ...
a45b17e4493516233a82da950095e4ce919e2c3e
SilvinoPresa/Python
/Ultrasound_meas.py
1,130
3.5625
4
import serial #import serial libray from visual import * #import all vPython library (for visual interface) arduinoSerialData = serial.Serial('com3',9600) #Create object for serial data from arduino #set up virtual world measuringRod = cylinder(length=50, color=color.yellow, radius=1, pos=(-15,0,0)) lengthLabel = lab...
5620bf5150baa7f4ca6514eccd3f6e40c9197a00
kcpedrosa/Python-exercises
/ex043.py
634
4.15625
4
#esse programa vai calcular o IMC e definir categorias massa = float(input('Digite a sua massa[peso] em kgs: ')) h = float(input('Digite a sua altura em metros: ')) imc = massa/(h * h) print('Seu IMC é de {}'.format(imc)) if imc < 17: print('Você está MUITO ABAIXO DO PESO, atenção!') elif imc >=17 and imc < 18.5: ...
8e0fd11f42134a313faf3408e9fef720d8da1396
sravi4701/Projects
/pitonthdigit.py
550
4.28125
4
''' Problem : Find PI to the Nth Digit - Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program will go. ''' import math def pitonthdigit(digit): print '%.*f' % (digit, math.pi) if __name__ == "__main__": d = 0 while(True): f = True try: d...
bcc711b60061ef0e92c3a297bec4c5cfba202659
NadyZabi/WizardCasino
/raw_data_preparation.py
939
3.890625
4
import pandas as pd from typing import List def column_to_int(df: pd.DataFrame, column: str) -> List: """ Cast raw data in str format to integer :param df: raw input data frame read from csv file :param column: specific column in df to read the numbers from :return: List of numbers """ # ...
e3159b12083e7fda5b06073f6c159389335a1c41
kellyseeme/pythonexample
/329/reverse.py
918
4.65625
5
#!/usr/bin/env python """ this is for a string reverse and the key word reverse """ #this is define a string text chars = "this is a string" #this is the easy way use the slice to reverse the strings by chars print chars[::-1] #this is use the split get the word list,then use the list reverse function ,and join to ge...
b2dbe2785d69ac3f35c3633e4c584e1093190f0c
ironheartbj18/Data-Structure-and-Algorithm
/Data Structures/L1-Overview-of-C/Lecture1_C_prog/TruthValues.py
233
3.84375
4
def main(): a = (2 > 3) b = (3 > 2) print("a =", a, "; b =", b) print("----- With Python TypeCast -----") a = int(2 > 3) b = int(3 > 2) print("a =", a, "; b =", b) return 0 if __name__ == "__main__": main()
db43c91c2077fd5c7ec6bdccd29c24c554c11dbb
yifengyiye/PythonModels
/model_05_sort.py
697
3.8125
4
# coding: utf-8 """ 题 目:输入三个整数x,y,z,请把这三个数由小到大输出。 程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。 """ import numpy as np l = [] sum = 0 for i in range(5): x = float(raw_input("integer:")) l.append(x) sum = sum + x mean = np.mean(x) l.sort() print l print su...
24b34818f0973c782e820c6f279e6bc155a5fa6c
BigMountainTiger/python-excercise-repository
/miscellaneous/a_01_oo_excercise/p_06_inheritance_the_self.py
486
3.96875
4
class ParentClass: def parent_self(self): return self class ChildClass(ParentClass): def child_self(self): return self if __name__ == '__main__': obj = ChildClass() print(obj.__dict__) print(f'Parent self is the object -> {obj.parent_self() is obj}') print(f'Child self i...
807a48d9822114fd82de25f5ac10c5640698f98f
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4188/codes/1595_1015.py
412
3.625
4
# Teste seu codigo aos poucos. # Nao teste tudo no final, pois fica mais dificil de identificar erros. # Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. var=int(input("digite um numero:")) var2=int(input("digite um numero: ")) var3=int(input("digite um numero: ")) menor=min(var,var2,var3) m...
2907ab7a7a428d8141fb7c35cf3a81d9cbbf1ac5
cmparlettpelleriti/CPSC230ParlettPelleriti
/Lectures/PythonBasics_3_CW.py
824
3.671875
4
# numeric types # x = 1 # print(type(x)) # y = 6.34 # print(type(y)) # z = 1.0 # print(type(z)) # # # booleans # x = True # print(type(x)) # y = False # print(type(y)) # # # string # s1 = 'Chelsea' # s2 = "Chelsea's" # s3 = '''Chelsea's # # # ''' # print(type(s1), type(s2), type(s3)) # # # lists # my_list = [1,2,3,4,5]...
eaf367a2e70564c3005b53e8ccd3d28839e7e8b9
jonathansoto2/python-projects
/username.py
1,462
4.4375
4
# In-Class Assignment 3 # Username Generator # Boston Cartwright, Dallin Kimber, Jonathan Sexy Soto, ''' Generate a username for the user with the length of the string attached to the end. The username will be the LastName with the initials of the first and middle attached to the end and then length. ''' # main ...
fa6bd7a67a79047d3f656ffd87ff0f286b77ebd9
Linkitz/exercises-coronapython
/chapter_3_3_2.py
408
4.3125
4
# 3-2. Greetings: Start with the list you used in Exercise 3-1, but instead of just printing each person’s name, print a message to them. The text of each message should be the same, but each message should be personalized with the person’s name. names = ['Andre', 'Matheus', 'Thales'] message = "One of my best friends...
d2d050d3af53731181c911e4fff23555523147c2
htw-imi-info2/learn-python-with-tests
/duck_type.py
779
3.6875
4
import unittest class Duck: def quack(self): return "quaaack!" class Dog: def bark(self): return "woooof!" def function_that_expects_duck_type(maybe_a_duck): return "let it quack: " + maybe_a_duck.quack() class TestDuckTyping(unittest.TestCase): def test_ducks_quack(self): duck = Duck...
1773d948339767d6fd88d4a3f71badf057228b57
AlmasSinev/SimpleAlgorithms
/Simplecs.py
2,522
3.671875
4
import math def koord_1(x1_01, x2_01, xj_11): return (x1_01 + x2_01 + xj_11) - 2 * xj_11 def koord_2(x1_11, x2_11, xj_22): return (x1_11 + x2_11 + xj_22) - 2 * xj_22 def solve(x1, x2): return a*x1**2 + b*x1*x2 + c*x2**2 + d*x1 + e*x2 + f E = 0.0001 # float(input('Введите эпсилон: ')) x1 = 1 # floa...
c6d1c70369b29716532e333ca91899adfb4c84e1
Moscow70/Course-Review
/Data-Mining/project/code/decision_tree.py
17,248
4.09375
4
import numpy as np import math class DecisionTree: '''Decision Tree Classifier. Note that this class only supports binary classification. ''' def __init__(self, criterion, max_depth, min_samples_leaf, first_cut = False, ...
0cc14383d3645a8fb504815a2471d74f7670e676
Jaresma/Aprendiendo-Python
/conceptos basicos/funciones.py
250
3.796875
4
""" la identacion es muy importante """ def mensaje(): print("estamos aprendiendo python") def sumasr(num1,num2): print(num1+num2) def sumacr(num1,num2): resultado=num1+num2 return(resultado) mensaje() sumasr(3,3) print(sumacr(4,5))
e24d459ec3a4bc7419b4d54e93f6edd6aebc3746
kathleenfwang/password-verifier
/kathleenwanglab2.py
3,118
4.0625
4
############################################################################### # CS 21a Python Programming: Lab 2 # Description: Programming with Loops and Functions # Name: Kathleen Wang # Date : July 17, 2018 ############################################################################### """The Program Spec Write...
b212820973e3847c6d88aad0eda69855977b2749
jdlambright/Hello-World
/data structures class/quicksort.py
380
3.78125
4
def quick_sort(seq): length = len(seq) if length <= 1: return seq else: pivot = seq.pop greater = [] lower = [] for item in seq: if item <= pivot: greater.append(item) else: lower.append(item) return quick_sort(items_lower) + [pivot]...
32d062d1b81d03cbcdd4995f3bca8d73af84a5a2
cbrightly1/36-650
/Homework 5/q2/q2.py
501
3.8125
4
# Q2 def remove_punct(input_string): punct_list = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' final_string = input_string for i in range(len(input_string)): for j in range(len(punct_list)): if input_string[i] == punct_list[j]: final_string = final_string.replace(input_string[i],"...
184bea80a96854b169d8e306059cfc7e90eb0a8a
standrewscollege2018/2020-year-12-python-code-lbl4537
/credit manager practise.py
1,037
4.25
4
# manage student info about L1 NCEA credits # Liam Blackmore # 11/2/20 # Display name function def display_all_students(): for index in range(0, len(students)): print(index+1, students[index]) # stores student details students = [["Lucas Very Cool",10], ["Danny B",0], ["Ollie Od",12], ["Rhys Brother", 65...
52cbd847353ee688e2ea1946b0b4e5c14fe3ca85
dvsu/regex_patterns
/001_rearrange_name/sample.py
933
4.15625
4
import re def rearrange_name(name: str) -> str: # Add a period '.' and space inside square bracket to capture period and space after a word result = re.search(r"^([\w \.-]*), ([\w \.-]*)", name) return name if not result else f"{result[2]} {result[1]}" # Fictional name list which consists of # - names in...
34214e0e5aad0faf11c0f21162cdcbd23b366aa4
notmahsa/csc411
/a3/q1.py
460
3.703125
4
# # CSC411 # Assignment 3 # Mahsa Naserifar # # import numpy as np def gradient_descent(X, y, w, b, learning_rate, iter, zeta): x_trans = X.transpose() for i in range(0, iter): a = (np.dot(w, X) + b) - y if np.abs(a) <= zeta: loss = np.sum(a ** 2) / (2 * len(X)) else: ...
da0f91f41892476534fd56bd23b1282829255ecf
qenie/Exercises
/Santa and boys.py
1,223
3.765625
4
"""" The task is to find amount of "Bad boys" (represented by '=o' symbols) and "Good boys" (represented by 'o=' symbols) in the given string. There is also Santa (represented by 'd' symbol) but actually 'd' symbol treated just like other symbols (not sufficient). """ symbols_counter = 0 # just a counter that cha...
9251b3025e2ca51b70ea820234f186c6cf99d8ab
imgomez0127/daily-programming
/randomCode/tictactoe.py
1,696
4.09375
4
board = [] def create_board(): for i in range(3): board.append([' ',' ',' ']) def display_board(): global board board_str = "" for i in range(3): board_str += str(i) for j in range(2): board_str += board[i][j] + '|' board_str += board[i][len(board[i])-1] + '\n' if i != 2: board_str += '...
8ddc35935f62e52fa7f54548ca0939386d41bc87
ven0226/x9115Naruto
/hw/code/3/Employee.py
457
3.953125
4
__author__ = 'Venkatesh' class Employee: def __init__(self,name,age): self.name = name self.age = age def __repr__(self): return 'Name: %s Age: %d' % (self.name,self.age) def __lt__(self, other): return self.age < other.age emp1 = Employee('Venky',27) print emp1 emp_list...
3cb6884d40430a9dad5daca1b1a43c09f2c66b88
Uche-Clare/python-challenge-solutions
/elif_bayindir/phase_1/python_basic_1/day_5/q1.py
367
3.921875
4
# Question 1 # Greatest common divisor of 2 positive integers num1 = int(input("Enter 1st integer: ")) num2 = int(input("Enter 2nd integer: ")) if num1 > num2: if num1 % num2 == 0: gcd1 = num2 a = num2 elif num2 > num1: if num2 % num1 == 0: gcd1 = num1 a = num1 gcd2 = 1 for i in range(2, a+1): if num1 % i =...
dae0e1267d1838244ce93fead7b24a599667c154
rodrigodub/Output
/ProgramacaoBasic/Input05PB06_a.py
434
3.8125
4
################################################# # INPUT # Programação Basic 6 # O que são variáveis # # Usage: # > python3 Input05PB06_a.py # # v2.095 # 20180121 ################################################# import time def main(): x = 0 while True: print('{} '.format(x), end=...
7b657075a81cefec0adb4d5bd8af79c8d44b3789
ganyuanyuan/myLeetCode
/062Unique Paths.py
384
3.609375
4
class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m ==0 or n==0: return 0 line = [1]*n matrix = [line]*m for i in range(1,m): for j in range(1,n): matrix[i][j]...
d5b4ed3d7615b89070091be09b2f4684dde99ef5
sagarpm/Typing-Test-GUI
/login.py
1,933
3.75
4
from tkinter import * def login_click(): global username_entry, password_entry, error_message #all that was needed to get it work was declaring global for entry widgets(works without bind also). #username='a' #password='a' username_text=username_entry.get() password_text=password_entry.get() #print("u "+usernam...
b7e8151460e2e2b19a115e54efb5de431ed7426b
kajendranL/Daily-Practice
/strings/first_three.py
336
4.25
4
print(''' Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string. ''') print() def first_three(str): return str[:3] if len(str)>3 else str print(first_three('python')) print(fir...
003b09795d68ca014713952752f40a8c2a15a875
sandeepvempati/lpthw_examples
/ex6.py
196
3.90625
4
n = [[1,2,3],[4,5,6,7,8,9]] def flatten(lists): results = [] for item in lists: for x in range(len(item)): results.append(item[x]) return results print flatten(n)
a0a759adadcb38214f1a43ce887b04b022073199
Jnajera1/python-challenge
/PyPoll/PyPoll.py
2,483
3.921875
4
# Import Dependencies import os import csv # Open CSV file to read and a text file to write csv_path = os.path.join('Resources','election_data.csv') with open(csv_path, 'r') as csv_file,\ open('Eletion_Results.txt', 'w') as text_file: # Read CSV file election_data = csv.reader(csv_file, delimiter=",") ...
1a473ab14e97b5d54e2f7c9d6d88a774c5c8ed9e
fabianbrash/python-demoes
/fib.py
191
3.890625
4
# Calculate fib sequence def fib(i): if i == 0: return 0 elif i == 1: return 1 else: return fib(i-2) + fib(i-1) for f in range(20): print(fib(f))
4f1f59094a6ef8f1a35aebc97a0f510093a47b96
Bangtx/global
/myFunction.py
379
3.6875
4
""" f(x) = y f(x) = x^2 + 2x + 1 cứ mỗi giá trị truyền vào của x -> f(x) f(x, y) = x^2 + 2xy + y^2 cứ mỗi x, y truyền vào -> (return) f(x, y) y = 1 """ def tinh(x, y): return x * x + 2 * x * y + y * y def test(): return 1 ten = 'con cho' def change_name(name): name = 'con chim' return name ...
1253606e305098b0b283ceec347e42832ae4fd00
kwgarylam/ROSproject
/motorModule.py
2,490
3.6875
4
''' -This module allows creation of robot objects for 2 or 4 wheeled robots. -The motor driver used is the L298n. -The base package used is the Rpi GPIO -The Object Motor needs to be created first -Then the move() function can be called to operate the motors move(speed,turn,delay) -Speed and turn range from -1 to 1 -D...
c781f4712066c896d64d9045ec8cb2c636e5a1ff
simrangrover5/Advance_batch2020
/OOPs/oops1.py
889
3.703125
4
from time import sleep class Student: total = 0 def __init__(self,name,age,phno): self.name = name self.age = age self.phno = phno Student.total += 1 def get_attr(self): for attr,value in self.__dict__.items(): print("Attribute : ",attr,"Value : ",value)...
f86a8e048d92a54fa6f54b1d439b70663c2f1a13
nuokey/SimpleCalc
/main.py
1,484
3.984375
4
from tkinter import * def plus_entered(): n_1 = int(first_number.get()) n_2 = int(second_number.get()) answer['text'] = str(n_1 + n_2) def minus_entered(): n_1 = int(first_number.get()) n_2 = int(second_number.get()) answer['text'] = str(n_1 - n_2) def multiplication_entered(): n_1 = int(...
e800a1a1b0cc6f857c23522ec097954c659659a4
mugeshmuthukumaran/MUGESHKUMAR
/pro58.py
252
3.59375
4
#mugi number = int(input()) b = [] ain = number//2 + number for i in range(1,number+1): if i%2==0: b.append(i) for i in range(1,number+1): if i%2!=0: b.append(i) for i in range(1,number+1): if i%2==0: b.append(i) print(ain) print(*b)
e17ad02385592bb176f47fe477837f13f2d5aa0e
pmav99/pyschism
/pyschism/dates.py
1,125
3.6875
4
from datetime import datetime import numpy as np import pytz def pivot_time(input_datetime=None): """ "pivot time" is defined as the nearest floor t00z for any given datetime. If this function is called without arguments, it will return the pivot time for the current datetime in UTC. """ inpu...
49f05bf7031da5cb1189c2a817fc49741fc6aac1
forthing/leetcode-share
/python/050 Pow(x, n).py
574
3.734375
4
''' Implement pow(x, n). ''' class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ flag = 1 if n >= 0 else -1 result = 1 n = abs(n) while n > 0: if n & 1 == 1: ...
6fcbd6dbed7ab77fc4a2d5948c93c70e98155aa3
oonisim/python-programs
/lib/util_collection.py
2,183
4.40625
4
"""Module for collection (list, set, dict) utilities """ from typing import ( List, Callable, Any, ) # -------------------------------------------------------------------------------- # Sort: # sorted(collection, key=func) sorts the collection according to the values from # the key function. func will get...
da8b19bb7d0f0f2b848a89fbc2e3e4dda08a4368
peltierchip/the_python_workbook_exercises
/chapter_1/exercise_34.py
473
4
4
## #Compute the price od day old bread PRICE_LOAVE=3.49 SCOUNT=0.60 #Read the amount of loaves of day old bread loaves=int(input("Enter the number of loaves of day old bread:\n")) #Compute the price price=loaves*PRICE_LOAVE discount=price*0.60 price_with_discount=price-discount #Display the result print("The normal pri...
ce37ba266576a3f1fd1dfa0f236ee9dcc4b7c770
wolf43/crpytographic_hash_functions
/hash_examples.py
878
4.21875
4
"""This module shows various examples of computing hashes.""" import hashlib import requests # Computing hash of a string STRING_TO_HASH = 'This is a string' HASH_OF_STRING = hashlib.sha256(STRING_TO_HASH).hexdigest() print "Hash of string: " + STRING_TO_HASH + " is " + str(HASH_OF_STRING) # Computing hash of a file...
e1941e4cf61c856fb20c48b9afbf17b4ed605364
jtrinklein/advent-of-code
/2020/16/main.py
3,575
3.609375
4
#!/usr/bin/env python3 data = [] with open('./data.txt') as f: data = [line.strip() for line in f.readlines()] def parse_data(d): end_first_section = d.index('') end_second_section = d.index('', end_first_section+1) #get my ticket my_ticket = [int(x) for x in d[end_first_section+1:end_second_sec...
b0912e806df183973ec744a8f45839c1529b8904
lklr89/lndw-rubik-robot
/controller/solver/utils/sides-loop.py
352
3.625
4
#!/usr/bin/env python3 foo = [8, 12, 13, 14, 18] offset = 0 side_name = { 0 : "Upper", 1 : "Left", 2 : "Front", 3 : "Right", 4 : "Back", 5 : "Down", } #for side_index in range(1,5): for side_index in range(6): print(" %s, # %s" % (', '.join([str(x + offset) for x in foo]), side_name...
92464b02d80f9faca7a3bbca6136bb7445cc1d56
Bongkot-Kladklaen/Programming_tutorial_code
/Python/Python_Beginners/Sorting/list.py
331
3.828125
4
num = [10,2,3.4,56,1,1,11] num2 = [10,2,3.4,56,1,1,11] num.sort() print(num) num2.sort(reverse=True) print(num2) list1 = ['aa','b','eeee','ccccc','ddd'] list1.sort(key=len) print(list1) list2 = [[2,9],[1,10],[3,7]] list2.sort() print(list2) def SortBySec(element): return element[1] list2.sort(key=SortBySec) p...
0132982901ea109f58711409c9a6c6fb40a587f1
SunayaShivakumar/FilmoGraphy
/graphlibrary/Edge.py
370
3.703125
4
class Edge(object): """ edge object represents the connection between movies and actors in a graph """ def __init__(self, actor="", movie=""): """ edge constructor for the edge object :param actor - the actor node for the edge :param movie - the movie node for the edge """ ...
6d55f0fac89302e303f03a9999b852e8a9891931
FPSarmin/HSECAOS
/ОиМП - 1/SEM2/E.py
327
3.75
4
import string a = input() if a[0].isdigit() or a[0] == "_": print("FALSE") else: is_ind = 1 i = 0 while i < len(a): if not a[i].isascii() and not a[i].isdigit() and a[i] != '_': is_ind = 0 break i += 1 if is_ind: print("TRUE") else: print("...
66e8e5b729f79a4e46d3d5c63551b85032cc20fa
ArchWizard56/democraciv-utilities
/stv/mstv.py
4,733
3.78125
4
import csv import argparse import sys parser = argparse.ArgumentParser(description='Calculate the winner of an election using IRV or STV.', epilog='To have it print detailed results, use -v. Since we tend to use droop for most results, that is the default, but you can change it to hare by using `-q hare`') parser.add_...
dfe5e0e1a1db689ebc7f27a3d67271a2d04dd89a
SRin23/hongong-python
/dict_basic.py
1,071
3.703125
4
#dictionary #여러 값을 저장해두고 필요한 값을 꺼내 쓰는 기능 #이릉표를 이용하여 값을 꺼내 사용 """ 딕셔너리명 = { '이름표1' : '값1', '이름표2' : '값2' } """ wintable = { '가위' : '보', '바위' : '가위', '보' : '바위' } def rsp(mine, yours) : if mine == yours : return 'draw' elif wintable[mine] == yours : return 'win' else : return 'lose' resu...
e401cb1254931655bba15eab3db33b396bbf8aab
slcdiallo/pythonClass
/Lesson1.py
1,353
4.5
4
#Saliou Diallo #Write a module that first asks the user to enter 2 integers and then print the sum, difference, #product, quotient, integer quotient, and modulus of the 2 numbers. Then ask the user to enter 2 real #numbers. Print the sum, difference, product, quotient, integer quotient, and modulus using the % #operato...
6b5da6e522803635ab031666abd688734d8ace0f
savadev/interviewbit
/Dynamic Programming/best-time-to-buy-and-sell-stocks-i.py
694
3.578125
4
''' Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Example : Input : [1 2] Return : 1 ''' class Solution: # @pa...
e656c2a696aa5a9a45d1eed95d13ca2155ef37d2
GLAU-TND/python-lab-kapilkumarsinghal
/questio2_sol.py
304
3.53125
4
try: n = int(input()) b = int(input()) a = input() c = n + b l = a + b n.append(3) except ValueError: raise ValueError("value error occured") except TypeError: raise TypeError("Type error occured") except AttributeError: raise AttributeError("Attribute error occured")
aa9cadd2419a43bb493166173c55f6527851828c
nikkisquared/nikki-adventure
/game.py
5,162
3.8125
4
from rooms import * class map(object): # log of every room in the game, for easier referencing def __init__(self): # there is no room 0 for x in range(1, 21): exec 'self.room_%s = room_%s()' % (x, x) class game(object): def __init__(self): self.m = map() pr...
6a3fc90ffa00490d8f52817a7dddbc3d241427c7
Chime-Xu/data_structure
/6.22/练习1.py
2,595
3.71875
4
class Node: def __init__(self,data): self.data=data self.next=None def __repr__(self): return f'Node({self.data})' class LinkList: def __init__(self): self.head=None self.tail=None self.size=0 def __repr__(self): curr=self.head str='' ...
01503d56c2bf8e8694aa46f848bd68dbc2767497
TanvirAhmed16/Python-Basics---2
/4. Truthy and Falsy.py
1,237
4.53125
5
""" Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations. it just refers to values which are evaluated to True or False. For instance, to see if a list is not empty, instead of checking like this: """ my_list = [1, 2, 3] if len(my_list) != 0:...
ad2fea905efe52b766c025e9f1750d6769001145
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/2933.py
689
3.515625
4
from __future__ import print_function import numpy as np import math cast = lambda x: True if x == '+' else False def pancakes(row, k): if len(row) == 0: return 0 if len(row) < k and False in row: return 'IMPOSSIBLE' flips = 0 for i in range(len(row)-k+1): if not row[i]: ...
548c1c6b01b39d7fc47ebc127315f0926c5cea8a
Vaibhav-84/python-projects-and-basic-program
/search_algorithms/binarysearch.py
759
4.03125
4
l = [] n = int(input("Enter no of elements to be added in list : ")) i = 0 while i < n: get_num = int(input("Enter Value: ")) l.append(get_num) i += 1 value = int(input("Enter value to be found : ")) def binary_search(arr, low, high, x): if high >= low: mid = (high + low) // 2 # If ele...
8c197bca253c7195ce4096a9e27db6c2d78bc546
Brandyzwz/practice
/练习/star1.py
128
3.640625
4
hang = 1 while hang <= 10: lie =1 while lie <=hang: print('*',end='') lie+=1 print('') hang +=1
b48b35647bc515f931d77bd85a776662cada2938
darshikasingh/tathastu_week_of_code
/day1/program3.py
180
3.921875
4
a = int(input("ENTER THE VALUE OF a: ")) b = int(input("ENTER THE VALUE OF b: ")) a = a+b b = a-b a = a-b print("AFTER SWAPPING") print("VALUE OF a =", a) print("VALUE OF b =", b)
d4cb875d82917a0d508960bec3c031697bd95432
saha-lab/scripts
/RNA-Seq_Pipeline/Annotation/remove_gene_names.py
504
3.609375
4
file_path = input("What is the path to the .txt file you wish to process:\n>>> ") file = open(file_path) DE_genes = file.read() file.close() gene_list = DE_genes.split('\n') final_list = [] for line in gene_list: line = line.split('_') temp = line[0:2] gene_name = '' gene_name = gene_name.join(temp)...
b9ceda420e55045c5c8ea3294a91f8abaa37da37
RafaelxFernandes/coursera
/interactive-python/guessnumber.py
2,513
4.0625
4
# URL http://www.codeskulptor.org/#user26_sITUEbTVWQ_7.py # template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import math import random # initialize global variables used in your code game_range =...
193b4939b2917e827bc4253af8a015acd4073907
virginiacattaneo/intermediate-python-course
/dice_roller.py
351
4
4
import random dice_rolls = 2 dice_sum = 0 for i in range(0,dice_rolls): roll = random.randint(1,6) dice_sum= dice_sum + roll if roll == 1: print(f'You rolled a die {roll}! Critical faild') elif roll == 6: print(f'You rolled a {roll}! Critical Success!') else: print(f'You rolled a {roll}') print(f'You have ...
e2f3bc6d4bc359210ef65ddd1986d6db6337d87f
surya-vats/albanero-sdp-hack-week
/30_meanofdidit.py
279
3.84375
4
def meanofdigit(num): nbr = str(num) lst = list(nbr) sum =0 count =0 for i in lst: k=int(i) sum = k+sum for i in lst: count += 1 mean =(sum/count) return mean num = 575 print(meanofdigit(num))
6b17786c34bba7bc05c77a5d14c83857f209c24f
Otnielush/Aia_Base
/application/database/edit_data_in_db.py
972
3.515625
4
import sqlite3 as sql def read_data(name): # Make a connection to the SQLite DB dbCon = sql.connect("database.db") dbCon.row_factory = sql.Row cur = dbCon.cursor() command = "SELECT id, name, phone FROM "+name+" WHERE "+name+".phone LIKE '5%'" try: cur.execute(command) print('1...
92c3ac1b2d9612d6e5118c87f48df46fdc48d753
adichouhan14/python-assignment
/py assignments/Module 1/shift_demo.py
135
3.734375
4
a=int(input("Enter a no")) print("multiplication by 2 with left shift ",a<<1) print("multiplication by 2 with right shift ",a>>1)
3a3210dbe69ab8858b57622441ae07711794d7dc
LikeABird-CX/Learn-python-the-hard--way
/ex3.py
1,133
4.25
4
#coding: utf-8 # + plus 加号 # - minus 减号 # / slash 斜杠,除以 # * asterisk 星号 # % percent 百分号,求余数 # < less-than 小于号 # > greater-than 大于号 # <= less-than-equal 小于等于号 # >= great-than-equal 大于等于号 print "I will now count my chickens:" print "Hens", 25 + 30 / 6#求25+(30/6)的结果,结果=30 print "Roosters", 100 - 25 * 3 % 4#求100-(25*3)%4的...
1133721e1b03adc6f97f7f86aafc796368a74516
pramilagm/FTask
/LinkedList/SinglyLL/findElement.py
1,465
3.875
4
class Node: def __init__(self, data): self.data = data self.next = None class SinglyLL: def __init__(self): self.head = None def printList(self): if self.head is None: print('Singly LL is empyty') current = self.head while current: p...
6a77ab678956098124e05210cba49f17994a6d86
TypAnna/GruProgDD1331
/Övning6/uppg2Memory.py
219
3.609375
4
def funB(a, b): a[1]= "hej" b = ("katt", "lo") def funA(): a = [[1, 2], [3, 4]] b = (5, 6) funB(a, b) #what does the memory look like here? print("this is p", a) print("this is q", b) funA()
a245140ea921082218c85cfdfc4e52ee3fc22f8e
Right-Click-Code/Calculator-by-Python
/claculater3.py
496
4.21875
4
# Right Click => r-click.ir num1 = input("Enter your Number1: ") num2 = input("Enter your Number2: ") work = input("Enter your work: ") if work is '*': print(float(num1) * float(num2)) if work is '+': print(float(num1) + float(num2)) if work is '/': print(float(num1) / float(num2)) if work is '-...
b337e8f28163f42861f87e52eca245b8fd274f10
exclusivedollar/Team_5_analyse
/kundani_function_1.py
406
3.609375
4
def dictionary_of_metrics(items): """returns a dictionary of the metrics from a list of items """ dict = {'mean': round(np.mean(items), 2), 'median': round(np.median(items), 2), 'var': round(np.var(items, ddof=1), 2), 'std': round(np.std(items, ddof=1), 2), 'min':...
448303e5cb2a5db9c9a580b3788189fd2456ce7a
alexofechoes/project-lvl1-s566
/brain_games/games/brain_calc.py
820
4.09375
4
# -*- coding:utf-8 -*- """Brain calc game functions.""" import operator import random DESCRIPTION = 'What is the result of the expression?' operations = { '+': operator.add, '-': operator.sub, '*': operator.mul, } def generate_question(): """Create game question.""" num1 = _generate_number() ...
415a034d07ee04e129da2e91eefb7a0d57904f80
byeongal/KMUCP
/week05/code04.py
284
4.03125
4
print("0부터 9까지 출력") for i in range(10): print(i) print("3부터 9까지 출력") for i in range(3, 10): print(i) print("2부터 10까지 짝수 출력") for i in range(2, 11, 2): print(i) print("10부터 1까지 출력") for i in range(10, 0, -1): print(i)
f427fb40c1f691190ca1cf1b20df2384fd35cb5e
Elijah3502/CSE110
/Programming Building Blocks/Week 3/06TeamActivity.py
969
4.21875
4
#Get the age of rider_one #init variables age_two = 0 age_one = int(input("What is the age of the first rider? : ")) #Get the height of rider_one height_one = int(input("What is the height of the first rider? : ")) #Ask if second rider is_second = bool(input("Is there a second rider? (true/false): ")) #Get age of rid...
0f73622d9311ce21b8d02f97266b2a016657df2f
geneilson1980/PythonCourse
/longestDigitsPrefix.py
377
4.03125
4
def longestDigitsPrefix(inputString): expectedOutput = '' for i in range(len(inputString)): currentValue = inputString[i] if not(currentValue.isnumeric()): return expectedOutput else: expectedOutput += currentValue return expectedOutput inputString = "aaaaaaa...
a7eea95cf8019f097cb0c4ad9e1bfdba07f9f3d1
aboyd20/python-exercises
/break_continue.py
2,397
4.25
4
def breakOneLoop(): 'prints numbers in list until it encounters first even number' lst = [ 1,3,23,8,5,20,17 ] for i in lst: if i%2 == 0: # if i is even break # terminate for loop print( i, end=' ') ''' >>> breakOneLoop() 1 3 23 ''' def breakNestedLoop(): ...
4eed377e8ee78965cbc14778089084224b3b676d
Wenxin-CHEN/IBI1_2019-20
/Practical5/spyder20200311/collatz.py
317
4
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 09:17:49 2020 @author: 陈文心 """ #if n is not equal to 1. if n is even, n=n/2, if n is odd n=n*3+1 #if n is equal to 1, stop the loop n=45 print(n) while n!=1: if n%2==0: n=n/2 print(n) else: n=n*3+1 print(n)
0aa4d987736b101bd17461c4652af3c24d879932
birdhermes/CourseraPython
/3_week/Количество слов.py
343
3.78125
4
# Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов. # Формат ввода. Вводится строка. # Формат вывода. Выведите ответ на задачу s = str(input()) a = s.count(' ') a += 1 print(a)
84a13e3b51e688c4929df1fe95e17759f47b6e6f
leticiamarty/phyton02
/python.py
2,277
4.09375
4
# print("ola mundo, bom dia !") # nota1 = float(input("me informe sua primeira nota ?: ")) #float quer dizer que a responta vai ser um numero # nota2 = float(input("me informe sua primeira nota ?: ")) # nota3 = float(input("me informe sua primeira nota ?: ")) # media = (nota1 + nota2 + nota3 ) /3.0 #para manter u...
a6b635a7b43b753eaf69320470ccfb93635da3f6
RandyHodges/Self-Study
/Python/controlStructures/numberGuess.py
2,232
4.375
4
# ================= BONUS Optional Task ================== # Create a new Python file in this folder called “Optional_task.py” # Create a program that allows the user to play the lottery. # Generate a random two digit number (between 10 and 99) this number will be the lottery number. # Ask the user to enter any two dig...
8b10e5a7eb5f72c7bf6d5a8c8011daf76bcdf1bb
isears/SpamFilter
/util.py
1,754
3.890625
4
""" Define utility classes used by the spamAgent """ class word: """ Store information about a word object. Word objects make up the spam agent's lexicon. """ def __init__(self, wordName, wordCount): """ Word object constructor \param wordName (string): The word as a string ...
0f000fc6e6077ef931f4ecb805f51a1a4f2a88ca
mveselov/CodeWars
/tests/kyu_7_tests/test_coding_3_min_to_lover_case.py
657
3.53125
4
import unittest from katas.kyu_7.coding_3_min_to_lover_case import to_lover_case class ToLoverCaseTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(to_lover_case('LOVE'), 'EVOL') def test_equal_2(self): self.assertEqual(to_lover_case('love'), 'EVOL') def test_equal_3...
aabc746b058cece7d66c5594e286762776fa9de7
sernanic/python_projects
/python/proj02.py
2,808
4.0625
4
quarters = 10 dimes = 10 nickels = 10 pennies = 10 quarterneeded = 0#keep track of how many quarters used dimesneeded = 0#keep track of how many dimes used nickelsneeded = 0#keep track of how many nickels used penniesneeded = 0#keep track of how many pennies used print("Welcome to change-making program.") print("\nSt...
0ce4825cb19932d5f67f67d50acdb6ea107cfb6b
mmeest/Photo-to-ASCII-art-in-Python
/ascii.py
1,230
3.59375
4
import PIL.Image # ascii characters ASCII_CHARS = ["@", "#", "S", "%", "?", "*", "+", ";", ":", ",", "."] # resize image to new width def resize_image(image, new_width=100): width, height = image.size ratio = height / width / 1.65 new_height = int(new_width * ratio) resized_image = image.resize((new_...
f237221b5fa95c20992e4dd916a060d090fe2b05
happy5205205/PythonProjects
/DataAnalysis/day01_BaseOfDataAnalysis/lambda.py
214
3.796875
4
my_fun = lambda a, b, c: a * b print(my_fun) print(my_fun(1, 2, 3)) #结合map print('lambda结合map') l1 = [1, 3, 5, 7, 9] l2 = [2, 4, 6, 8, 10] res = map(lambda x, y :x * y, l1, l2) print(tuple(res))
bf3eaaaaaed5635048f11dd1fd4df7eaf4ecb9c4
axd8911/Leetcode
/1st_try/101_Symmetric_Tree_1st_try.py
938
3.671875
4
''' 99.46% ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isSymmetric(self, root: TreeNode) -> bool: self.result = True root2 = root ...
f8929147c5370f247a38588c387b18e0b0a36a25
okaymunsi/sandbox
/code_challenges/2_sortlist.py
1,920
4.28125
4
""" Create a function in Python that accepts two parameters. The first will be a list of numbers. The second parameter will be a string that can be one of the following values: asc, desc, and none. If the second parameter is "asc," then the function should return a list with the numbers in ascending order. If it's "...
9709cf1165e96aaef256b827b810057f861daad8
superMC5657/leetcode-py
/dichotomy/33.py
1,942
3.78125
4
# -*- coding: utf-8 -*- # !@time: 2021-01-05 11:39:12 # !@author: superMC @email: 18758266469@163.com # !@question title: search-in-rotated-sorted-array # 升序排列的整数数组 nums 在预先未知的某个点上进行了旋转(例如, [0,1,2,4,5,6,7] 经旋转后可能变为 [4,5,6,7,0,1,2] )。 # # # 请你在数组中搜索 target ,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # # # # 示例 1: # # ...