blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3a62cd4ae146dd66b9ceacd8d09bd4bcd1c63010 | NataFediy/MyPythonProject | /codingbat/last2.py | 1,044 | 4.03125 | 4 | #! Task from http://codingbat.com:
# Given a string, return the count of the number of times that a substring
# length 2 appears in the string and also as the last 2 chars of the string,
# so "hixxxhi" yields 1 (we won't count the end substring).
#
# Examples:
# last2('hixxhi') → 1
# last2('xaxxaxaxx') → 1
# last2('axx... |
fe5e7de728cabcf51c7a8d441b0a70d259f20f07 | NataFediy/MyPythonProject | /other_resources/factorial.py | 213 | 4.03125 | 4 | #! factorial via recursion:
def fact(num):
if num < 0:
return -1
elif num == 0:
return 1
else:
return num * fact(num - 1)
print(fact(5))
for i in range(6):
print(fact(i))
|
aa2ec44495cc9f37fdf6428d803fecc7b1281202 | leohliao/interview_study_guide | /leetcode/akamai_maximum_learning.py | 3,426 | 4.125 | 4 | """
Leetcode: https://leetcode.com/discuss/interview-question/1063118/Akamai-or-Maximum-Learning
Repl.it: https://replit.com/@HadisDaqiq2/maxvaluei#main.py
Tags: Dynamic Programming, Knapsack
You will be given a list of articles with their page lengths and intellectual value coefficients.
Given a ... |
0c8919a341e1b1594d4d62beacb413c160779042 | leohliao/interview_study_guide | /hackerrank/timeConversion.py | 1,817 | 4.28125 | 4 | # Given a time in -hour AM/PM format, convert it to military (24-hour) time.
# Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
# - 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.
# Example
# Return '12:01:00'.
# Return '00:01:00'.
# Function Description
# Complete the timeCon... |
11b6014ec0145517d9b4dbefbdd2d03fc4309ee0 | aakashshankar/coursehw | /hw1/problem2.py | 1,327 | 3.53125 | 4 | import pandas as pd
# from pandas import DataFrame
import numpy as np
import matplotlib.pyplot as plt
countries=pd.read_csv('data/countries.csv')
print(f'{countries}')
income=pd.read_excel('data/income_per_person_gdppercapita_ppp_inflation_adjusted.xlsx')
print(f'{income.head()}')
print(f'{income.transpose()}')
#----EN... |
5dbc3ea8bfda68700618d8b6a2cc14fec12f83c3 | yash1th/ds-and-algorithms-in-python | /binary search/find_fixed_number.py | 890 | 3.890625 | 4 | def by_linear_search(data):
for i, v in enumerate(data):
if i == v:
return i
return None
def by_binary_search(data):
low = 0
high = len(data) - 1
while low <= high:
mid_index = (low + high) // 2
if mid_index > data[mid_index]:
low = mid_index + 1
... |
e1520bfff292e8419f6f8a09128be4a8761cd123 | yash1th/ds-and-algorithms-in-python | /string processing/is_unique.py | 212 | 3.5 | 4 | def is_unique(s):
setS = set()
for i in s:
if i.isspace():
continue
if i.lower() in setS:
return False
else:
setS.add(i.lower())
return True |
320c81a6d2de7a9603109e8df3dedc3419663cfd | yash1th/ds-and-algorithms-in-python | /linked_list/linked_list.py | 4,695 | 4.0625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def append(self, data):
... |
f20ad3f1a90fa7771f4a3df24d743c781d5d8bde | yash1th/ds-and-algorithms-in-python | /binary search/integer_square_root.py | 425 | 3.640625 | 4 | def by_linear_search(k):
n = 1
while n**2 <= k:
n += 1
return n - 1
def by_binary_search(k):
low = 0
high = k
while low <= high:
mid = (low + high) // 2
if mid ** 2 > k:
high = mid - 1
else:
low = mid + 1
return low - 1
print(by_linea... |
edbc075b486113e3e2214d6ab11c9bd9379cb653 | A-Kyr/AdventOfCode | /day1/project1_2.py | 573 | 3.578125 | 4 | with open('data.txt') as f:
lines = f.read()
def sum_to_2020(number1, number2, number3):
if number1+number2+number3 == 2020:
return True
return False
def solution(lines):
for i in range(len(lines)):
for j in range(i+1, len(lines)):
for k in range(j+1, len(lines)):
... |
104789d5f583c5fd405151eb49969a5d24408ceb | dimitrisadam/askhseis | /ask1.py | 1,122 | 3.640625 | 4 | keimeno = raw_input("Dwste to keimeno \n")
output =""
marksCount=0 # metraei !
spaceCount=0 # metraei kena
for i in range(len(keimeno)):
if keimeno[i] is " " and marksCount is 0:
print "keno"
output+=" "
continue
elif keimeno[i] is " " and marksCount is not 0 and keimeno[i+1].isupper():
for j in range(marks... |
c0854c6b7d78dc7d375d1a806bc890e830597137 | nj009/janken | /janken.py | 1,049 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import random
dic = {"a": "グー", "b": "チョキ", "c": "パー"}
print("じゃんけーん")
print("a=グー, b=チョキ, c=パー,a,b,cのいずれかを入力")
word = input()
print("your input: {}".format(word))
try:
user_choice = dic.get(word)
choice_list = ["a", "b", "c"]
pc = dic[random.choice(choice_list)]
draw = 'ドロー... |
ac7437fa7fba534e287ccae6428d2412c02c0051 | JiageWang/data_structure_python | /线性表/循环双链表.py | 3,585 | 3.890625 | 4 | class Node:
def __init__(self, elem):
self.elem = elem
self.next = None
self.pre = None
class CircleDoubleLinkList:
def __init__(self):
self._head = None
self._rear = None
def is_empty(self):
return self._head is None
def length(self):
if self.... |
29ddf22e80a3ade6d44bf15a869231e3d23fcf0a | mehanaik/Data-Visualisation-with-Python | /task2.py | 518 | 3.5625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_json(r'./rain.json')
#graph for temperature
plt.figure(figsize=(15,5))
plt.plot( df['Month'],df['Temperature'],label='Temperature')
plt.show()
#graph for rainfall
plt.figure(figsize=(15,5))
plt.plot( df['Month'],df['Rainfall'],lab... |
255133d5be9715cc98de9c10f0d0487f80dab5af | jilikuang/practice | /leetcode/two_sum/two_sum.py | 379 | 3.625 | 4 | def two_sum(nums, target):
table = {}
ret = []
for i in range(len(nums)):
search = target - nums[i]
if search in table:
ret.append(table[search] + 1)
ret.append(i + 1)
break
table[nums[i]] = i
return ret
if __name__ == "__main__":
nums = [... |
f3b568254dadb90be3273970dd806d261d6faf50 | vasu19126/introduction | /samples/f2.py | 128 | 3.953125 | 4 | def add(a,b):
return a+b
a =float(input("enter any no.= "))
b =float(input("enter any no.= "))
print(add(a,b))
#print(a+b)
|
11d6d1394e5333fc446a6be59c94aa0cb1a2901c | Dhar15/Machine-Learning-Laboratory | /3/DecisionTree.py | 4,548 | 3.953125 | 4 | ''' Q.3) Write a program to demonstrate the working of the decision tree based ID3 algorithm. Use an appropriate data set for building the decision tree and
apply this knowledge to classify a new sample. '''
import numpy as np
import math
import csv
def read_data(filename):
with open(filename, 'r... |
635cfef3a6cffdec9377d4ec04cdaf657d05bc04 | gibarsin/IEEEx-10.0 | /src/mancalah.py | 716 | 3.765625 | 4 | board = [int(i) for i in input().strip().split(' ')]
boards = [board]
def get_next_board(board):
seeds = board[0]
newboard = board[1:]
i = 0
while seeds:
if i < len(newboard):
newboard[i] += 1
else:
newboard.append(1)
seeds -= 1
i += 1
r... |
904b9addb046260375441be28a4264872f877bee | cychug/projekt3 | /Divide/divide.py | 483 | 3.59375 | 4 |
def replace_string(text):
newText1 = text.replace("\"", "")
newText2 = newText1.replace(" ", ",", 1)
newText3 = newText2.replace(" - ", "-")
newText4 = newText3.replace(" – ", "-")
return newText4
with open("input.csv") as inFile:
for line in inFile:
line = line.strip()
print... |
b08288daec6f0949f8c13f6030dbdd9decdaf4d0 | cychug/projekt3 | /021 funkcja break.py | 476 | 3.625 | 4 | """
break to przerwanie pętli i wyście
continue przerywamy od tego momentu i wracamy, następne nie zostaną wykonane ale tylko w tym jednym przejściu
"""
wynik = 0
for i in range(3):
x = int(input("Podaj liczbę dodatnią:"))
if (x > 0):
wynik += x
else:
print("Miała być liczba większa od zera.... |
f95b7a9e34a866bafb5393d905f27c2d63f2d728 | cychug/projekt3 | /001c_operatory_porownania.py | 171 | 3.921875 | 4 | a = 5
b = 5
print(a == b)
print(a != b)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
print(a is b) # operator is NIE porownuje wartości a ADRESY w pamięci
|
656c16dd662ba16768b4537bff71b82216b12eb9 | cychug/projekt3 | /Exercises/011_suma_elementów_krotki.py | 547 | 3.65625 | 4 |
krotka = (2, 4, 6, 8, 2)
lista = [2, 4, 6, 8, 2]
zbior = {2, 4, 6, 8, 2} # elementy zbioru nie mogą się powtarzać !!!
def sum_elements(where): # na piechotę
sum = 0
for i in range(0, len(where)):
sum = sum + (where[i])
return sum
def sum_elements1(where): # z wykorzystaniem sum
... |
a7097539e1cb6fd4d176d0759e12659a5d94094c | cychug/projekt3 | /057_domyslne_argumenty_funkcji.py | 341 | 3.5625 | 4 | # domyslne argumenty funkcji
# jezeli nie podamy drugiego argumentu funckcji to przyjmie on wartość podaną za =
def increment(x, amount = 1):
return x + amount
print(increment(1, 100)) # tu są podane oba argumenty
print(increment(1)) # tu nie ma drugiego argumentu ale pierwszy jest, drugi przyjmie wa... |
56a0abcf5c1f9590610d905bee9a11d482d3b5da | cychug/projekt3 | /045_wyrazenia_slownikowe.py | 1,331 | 4 | 4 | # wyrazenia słownikowe TWORZYMY SŁOWNIKI NA PODSTAWIE INNYCH
# tworzymy SŁOWNIK, którego kluczem jest imię a wartością długość imienia
names = {"Krzysiek", "Ania", "Marek", "Karol", "Wojtek"}
nameLenght = {
name: len(name)
for name in names
if name.startswith('A') # mozemy dodac taki warunek lub nie
}
pri... |
8caac9f09c0c3f4ce9ffe5a42b1329fa9f377b60 | JaeSeoKim/42piscine_python_django | /d02/ex03/beverages.py | 1,360 | 3.921875 | 4 | #!/usr/bin/python3
class HotBeverage:
def __init__(self) -> None:
self.price = 0.30
self.name = "hot beverage"
def description(self) -> str:
return "Just some hot water in a cup."
def __str__(self) -> str:
TEMEPLATE = ("name : {name}\n"
"price: {price:... |
cb8a422bb2f7ed59bf84dfc0976b4fd855e91793 | theyadev/ile-au-python | /minigames/fizzbuzz.py | 5,513 | 3.65625 | 4 | from random import randint,seed
from prints import printAt, printAnimation
from time import sleep
from Colors import TextColors
from settings import *
game_board_height = 4
game_board_width = 100
center_size = [40,60]
def printGameBoard():
for y in range(game_board_height):
for x in range(game_board_width... |
eb456f71fad70c121c8399cdb8ff3491ef528286 | AI-4-SE/Exploring-Hyperparameter-Usage-And-Tuning-In-Machine-Learning-Research | /src/paper_stats.py | 19,571 | 3.640625 | 4 | """
This script calculates the results for the second research question: Are hyperparameters tuned and if so by which method?
Specifically, the script answer the following sub-questions:
(1) How many research paper write about hyperparameter tuning/final values?
(2) What ML fields report hyperparameter tuning?
(3) Wh... |
9f75c7a8e7c52c46073d7b208288014f198cbcab | MaLL-UFSCar/git-study | /study_1/loliveira/summer.py | 298 | 3.828125 | 4 | #coding: utf-8
import sys
#use this file to write your summer application
#the summer should receive two integers a and b and return:
#"the sum of a and b is a+b"
a = float(sys.argv[1])
b = float(sys.argv[2])
soma = float(a+b)
print 'O valor de ',str(a),' + ',str(b),' é igual a ',str(soma)
|
190055b8a540080d35b174ad60368ea8f83bbc5e | BlancaCC/aprendizaje-automatico | /practica1/code/exercise_3.py | 5,434 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Exercise 3
Author: Blanca Cano Camaro
"""
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1)
def STOP_EXECUTION_TO_SEE_RESULT():
input('\n--- End of a section, press any enter to continue ---\n')
def f(x,y):
'''
Function to minimize
'''
return np... |
6514a9b05a207ae55db7d8b792e00b0cc7ae52ff | BlancaCC/aprendizaje-automatico | /practica1/code/exercise_1.py | 8,264 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
TRABAJO 1.
Autor Blanca Cano Camarero
Grupo 2
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # to display 3d function
np.random.seed(1)
print('EJERCICIO SOBRE LA BUSQUEDA ITERATIVA DE OPTIMOS\n')
print('Ejercicio 1\n')
... |
163a2c765932e85594e8524dc0a3c5c97ffc8483 | 2579356425/prosodylab.alignertools | /phone_frequency.py | 4,538 | 3.703125 | 4 | # Calculate the frequency of a set of phones, provided a dictionary and a set of .lab
# files.
import codecs
from glob import glob
def dirclean(string):
"""Clean raw input strings so that they are readable as directories."""
if string[-1]==" ":
string = string.replace(" ","")
if string[-1]!="/":
string = strin... |
520a3ed61998ea595ff0a5951fba23c38d7f987c | bradenaa/MITOCW | /6.0001 Introduction to Computer Science and Programming in Python/ps1/ps1a.py | 777 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 10:17:50 2018
@author: bradenaltstatt
"""
annual_salary = float(input("Please state your annual salary: "))
portion_saved = (float(input("Please state percentage of salary saved each month: ")))/100
total_cost = float(input("Please state the t... |
2f933e00df4dfadffbbe0f1f2b7312b36bd3d05e | zczxzxzc/category | /PythonProjects/num&matplotlib.py | 691 | 3.734375 | 4 | import matplotlib.pyplot as plt
import numpy as np
x_values = np.linspace(0,20,100) # 创建一个列表
plt.plot(x_values,np.sin(x_values)) # 对于每个点的sin值绘图
plt.show() # 显示
y_values=[x**2 for x in x_values]
#y轴的数字是x轴数字的平方
plt.plot(x_values,y_values,c='green')
#用plot函数绘制折线图,线条颜色设置为绿色
plt.title('Squares',fo... |
c8c4e420635b3358583deb681e5b1db935c2b76b | Tjuvenile/dnf_game | /game_package/tool/windows_constant.py | 654 | 3.78125 | 4 | #-*- coding:utf-8 -*-
import os
import win32api
'''
关于windows的一些工具和常量定义
'''
#SCREEN ORIGIN in window x = 400,y = 230
SCREEN_ORIGIN_COORDINATE = (400, 230)
#get Windows screen size
WINDOWS_SIZE = (win32api.GetSystemMetrics(0),win32api.GetSystemMetrics(1))
#给一个大图片的大小和坐标,给小图片的大小,返回小图片在大图片居中的x,y坐标
def center_coordinat... |
498f832fa7a5aebb4b316fd4c85afcf0a5a46f7a | aflag/exercises | /taxes/test_taxes.py | 1,097 | 3.5 | 4 | import unittest
import taxes
class ProductTestCase(unittest.TestCase):
def test_parse_book(self):
product = taxes.parse("1 book at 12.49")
self.assertEqual(product.quantity, 1)
self.assertEqual(product.type, "book")
self.assertEqual(product.name, "book")
self.assertEqual(pr... |
b8dab816d45c1f22c22c2b293cb24fd13a279c46 | bolondienrico/esercitazione | /main.py | 132 | 3.765625 | 4 | print("Inserisci un numero")
x = int(input())
y = int(input("Inserisci il numero con cui vuoi moltiplicarlo"))
z = int(x*y)
print(z) |
c777cf4d1bab83a19900ac201c774d704723484a | calinwolf08/python-projects | /decorators.py | 372 | 3.671875 | 4 | def hi(name = "calin"):
return "hi " + name
print hi()
greet = hi
print greet()
del hi
#print hi()
print greet()
del greet
def hi(name = "calin"):
print "in hi"
def greet():
return "in greet"
def welcome():
return "in welcome"
print greet()
print welcome()
print "in hi again"
return greet
x = h... |
20c0211370056f558e58ebbebc09f62b957c6f09 | nogaanaby/python-mmns | /mmn3/drafts/stats.py | 1,810 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Student: Noga Anaby
ID: 318298296
Assignment no. 3
Program: stats.py
comment: I know that you have beet tring to teach neasted loops,
but I feel in most of the cases - the best practice might be to avoid it where you can
since it is not clean and afficiant solotion when you have the choise... |
ca232e0c40a07ed098940ed831c5714d7551874f | nogaanaby/python-mmns | /mmn4/ex4-einbar.py | 1,904 | 3.84375 | 4 | """
Student: Ein-Bar Surie
ID: 316011683
Assignment no. 4
Program: vigenere.py
"""
# sum the new value of latin letters
def add_letters(str1: str , str2 : str):
if len(str1) != 1 or len(str2) != 1:
return None
if not (str1.isalpha and str2.isalpha): #de morgan's laws
return None
... |
53356135f8b7df51f37b2e86d3cc77d3e36efd32 | petalsofcherry/show-me-the-code | /the_0021th_problem.py | 836 | 3.609375 | 4 | # -*- coding:utf-8 -*-
import os
from hashlib import sha256
from hmac import HMAC
#加密密码,保证盐值类型是bytes
def encrypt_passwd(passwd, salt = None):
if None == salt:
salt = os.urandom(8)
assert len(salt) == 8
assert isinstance(salt, bytes)
if isinstance(passwd, str):
passwd = passwd.encode()... |
90b3e27d9bf1ff5a10b1f7bc1ad4dcfc2f3d5001 | electriclo/coinflipgame | /coinfilp.py | 323 | 4.0625 | 4 | import random
print ("The Coin Flip Game\n")
heads = 0
tails = 0
count = 0
while count< 2:
coin = random.randrange(2)
if coin == 0:
heads = heads + 1
else:
tails = tails + 1
count += 1
print ("Heads: ", heads)
print ("Tails: ", tails)
input("\nPress enter to exit... |
bb6093457d91c97745aba95c846cf01c7a2a2286 | Rajamanikam/JetBrains-Python-Projects | /Tic Tac Toe/Stage 3/tictactoe3.py | 925 | 3.90625 | 4 | cells = input("Enter the cells: ")
print("""---------""")
print(f"| " + cells[0] + ' ' + cells[1] + ' ' + cells[2] + " |")
print(f"| " + cells[3] + ' ' + cells[4] + ' ' + cells[5] + " |")
print(f"| " + cells[6] + ' ' + cells[7] + ' ' + cells[8] + " |")
print("""---------""")
def returnWinner(board):
for ro... |
28068e60e332f979a2f90584442bf109f5e14624 | madhu1836/Fibonacci-Numbers.py | /Fibonacci.py | 327 | 4.15625 | 4 | nterms = int(input())
n1=0
n2=1
count=0
if nterms <= 0:
print("please enter a positive integer")
elif nterms==1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth=n1+n2
n1=n2
n2=nth
co... |
066aaa3c128508072d47cb4cadd14aa13f3b92b8 | jayednahain/AI-LAB-assinment- | /3_spedd_test.py | 358 | 3.75 | 4 | a = int(input("enter a speed: "))
def check_speed(speed):
count = 0
if speed<70:
print("OK")
elif speed>70:
for i in range(70,speed,5):
count = count+1
print("points: ",count)
if count>12:
return print("License suspended")
return ... |
b5b651c2e55c68e30ef954ecac82d4ad1c47d0c4 | tanni-Islam/test | /comprehnsn.py | 285 | 3.625 | 4 | '''
sentence = "Once upon a time there was a little girl name Tanni"
word = sentence.split()
length = []
for i in word:
length.append(len(i))
print length
'''
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = [int (x) for x in numbers if x > 0]
print newlist
|
c339702e2545849e13e5b2f5c5528b14516b2f11 | tanni-Islam/test | /generator.py | 379 | 3.53125 | 4 | '''import random
def lottery():
for i in xrange(6):
yield random.randint(1,40)
yield random.randint(1,15)
for i in lottery():
print "And the next number is %d" % i
'''
a=1
b=1
def fib():
a,b = 1, 1
while 1:
yield a
a, b = b, a + b
count =0
for i in fib():
p... |
4675397960248148dc6dced934992bb7ca4b8d9b | Kirbyszsr/githubCrawler | /csvParser.py | 834 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import csv
from urlParser import url_parser
def read_csv(file):
# read csv file and convert the urls into lists
result = []
with open(file, 'r') as f:
reader = csv.reader(f)
# is_header = True
for row in reader:
resul... |
ed43c867a9653b42203e5ebb336cc9368ea10c6c | sivssdn/aes_encryption | /key.py | 1,911 | 3.609375 | 4 | from miller import *
import math
def modexp( base, exp, modulus ):
return pow(base, exp, modulus)
def loopIsPrime(number):
#looping to reduce probability of rabin miller false +
isNumberPrime = True
for i in range(0,20):
isNumberPrime*=isPrime(number)
if(isNumberPrime == False):
return isNumberPrime
... |
c2469f78dd75bae9a655c2e16e83fa2d272285e2 | Prasannadhungel4/Python-Basics | /Python Basics (Selection, Iteration, Queue, Stack, Distionaries, List).py | 3,196 | 4.09375 | 4 | #Selection
print("what is your name")
name = input("enter your name")
length = len(name)
print(length)
if length > 7 :
print("your name is lengthy")
elif length < 5:
print("your name is short")
else:
print("beautiful name")
# Iteration
for i in range(1, 6):
print(i)
i =1
while i < 6:
print(i... |
2d7998dd65147617890d7090ef1de0588c56c585 | axtell5000/python2020 | /data-tuples.py | 484 | 3.609375 | 4 | # Tuples are immutable
t = tuple()
print(dir(t))
t2 = ('a', 'b', 'd', 'c')
# t2.sort() cant do this
# tuples are comparable
print((0, 1, 3) < (5, 4, 3))
fhand = open('romeo.txt')
counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1
lst = li... |
b10e1feb6c6fced7756542b0b316deb7e65f736f | kamyanskiy/demo | /simple_gen.py | 302 | 4 | 4 | def simple_gen():
for i in [1,2,3]:
yield i
# Get generator from function
gen = simple_gen()
print("Type: ", type(gen))
# Iteration through generator
print("Iter #1: ", next(gen))
print("Iter #2: ", next(gen))
print("Iter #3: ", next(gen))
# Generator is empty, StopIteration
next(gen) |
1180792f6e4a7ebbb2b9c85ef18ed2ac13a5ad00 | HHonoka/LeetCode- | /LeetCode Tree/venv/LeetCode 94 Binary Tree Inorder Traversal.py | 985 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
while root or stack:
whi... |
58f08575912af58846dfb14d5916049abd3b6cfa | HHonoka/LeetCode- | /LeetCode Tree/venv/LeetCode 230 Kth Smallest Element in a BST.py | 1,226 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
if not root:
return 0
stack = []
curnode = root... |
07621d609ec53b10a61445dfeadda1025061ae55 | HHonoka/LeetCode- | /LeetCode Tree/venv/LeetCode 428 Serialize and Deserialize N-ary Tree.py | 1,326 | 3.6875 | 4 | """
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
res = []
... |
5b02408adec924861627f7cf67ac4fc9328feb9b | HHonoka/LeetCode- | /LeetCode Tree/venv/LeetCode 257 Binary Tree Paths.py | 1,321 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
self.res = []
self.dfs(root, "")
return self.res
def ... |
79b6f12d189d05a84b920011158567384acd6d70 | HHonoka/LeetCode- | /LeetCode Search/venv/LeetCode 212 Word Search II.py | 1,214 | 3.5625 | 4 | class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
dic = {}
self.res = set()
for word in words:
curnode = dic
for c in word:
if c in curnode:
curnode = curnode[c]
else:
... |
2e666408be41f908555ec9999cd5317d3783f436 | Vilyanare/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/model_city.py | 603 | 3.515625 | 4 | #!/usr/bin/python3
"""
Module containing the database model for city table
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from model_state import Base, State
class City(Base):
"""Class for city table"""
__tablename__ = 'cities'
... |
46eb742655c75beca5b84ec004ffd1ee9e55a94d | Vilyanare/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 381 | 4.25 | 4 | #!/usr/bin/python3
"""0-add_integer module
Has one function, add_integer(a, b)"""
def add_integer(a, b):
"""
Returns the sum of two integers or floats cast to int
"""
if type(a) not in (int, float):
raise TypeError("a must be an integer")
if type(b) not in (int, float):
raise ... |
de302fd52e5416cf52274accba972c0dc16f6445 | Vilyanare/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 264 | 3.90625 | 4 | #!/usr/bin/python3
"""Module holding a sub class of list"""
class MyList(list):
"""Sub class of list class"""
def print_sorted(self):
"""Method to print a sorted version of your list"""
new = self[:]
new.sort()
print(new)
|
674c35f34ea0461563c4ac1318d17dd175607a24 | Vilyanare/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 512 | 3.953125 | 4 | #!/usr/bin/python3
def append_write(filename="", text=""):
"""Appends text to a file and returns how many characters were written"""
first = 0
second = 0
try:
with open(filename, mode="r", encoding='utf-8') as a_file:
first = len(a_file.read())
except:
pass
with open(... |
76fc47cf6e7188390ceecfb6d0f7e918cb5dae88 | Vilyanare/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,222 | 4.125 | 4 | #!/usr/bin/python3
"""Stand alone function that divides all elements of a matrix
by n"""
def matrix_divided(matrix, div):
"""Function that divides a matrix by div"""
length = 0
new_matrix = []
if type(matrix) != list:
raise TypeError('matrix must be a matrix \
(list of lists) of integers/float... |
62d70fc413f2a7e5d0cc625b6d78303d4e0367f0 | sdiemert/CodeMagnets | /src/CodeMagnets/colorConstants.py | 1,246 | 3.546875 | 4 | import constants as c
GREEN = 0
PINK = 1
YELLOW = 2
ORANGE = 3
WHITE = 4
BLUE = 5
PURPLE = 6
def getColorFromNumber(i):
if i == GREEN:
return "GREEN"
elif i == PINK:
return "PINK"
elif i == YELLOW:
return "YELLOW"
elif i == ORANGE:
return "ORANGE"
elif i == WHITE:
... |
d0f55b53237b0e12d0baeba0e8d006fbacc256c3 | daniel-trevino/adventofcode2020 | /2/secondPuzzle.py | 698 | 3.875 | 4 | from utils import getInputValues
def findValidPasswords():
inputValues = getInputValues()
count = 0
for passwordObject in inputValues:
if isValidPassword(passwordObject) is True:
count += 1
print(passwordObject)
return count
def isValidPassword(passwordObject):
pa... |
d1f13dc7e55d9055671c38c61039f6a6b617aa2b | Philip-Crowther/sudoku | /Sudoku.py | 2,742 | 4.25 | 4 | import random
import numpy as np
class Sudoku:
def __init__(self):
# here the puzzle is empty, each group of three rows is generated within its own array referred to from here on as a "superrow"
self.puzzle = np.zeros([9, 9])
nums = list(range(1, 10))
random.shuffle(nums)
se... |
1ec7734e50b659441947f1bd068b42d2264303f3 | sravanthidl/chess | /Chess.py | 3,335 | 3.734375 | 4 | import piece_obstacles
import piece
import check
#BUILDING THE CHESS BOARD
def initial_board() :
l = [[' ', 1, 2, 3, 4, 5, 6, 7, 8], [1, 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], [2, 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], [3, '_', '_', '_', '_', '_', '_', '_', '_'], [4, '_', '_', '_', '_', '_', '_', '_', '_'], [5, '_... |
ceec257ca69a475e38367e7a9e6f713caf6387a3 | NoahCardoza/july-programming-class | /w01/python/d00/ex00/solution.py | 1,044 | 4.375 | 4 | print ("This program will calculate the area of a figure.")
shapechoice = int(input("Would you like to find the area of a square (1), rectangle (2), triangle (3), or circle (4)."))
if shapechoice == 1:
sidelength = float(input("What's one of the sides length? "))
area = sidelength * sidelength
shape = "s... |
ebe366fe420e0e6ca9a939d80929d9191e89d176 | saife245/PYTHON-PROGRAM | /panishment for over limit-hacker.py | 281 | 3.96875 | 4 | speed = int(input('ENTER THE SPEED: '))
if speed <= 90:
print("0 No punishment")
elif speed >= 91 and speed <= 110:
FINE = (speed - 90)*300
print("{} WARNING".format(FINE))
else:
FINE = (speed - 90)*500
print("{} LICENSE REMOVED".format(FINE))
|
aefe012ebd1a41b12cab9cbeabf49f9cf17f00f7 | unsilence/Python-function | /数据结构与算法/图搜索/BFS搜索.py | 1,643 | 3.515625 | 4 | from queue import Queue
import numpy as np
import matplotlib.pyplot as plt
class Solution(object):
def numIslands(self, grid):
try:
r = 0
m = len(grid)
n = len(grid[0])
around = ((0, 1), (1, 0), (0, -1), (-1, 0))
except:
print('非法字符')
... |
0a79a3cf4cc7cc78e7f94d92f5da34789cc3f111 | unsilence/Python-function | /数据结构与算法/排序算法/merge_sorted.py | 979 | 3.90625 | 4 | import numpy as np
def merge_sorted(list):
n = len(list)
if n <= 1 :
return list
mid_value = n // 2
# ####################################################
# 分割列表
# ####################################################
left_li = merge_sorted(list[:mid_value])
right_li = merge_... |
e20c8fc7f33566ec7e69bf1a5ba272f90fc27f71 | unsilence/Python-function | /数据结构与算法/排序算法/桶排序.py | 599 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 桶排序
def bucket_sort(the_list):
# 设置全为0的数组
all_list = [0 for i in range(100)]
last_list = []
for v in the_list:
all_list[v] = 1 if all_list[v] == 0 else all_list[v] + 1
for i, t_v in enumerate(all_list):
if t_v != 0:
for j in ra... |
4573776d395930438b3ae76782bf154f6ac1eeb3 | unsilence/Python-function | /数据结构与算法/线性表/92-reverse_link_list_2.py | 1,711 | 3.828125 | 4 | # Definition for singly-linked list.
def list2LinkList(alist):
'''list --> Link List'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
node_list = [
ListNode(i) for i in alist
]
for i in range(len(node_list) - 1):
node_list[i].... |
732de6cdceee7803bd31fa0fd1d69200a00f579a | unsilence/Python-function | /数据结构与算法/树/二叉树实现.py | 2,315 | 3.75 | 4 | class Node:
def __init__(self, ele):
self.ele = ele # dytpe: float
self.lchild = None # dytpe: node
self.rchild = None # dytpe: node
def travel(self):
print(self.ele, end=' ')
if self.lchild is not None:
print(self.lchild.ele, end=' ')
else... |
f5a181bdee6821c0a8b4ac7c5625b282660e2733 | unsilence/Python-function | /数据结构与算法/排序算法/快速寻找最大值.py | 2,737 | 3.84375 | 4 |
class MinHeap():
def parent(self,n):
return (n-1)//2
def leftChild(self,n):
return 2*n+1
def rightChild(self,n):
return 2*n+2
#将list的前n个值构建为最小堆
def build_min_heap(self,n,list):
for i in range(n):
t=i
while (t!=0 and (list[self.parent(t)] > li... |
e3f478025133064ab2e5ec4073b21299ab931af3 | unsilence/Python-function | /数据结构与算法/排序算法/基本有序数组变有序数组.py | 1,786 | 3.84375 | 4 | '''
I.给一个长度为n的数组•共顺序本來已经排好但后来因为各种原因变为只畑jfe本刘崖的-
但其混乱度有上限k,表现为:对元素 >.设共在宪全有序后的数组中index为i』,在给与
的站本有序的数组中index为i_n.那么|i_n - i_o| <= k
要求:给与基本有序数组arr号®乱度k「将Jr变为丸全有序的.井估计时空
'''
def order_list(arr, k):
'''
以2K为进行堆排序,滑动步长为k,进行遍历
:param arr:
:param k:
:return:
'''
if not arr or arr == []: return
... |
7c0aad66744b1180fa154a673cb1c4fb68d36f4a | rlavanya9/cracking-the-coding-interview | /chapt-02-trees/BST.py | 950 | 4.0625 | 4 | class Node(object):
def __init__(self,data):
self.data = data
self.left = 0
self.right = 0
class Tree(object):
def __init__(self,root):
self.root = Node(root)
def is_BST(root,low = float('-inf'),high = float('inf')):
if not root:
return True
val = root.... |
3487559c2c02a40f8005bc055bbdb0d4ae1e5078 | rlavanya9/cracking-the-coding-interview | /chapt-03-stack-queue/stack-tower-hanoi.py | 1,246 | 4.03125 | 4 | class Stack(object):
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
... |
1026d17fb2818534d0c3033e7606b794a99f7215 | rlavanya9/cracking-the-coding-interview | /recursion/substring.py | 149 | 3.75 | 4 | def substr(str1):
res = [str1[i:j] for i in range(len(str1))
for j in range(i+1, len(str1)+1)]
return res
print(substr("Geeks")) |
943620de5cd32881400bd2446c44f8b8e5c50b42 | rlavanya9/cracking-the-coding-interview | /recursion/permutation.py | 322 | 3.53125 | 4 | def perm(remaining, candidate=""):
if len(remaining)==0:
print(candidate)
for i in range(len(remaining)):
newcandidate = candidate + remaining[i]
newremain = remaining[0:i] + remaining[i+1:]
perm(newremain, newcandidate)
if __name__ == '__main__':
s = "ABC"
perm(... |
4ccb8f9f1998c09be8bf469390fc7e0230ea2fba | tarun9199/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | /Beginner/fibbonaci_251701142.py | 197 | 4.15625 | 4 | num1=0
num2=1
print("enter the number upto which series is to be printed")
n=int(input())
print("fibbonaci series ")
for i in range(1,n):
print(num1,end=' ')
num3=num1+num2
num1=num2
num2=num3
|
338b79892937457099ce80c7ceb4f88d9603b425 | ishiko732/DataStructure | /Data7/BubbleSort.py | 850 | 3.84375 | 4 | def Bubble_Sort(our_list):
our_sort_list=our_list.copy()
for i in range(len(our_sort_list)):
for j in range(len(our_sort_list)-1):
if our_sort_list[j]>our_sort_list[i]:
our_sort_list[i],our_sort_list[j]=\
our_sort_list[j],our_sort_list[i]
return our_sort_l... |
c3aca50201c72a7e87ecffd1fb2fba6577d9e99c | ishiko732/DataStructure | /TextC/9.py | 58 | 3.578125 | 4 | n=1
sum=1
while sum<5:
n+=1
sum+=1/n
print("%d"%n) |
6f60c5d7c8dfb49b0ba9bd6188aa92a81cfdc300 | bazilevs31/MD_gel_simulation | /create_saw_vonmises_chain.py | 4,117 | 3.59375 | 4 | """Summary
"""
import numpy as np
import distances
def cart2spher(x_):
"""return spheraical coordinates of a cartesian vector
Args:
x_ (TYPE): Description
"""
x, y, z = x_[0], x_[1], x_[2]
rho = np.sqrt(x**2 + y**2 + z**2)
theta = z/float(rho)
phi = np.arctan2(y, x)
return(rho,... |
007d7e6cd6ce2bb84af31831c7d7756e34c84962 | yanghwai/design-pattern-python | /main/src/template_method.py | 2,116 | 3.609375 | 4 | from abc import ABCMeta, abstractmethod
class Compiler(metaclass=ABCMeta):
@abstractmethod
def collect_source(self):
pass
@abstractmethod
def compile_to_object(self):
pass
@abstractmethod
def run(self):
pass
def compile_and_run(self):
""" Template ... |
e9e802ddd66d6ffb5973902a44a44ce91a682570 | PrimeNumbers/primes_search | /str_sq_root.py | 6,028 | 4.28125 | 4 | #this function takes a string that only contains
#string.digits and returns the square root
#(rounded down to the nearest integer) as a string
#The purpose of this function is to know where to stop
#when diving by prime numbers as this should be
#the upper boundry for numbers to divide by
from str_add import add
fro... |
530b821df6868d77f13fb8d6ed3615fdf0da7eea | PrimeNumbers/primes_search | /check_seven.py | 648 | 4.03125 | 4 | from str_subtract import subtract
#the trick for 7 is to take the last digit and double it
#then subtract that from the remaining digits
#if the number is still too big repeat
def check_seven_(c):
#input a number stored as a string e.g. '1234'
#it will return if it is divisible by ____ or not
running_tall... |
6d3ccd4a91fc8dd8e1fe61173c48f66255b67c87 | PrimeNumbers/primes_search | /check_three.py | 905 | 4.375 | 4 | #the trick is if the sum of the digits is divisible by 3,
#then the candidate is divisible by 3
def check_three_(c):
#input a number stored as a string e.g. '1234'
#it will return if it is divisible by three or not
running_tally = 0
for each in c:
#expanding on that by combining terms that have ... |
79f8af22232e1c9347d607b68d42ed2c92e473ac | SamHearne/Lab_test | /LabTest2.py | 2,694 | 4.40625 | 4 | ##this program can be used to create a vector (cartesian point)
##and then add ,subtract, or multiply a point by a number , or by another point
##the program can also be used to find the magnitude of a point
##Throughout the code while adding subtracting etc q w e are used to repsent the xyz points of a new vector
##C... |
cd1c76e350a0d56b19d4b73c3e6bf8db0a04faf3 | rafal1996/Tic-Tac-Toe | /game.py | 4,094 | 4.28125 | 4 | X = 'X'
O = 'O'
EMPTY = ' '
DRAW = 'DRAW'
NUM_SQUARES = 9
def display_instruction():
print(
"""
Welcome in game Tic Tac Toe. Your opponent will be the Computer.
You indicate your moves by choosing the number 0-8.
This number corresponds to the position on the board.
... |
dfbce0307cf94e64ec888ab784f1b28aa8c72748 | antbrkic/DSTG-Goldberg | /3BellmanFordPokusaj.py | 1,998 | 3.546875 | 4 | import time
import datetime
from datetime import timedelta
"""
Ovo je implementacija Bellman Forda koja uzima najkraće vrijeme dolaska u određene gradove, ali Bellman ford ne
konstruira Hamiltonov put što od nas zadatak zapravo i traži. Taj problem nema efikasan algoritam za rješavanje.
Težine su zadane u seku... |
85640d1eb45d81977d4eba337a8cb43fd44d2663 | jzoudavy/AOC2020 | /day2.py | 1,017 | 3.703125 | 4 |
def password_check_part1(policy_min, policy_max, policy_char, password):
print(policy_min, policy_max, policy_char, password)
if int(policy_min)<= password.count(policy_char) <= int(policy_max):
return 1
return 0
def password_check_part2(policy_index1, policy_index2, policy_char, password):
... |
55f40cae2fc7ede59bdc739f8a9471705234450b | GCiatta88PhD/Python-Programming-A-Concise-Introduction | /ProblemSet2_8.py | 1,643 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 16:34:56 2020
@author: Gianluca Ciattaglia
"""
"""
Problem 2_8:
The following list gives the hourly temperature during a 24 hour day. Please
write a function, that will take such a list and compute 3 things: average
temperature, high (maximum temperature),... |
3ebd3918e998a4319eabc0d00a792aa17aa0ab22 | KerberosHD/sj20_5ahit_ki_steiner | /Archiv/Uebung/Ue05/06_for_loops_exercise.py | 1,715 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 1. Fill the missing pieces
# Fill the `____` parts in the code below.
# In[1]:
words = ['PYTHON', 'JOHN', 'chEEse', 'hAm', 'DOE', '123']
upper_case_words = []
for i in words:
if i.isupper():
upper_case_words.append(i)
# In[2]:
assert upper_case_words == ['P... |
ea40bfe0ad3b3e79364f3f4aff56939ccdac079c | KerberosHD/sj20_5ahit_ki_steiner | /Archiv/Uebung/Ue05/07_functions_exercise.py | 2,428 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 1. Fill the missing pieces of the `count_even_numbers` function
# Fill `____` pieces of the `count_even_numbers` implemention in order to pass the assertions. You can assume that `numbers` argument is a list of integers.
# In[6]:
def count_even_numbers(numbers):
count =... |
2fc95c9343d4a36a48107eeff6d9cdb484b231e1 | joaonetto/python_HardWay | /ex_33_study_drills.py | 1,227 | 4 | 4 | from sys import argv
def usingwhile(point1, point2, increment_while):
""" This function have 2(two) variables:
point1 -> Start Point for While
point2 -> End to While
increment -> Increment between loops
"""
numbers = []
while point1 < point2:
print(f"At the top i is {poi... |
49eacfb5b8f6d963443497435103e9a5d2e897ac | joaonetto/python_HardWay | /ex_44_Override_Explicity.py | 1,173 | 4.4375 | 4 | ## Override Explicity
##
## The problem with having functions called implicitly
## is sometimes you want the child to behave differently.
## In this case you want to override the function in the
## child, effectively replacing the functionality. To do
## this just define a function with the same name in Child.
## Here’... |
b150bd229992ab039d22bb47d98d07876fc8ce0a | joaonetto/python_HardWay | /ex_25.py | 1,434 | 3.796875 | 4 | import ex_25_functions
sentence = "All good things come to those who wait."
print(f"A frase utilizada foi: \n\t{sentence}\n")
words = ex_25_functions.break_words(sentence)
print(f"A frase foi dividida por cada palavra, veja abaixo:\n\t{words}\n")
sorted_words = ex_25_functions.sort_words(words)
print(f"A frase foi o... |
62fc0e94b9e0f8546cdfe2c7e5511ebc312a7809 | joaonetto/python_HardWay | /ex_20.py | 1,546 | 4.25 | 4 | from sys import argv
if len(argv) != 2:
print(f"Para este script é necessário 2 argumentos, mas você passou apenas {len(argv)}")
exit()
script, input_file = argv
def print_all(f):
print(f.read())
def rewind(f):
# O número dentro de Seek reflete a posição em caracteres que irá iniciar o arquivo
#... |
159ad63974bdf1e7aa8f77346e28f27c370ee451 | ichabod801/cli_tutorial | /menu_class.py | 3,702 | 4.09375 | 4 | """
menu_class.py
A simple menu example with a class.
Classes:
Menu: A basic menu interface. (object)
"""
from collections import OrderedDict
from string import ascii_uppercase
class Menu(object):
"""
A basic menu interface for an integer graph. (object)
Class Attributes:
menu_data: The menu descri... |
57e154044c14b5158250caba23376b650b5acc9f | Chatchai222/Blackjack | /testcode.py | 1,522 | 3.6875 | 4 | # Code for transferring items from one list to another
from character import *
"""
class Food:
def __init__(self, name ,score):
self.name = name
self.score = score
def __repr__(self):
return str(self.name)
a = Food("Apple", 7)
b = Food("Banana", 10)
c = Food("Coconut", 5... |
771b646ad7faf09a58ad1b292814265b46eb1a69 | endlessseal/Python-Reddit-Challenges- | /287e.py | 504 | 3.75 | 4 | import itertools
def find_max_digit(num):
return max(str(num))
def arrange_largest_num(num, mode=True, number_of_digits=4):
return int(''.join(sorted(str(num).zfill(number_of_digits), reverse=mode)))
def counting_iteration_for_Kaprekar(num):
answer = num
for iteration in itertools.count(1):
if arrange... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.