blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
fd412be9df1c603835c2514bd7246f4cfaca2ee0 | vitorandrietta/UNICAMP | /MC906/P1/codigo/P1/labyrinth_problem.py | 1,845 | 3.8125 | 4 | from search import Problem
"""
the state and go are defined as a coordinate in tuple (x,y)
"""
class Labyrinth(Problem):
#repeat coord is a boolean responsable for informing if the agent is allowed to Go
#back in a position He already visited.
def __init__(self, initial, goal, repeat_coord, board):
... |
2aab0da4b839718daef6c9b144bea45f6f02ecff | BangAbe88/modul_python | /abe.py | 989 | 3.65625 | 4 | import math
def grade(nilai):
if nilai<50:
return("Nilai Anda E"+" __Maaf, anda tidak lulus mohon coba kembali")
elif nilai>=50 and nilai<=59:
return("Nilai Anda D"+" __Maaf, anda masih belum lulus mohon coba kembali")
elif nilai>=60 and nilai<=74:
retu... |
66e2f03da968eceb9b958f6a9ac424b20517dd25 | Nihadkp/python | /CO2/1_factorial.py | 140 | 4.3125 | 4 | fact = 1
num = int(input("Enter the number:"))
for i in range(1,num+1):
fact = fact * i
print("Factorial of the given number is:", fact) |
b5efc5698eac40c55d378f100337a8e52f9936fa | Nihadkp/python | /co1/16_swap_charecter.py | 396 | 4.1875 | 4 | # create a single string seperated with space from two strings by swapping the charecter at position 1
str1 = "apple"
str2 = "orange"
str1_list = list(str1)
str2_list = list(str2)
temp = str1_list[1]
str1_list[1] = str2_list[1]
str2_list[1] = temp
print("Before exchanging elements:", str1, str2)
print("string after ex... |
9eae3f6c54b83f556ad26a1513adc833ac6d0b5a | Nihadkp/python | /co1/7_lists.py | 1,096 | 3.890625 | 4 |
list1=list()
list2=list()
sum1=0
sum2=0
#Inputing values into the list
limit = int(input("Enter the limit:"))
for x in range(limit):
num = int(input("Enter number " + str(x + 1) + ":"));
list1.append(num)
limit = int(input("Enter the limit:"))
for x in range(limit):
num = int(input("Enter number " + str... |
65efd951f0153acbaee277e256b3e891376ab64a | Nihadkp/python | /co1/4_occurance_of_words.py | 211 | 4.3125 | 4 | #Count the occurrences of each word in a line of text.
text=input("Enter the line : ")
for i in text.strip().split():
print("Number of occurence of word ","\"",i,"\""," is :",text.strip().split().count(i))
|
79089d1d66ca923b41b67afddda3649c58156236 | mjfernez/Project_Euler_Solutions | /05-Smallest-Multiple/smallmult.py | 613 | 3.96875 | 4 | # Problem 5 smallest multiple
# 2520 is the smallest number that can be divided by
# each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible
# by all of the numbers from 1 to 20?
import PIL
import math
def isDivisible(num, divisors):
divisible = Tru... |
7fdab23d55def28bcb699107f6163d239434c1ac | RustPython/RustPython | /Lib/fileinput.py | 16,422 | 3.75 | 4 | """Helper class to quickly write a loop over all standard input files.
Typical use is:
import fileinput
for line in fileinput.input(encoding="utf-8"):
process(line)
This iterates over the lines of all files listed in sys.argv[1:],
defaulting to sys.stdin if the list is empty. If a filename is '-' it... |
91adb9f6aaee1eb4530f4fec2ba7ecf0ba5cb8ca | RustPython/RustPython | /wasm/demo/snippets/fizzbuzz.py | 159 | 3.84375 | 4 | for i in range(1, 100):
print(f"{i} ", end="")
if not i % 3:
print("fizz", end="")
if not i % 5:
print("buzz", end="")
print()
|
b064eecf3e073be9189e165f00d64d1d11507992 | RustPython/RustPython | /Lib/test/test_dictcomps.py | 5,325 | 3.71875 | 4 | import unittest
# For scope testing.
g = "Global variable"
class DictComprehensionTest(unittest.TestCase):
def test_basics(self):
expected = {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17,
8: 18, 9: 19}
actual = {k: k + 10 for k in range(10)}
self.assertEqual... |
6b182722efd9e2b1309aa339a2ac31d461d8f4c4 | RustPython/RustPython | /Lib/sqlite3/dump.py | 3,277 | 3.734375 | 4 | # Mimic the sqlite3 console shell's .dump command
# Author: Paul Kippes <kippesp@gmail.com>
# Every identifier in sql is quoted based on a comment in sqlite
# documentation "SQLite adds new keywords from time to time when it
# takes on new features. So to prevent your code from being broken by
# future enhancements, y... |
3d3c053d964d4e5c05347a8048f75f0b169de289 | RustPython/RustPython | /Lib/heapq.py | 22,991 | 4.09375 | 4 | """Heap queue algorithm (a.k.a. priority queue).
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0. For the sake of comparison,
non-existing elements are considered to be infinite. The interesting
property of a heap is that a[0] is always its smallest element.
Usag... |
9b3c9b00d03267a6150b959a685f9263bbd4ae0e | RustPython/RustPython | /extra_tests/snippets/syntax_with.py | 1,353 | 3.5625 | 4 |
class ContextManager:
def __enter__(self):
print('Entrada')
ls.append(1)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
ls.append(2)
print('Wiedersehen')
def __str__(self):
ls.append(3)
return "c'est moi!"
ls = []
with ContextManager()... |
869b97ff6df167cc3acd802823a51f545bd91387 | RustPython/RustPython | /Lib/copy.py | 8,681 | 3.5625 | 4 | """Generic (shallow and deep) copying operations.
Interface summary:
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
For module specific errors, copy.Error is raised.
The difference between shallow and deep copying is only relev... |
e05f8192c46650e725b3c7f0276705f626a272a6 | RustPython/RustPython | /extra_tests/snippets/intro/3.1.1.2.py | 506 | 3.921875 | 4 | assert 5.666666666666667 == 17 / 3 # classic division returns a float
assert 5 == 17 // 3 # floor division discards the fractional part
assert 2 == 17 % 3 # the % operator returns the remainder of the division
assert 17 == 5 * 3 + 2 # result * divisor + remainder
print(17 / 3) # classic division returns a floa... |
ceba1057939cdf27dfc7e5ff01276fd01d97393d | RustPython/RustPython | /Lib/nturl2path.py | 2,887 | 3.953125 | 4 | """Convert a NT pathname to a file URL and vice versa.
This module only exists to provide OS-specific code
for urllib.requests, thus do not use directly.
"""
# Testing is done through test_urllib.
def url2pathname(url):
"""OS-specific conversion from a relative URL of the 'file' scheme
to a file system path; ... |
27077609ae2a04ffb9846a8af6bbe3cc7be4b85c | srnazng/quarantine_game | /application.py | 3,565 | 3.84375 | 4 | import random
# Keep track of which player is going
turn = 1
# Positions starting at 0
player1_pos = 0
player2_pos = 0
# Sums required to be rolled when position = index
board1 = [6, 5, 4, 7, 10, 8, 9, 4, 3, 12]
board2 = [10, 4, 8, 9, 5, 6, 4, 7, 2, 11]
# Random roll of each die
class Roll:
def __i... |
3942cfcf9cdd2d3d5a1da0ee2a113147e961ec30 | sudhanthiran/Python_Practice | /Competitive Coding/Remove Duplicates.py | 185 | 3.78125 | 4 | import pandas as pd
dframe = pd.DataFrame({'col1':['A']*3+['B']*4+['C','B','A'],'col2':[2,3,4,2,4,2,1,3,4,4]})
print(dframe.drop_duplicates(subset='col1',keep='first'))
print(dframe) |
97b16a9798970f1f2d734ed16a60187ae7f3f7e1 | sudhanthiran/Python_Practice | /Competitive Coding/RegEx matching.py | 1,621 | 4.5625 | 5 | """
Given a pattern string and a test string, Your task is to implement RegEx substring matching.
If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with
the starting position of the text string. Similarly, if it is preceded by a $, the
pattern(excluding the ^) will be matched with the endi... |
7f8732d4bd4183ba5d8ef5e70d1971aa92ebb84e | sudhanthiran/Python_Practice | /Competitive Coding/longest palindrome in string.py | 433 | 3.984375 | 4 | def palindrome(list_b):
longest_palindrom = ''
for i in list_b:
if(i == i[::-1]):
if(len(i)> len(longest_palindrom)):
longest_palindrom = i
print(longest_palindrom)
a= "abcdcba"
list_a =[]
for i in range(1,len(a)-1):
list_a.append(a[i::1])
for i in range(1,len... |
d688ae984376ca6791f6cbd6e010c1b759b951f0 | pierg/wasp-secourse-lund | /src/pigtranslator.py | 2,150 | 3.734375 | 4 | import re
def extract_punctuation(text):
new_text = []
for word in text:
m = re.split('(\W+)',word)
m = list(filter(None, m))
new_text.extend(m)
return new_text
def Translate(sentence):
#algorithm to translate from english to pig latin
#based on the rules set in wikip... |
dd5e52323d02710e902a1bb7ca8615a18ecfb258 | RockMurdock/Python-Book-1-Tuples | /zoo.py | 1,703 | 4.46875 | 4 | # Create a tuple named zoo that contains 10 of your favorite animals.
zoo = (
"elephant",
"giraffe",
"hippopotamus",
"monkey",
"otter",
"peacock",
"panther",
"rhino",
"alligator",
"lama"
)
# Find one of your animals using the tuple.index(value) syntax on the tuple.
print(zoo.i... |
51b04ff1474070324fd699dad10947b9ff95896d | abhishekmajhi42/text_to_pdf_app-python | /texttopdf.py | 440 | 3.703125 | 4 | #import FPDF from fpdf module
from fpdf import FPDF
# save FPDF() class into a
# variable pdf
pdf=FPDF()
#Add a page
pdf.add_page()
# set style and size of font
# that you want in the pdf
pdf.set_font("Arial",size=15)
#open the pdf file in text mode
f=open("myfile.txt","r")
#insert the texts in pd... |
b7363bc7c71f2dc70bbc066cf536dee7ebd34865 | kmollee/2014_fall_cp | /5/section/for_ex0.py | 113 | 3.546875 | 4 | total = 0
for num in range(1, 10 + 1):
total = total + num
assert total == 55
print("1~10 total is", total)
|
97b930dd77a4af53083b1e8fa02a6b64a3249c2f | kmollee/2014_fall_cp | /7/other/MITx6001_w5/intToStr.py | 304 | 3.90625 | 4 | def intToStr(i):
if type(i) != int:
raise TypeError("i should be int")
digits = '0123456789'
if i == 0:
return '0'
result = ''
while i > 0:
result = digits[i % 10] + result
i = int(i / 10)
return result
print(intToStr(123))
print(intToStr(123.1))
|
a610e27f93578dff94bf13b4d8c1a213f2997af0 | kmollee/2014_fall_cp | /7/other/isPalindrome.py | 919 | 4.25 | 4 | # palindrome
# remove all white space
# and don;t care about capitalization, all character should be lowercase
# base case
# a string of length 0 or 1 is a palindrome
# recursive case
# if first character matches last character,
# then is a palindrome if middle section is palindrome
# http://www.palindromelist.net/
... |
ccc34cb8803999f5fe0afad411d489a822baba0f | kmollee/2014_fall_cp | /6/other/findRoot2.py | 1,035 | 3.578125 | 4 | def findRoot2(x, power, epsilon):
if x < 0 and power % 2 == 0:
return None
low = min(0, x)
high = max(0, x)
ans = (low + high) / 2.0
while abs(ans ** power - x) > epsilon:
if ans ** power < x:
low = ans
else:
high = ans
ans = (high + low) / 2.0... |
cdcef07b58df75160fddaa5a5ae99823f099af83 | kmollee/2014_fall_cp | /11/decorator_ex1.py | 502 | 3.609375 | 4 | from functools import wraps
def debug(func):
# func is function to be wrapped
@wraps(func)
def wrapper(*args, **kwargs):
# print(func.__name__)
print(func.__qualname__)
return func(*args, **kwargs)
return wrapper
@debug
def add(x, y):
"""
return x + y
"""
retu... |
21e1c9cca795f497bafb68fc97394d89a214dad5 | kmollee/2014_fall_cp | /5/other/dec_to_bin.py | 612 | 4.09375 | 4 | # convert decimal to binary
num = 3
# check num is neg?
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
result = ""
# if num equal 0, result should be 0
if num == 0:
result = "0"
else:
while num > 0:
result = str(int(num % 2)) + result
num = int(num / 2)
if isNeg:
r... |
196fff69be6453c0cc3c6cfd85b689fad441add9 | kmollee/2014_fall_cp | /6/other/findRoot3.py | 1,329 | 3.984375 | 4 | def findRoot3(x, power, epsilon):
'''
x and epsilon int or float, power an int
epsilon > 0 and power > 1
'''
if x < 0 and power % 2 == 0:
return None
low = min(-1, x)
high = max(1, x)
ans = (low + high) / 2.0
while abs(ans ** power - x) > epsilon:
if ans ** power ... |
c95d54e49c03fc707c8081fb3fa6f67bb27a8046 | kmollee/2014_fall_cp | /7/other/quiz/McNuggets.py | 1,336 | 4.34375 | 4 | '''
McDonald’s sells Chicken McNuggets in packages of 6, 9 or 20 McNuggets. Thus, it is possible, for example, to buy exactly 15 McNuggets (with one package of 6 and a second package of 9), but it is not possible to buy exactly 16 McNuggets, since no non- negative integer combination of 6's, 9's and 20's add up to 16. ... |
ac1b5915dd0fcb42941a015fd24013f957f42046 | hariharan31998/Python-Programming | /player level/sort.py | 77 | 3.5625 | 4 | a=str(input())
print(a)
if a.isnumeric():
print("yes")
else:
print("no")
|
c7c9dd7421aaaa9e0d37c0a067239b30eb3c4e01 | hariharan31998/Python-Programming | /Beginner level/prime in interval.py | 125 | 3.96875 | 4 | a=int(input())
b=int(input())
print(a,b)
for i in range(a+1,b):
if((i%2!=0) and (i%3!=0)) or (i==2) or(i==3):
print(i)
|
814cacb2a8db654fb7030330939d58814d09b779 | hariharan31998/Python-Programming | /Beginner level/Hello to N time.py | 66 | 3.75 | 4 | a="Hello"
b=int(input())
print(b)
for i in range(0,b):
print(a)
|
7736697305dc19699ee23f0c3338006f9d1fc956 | hariharan31998/Python-Programming | /Beginner level/palindrome.py | 97 | 3.65625 | 4 | a=int(input())
print(a)
b=str(a)
c=b[::-1]
d=int(c)
if(a==d):
print("yes")
else:
print("no")
|
69cfda5b4f63d2d7eaa4868443ac9747435e216e | shailesh1001/CodingExperiments | /Python/HelloPython/booleans.py | 980 | 3.640625 | 4 | def i_say_which_function_i_am(order):
print "I'm function number ", order
def tell_me_true(order):
i_say_which_function_i_am(order)
print "I'm going to return True!"
return True
def tell_me_false(order):
i_say_which_function_i_am(order)
print "I'm going to return False!"
return False
def ... |
ca3dee1d4b0a521d79d9c5d5fd4f03b67a5d373d | zance1054/Cyber | /ccipher.py | 499 | 3.578125 | 4 | #!/usr/bin/python
'''
Simple ceaser cipher
Alexander Fielding
Markus Ahling
Inputs: plaintext file to be encoded
Outputs: ciphertext file
Program Description here
'''
#testing my first commit!
<<<<<<< HEAD
print("TESTING")
=======
def writeToFile():
filename = input("Enter the file name ... |
98b3ebc1cf9322ae05892d7ffbe8abe8102ae8d2 | AnshulMehta1/Finding-Stable-States-in-Markov-Chains-Using-Linear-Algebra | /Project/PageRankAlgorithm.py | 1,076 | 3.953125 | 4 | ''' NOTE: The Pagerank Algorithm is essentially not a part of our defination. It has been used to illustrate the fact steady state is actually,
# what we intended to find through Page Rank Algorithm as well. The page rank algorithm has been imported from Wikepedia.'''
import numpy as np
def pagerank(M, num_itera... |
deaaf816ff3deab54b62b699d53b417ad3cbb3f1 | MehdiNV/programming-challenges | /challenges/Staircase | 1,216 | 4.34375 | 4 | #!/bin/python3
"""
Problem:
Consider a staircase of size (n=4):
#
##
###
####
Observe that its base and height are both equal to n and the image is drawn using # symbols and spaces.
The last line is not preceded by any spaces.
Write a program that prints a staircase of size n
"""
import math
import os
impor... |
c957f654ddb5d6c2fa6353ad749a7dbbb151bc44 | MehdiNV/programming-challenges | /challenges/Diagonal Difference | 1,576 | 4.5 | 4 | #!/bin/python3
"""
Problem:
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
For example, the square matrix (arr) is shown below:
1 2 3
4 5 6
9 8 9
Looking at the above, you can see that...
The left-to-right diagonal = 1 +... |
c37e42f863bdda5c07444d3b3f97e326a1ad8e8c | Stephan872/python | /search.py | 3,757 | 4.03125 | 4 |
from pathlib import Path
import os
import glob
import shutil
import os.path, time
def main():
''' This is the main part of the function,
user should put the path of a file as the input '''
root = input()
while os.path.exists(root)==False:
print ('ERROR')
... |
78d97f8be3f688ed5086dcd3dacc9187ab413d59 | CodecoolBP20172/pbwp-2nd-tw-pair-programming-exercises-team-9 | /years/years_module.py | 336 | 3.875 | 4 | import datetime
def years(age):
# name = input("Please enter your name: ")
# age = int(input("Please enter your age: "))
return (99 - age + 2017)
def main():
repeat = int(input("Repeat: "))
for i in range(repeat):
print(years(2017))
if __name__ == '__main__':
main()
#print(years... |
4b2d6f8cbd39971c02c8dc436f2e42b972986496 | renanmat/ExPython | /ex055.py | 414 | 3.84375 | 4 | maior = 0
menor = 0
for cont in range(1, 6):
peso = float(input('Digite o peso da {}ª pessoa em Kg: '.format(cont)))
if cont == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
elif peso < menor:
menor = peso
print('A pessoa com maior p... |
8d2079a3b59014326745ce78f2c59e5bb6545f41 | renanmat/ExPython | /ex049.py | 213 | 3.75 | 4 | m = int(input('Qual tabuada voce deseja ver? '))
print('{:-^20}'.format(' TABUADA DO {} '.format(m)))
for cont in range(1, 11):
r = m * cont
print('{:5} x {:>2} = {:>2}'.format(m, cont, r))
print('-'*20)
|
1a7a08505d2a8d51f0d84213113f572ef123fbe9 | renanmat/ExPython | /ex089.py | 763 | 3.515625 | 4 | lista = []
while True:
aluno = str(input('aluno: ')).strip()
nota1 = float(input('1° nota: '))
nota2 = float(input('2° nota: '))
media = ((nota1 + nota2) / 2)
lista.append([aluno, [nota1, nota2], media])
op = str(input('Quer continuar?[S/N] '))[0].strip()
if op in 'nN':
break
print(... |
74f1edc033c4c7f58885ea18168e977ab9800293 | renanmat/ExPython | /ex095.py | 1,376 | 3.578125 | 4 | dados = dict()
jogadores = list()
while True:
dados.clear()
dados['nome'] = str(input('Nome do Jogador? '))
dados['partidas'] = int(input(f'Quantas partidas {dados["nome"]} jogou? '))
dados['gols'] = list()
for cont in range(dados['partidas']):
dados['gols'].append(int(input(f'Quantos gols n... |
ff6d96523a1b988c405bc4aafd2c2aa5a98cd475 | renanmat/ExPython | /ex100.py | 676 | 3.875 | 4 | from random import randint
def soma(lista):
somapar = 0
for n in lista:
if n % 2 == 0:
somapar += n
print(f'A soma dos numeros pares {lista} é igual a {somapar}.')
def sortlista(lista):
"""
-> Sorteia 5 numeros de 0 até 10, depois coloca em uma lista.
:param lista: lista ... |
88f7870fbb86efa3a035db1d39c4b98421412bd7 | renanmat/ExPython | /ex054.py | 374 | 3.96875 | 4 | from datetime import date
maior = 0
menor = 0
for cont in range(1, 8):
ano = int(input('Digite o ano de nascimento da {}ª pessoa: '.format(cont)))
idade = date.today().year - ano
print('{} anos'.format(idade))
if idade > 21:
maior += 1
else:
menor += 1
print('Maior de idade: {}'.form... |
a4800554de0f69924b949e2ce31ac8bc7fb23f29 | venusing1998/learning | /python3-leetcode/690-Employee-Importance.py | 824 | 3.796875 | 4 | """You are given a data structure of employee information, which includes the employee's unique id, his importance value and his direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee... |
535e3556f84d3ab1307a81e5d8764160055c89a6 | venusing1998/learning | /python3-liaoxuefeng.com/3.py | 278 | 3.9375 | 4 | """小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点,并用字符串格式化显示出'xx.x%',只保留小数点后1位:
s1 = 72
s2 = 85
"""
s1 = 72
s2 = 85
r = (s2 - s1) / s1 * 100
print('小明成绩提升%.1f%%' % r)
|
7fd0a4191c22cd9826c3c5cb66f38909d3c436c2 | acostasaul98/Ejercicios-python | /ejercicio56.py | 246 | 3.859375 | 4 | """
Mayor a 70 aprobado
"""
promedio_cadena = input("Dime tu promedio: ")
promedio = float(promedio_cadena)
if promedio >= 70:
print("Excelente has APROBADO")
else:
print("Hechale mas ganas esta vez no aprobaste la unidad")
|
00ad87a8a3d26b04288d4dddd5a76203df02b270 | pantrinkl/caesarova_sifra | /caesar_sifra.py | 3,378 | 3.6875 | 4 | # defining functions
# load input data
def load_text(textfile):
try:
with open(textfile, 'r') as h:
content = h.readlines()
return content
except FileNotFoundError:
exit("Nenalezen vstupní soubor.")
except PermissionError:
exit("Nemám přístup k vstupnímu souboru... |
0e74c2016dff25dbaaf6e8925b47bcd7d092d63d | alishhde/Evolutionary-Strategy-UMZ | /Evolutionary strategy/Part 3/Part 3.py | 7,827 | 3.609375 | 4 | import numpy as np
from copy import deepcopy
import random
# ------------- Fitness Function start ------------- #
def f(vectors):
""" This Function Takes N-dimension vectors
and calculates fitnesses for each of the vectors
and return the fitness.
vector: It's a list or an array that consist of
som... |
06eff9ec7451f6a08775ed6dfa751038473f4423 | larasproesser/-RPA-EmailAutomatico | /emailautomatico.py | 961 | 3.78125 | 4 | # automatização para mandar e-mail automático!
import pyautogui
import time
import pyperclip
pyautogui.alert("Automação irá iniciar")
# abrir gmail
pyautogui.hotkey('win')
pyautogui.write("chrome")
pyautogui.press('enter')
time.sleep(4)
pyautogui.write("gmail.com")
pyautogui.press('enter')
time.sleep(8)
# clicar em ... |
fb69004324f87913da37e1a3c2071e23340860ee | muladzevitali/football_project | /utils/ocr/utils/ocr_utils.py | 654 | 3.6875 | 4 | from __future__ import print_function
def filter_text(text, names_dict):
text = [each for each in text if each.isalpha() or each == ' ']
text = ''.join(text).strip()
text = text if names_dict.get(text) else None
return text
def get_names(file_name):
"""
Creates allowed words list:
:para... |
1850394f2f8d6c54deb9901d49c1994f569b2314 | SimRose/tercera_semana_nate | /numero_mas grande_def.py | 266 | 3.71875 | 4 | def mas_largo(primero, segundo, tercero):
if primero >= (segundo and tercero):
return primero
elif segundo >= (primero and tercero):
return segundo
elif tercero >= (primero and segundo):
return tercero
print(mas_largo(1, 2, 3))
|
f0d94aa0c248da11410c20003700015a718dbaab | coreytan00/checkers | /aicopy.py | 6,148 | 3.609375 | 4 | from random import randint
from BoardClasses import Move
from BoardClasses import Board
from collections import defaultdict
import math
import copy
import time
#The following part should be completed by students.
#Students can modify anything except the class name and exisiting functions and varibles.
class MCTS():
... |
0b9924d4df0fba98e1ebcd27801d26d7bac776c2 | OlegYP/practice-B5 | /classes.py | 1,274 | 3.671875 | 4 | import time
import random
class Timing:
def __init__(self, function_to_run):
self.num_runs = 3
self.func_to_run = function_to_run
def __call__(self, *args, **kwargs):
avg = 0
for _ in range(self.num_runs):
t0 = time.time()
self.func_to_run(*a... |
586bd4a6b6ec0a7d844531448285fab1499f10bd | NontandoMathebula/AI-futuristic | /Python functions.py | 1,492 | 4.53125 | 5 | import math
#define a basic function
#def function1():
# print("I am a cute function")
#function that takes arguments
#def function2(arg1, arg2):
#print(arg1, " ", arg2)
#funcion that returns a value
#def cube(x):
#return x*x*x
#function with default value for an argument
def power(num, x = 1)... |
89d7656f6beb4e9f5d9a00b2482aa432d0ac89b4 | detroitsteel/IS211_Assignment4 | /sort_compare.py | 7,827 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Intakes a list and sorts the list"""
import time
def insertion_sort(a_list):
"""insertion_sort Function - intakes a list of objects and sorts the list.
Args:
a_list (list): A list of objects to be sorted
Output: a_list sorted and the time it took t... |
1c30f539cc45a1f34b4ca83cb8a39d88b878b2ad | kiki211/algorithms-and-data-structures-Udemy | /strings_problems.py | 1,490 | 3.8125 | 4 | # 1 Anagram. Second method preferred
sentence1 = "dog and cat"
sentence2 = "cat and god"
def anagram(sentence1, sentence2):
s1 = sentence1.replace(" ", "").lower()
s2 = sentence2.replace(" ", "").lower()
return sorted(s1) == sorted(s2)
print(anagram(sentence1, sentence2))
def anagram2(sentence1, senten... |
50cfbfac92a304045b535651ef9412bd7e6ce151 | Rutujapingale10/uplift-python-resources-rutuja | /list/find_average_of_list.py | 487 | 3.984375 | 4 | our_list = [34,90,56,43,23,29,87,47]
count = 0
for i in our_list:
count +=i
# we can do using by sum function that take our_list as an arguement and also do by using count by iterating over for list
sumOfour_list = sum(our_list)
average = count / len(our_list)
print("sum of our list is {}".format(count)... |
46bd90a70cb1e67c00d2cdd3d0093bb39dedf667 | albertisfu/devz-community | /arrays-strings/matrix_rotation.py | 622 | 3.78125 | 4 |
def rotate1(matrix):
new_matrix = []
counter = 0
while counter != len(matrix):
aux_matrix = []
print('entro while')
for i in range(len(matrix)):
print('entro first for')
index = len(matrix)-1-i
for j in range(len(matrix[index])):
... |
cf8e3546673231056cd11c663e0dfde3b158fb9c | albertisfu/devz-community | /stacks-queues/stacks-queues-2.py | 2,013 | 4.21875 | 4 |
#Node Class
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
#LinkedList Class
class Stack:
def __init__(self):
self.head = None
#append new elements to linked list method
def push(self, data):
new_node = Node(data)
if self.head =... |
69b1e800b03bebd1227654aa4a85ddbcd63dfa61 | even4void/scratch | /test-lsp-yates.py | 516 | 3.609375 | 4 | import os
import random
# Sattolo algorithm & Co.
# https://danluu.com/sattolo/
# This is an extra long comment line to test whether it is highlighted correctly as too
def shuffle(a: list[int]) -> None:
n = len(a)
for i in range(n - 1):
j = random.randrange(i, n)
a[i], a[j] = a[j], a[i]
def... |
71c68a9bc75adb583dec745aecbe21f905e22fe8 | wptasinski/Speech-Command-Recognition | /cnn_clf_model.py | 3,880 | 3.546875 | 4 | import tensorflow as tf
import matplotlib.pyplot as plt
def get_model(input_shape, loss="categorical_crossentropy", learning_rate=0.005,num_outputs = 10):
"""Build neural network using keras.
:param input_shape (tuple): Shape of array representing a sample train. E.g.: (44, 13, 1)
:param loss (str): Loss... |
6047a3930c5bcbff02d0975e4576ce7bf5cb0784 | scrambleegg7/SelfCar | /CarND-Behavioral-Cloning-P3/imgProcess.py | 984 | 3.78125 | 4 | def resize(image):
"""
Returns an image resized to match the input size of the network.
:param image: Image represented as a numpy array.
"""
return cv2.resize(image, (200, 66), interpolation=cv2.INTER_AREA)
def normalize(image):
"""
Returns a normalized image with feature values from -1.0... |
0304557055cb869dfbb90c54dee15a3fc4ec1c32 | aaronfox/CECS-622-Simulation-and-Modeling | /Homework 04/Fox_Homework_4.py | 14,239 | 3.53125 | 4 | # Aaron Fox
# CECS 622-01
# Dr. Elmaghraby
# Homework 4
# For plotting
import matplotlib.pyplot as plt
### Part 1: Chi-Squared Test ###
def part_1_a():
## Compute the histogram over the 10 subintervals: [0, 0.1), [0.1, 0.2) … [0.9, 1.0). ##
random_numbers = [0.21, 0.88, 0.37, 0.06, 0.98, 0.61, 0.89, 0.28, 0.... |
3c00935ec7bde1018a23f5a873cbaa2f23e9ef84 | sandeepmendiratta/python-stuff | /animal1.py | 221 | 3.65625 | 4 | class Animal:
def __init__(self, name):
self.name = name
def whoAmI(self):
print("Animal")
def eat(self):
print("Eating")
d = Animal("buddy")
#print d
print d.name
print d.whoAmI
|
551157d4bf0c0920b0bad12c6db6f1f7559f12a0 | sandeepmendiratta/python-stuff | /line.py | 286 | 3.75 | 4 | class Line:
def __init__(self, coor1,coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
return ((x2-x1)**2 +(y2-y1)**2)**.5
c1 = (3,2)
c2 = (8,10)
l = Line(c1,c2)
print(l.distance())
|
796196c624f370d5237a3f5102e900e534adc4e7 | sandeepmendiratta/python-stuff | /pi_value_to_digit.py | 1,004 | 4.28125 | 4 | #!/usr/bin/env python3
""""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 getValueOfPi(k):
return '%.*f' % (k, math.pi)
def main():
"""
Console Function to create the interactiv... |
88c51e8f43f351b6472a224be8bdc8ee7874b42f | sandeepmendiratta/python-stuff | /bankaccount.py | 706 | 3.625 | 4 | class Account:
def __init__(self,owner,balance=0):
self.owner = owner
self.balance = balance
def __str__(self):
return f" Account Owner: {self.owner} \n Account balance: ${self.balance}"
def deposite(self,dep_amt):
self.balance += dep_amt
print(f" ${dep_amt} added t... |
428e353b8584dc61b1d78eb29be138ebc6d75cc0 | xc21/Leetcode-Practice | /Python/283. Move Zeroes.py | 1,212 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 23:18:44 2018
@author: Xun Cao
"""
"""
283. Move Zeroes
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your f... |
52c12e8dcb1b1bcc1b6828b64356786f4fc3ca2e | tarek-elhak/Spreadsheets | /SpreadSheets.py | 1,251 | 3.90625 | 4 | import re
NumberOfCoordinates = int(input('Enter the number of coordinates\n'))
for coordinate in range(NumberOfCoordinates):
sequence = input('enter a coordinate\n')
pattern = re.match(r'R(\d+)C(\d+)', sequence)
if pattern: # convert to Excel Numeration System
RowNumber = pattern.group(1)
... |
092a3fd97569804c742af907c3279274384885fa | 333TRS-CWO/scripting_challenge_questions | /draw_box.py | 545 | 4.25 | 4 | from typing import List
'''
Complete the draw_box function so that given a non-negative integer that represents the height and width of a box,
the function should create an ASCII art box for returning a list of strings.
Then wall of the box should be made up of the "X" character
The interior of the box should be ma... |
0fb5996808ac5b44308ed95a25f7c7fed6fb417f | 333TRS-CWO/scripting_challenge_questions | /test_groceries.py | 535 | 3.5 | 4 | from groceries import groceries
import unittest
class SimpleTest(unittest.TestCase):
def test_first(self):
self.assertEqual(groceries(["22-Popsicle", "37-Milk", "68-Bread", "70-Chips", "20-Chicken", "39-OJ"]), [["Popsicle","Chicken"],["Milk", "OJ"],["Bread", "Chips"]])
def test_second(self):
... |
eadd40961a13fa8bf6af7167acc85bf8d9fb1094 | raiden-network/raiden-echo-node | /echo_node/logic.py | 2,423 | 3.78125 | 4 | from dataclasses import dataclass
from typing import List, Optional
@dataclass(frozen=True)
class Payment:
token: str
amount: int
sender: Optional[str] = None
recipient: Optional[str] = None
class EchoLogic:
"""
Logic class defining the Raiden echo node:
- Every received payment will be... |
14fa12eac8041101616726d17987b3d873f80b79 | andermic/Tabulator-v1 | /src/osdv/tabulator/xml_serializer.py | 1,270 | 3.59375 | 4 | def xml_serialize(dict_, indent):
"""
Serialize into xml a hierarchical data structure consisting of
dictionaries and lists of dictionaries, using recursion.
"""
result = []
spaces = ''
for i in range(indent):
spaces = '%s ' % spaces
keys_ = dict_.keys()
keys_.sort()
for... |
1b9edef7ed691bd1aef2c6d0b00f2c68eaa4015d | jflobos/python-data-structures | /data-structures/linked_list/test_LinkedList.py | 1,267 | 3.546875 | 4 | from .LinkedList import LinkedList
def test_find():
linked_list = LinkedList(1)
for x in range(20):
linked_list.append(x)
assert linked_list.find(4) == 4
assert linked_list.find(90) == None
def test_get_values():
linked_list = LinkedList()
for x in range(5):
linked_list.appen... |
bd2686074db55323f3a38e4ecb74d424c476f3a2 | simonpatrick/all-about-designpattern | /data_structure/python/sorting/quick_sorting.py | 570 | 3.875 | 4 | __author__ = 'patrick'
"""
1. define a pivot data
2. smaller than pivot, put in left side, other wise put in right side
3. do 1 and 2 for left side and right side
"""
def quick_sort(source):
if len(source) <= 1:
return source
pivot = source.pop()
less = []
greater = []
for item in sourc... |
3cdaa0ae3fbb0edd1d58ed4424538c59b96897a6 | talnir/TicTacToe | /TikTacToe/board.py | 633 | 3.671875 | 4 | class InvalidSizeArgException(Exception):
pass
class Board(object):
def __init__(self):
self._size = None
def draw(self, size):
if not size.isdigit():
raise InvalidSizeArgException
self._set_size(int(size))
self._print_board()
def _set_size(self, size):
... |
650a2e3c052432dff48881d0224d7c2eb8ed1d5a | raymondaksu/Sprint-5_Letter_Count | /letter_count.py | 113 | 3.625 | 4 | def letter_count(word, letter):
counter = word.count(letter)
print(counter)
letter_count('ramazan', 'a') |
fa0e44a6ffbb24a2bfddf152e3d55ac82224ba20 | akobyl/advent_of_code | /2017/2017_19.py | 1,291 | 3.53125 | 4 | class Point(object):
letter = None
vertical = False
horizontal = False
UP = 0
DOWN = 1
RIGHT = 2
LEFT = 3
map = []
with open('input/day19_in.txt') as file:
for line in file:
map.append(list(line.replace('\n', '')))
y = 0
x = map[y].index('|')
direction = DOWN
letters = []
map_chars = ['|', ... |
50e06467aea907107c4413a66e199640f5f17809 | mz-jobs/LeetCode | /189RotateArray.py | 170 | 3.578125 | 4 | nums = [1, 2, 3, 4, 5, 6, 7]
k = 3
def rot(nums):
nums[:] = nums[-k:] + nums[:-k]
# for i, x in enumerate(res):
# nums[i] = x
rot(nums)
print(nums)
|
19d678641d2dee757834911a9b1fa891320198a5 | mz-jobs/LeetCode | /061RotateList.py | 786 | 3.953125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# class Solution:
def printList(h):
while h:
print(f'{h.val}->', end='')
h = h.next
print('NULL')
h = ListNode(1)
h.next = ListNode(2)
h.next.next = ListNode(3)
h.next.... |
2b2ad527b5a1f1366223127d266925f27a781147 | mz-jobs/LeetCode | /99. Recover Binary Search Tree.py | 2,845 | 3.734375 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
... |
2f707d17922449d1f1f3b82e9ddd749d400fcb08 | mz-jobs/LeetCode | /234. Palindrome Linked List.py | 1,022 | 3.75 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
l1 = ListNode(1)
l1.next = ListNode(2)
l2 = ListNode(1)
l2.next = ListNode(2)
l2.next.next = ListNode(2)
l2.next.next.next = ListNode(1)
def isPalindrome(head: ListNode) -> bool:
def listLen(head: ListNode) -> int:
... |
5fbc10392a9c4b282e1c2d1005d704dd98489dc1 | mz-jobs/LeetCode | /124BinaryTreeMaximumPath.py | 671 | 3.609375 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
t1 = TreeNode(-10)
t1.left = TreeNode(9)
t1.right = TreeNode(20)
t1.right.left = TreeNode(15)
t1.right.right = TreeNode(7)
t2 = TreeNode(2)
t2.left = TreeNode(-1)
def maxPathSum(self, root: TreeN... |
995a19836038575dea72618204b904edb53cceaf | mz-jobs/LeetCode | /129SumRoottoLeafNumbers.py | 716 | 3.671875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
t = TreeNode(4)
t.left = TreeNode(9)
t.right = TreeNode(0)
t.left.left = TreeNode(5)
t.left.right = TreeNode(1)
t1 = TreeNode(1)
t1.right = TreeNode(5)
def sumNumbers(self, root: TreeNode) -> int... |
0a872520dca5fa446a8165cd8a7b003ad204f8aa | Tommy-Long4358/Beach-Arcade | /hangman.py | 3,761 | 4.15625 | 4 | import random
from words import words
import string
class HangmanGame:
def __init__(self):
self.attempts = 0
self.hidden_word = "-"
self.user_letter = " "
self.lettersDict = {}
# Displays options for hangman
def menu(self):
print("\nWelcome to Hangman!")
print("1. Play ")
print("2.... |
096a51092b7590d061ffa32b5159eceb1436fef8 | kovacsav/python-training-2021-10-13 | /employee.py | 616 | 4.0625 | 4 | class Employee:
"""Ez egy alkalmazottat tárol"""
def __init__(self, first_name, last_name, age):
print("Konstruktor")
self.first_name = first_name
self.last_name = last_name
self.age = age
def get_name(self):
return self.first_name + " " + self.last_name
def in... |
fe3ccae186e96ff4833b544a0a681384b7389e78 | kovacsav/python-training-2021-10-13 | /menu.py | 621 | 3.90625 | 4 | menu_text = """Válassz a menüpontok közül!
1. Új név rögzítése
2. Nevek listázása
3. Kilépés
"""
menu_input = "1"
menu_print = "2"
menu_exit = "3"
names = []
selected_menu = 0
while selected_menu != menu_exit:
selected_menu = input(menu_text)
print("Valasztott menüpont: " + selected_menu)
if selected_men... |
10f4ccff6d528699e45f123fc01d6ffcd06ff395 | kovacsav/python-training-2021-10-13 | /algs.py | 1,703 | 3.8125 | 4 | # Összegzés tétele
# Egész számokat tartalmazó lista elemeit adjuk össze
numbers = [10, 24, 21, 25, 2, 234, 64, 234, 534]
sum = 0
for number in numbers:
sum += number
print(sum)
# i = 0
# while i < len(numbers):
# print(numbers[i])
# i += 1
# Szélsőérték keresés tétele
min = numbers[0]
for number in numb... |
2738ee7491b73bf5118ac4c21c026e1b0c537c89 | altraman00/mdl_python | /learn_python/basedemo/test05.py | 168 | 4.03125 | 4 | #!/usr/bin/python3
count = 0
while (count < 9):
count += 1
if count % 2 == 0:
continue
else:
print('this count is :', count)
print("bey")
|
3d072ec3dc14b4d82f502e7c0cc81e9e4ea0b3d4 | altraman00/mdl_python | /learn_python/spiker_geekbang/2.py | 624 | 3.609375 | 4 | # -*- coding: UTF-8 -*-
import urllib.request
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def getHtml(url):
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
html = response.read()
return html
def saveHtml(file_name, file_content):
... |
d53ed1c00d525dd46115d7beb022751da0e02f55 | altraman00/mdl_python | /learn_python/operate_office/csv_hiit_3.py | 572 | 3.859375 | 4 | # -*- coding: UTF-8 -*-
import pandas as pd
# List of Tuples
students = [
('Ankit'),
('Swapnil'),
('Priya'),
('Shivangi'),
]
# Create a DataFrame object
stu_df = pd.DataFrame(students, columns=['Name'], index=['1'])
# Iterate over column names
for column in stu_df:
# Select column contents by col... |
14318f0b4f8879d2d365b74667330c2e47aa0cf6 | altraman00/mdl_python | /learn_python/basedemo/test11.py | 302 | 3.96875 | 4 | #!/usr/bin/python3
dict = {'name': 'xk', 'age': '7'}
print(dict)
print(dict['name'])
# del dict['name']
# dict.clear()
dict['birth'] = 9
print(dict)
dict['birth'] = 8;
print(dict.items());
print(dict.keys());
print(dict.values());
print(dict)
aa = dict.pop('name')
print(aa)
print(dict)
|
e333142ed840c5d84d9f4f40b49af6edbebb9c71 | Justinyu1618/python-bee | /easy/5.py | 466 | 4 | 4 | ''' Q5: Given a list x and two positive integers i and n as input, return a list with an element i inserted into the nth position of list x (n <len(x))
>>> f([1,2,3,4,5], 6, 2)
[1,2,6,3,4,5]
>>> f([],1,0)
[1]
>>> f(['a','b'], 2, 2)
['a','b',2]
>>> f([[1,2],[2,3]], 2, 1)
[[1,2],1,[2,3]]
>>>f([‘hello’, ‘world’])
[‘worl... |
679ccdc40ad493c36dfc5fe5bf4273c937587d48 | Justinyu1618/python-bee | /hard/8.py | 429 | 3.984375 | 4 | """A perfect number is a natural number equal to the sum of its positive divisors
other than itself.
Write a function, f, which takes a positive integer as an argument and
returns True if it's perfect, or False otherwise.
>>> f(1)
False
>>> f(5)
False
>>> f(6)
True
>>> f(28)
True
>>> f(27)
False
>>> f(496)
True
>>> f... |
d9de681117cd60de2bcf573290b5d1367f3c2040 | Justinyu1618/python-bee | /medium/4.py | 393 | 3.875 | 4 | ''' Q4: Given a list x, return how many of an element n is in the list.
>>> f([1,2,3],3)
1
>>> f(['a','b','c'],3)
0
>>> f(['a','b','c'],'c')
1
>>> f([1,2,3,4,3,2,3],3)
3
>>> f(['a','b','c',1,2,3],'a')
1
>>> f(['1','1','2','3'],'1')
2
>>> f(['1','1','2','3'],1)
0
>>> f([],1)
0
'''
def f(x,n):
# Your Code Here!
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.