blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7e57fca9717e62dbba10ab777a34eeb005af248a
sahil-dhingra/Reinforcement-Learning
/Project 3/Soccer_game.py
4,854
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 10 23:06:41 2019 @author: sahil.d """ import random class soccer: # Board board = [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1]] ...
e2db1ca72b5571cf8936182d89a2fe90c5b94a63
BPCao/Assignments
/ACTIVITIES/python/Calculator/test_operator.py
869
3.953125
4
import unittest from calculator import Calculator class CalculatorTests(unittest.TestCase): def setUp(self): self.Calculator = Calculator() print("SETUP") def test_add_two_numbers(self): print("test_add_two_numbers") result = self.Calculator.addition(2, 3) self.assert...
5a44fb4b82fa16813715db13e98c94ae3c46b338
maris205/secondary_structure_detection
/src/evaluate/get_svm_data.py
1,159
3.5
4
#!/usr/bin/env python #coding=utf-8 import math import sys #ȡngramǷǴʵlabel word_dict={} #װشʵ def load_dict(dict_file_name): #سʼʵ dict_file = open(dict_file_name, "r") word_dict_count = {} for line in dict_file: sequence = line.strip() key = sequence.split('\t')[0] value = float(...
8cf049b369af25b8d38303b54823b9254fe944ad
jasonwee/asus-rt-n14uhp-mrtg
/src/lesson_dates_and_times/datetime_time.py
216
3.609375
4
import datetime t = datetime.time(1, 2, 3) print(t) print('hour :', t.hour) print('minute :', t.minute) print('second :', t.second) print('microsecond:', t.microsecond) print('tzinfo :', t.tzinfo)
37ade2db051a8a2f06430bbd2df5891db528c234
Vegadhardik7/DATA_STRUCTURES_AND_ALGO
/SORTING/Bubble.py
244
4.03125
4
def bubblesort(A): for i in range(len(A)-1, 0, -1): for j in range(i): if A[j] > A[j+1]: A[j], A[j+1] = A[j+1], A[j] A = [85,6,15,24,36] print("Before Sorting:",A) bubblesort(A) print("After Sorting:",A)
21790ed3b7639de7b24fd9071ea20e1f76450963
Tyler-Carter/100-Days-of-Code
/Day 17 - The Quiz Project/main(example).py
426
3.59375
4
class User: def __init__(self, user_id, username): self.id = user_id self.username = username self.followers = 0 self.following = 0 def follow(self, user): user.followers += 1 self.following += 1 user_1 = User("001","angela") user_2 = User("002", "not_angela")...
5b8007d8375f10761eb33541e2613fa84419c0bc
DarioBernardo/hackerrank_exercises
/tree_and_graphs/tree_level_avg_bfs_and_dfs.py
2,231
3.859375
4
""" Given a binary tree, get the average value at each level of the tree. Explained here: https://vimeo.com/357608978 pass fbprep """ import numpy as np class Node(object): def __init__(self, value): self.value = value # print(f"creating node with value {self.value}") self.children = [] ...
c00ed09a70a60293af61e1c35966ebb5e7da419d
hypersport/LeetCode
/valid-palindrome-ii/valid_palindrome_ii.py
561
3.65625
4
class Solution: def validPalindrome(self, s: str) -> bool: left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return self.isPalindrome(s, left+1, right) or self.isPalindrome(s, left, right-1) or False left += 1 right -= 1 ...
a7e104da027ed59a1df6a02033541beaf7cda39a
CodeVeish/py4e
/Completed/ex_02_03/ex_02_03.py
173
3.9375
4
entry_hours = input("Enter Total Hours Worked: ") entry_rate = input("Enter Employee Pay Rate: ") total_pay = float(entry_hours) * float(entry_rate) print("Pay,",total_pay)
5676088e0bf4a67a00cbefad8cc4db2c8e5992fb
Submitty/Submitty
/sbin/get_version_details.py
6,625
3.578125
4
#!/usr/bin/env python3 """ Generate a list of active versions for students. Useful for when the database gets bad values for the active version and then you can just run this function to get the proper values to update the database with. Basic usage of this script is ./get_version_details.py <semester> <course> which...
d010f9ac5a0e794325476ad3f6b7e7d17e8e6706
Tahaa2t/Py-basics
/Conditions.py
1,231
4.34375
4
#-----------------------------simple if else ------------------------------------ #BMI calculator height = float(input("Enter height in cm: ")) weight = float(input("Enter weight in kg: ")) height = height/100 bmi = round(weight/(height**2)) #round = round off to nearest whole number if bmi < 18.5: print(f"{...
dab39dca767fd9c96b77482dbcdc9c10ba21cfb8
moore1474/public
/archive/Practice/Python_Leetcode_Solutions/019_Remove_Nth_Node_From_End_of_List.py
856
3.5625
4
from _Node_Tests_Util import * class Solution(object): def removeNthFromEnd(self, head, n): current = head #Find first n ahead i = 0 while i < n: current = current.next if current is None: return head.next if n == i+1 else head i +=...
6697269aaf11f377b22ef5ef5188e7ce15ac307e
joaofig/dublin-buses
/geomath.py
1,913
3.578125
4
import numpy as np import math def haversine_np(lat1, lon1, lat2, lon2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) All args must be of equal length. Taken from here: https://stackoverflow.com/questions/29545704/fast-haversine-approximat...
18f842c23d1a4bdcf4918f0e34cb2815fd70ba0d
ronaldoedicassio/Pyhthon
/Arquivos Exercicios/Exercicios/Ex072.py
631
4.09375
4
'''' Exercício Python 72: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso. ''' extenso =('zero','um','dois','tres','quatro','cinco','seis','sete','oito','nove','dez','onze',...
8b4bcb6a35682462e659e512120a59b1c21d1553
Gabrielganchev/week2final
/whilelloops/count_to_user2.py
140
3.8125
4
a=int(input()) b=1 while b<=a: print(b) b+=1 if b==a: print("good facking logic my friend sorry for the cursing words")
bf7ee1a39aee2fad47a6eeb69b7bdd7e82c7c95e
Aarav6790/pst_to_ist.py
/psttoist.py
1,160
3.90625
4
time = input("enter time in pst(hh:mm am/pm): ") hours = int(time[0:2]) min = int(time[3:5]) if hours == 11 and min == 30 and time[-2].lower()=='a': print("12 midnight") elif hours == 11 and min == 30 and time[-2].lower()=='p': print("12 noon") elif hours>11 and min>=30 and time[-2].lower()=='a': ho...
5cb19cf17aa1c58a9bc7bead4c6e5e80806b6bea
Dayanand-Chinchure/assignments
/python/prog/number.py
58
3.609375
4
a=[1,2,3,4,5] if 2 in a: print 'yes' else: print 'no`'
3c8c98a0b54582dc1fb99b1ff64238304d78b178
KseniaMIPT/Adamasta
/graph/test/B1.py
309
3.875
4
def check(matrix): N = len(matrix) for i in range(N): for j in range(N): if matrix[i][j] != matrix[j][i]: return 'NO' return 'YES' N = int(input()) matrix = [] for i in range(N): data = str(input()).split() matrix.append(data) print(check(matrix))
fbe2cec4ed178b7b0eb736167549af2697ec9959
Seok-in/PythonCodingTest
/Solution/BinarySearch/BinarySearch01.py
664
3.890625
4
n = int(input()) array_n = list(map(int, input().split())) m = int(input()) array_m = list(map(int, input().split())) array_n.sort() array_m.sort() def binary_search(array, target, start, end): if start > end: return False mid = (start+end)//2 if target == array[mid]: return True elif...
d6b1fcc56424f573e53b46bd9195ff89dd536360
gaeun0516/python_projects
/Basic_grammer/class/Remove_the_same_word.py
683
3.703125
4
class find: def __init__(self): self.flag = 0 self.input_word = i_word self.list_word = l_word self.same_list = same_word def find_word(self, input_word, list_word, same_list): for i in range(0, len(input_word)): for o in range(0, len(list_word)): ...
de1c68abe87136803a8f72457664e8196c708ecd
Rex7/PythonDemo
/hackerrank/Sets/SymmetricDifference.py
370
4.34375
4
""" Given sets of integers, m and n, print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both. """ m = input() a = set(map(int, input().split())) n = input() b = set(map(int, input().split())) c = sorted(a.symmetric_di...
646823aebe61a3800d7fbb3a45c6cd00d3ce3fa7
dntandan/VTU-Lab-Programs
/SEM-6 (File Structures Laboratory)/4 RRN Records/student_record_using_rrn.py
1,911
3.703125
4
rrn = [-1] cnt = 0 class student: def __init__(self, usn, name, sem): self.usn = usn self.name = name self.sem = sem def display_data(self): print(f"\nUSN -> {self.usn} \nName -> {self.name} \nSem -> {self.sem} \n") def pack(self, file): global cnt pos = fi...
1608302fa6f26b5dc2211cf5cfd923bc10b96ecd
IswaryaNidadavolu/python
/divisible.py
142
4.21875
4
x=int(input("enter the number")) y=int(input("enter the number")) if x%y==0: print("divisible") else: print("not divisible")
be288af37233916858ea687e4335a403eec28631
tanoabeleyra/algorithms.py
/searching/binary_search.py
473
3.96875
4
def binary_search(sorted_collection, target_elem): lo, hi = 0, len(sorted_collection) - 1 while lo <= hi: mid = (lo + hi) // 2 current_elem = sorted_collection[mid] if target_elem == current_elem: # Element found! return mid if target_elem < current_elem: # Search o...
423d9b5c9e1a9f1cf2c191b3e29cbfbf4952628b
Moerai/algorithm
/goorm/bitaalgo/temins_hobby.py
288
3.59375
4
# 고속거듭제곱 알고리즘 # def power(a,b,m): # result = 1 # while b > 0: # if b % 2 != 0: # result = (result * a) % m # b //= 2 # a = (a * a) % m # return result n = int(input()) answer = 0 for i in range(1, n+1): answer = answer + i*i*i print(answer%1000000007)
2102569e3fa88e0597ae8a091ffbe399f21e9afb
sillyCod/multiprocessing_demo
/condition.py
1,889
3.578125
4
# -*- coding: utf-8 -*- # time: 19-3-8 下午4:44 """ 多进程状态下的condition不可用 """ import multiprocessing from multiprocessing import Manager from multiprocessing.managers import BaseManager import time class Producer(multiprocessing.Process): def __init__(self, con): self.condition = con super().__init__...
4d482588627d326f54efd8e53ac72ed472015efd
daniela-mejia/Python-Net-idf19-
/PhythonAssig/4-24-19 Assigment4/4-24 Assigment5(Palindrom).py
592
4.28125
4
#Return the reversal of an integer in hexa, eg. reverse (456) returns 654 def reverse(number): reverse = 0 while number > 0: #this I took from GOOGLE endDigit = number % 10 reverse = (reverse*10) + endDigit number = number // 10 def isPalindrome(number): reverse(number)...
960e8264718ae5ae48d461e2de2e774f00df580c
suyeon-yang/CP1404practicals
/prac_01/loops.py
468
4
4
""" first loop """ for i in range(1, 21, 2): print(i, end=' ') print() """ second loop """ for j in range(0, 100, 10): print(j, end=' ') print() """ third loop """ for i in range(20, 0, -1): print(i, end=' ') print() """ fourth loop """ stars = int(input("Number of stars: ")) for j in range(stars): ...
58011fd09f64afe5b2a56118bfa131800b6039ec
aidangainor/Physics-97b-TTL-CPU
/src/microcoder/Instruction.py
5,019
3.609375
4
from MicroInstruction import MicroInstruction from Encoders import * class Instruction: """Corresponds to an instruction from the ISA level. It stores a sequence of up to 16 micro instructions needed to execute a programmer specified instruction. Default micro instructions are specified as class varialbes ...
4aa3552eaf65caf7d09f530a47b6105c3feb81c5
SoosX/python_study
/chapter3/3.2.py
535
3.828125
4
motorcycles =['honda','yamaha','suzuki'] print(motorcycles) motorcycles[2]='ducati' print(motorcycles) motorcycles.append('suzuki') print(motorcycles) motorcyclestwo =[] motorcyclestwo.append('1honda') motorcyclestwo.append('2yamaha') motorcyclestwo.append('3suzuki') print(motorcyclestwo) motorcyclestwo.insert(1,'ducat...
208dfefa977b9d6c31755038161ddc592f01c2c3
Zzpecter/Coursera_AlgorithmicToolbox
/week2/6_last_digit_sum_of_fib_numbers.py
948
4.09375
4
# Created by: René Vilar S. # Algorithmic Toolbox - Coursera 2021 import time global start MAX_TIME = 9.9 def get_fibonacci_rene(n): pisano_period = get_pisano_period(10) remainder_n = n % pisano_period if remainder_n == 0: return 0 previous, current = 0, 1 for _ in range(remainder_n - ...
d12e6e1c9d63dde4e5f2b96e80eb491680d55c0e
cpiehl/Project-Euler
/python/092-Square_digit_chains/euler092.py
1,759
3.53125
4
#!/usr/bin/env python from Euler import sum_squared_digits, timing # A number chain is created by continuously adding the square of the digits # in a number to form a new number until it has been seen before. # For example, # 44 → 32 → 13 → 10 → 1 → 1 # 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 # Therefore a...
7144e90bf618377c31e00c4e60496d8e028034db
NarayanS321/Selenium-Project
/code cha10.py
446
4.34375
4
def isPalindrome(str): # ABCBA reverse_str = reverse(str) #print(reverse_str) result = False if reverse_str == str: #print("true") result = True else: # print("false") result = False return result # Python code to reverse a string # using extended slice syntax...
b5a9ba7cd6fa97d3990c7c70465c87af837c1dc3
txcavscout/tempConversion
/temp.py
796
4.34375
4
# Temp conversion print('Temperature Conversion Tool.') try: convert_type = int(input("Enter 1 for Celsius to Fareheit. Enter 2 for Farenheit to Celsius: ")) if convert_type == 1: temp = int(input('Enter the temp in celsius to convert: ')) converted = temp * 9/5 + 32 print(f'{temp} ce...
157aa0f7db30f8bd33f617c6ae49188d35793dfa
vierbergenlars/Informatica
/HC 2/types.py
685
3.671875
4
# Negeer al die try en except zever, dat is gewoon om effe fouten te vermijden # invoer = raw_input("Tekst voor de invoer > ") print "Invoer: " print invoer, "type: ", print type(invoer) # Welk is het type van deze variabele? # Omzetten naar een int try: print "Omzetten naar int: " omgezet = int(invoer) ...
51f8261cf381af3ba214ec0f410c25ddb98363e7
ccacoba/cmsc117project
/dmcspy/numdiff/second.py
1,702
3.703125
4
#credits: PAALAN import numpy as np from matplotlib import pyplot as plt #plt.rc('text', usetex=True) plt.rc('font', family='serif') #machine epsilon eps = np.finfo('float').eps #4/3 # stepsizes h = np.array([0.1/(1.1**k) for k in range(500)]) #takes stepsizes greather than eps #h = h[h>eps] from time impo...
8c736003b6f4ab0d32850552dadb2d7cede55fb7
Gromy4/Site
/Site/test_4.py
506
3.515625
4
import unittest import re import app class Test_test4(unittest.TestCase): def test_phone_True(self): phone = ["8-931-233-49-72"] for i in range (len(phone)): regex=re.search(r'^([+]?\d{1,2}[-\s]?|)\d{3}[-\s]?\d{3}[-\s]?\d{2}[-\s]?\d{2}$',phone[i]) if (reg...
6f088fd9ff8670f0006f28e3a8a01ec6d1a02709
nagireddy96666/Interview_-python
/COMPANIES/pracice.bangalur/numpy/nump.py
153
3.703125
4
import numpy as np x=np.array([[1,2],[3,4]]) y=np.array([[5,6],[7,8]]) print x+y print np.add(x,y) print x*y print np.multiply(x,y) print np.reversed(x)
861e7381eee1b427bb306709c4af71c9a75c2e41
suton5/partia-flood-warning-system
/test_flood.py
2,164
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 26 16:25:50 2017 @author: limyiheng """ import pytest from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.flood import stations_highest_rel_level, stations_level_over_threshold #stations = build_station_lis...
4393b13e151064175366d0d3a7dfcf2914506dda
lclong728/Daily-Coding-Problem
/problem #1-#20/dailyCoding#10.py
469
3.734375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 26 19:55:12 2018 @author: lenovo """ """ DailyCodingProblem #10 26/07/2018 Asked by: Apple Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds """ import time def delay_function(function, sleep_time): print('del...
a0dd69ff5d72d041c1ed2cf297fe89924b8ac161
ioam/featuremapper
/featuremapper/distribution.py
41,156
3.5
4
""" Distribution class """ # To do: # # - wrap bins for cyclic histograms # - check use of float() in count_mag() etc # - clarify comment about negative selectivity # # - function to return value in a range (like a real histogram) # - cache values # - assumes cyclic axes start at 0: include a shift based on range # # -...
dfebfce2e9601d9d33effa74ee361a9b9f00456f
soyal/py-gs
/src/data-struct/ds_using_tuple.py
263
3.765625
4
zoo = ('dog', 'cat', 'elephant') new_zoo = ('monkey', 'camel', zoo) print('zoo length: ',len(zoo)) print('the last animal about old zoo is', new_zoo[2][2]) # len == 1的元组 tuple_len1 = ('a',) print(type(tuple_len1)) print('len: ', len(tuple_len1)) # len, 1
6256050dedd92c725048cbca550062cdf87db3d0
Sudhanva1999/AllCodesPython
/Sorting/MergeSort.py
713
4
4
def merge_sort(arr): if len(arr)>1: middle=len(arr)//2 arr1=arr[0:middle] arr2=arr[middle:len(arr)] merge_sort(arr1) merge_sort(arr2) i=0 j=0 k=0 while i<len(arr1) and j<len(arr2): if(arr1[i]<arr2[j]): arr[k]=arr1[i]...
27d88ddac1d1fff0cd486a33ce2c8c559ed6447b
fabiannoda/PythonTutorial
/hashmap.py
226
3.8125
4
stra=hash("hola123.") str2=hash(input()) lista=["hola123/", "angel15/"] flag=True while flag: if stra==str2: print(lista) flag=False else: print("contraseña erronea") str2=hash(input())
e82b007daaa309b967e893cace158d45ca137ffc
programmeremmanuel586/investment_and_inflation_calculator
/investment_and_inflation_calculations.py
1,531
3.828125
4
import math # finding the value from investment def investment_value(investment, growth_rate, num_of_compounds, years): # converts growth rate to a decimal growth_rate = growth_rate/100 # exponential function equation value = investment * (1 + growth_rate/num_of_compounds) ** (num_of_compounds * year...
a97c234c714fefea8a9fe93f11a4ceecf13c5fda
yash161/jeniknsdemo8-10
/jenkins.py
59
3.5625
4
a=100 b=30 c=a+b print(f"The sum of Two numbers is:{c}")
ed1379a2c5324d04bc3623d8c9645b5f125102c3
jetbrains-academy/introduction_to_python
/File input output/What next/main.py
712
3.890625
4
def print_heart(n): for i in range(n // 2, n, 2): for j in range(1, n - i, 2): print(end=" ") for j in range(1, i + 1): print("*", end=" ") if (j == 1 or j == i) else print(end=" ") for j in range(1, n - i + 1): print(end=" ") for j in range(1, ...
d3f1a4c1806d0532404a4cbd6273fd84614338d6
farrowking37/CSI260Repo
/Week 5/Library Project 1/main.py
6,403
3.796875
4
"""Implements the functions created in library_catalog.py and allows you to add/remove items to a catalog, print catalog contents, and search for specific catalog items. Author: John Shultz Class: CSI-260-03 Assignment: Library Project Part 1 Due Date: 2/26/2019 12:30 PM Certification of Authenticity: I certify that ...
5c4a743c57ae6c19cf75b9a79b81d2b09fe47175
cocacolabe/TechInterviewProblems
/hackerrank/quicksort.py
1,043
3.90625
4
''' https://www.hackerrank.com/challenges/quicksort1 divide-and-conquer algorithm divide: choose some pivot element, p, and partition your unsorted array into left, right, and equal, left < p, right > p, equal = p If partition is then called on each sub-array, the array will now be split into four parts. This proc...
5dfe77f140c84b2daa3e8db9ebf59124491ed0ed
Yulionok2/Netologia
/1.Fundamentals Python/Python.Знакомство с консолью/DZ_2.py
641
4.375
4
# Пользователь вводит длину и ширину фигуры.Программа выводит их периметр и площадь. square=int(input("Введите длину стороны квадрата:")) P=square*4 S=square**2 print("Вывод: ") print("Периметр:", P) print("Площадь:", S) rectangle_a=int(input("Введите длину прямоугольника:")) rectangle_b=int(input("Введите ширину пря...
786d331aacfac82a4900cb3929fda7e001a8d1ab
MohamedMagdyOmar/Arabic-Diacritization
/NN/tensorflow/5- combine 2, 3, 4.py
6,349
3.734375
4
import os import tensorflow as tf import pandas as pd from sklearn.preprocessing import MinMaxScaler os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Load training data set from CSV file training_data_df = pd.read_csv("sales_data_training.csv", dtype=float) # Load testing data set from CSV file testing_data_df = pd.read_c...
2ac360e3c1a07e7657a216f587f807b055f1111c
oulenz/fuzzy-rough-learn
/examples/data_descriptors/one_class_classification.py
3,139
3.796875
4
""" ======================== One class classification ======================== Data descriptors generalise knowledge about a target class of data to the whole attribute space. This can be used to predict whether new data instances belong to the target class or not, or to identify which new instances should be subjecte...
a034799bb4e91d1ea630adf405a7611ff0ccf7d7
Naushikha/Old-Projects
/Python/Simple Tutorials/The All-in-One Converter/Chunked functions/deci_to_hexa_f.py
469
3.765625
4
#17 Feb 2017 #Converts a decimal into hexadecimal #Coded by _xXHun3rXx_ def dec_hexa(): res="" while n!=0: q=n//16 r=n%16 if r==10: r="A" elif r==11: r="B" elif r==12: r="C" elif r==13: r="D" elif r==14: ...
b8e8f37db75c0cbcb81e83c8cf531f9dcef21b5f
mm-uddin/HackerRankSolutions
/second_lowest.py
769
4.09375
4
''' Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. Input: st...
edf0ae5da9ddd499bfcf752e0e1a76fa8f1ea0e3
krisgrav/IN1000
/1. oblig/dato.py
1,473
3.796875
4
#Oppgave 3 #1 dag_1 = input("Skriv inn en dato med bruk av tall. Forst dag:") maaned_1 = input(", deretter maaned.:") dag_2 = input("Skriv så inn en annen dato. Forst dag:") maaned_2 = input(", deretter maaned.:") dato_1 = (dag_1 + maaned_1) dato_2 = (dag_2 + maaned_2) '''Her ber programmet brukeren om to datoer, og ...
d552fa3a40bbdce489293961a8059c723730bd35
ravi4all/PythonApril_21
/functions/12-func.py
466
3.53125
4
def temp_convert(c): return 9/5 * c + 32 def min_to_sec(m): return m * 60 def km_to_m(km): return km * 1000 def myMap(func, iter): data = [] for i in range(len(iter)): data.append(func(iter[i])) return data temps = [34.5,45.3,42.3,39.8,29.4,28.5,33.6] mins = [5,6,12,4...
9df0c805a58ec4efb7b40b1cb158ef761b150bd4
renlei-great/git_window-
/python数据结构/python黑马数据结构/链表/single_link_list.py
7,206
3.78125
4
"""重要的就是要考虑周全,普通情况和特殊情况""" class BaseLinkList(object): """链表基板""" def is_empty(self): """链表是否为空""" return self.head is None def length(self): """链表长度""" cur = self.head count = 0 while cur: count += 1 cur = cur.next return cou...
37257970bf8e9ad211d6a33f656265c508c70ac4
otisgbangba/python-lessons
/simple/todo.py
128
3.859375
4
items = [] while True: item = input('Item? ') if item: items.append(item) else: break print(items)
a0313dec7265e25f84b7be1ef3a67262c4a0cf22
Gabicolombo/Python-exercicios
/Dictionaries/exercicio 3.py
551
3.9375
4
''' 3. At the halfway point during the Rio Olympics, the United States had 70 medals, Great Britain had 38 medals, China had 45 medals, Russia had 30 medals, and Germany had 17 medals. Create a dictionary assigned to the variable medal_count with the country names as the keys and the number of medals the country had as...
92da246f3db0c5a0c39773fc1e7fe2dfe75a2a1f
imolina218/Practica
/Login_system/validation.py
1,282
3.859375
4
class Authentication(object): def __init__(self, input_value=''): self.input_value = input_value def __lower(self): lower = any(c.islower() for c in self.input_value) return lower def __upper(self): upper = any(c.isupper() for c in self.input_value) return...
c283c3a0fe5848138890eb4499ac0fa675cc3448
Cr1s1/bfsutechlab-1week-python
/学习笔记/代码笔记/Day2/4.1_lists.py
2,598
3.84375
4
# 4.1 列表 # 4.1.1 定义一个列表 names = ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] # 用方括号定义一个列表,字符串元素需要用引号括起来 print(names) ''' 运行结果: ------------------------------------------ ['John', 'Bob', 'Mosh', 'Sarah', 'Mary'] ------------------------------------------ ''' # 4.1.2 列表中单个元素的索引 # 相关知识点:可复习2.2字符串的索引 names =...
548e9536380b869da7fa727e49cc631dba03399a
jay6413682/Leetcode
/Merge_k_Sorted_Lists_23.py
6,442
3.984375
4
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: """ 顺序合并: https://leetcode-cn.com/problems/merge-k-sorted-lists/solution/he-bing-kge-pai-xu-lian-biao-by-leetcode-solutio-2/ """ def merge_two_lists(se...
9c957cc382445c1747af3d99c90da18e44068934
KojiNagahara/Python
/TextExercise/13-2/binaryTree.py
1,326
3.8125
4
"""動的計画法に使用するRooted Binary Treeのpython実装をclass化したもの。 関数バージョンだとキャッシュの初期化を明示的に書かないといけないので、class化することでその問題を解消する""" class CachedBinaryTree(): """キャッシュを考慮したRooted Binary Treeクラス""" def __init__(self): """sourceはツリーを生成するための元になるItemのList""" self._cache = {} def max_value(self, source, avail): if (len...
4710d526b1c43bd18e7e4f7077c823043f36d94d
dmitryzhurkovsky/stepik
/python_profiling/euler_7.py
1,873
3.546875
4
"""Project euler problem 7 solve""" from __future__ import print_function import math import sys import cProfile def profile(func): """Decorator for run function profile""" def wrapper(*args, **kwargs): profile_filename = func.__name__ + '.prof' profiler = cProfile.Profile() result = p...
f793319b2d63ca0fbf6b4a286dedcab3d66b1a33
elsantodel90/cses-problemset
/concert_tickets.py
2,832
3.671875
4
# MAGIC CODEFORCES PYTHON FAST IO import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) # END OF MAGIC CODEFORCES P...
f6812ed3e0a165dd0bed8726d65bbcdf37de5b82
lightening0907/algorithm
/SwapTwoNodeInPair.py
522
3.875
4
# Given a linked list, swap every two adjacent nodes and return its head. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode ...
fe1fead1b6716947dbb093a5d955a31b3f8fd44e
AdamZhouSE/pythonHomework
/Code/CodeRecords/2936/60634/250951.py
1,239
3.59375
4
table = ['2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','#','7','7','8','8','8','9','9','9','#'] def transform(phoneNum): result = "" for x in phoneNum: if x <= 'Z' and x >= 'A': result += table[ord(x) - ord('A')] elif x >= '0' and x <= '9': result += x ...
1c75a2f4f0e1689a7eca3b528d4221f1073c3d4e
tapachec0/Algorithms-Data-Structures
/Monitoring Activities/List #3/DoublyLinkedList.py
10,902
3.921875
4
''' Univesidade Federal de Pernambuco -- UFPE (http://www.ufpe.br) Centro de Informatica -- CIn (http://www.cin.ufpe.br) Bacharelado em Sistemas de Informacao IF969 -- Algoritmos e Estruturas de Dados Autor: Talyta Maria Rosas Pacheco Email: tmrp@cin.ufpe.br Data: 2018-09-07 Descricao: Implementação de uma li...
1c532103db2d814eb3a9250454ea9abb99b94838
Suzie-to/Python_Data_Structures
/Stacks_Tuples_Sets/04.Honey.py
3,407
4.34375
4
''' Worker-bees collect nectar. When a worker-bee has found enough nectar, she returns to the hive to drop off the load. The worker-bees pass the nectar to waiting bees so they can really start the honey-making process. You will receive 3 sequences: • a sequence of integers, representing working bees, • a s...
c59d063724dc0114126740c1af759c3f84d9c945
tgspacelabs/Dev
/PythonApplication1/PythonApplication1/PythonApplication1.py
312
4.03125
4
def Test(n): print('Function called with ', n) print('This is python...') for i in range(10): print('For loop value: ', i) Test(i) # Python 3: Fibonacci series up to n def Fibonacci(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a+b print() Fibonacci(10000)
479e714f12fb49b3e410d29e5ea9b811f3e990c5
Master-of-moyu/sh_and_md
/python/array.py
462
3.546875
4
import matplotlib.pyplot as plt import numpy as np a = [1, 2] print(a) for x in a: print(x) a.append(3) print(a) b = np.arange(0, 1, 0.1) print("np.arange: ") print(b) c = np.linspace(1, 10, num= 5, endpoint = True) print("np.linspace: ") print(c) arr = [] l = len(arr) print(l) arr.append(100) l = len(arr) prin...
2fe8c28fbad8a712b5f57c72dfabe82ec7812a80
williamsyb/mycookbook
/algorithms/BAT-algorithms/The beauty of programming/chapter-3/3-计算字符串的相似度.py
982
3.890625
4
def calculate_string_distance(str_a, start_a, end_a, str_b, start_b, end_b): if start_a > end_a: if start_b > end_b: return 0 else: return end_b - start_b + 1 if start_b > end_b: if start_a > end_a: return 0 else: return end_a - sta...
dad93ea293a3adc68ba3f6b01e86c0dea9e01fe6
qnadeem/solutions_to_some_programming_puzzles
/six/PrA.py
347
3.8125
4
x = str(raw_input()) def printt(a): r = "" if a ==0: print "0" else: while a>0: i = a%2 a = a/2 r = str(i) + r print r while( x!= "#"): N = int(x, 2) ans = 17*N printt(ans) ...
854ff732f61fbcc1b089b25bb40050aedef1ffd8
fran757/battles
/model/factory.py
1,547
3.578125
4
"""Army-oriented Unit factory, using generic stats stored in json file.""" from dataclasses import dataclass, field as dfield from typing import List import json from tools import tools from .unit import Unit, UnitBase, UnitField, Strategy from .army import Army @dataclass class Factory: """Interface to build u...
1e05ea0ebf34f5310ce37f6c34d5a90b7f304f86
7vgt/CSE
/Andrew Esparza - Programmer.py
629
3.765625
4
class Person(object): def __init__(self, name, age): self.name = name self.age = age def work(self): print("%s gose to work" % self.name) class Employee(Person): def __init__(self, name, age, length): super(Employee, self).__init__(name, age) self.length = length ...
843409930b29c9cea6952dda33839169afa3b059
As4klat/Tutorial_Python
/Tanda 1/04.py
234
3.84375
4
def fahrenheit_celsius(f): return (f - 32)*5/9 print("Grados Fahrenheit Grados Celsius") print("================= ==============") for f in range(0, 121, 10): print(" ", f, " ", fahrenheit_celsius(f))
fe6f13e1e74686b068e8fa8dd7a1a28dc6b0ee72
janmlam/TDT4110
/oving1/messages.py
559
3.5625
4
counter = 1 def logg(name, time, msg): global counter print ("MSG", counter, ", " + name + " sent this message: " + msg + " at " + time + " o'clock.") counter = counter + 1 return def main(): logg("Mr. Y", "23:59", "Har du mottatt pakken?") logg("Mdm. Evil", "0:00", "Ja. Pakken er mottatt.") logg("Dr. Horrib...
39a99861d4f0a4c068fcacd0a886d95cfd004fc4
spacemanlol/Python-DataStructures-Reference
/SinglyLinkedList.py
6,077
4.21875
4
# Singly Linked List class Node: def __init__(self, data=None): self.data = data self.next = None class SinglyLinkedList: # Default Constructor def __init__(self): self.head = None self.tail = None self.length = 0 # Add to end of linked list def push(self, ...
4442ed29b6b1ae736e7c53fa7a956a934468234c
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/without_level/314/to_columns.py
335
3.765625
4
from typing import List # not needed when we upgrade to 3.9 from itertools import zip_longest def print_names_to_columns(names: List[str], cols: int = 2) -> None: names = list(map(lambda x: f'| {x:10}', names)) groups = zip_longest(*[iter(names)] * cols, fillvalue='') for group in groups: print('...
185e897df5f1b45edbfb88d72a94638ef9ee33e1
shubham2441/movierental
/BackEnd.py
1,644
3.515625
4
import sqlite3 def connect(): conn=sqlite3.connect("Movie.db") cur=conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS rental (id INTEGER PRIMARY KEY, name text, title text, time integer, phone integer, address text)") conn.commit() conn.close() def insert(name, title, time, phone, addr...
2ccdf66e29855c0dac9d70c1781cd9d16fd2b5e7
SuryamitraAkkipeddi/Codility
/Nesting.py
295
3.828125
4
def solution(S): parentheses = 0 for element in S: if element == "(": parentheses += 1 else: parentheses -= 1 if parentheses < 0: return 0 if parentheses == 0: return 1 else: return 0
a568db684e331b7d6353ee7ba251c566ad4f5731
zhjw8086/MagikCode
/第二季/tkinterProjectS02TEST/paddleGame1~9/paddolGame5/paddleGame5.py
2,898
3.65625
4
""" 12.5 让球拍移动 """ from tkinter import * import time import random tk = Tk() tk.title('paddle game') tk.resizable(0, 0) # 设置窗口的大小是否可以调整, (0, 0)的意思是在水平和垂直方向上都不能改变 tk.wm_attributes("-topmost", 1) # 窗口置顶(无条件记住该方法和括号内的选项) canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=5) # 指定高亮边框的...
946bcb5c8016c99c844b5f4a4e1525f2b5042bde
vv31415926/python_lesson_08_UltraLite
/main.py
1,163
3.953125
4
''' 1. Написать свой генератор последовательностей, свой тернарный оператор 2. Написать свой декоратор ''' # тернарный оператор f = lambda x: 'дед' if x > 50 else 'пацан' print( f(30), f(60)) # Генератор последовательностей *************************************************** lst = [ [x,x**3] for x in range( 10 ...
d47727cbec4aed19ba134225be452d3953dc7046
s0m35h1t/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
379
4.28125
4
#!/usr/bin/python3 """ append text to file """ def append_write(filename="", text=""): """append a string to a text file (UTF8) and returns the number of characters written Args: filename (str): file name text (int): text to write Returns: (int) """ with open(filename,...
5599c3504e3ba15bb055e7e4d9632065c096fcb4
Nadim-Nion/Python-Programming
/xargs.py
528
4.21875
4
''' xargs is used to print multiple numbers of arguments for the same number of parameter. if we change the numbers of argument , the function still can print the output. Note: xargs works like Tuples. ''' def add(*details):# syntax: def function_name(*text) print(details) print(details[1]) add(101,"Physics")...
7ad417ac25510689517f115ae6fa0a2d3f8797e5
pbinneboese/CD_Python
/fundamentals/stars.py
797
3.75
4
# stars, part 1 # def convertToChars(num, chr): # return string with num characters of chr str = "" for i in range(0,num): str += chr return str # def draw_stars(arr, chr): for i in arr: str1 = convertToChars(i, chr) print (str1) return # starArray = [4,6,1,3,5,7,25] print "s...
d0812a2f6a355269748f065b0252463a8b64b6f7
TanishTaneja/Python-Questions
/Coding Ninjas/Conditionals & Loops/Q4_Fahrenheit_to_Celsius.py
985
4.15625
4
# Given Given three values - Start Fahrenheit Value (S), End Fahrenheit value (E) and Step Size (W), you need to # convert all Fahrenheit values from Start to End at the gap of W, into their corresponding Celsius values and print # the table. Input Format : 3 integers - S, E and W respectively Output Format : Fahrenhei...
6b6562c63a3a05dbaf728b3d767b1c76b6e986b3
Akshaya-Dhelaria-au7/coding-challenges
/coding-challenges/week02/day3/alphabet_rangoli.py
410
3.5
4
size=3 for i in range(1,size+1): print ("-"*(2*(size-i)),end="") s=chr(96+size) for j in range(1,i): s+=("-"+chr(96+size-j)) s2= s[::-1] print (s+s2[1::],end="") print ("-"*(2*(size-i))) for i in range(size-1,0,-1): print ("-"*(2*(size-i)),end="") s=chr(96+size) for j in range(1,i): s+=("-...
bb15928f8b089b749025ffedc10b3c9e20a26c78
nyirweb/python-t
/Exam2.py
836
3.890625
4
#Üzenet a napokra válaszként nap = int(input("Add meg hanyadik napja van a hétnek?\n")) if(nap == 1): print("Hétfő - Work hard live hard - Éld túl ezt is!") elif(nap == 2): print("Kedd! Akkor még egy kis erő maradt a hétvégéből?") elif(nap == 3): print("Szerda! A nap végén több telt el a hétből, ...
0d791c5333b25bef3a1a47451243b2e594f65434
whime/dataStructure-algorithm
/剑指offer/左旋转字符串.py
413
3.953125
4
""" 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务, 就是用字符串模拟这个指令的运算结果。 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。 """ # -*- coding:utf-8 -*- class Solution: def LeftRotateString(self, s, n): # write code here tmpstr=s[0:n] s=s[n:]+tmpstr return s
2b9d56106fa73e6b8a1ac114d9d611c0bd71bcc2
BumbarG/Hex-Tournament
/hex/libs/disjoint_set.py
838
3.703125
4
class DisjoinSet: def __init__(self): self.parents = {} self.ranks = {} def find(self, a): if a not in self.parents: self.parents[a] = a self.ranks[a] = 0 return a while self.parents[a] != a: prev = a a = self.parents[...
ef0cb1cc84ca2f43073d090ea9ca691894556d6d
RonaldoLira/Mision_02
/cuenta.py
308
3.9375
4
# Autor: Ronaldo Estefano Lira Buendia # Programa donde calcula el total de la cuenta c=int(input("Introduce el total de la comida: ")) p=c*.13 i=c*.16 t=c+p+i print("Costo de su comida: {0:.2f}".format(c)) print("Propina: {0:.2f}".format(p)) print("IVA: {0:.2f}".format(i)) print("Total a pagar: {0:.2f}"...
822b005755d4a0bc72e2ad1f383366a5a41d6350
fatimahammouri/HB_Restaurant_rating_lab
/ratings.py
930
3.9375
4
"""Restaurant rating lister.""" def Restaurant_scoring(file_name): opened_file = open(file_name) rating_dict = {} for line in opened_file: line = line.rstrip("\n") data = line.split(":") #print(data) rating_dict[data[0]] = data[1] # print(rating_dict) user_re...
18fa6677f3e607cb74d2681f7ba5b80dec931f55
UncleBob2/MyPythonCookBook
/data and variable types.py
967
3.828125
4
''' Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x =...
27544b52d9865f27d4a5780b09f11b59b38da578
binghe2402/learnPython
/刷题/Leetcode/p938 二叉搜索树的范围和.py
671
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def __init__(self): self.s = 0 def rangeSumBST(self, root: TreeNode, low: int, high: int) -> in...
c189d4dd818de4d56557c01aca4d87f8139a0056
eagletusk/PythonADS
/Trees/nodeTree.py
1,465
3.765625
4
class BT(object): def __init__(self,rootObj): self.key =rootObj self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BT(newNode) else: t = BT(newNode) t.leftChild = self.leftChild self.leftChild = ...
6c5327e6dab0ae0a5df388deaa7a904a59991edd
acaciooneto/cursoemvideo
/ex_aulas/ex.aula12-036.py
836
3.953125
4
print('Você quer alugar uma casa? Primeiro terá que se adequar a nossos critérios.') casa = int(input('Digite o valor da casa que você quer comprar: ')) salario = int(input('Diga o valor do seu salário: ')) tempo = int(input('Agora diga em quantos anos você pretende pagar: ')) parcelas = tempo * 12 prestação = casa / ...
106e4f7b4330a226c54f85051ad29239f8938600
PrivateVictory/Leetcode
/src/ziyi/Tree/MaximumDepthofBinaryTree.py
876
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2016-01-05 13:18:43 # @Author : Alex Tang (1174779123@qq.com) # @Link : http://t1174779123.iteye.com ''' description: ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = Non...
b99c49f96c2697a56f2c9197b6039891466417ef
DonValino/Python
/practice1/Conditionals.py
632
4.15625
4
import random import sys import os # if else elif == != > >= <= age = 21 if age >= 21 : print("You Are Old Enough To Drive A Bus") elif age >= 16 : print("You Are Old Enough To Drive A Car or Motorcycle") else : print("You Are Not Old Enough To Drive") # Combining conditions with logical operators # Log...
89ba15aa0fe4605c09afe376d402ac7c9ac3daff
sifirib/yoo
/src/Games/connect4/Board.py
2,141
3.625
4
from enum import Enum class Board: def __init__(self, height=6, width=7): self.width = width self.height = height self.board = [[Piece.EMPTY for _ in range(width)] for _ in range(height)] # 6 x 7 def getPiece(self, x, y): return self.board[y][x] def addPiece(self, col, p...