blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
5cd1c53677be741a0143e743eb462a5fe8025329 | kolasau/python_work_book | /functions/make_album.py | 449 | 3.578125 | 4 | def make_album(musician_name, musician_album, number_of_tracks= ''):
album_info = {'musician': musician_name, 'album': musician_album}
if number_of_tracks:
album_info['number_of_tracks'] = number_of_tracks
return album_info
album = make_album('john', '1987')
album2 = make_album('max', '123123')
album3 = make_albu... |
7475d2c70c530e44cf1140fa3d1f7351b75459da | Tienta/Techkids_C4E_Assignment | /Assignment 3/Serious exercises 2.6.py | 1,091 | 3.875 | 4 | size = [5, 7, 300, 90, 24, 50, 75]
print("Hello, my name is Tien and these are my ship size\n",size)
print("Now my biggest sheep has size", max(size), "let's shear it")
p = size.index(max(size))
size[p]=8
print("After shearing, here is my flock\n",size)
while True:
m = int(input("How many month has passed?"))
... |
f6992db5ade189820bf6cae398c73b476ea3e01d | MishRanu/udemy-python-masterclass | /write_file.py | 1,522 | 4.28125 | 4 | #in this file we are going to deal with writing files
cities = ["Adelaide", "Alice Springs", "Dublin", "Melbourne", "Sydney"]
with open("cities.txt", 'w') as city_file:
for city in cities:
print(city, file=city_file)
#Great three lines of code and it is written to the file cities.txt
#Really incredible... |
b5a9f75547f0fd98b52411ab55204d506374785f | Sergei-Morozov/Stanford-Algorithms | /Greedy Algorithms/week8/dsu.py | 2,029 | 4.53125 | 5 | """
Disjoint set implementation
Three operations:
- make_set(v) - creates a new set with element v
- union_sets(a, b) - merges the two specified sets (the set in which the element a is located, and the set in which the element b is located)
- find_set(v) - returns the representative (also called leader) of... |
1f773343c75f2f3c16df5b17f68968ab14f6f0b7 | thecuriousjuel/Python-2 | /program_2.py | 232 | 4.3125 | 4 | radius = int(raw_input("Enter the radius of the circle :: "))
area = 3.14 * radius * radius
circumference = 2 * 3.14 * radius
print "The area of the circle is :: ",area
print "The circumference of the circle is :: ", circumference
|
34e5f933e16c0398a9adfd7b1ca3d7f227e5bb41 | A01375932/Mision_04 | /Rectangulos.py | 1,463 | 4.0625 | 4 | #Autor: Guadalupe Iveth Serrano Hernández A01375932
#Descripción: Leer las dimensiones de dos rectángulos, calcular e
#imprimir el perímetro y área e indicar que rectangulo tiene mayor área.
def calcularArea (base, altura):
area = base*altura
return area
def calcularPerimetro(base, altura):
per... |
637ed4dde35f2c09ea90b3423775928b81f639db | hagom/python4inf | /list_of_words.py | 297 | 3.71875 | 4 | fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
line = line.split()
for word in line:
lst.append(word)
lst.sort()
newlst = list()
for words in lst:
if words in newlst: continue
newlst.append(words)
newlst.sort()
print newlst |
032fc60ee1fea68662fa410bc87301ceb787c55e | kykel/ForbiddenQuest | /testingfunctioncalls.py | 3,520 | 3.609375 | 4 | import time
import config
import items
def tableofcontents():
choice = raw_input("Where do you want to go?\n1. Mosuleaum.\n2. Rearpath.\n")
if choice == '1':
entermosuleaum()
elif choice == '2':
rearpath()
else:
exit()
def entermosuleaum():
def sarcophagus():
print ... |
72109201a44c51b1ca168d5ea0da97fcf3143c06 | StellaNguyen68/Fundamental-in-Python | /Python basic.py | 1,258 | 3.71875 | 4 | a=29.11
print(a)
print(type(a))
#take decimal from libraby
from decimal import*
getcontext().prec=3 #take max 30 number behind ,
print(Decimal(10)/Decimal(3))
print(type(Decimal(10)/Decimal(3)))
#Fraction
from fractions import*
frac=Fraction(6,9)
print(frac)
print(type(frac))
print(frac+2/3)
#Complex
... |
a21f560b464331fddd43d4b9f715cfb34b74a184 | webclinic017/super-quant | /sphinxquant/utils/const.py | 570 | 3.515625 | 4 | from enum import Enum
def enum_to_choices(enum: Enum):
""" cover enum to choice """
return tuple([(tag.name, tag.value) for tag in enum])
class BacktestStatusType(Enum):
""" 回测状态 """
START = "START"
PROCESS = "PROCESS"
DONE = "DONE"
ERROR = "ERROR"
ABORT = "ABORT"
class StrategyTy... |
cb5b24c0cbd062e5649fd608fe66f21b303950f8 | Astrid1898/SZU_CSSE_master | /SignalProcessing/homework/2_my_dft&my_idft/my_dft.py | 1,033 | 3.671875 | 4 | import numpy as np
def dft(Xn):
'''
@Hypo 1910273011
This is a function for Discrete Fourier Transform(DFT)
Parameters:
Xn : array_like, type = complex
Returns:
out : array_like, type = complex
'''
Xk = []; Xk_i = 0
N = len(Xn)
for k in range(N):
... |
ec45624fff23ae98b7a4677c52cd68baf4e552c8 | DestinedGamerz/PythonProjects | /rockpaperscissor.py | 835 | 4.03125 | 4 | import random
game_choices = ['Rock', 'Paper', 'Scissors']
pick = random.choice(game_choices)
choose = input("Please enter a value: ")
if pick == 'Rock' and choose == 'Rock':
print("It's a tie")
if pick == 'Rock' and choose == 'Paper':
print("Player wins")
if pick == 'Rock' and choose == 'Sc... |
901267b61191a3a1c8029ebc963f584eff4644c5 | jacksnyders/intro-geodynamic-modeling | /02_convection/plot_over_time.py | 380 | 3.6875 | 4 | import matplotlib.pyplot as plt
import numpy as np
# Load the columns of the csv file
x = np.genfromtxt('output/statistics', dtype=float, usecols = (1))
y = np.genfromtxt('output/statistics', dtype=float, usecols = (10))
# make the plot
fig, ax = plt.subplots()
cax = ax.plot(x, y, 'o-')
# add labels and units
plt.xl... |
6ff602fc320f407a1ec1be17aa2c1f107a6eda9b | xiaoloinzi/worksplace | /GR1/untitled1/reference.py | 1,022 | 4.28125 | 4 | #encoding=utf-8
print("simple assignent")
shoplist = ['apple','mango','carrot',
'banana']
mylist = shoplist#mylist is just anther name pointing to the same object
#mylist读取shoplist的内存,两个修改那个,另一个也会改变
print("shoplist is ",shoplist)
print("mylist is ",mylist)
del shoplist[0]
print("shoplist is ",shoplist)
prin... |
a2ee5a85f1bd3bbe3c29099494bbb97192471afb | dander521/Python_Learning | /10.19.1/10.19.1/Dictionary.py | 768 | 3.75 | 4 | #coding:utf-8
import sys
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键 'Name'
dict.clear() # 删除字典
del dict # 删除字典
# a, b = 0, 1
# while b < 1000:
# print(b, end=';')
# a, b = b, a+b
list1 = [1, 2, 3, 4]
it = iter(list1)
print(next(it))
print(next(it))
print('-----... |
011e26f854b7769dc680c79998e624ef8ace3098 | sdommi/python_rep | /FInd_Treasury_Add_Guess_Count.py | 1,533 | 3.859375 | 4 | from tkinter import *
import random
window = Tk()
x_coord = random.randint(0,200)
y_coord = random.randint(0,200)
button_counter=1
counter = 0
def guess_treasure(event):
global counter
counter +=1
if counter >10:
global button_counter
if button_counter == 1:
button = Button(wi... |
91f48e903b5e760c065457d3b12f1ef4e50438e0 | hamzzy/pymeet_abk_datastructure | /trees.py | 303 | 3.859375 | 4 | class Tree:
def __init__(self,root,left=None,right=None):
self.root=root
self.left=left
self.right=right
def __str__(self):
return (str(self.root)+", left child :"+str(self.left)+ ", right child :" +str(self.right))
tree=Tree(5,Tree(3,1,4),Tree(8,7,9))
print(tree) |
a8ce4642f3e964054e7deea1544562bb48246b61 | cvnlab/GLMsingle | /glmsingle/utils/chunking.py | 1,327 | 3.734375 | 4 | import numpy as np
def chunking(vect, num, chunknum=None):
""" chunking
Input:
<vect> is a array
<num> is desired length of a chunk
<chunknum> is chunk number desired (here we use a 1-based
indexing, i.e. you may want the frist chunk, or the second
chunk, bu... |
7965c2a7ac8e3bd1e77da3a5c9618ef9c1943150 | conganhhcmus/Codelearn.io | /sasuke 34/G.py | 395 | 3.640625 | 4 | def gcd(a,b):
if a == 0: return b
return gcd(b%a,a)
def lcd(arr):
ans = arr[0]
for i in arr:
ans = (ans*i)/gcd(ans,i)
return ans
def check_sum_divisible(n):
arr = []
sum = 0
for i in n: arr.append(int(i))
for i in arr: sum+=i
# print(sum,lcd(arr))
if sum % lcd(arr) ... |
71c15e4a3fbad13d475d649e4a0b1aaf646822f3 | Pandinosaurus/ensae_teaching_cs | /_unittests/ut_homeblog/data/quicksort2.py | 1,527 | 3.59375 | 4 | # coding: latin-1
import string
class SecondeInserstion (AttributeError):
"insertion d'un mot dj insr"
class NoeudTri:
def __init__(self, s):
self.mot = s
# la cration d'un nouveau noeud a t place dans une mthode
def nouveau_noeud(self, s):
return self.__class__(s)
# return... |
0561ffe74d403c7d11715a82fb64e8f341ef8846 | ssarrayya/python-deitel-exercises | /com/exercises/chapter_three/validating_user_input.py | 970 | 4.125 | 4 | # 3.1 (Validating User Input) Modify the script of Fig. 3.3 to validate its inputs. For any
# input, if the value entered is other than 1 or 2, keep looping until the user enters a correct
# value. Use one counter to keep track of the number of passes, then calculate the number
# of failures after all the user’s inputs... |
afbb11a46b550aee0011d096b7c4f6ece95a6166 | CertifiedErickBaps/Python36 | /Manipulacion de textos/numeros binarios.py | 497 | 3.765625 | 4 | # Definiendo un numero con binarios
def binario(n):
if n == 0:
return "0"
if n < 0:
negativo = True
else:
negativo = False
n = abs(n)
r = ""
while n != 0:
r = str(n % 2) + r
n //= 2
if negativo:
r = "-" + r
return r
... |
acc65db5b94e798fd3354463faf4a6f79e17e45c | EruDev/Learn_Algorithms | /算法图解/chapter-10/10.py | 418 | 3.84375 | 4 | # coding: utf-8
"""
有一个长度为n序列,移除掉里面的重复元素,对于每个相同的元素保留最后出现的那个
示例:
1,8,7,3,8,3,1
输出:
7,8,3,1
"""
def find_last(seq):
li = list()
for i in seq:
if i not in li:
li.append(i)
else:
li.remove(i)
li.append(i)
return li
if __name__ == '__main__':
seq = [1, 1, 7, 1, 8, 3, 1, 7, 8] # 3,1,7,8
print(find_... |
cfbfed703c1ce3df796e89de742cd4c466af03a9 | olmirjunior/CursoemVideoPython-Exercicios-e-Aula | /aula6a.py | 216 | 3.953125 | 4 | a = int(input('Digite um número: '))
b = int(input('Digite outro número: '))
s = a + b
print('A soma entre', a, 'e', b, 'vale:', s)
#Duas opções para a soma
print('A soma entre {} e {} vale: {}'.format(a, b, s)) |
a22d668919f5089988df37c23ce9f1bdd71713d5 | cczhong11/Leetcode-contest-code-downloader | /Questiondir/728.self-dividing-numbers/728.self-dividing-numbers_128808751.py | 507 | 3.546875 | 4 | class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
def is_div(n):
if n == 0:
return False
m = n
while m > 0:
k = m % 10
... |
d46e1707e4de2104a797189c3472a64f08e90896 | TheCodingAstronomer/Python-3 | /Tkinter/StringFunctions.py | 163 | 4.09375 | 4 | string="Girrafe Academy"
print(string.isupper)
print(string.upper)
print(string.lower)
print(string.islower)
print(string.index("A"))
print(string.find("Academy")) |
fef6af5f3b775dbf354322584e2d8834facc2b7e | Mark6197/Interview-Questions | /NQueens.py | 2,699 | 3.6875 | 4 | def nqueens_helper(n, row, col, asc_diag, desc_diag, queen_pos):
if len(queen_pos) == n:
return queen_pos
# Set the current row to the length of the queen_pos,
# at the beginning queen_pos is empty so we start from the first row and advance
curr_row = len(queen_pos)
# Run in range fr... |
2ee7431349641c433a076ebd4fe141367ee01503 | Aurian-G/Protein_Calculator | /Protein_Calculator.py | 1,790 | 4.25 | 4 | #Protein Intake Calculator
#Python v3.7.2
#Git test 1/5/2019
#R Studio Implementation Test 1/5/2019
import time
def bulking_routine(bulk):
equation = ((bulk/2.2)*2.3)
round_equation = round(equation, 2)
return (f'you must consume {round_equation} grams of protein to achieve your goals'.format(round_equati... |
86e242dd38f5522bc9698344a2b576ac84608ef2 | Lei-yiyi/object-oriented_programming | /inheritance .py | 1,789 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on 2020-05-16
Updated on 2020-05-16
@author: 小小磊
@requirements: Python 3.5
@decription: Python 类的继承
@ref: https://github.com/Lei-yiyi/object-oriented_programming/blob/master/inheritance%20.py
"""
"""
1.继承:父类有的子类也有(私有方法(__private_method)和私用属性(__private_attrs)除外) —— 类名(父类名) ... |
73e904676e935ee4cdf24242bd9180ff9ec67629 | jusmojito/HackerRank | /Simple_Array_Sum.py | 128 | 3.671875 | 4 | n=int(input())
sum=0
l=0
listofnumbers=(input().split())
for number in listofnumbers:
sum=sum+int(number)
print(sum)
|
7695fcc2eb814c0cf30aeff967412c03ade70018 | sizej/FilmSeasonality | /src/movie_func.py | 2,443 | 3.59375 | 4 | import pandas as pd
import numpy as np
def genre_col(g_name, g):
'''
Looks at the genre column and returns 1 if g_name is in genre
'''
if g_name in g:
return 1
else:
return 0
def weekly_plot(col):
'''
Creates 52 plot of some column
'''
pass
def get_dollars(s):
... |
2125e70ca6a95a6936ecdc10c7b1e478ba7f11f8 | TahaaFatima/PythonSamaan | /day5_cw.py | 2,337 | 4.03125 | 4 | def main():
moreStudent = 'y'
students = []
while moreStudent.lower().strip() == 'y':
name = getName()
gender = getGender()
age = getAge()
moreStudent = input(
"\n\nDo you want add more students if yes then press 'y' else press any key: ")
students.append... |
b83c98039b2cbb2ec64c101ac8c821f5b9ed4bf8 | UnrealRoot/core-python-programs | /text.py | 97 | 3.828125 | 4 | a = int(input(print("Enter value : ")))
if a==10:
print("Hello")
else:
print("Error") |
1a1305cd12a0f68865c68250517ab2ed05ca35f1 | borislavstoychev/Soft_Uni | /soft_uni_advanced/File Handling/exercise/3_file_manipulator.py | 1,157 | 3.59375 | 4 | import os
def creat(file):
with open(file, "w") as file:
return file.writelines("")
def add(file, message):
with open(file, "a") as file:
return file.write(message + "\n")
def replace(file, old, new):
try:
with open(file, "r+") as file:
tex = "".join... |
d04250118f4cb0d23c6ec681418cac6745b2a323 | thiagorb/FacebookHackerCup | /2020/Qualification/Alchemy/alchemy.py | 355 | 3.5 | 4 | #!/usr/bin/env python3
from collections import Counter
cases = int(input())
for case in range(1, cases + 1):
shards_length = int(input())
shards = input()
counter = Counter()
for shard in shards:
counter[shard] += 1
result = 'Y' if abs(counter['A'] - counter['B']) <= 2 else 'N'
prin... |
eae469e762186e858082efef99c19dcf79a81820 | Shibaken2017/Utils | /excel_wragling/merge_csv_into_excel.py | 997 | 3.5 | 4 | import openpyxl as px
import os
from typing import List
def write_excel(year:int,month:int,csv_dir:str):
#csv_fileをexcelファイルにまとめる
csv_fnames=os.listdir(csv_dir)#path
wb=px.Workbook()
for fname in csv_fnames:
titles=wb.get_sheet_names()
sheet=wb.get_sheet_by_name(titles[-1])
shee... |
a328a9ae0944131ea6cc991d9cc412c0f5a50605 | SPLURGE831/practice | /codes/py/basicDS/pBiLinTable.py | 267 | 3.515625 | 4 | import os
class Node():
value = 0
prev = None
nextN = None
def link(a,b):
if a.value > b.value:
a.nextN = b
b.prev = a
else:
b.nextN = a
a.prev = b
aNode = Node()
print (aNode.value)
|
74cf448e3bf480b5a2173cc69d286c170e33119f | ajohnson30/pythonchallenge | /clock.py | 590 | 3.59375 | 4 | import time
class Clock:
def __init__(self,root):
self.root = root
self.lb=Label(root,padx=5,pady=5,
fg='blue',font=('Times',20))
self.lb.pack()
self.root.after(1000, self.ck)
self.ck()
def ck(self):
self.... |
5dcf8d960877a6dd54a01138508a7500ad830306 | raihan-uddin/Python-practice | /AdvancedPythonModules/collections_module_ordereddict.py | 445 | 3.78125 | 4 | from collections import OrderedDict
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
d['e'] = 5
print(d)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
for k, v in d.items():
print(k, v)
# a 1
# b 2
# c 3
# d 4
# e 5
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
d['e'] = 5
for k, v in d.items()... |
60ec3c2e091711317d4e25587c708e2a04bd12a5 | pragatirahul123/practice_folder | /Break_practice.py | 127 | 3.71875 | 4 | index=0
while True:
print(index,"",end="")
index=index+1
if index==10:
break
print("for",index,"location")
|
8c60a4c48a33f4dbb92c5e2912e48be4ea2533fc | HomeBrewExercisesOnPython/DiveIntoPython3 | /tests/chap2/q0002.py | 1,340 | 3.734375 | 4 | #!/usr/bin/python
import unittest
from exercises.chap2 import q0002
data = ['Fizz Buzz', 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz',
11, 'Fizz', 13, 14, 'Fizz Buzz', 16, 17, 'Fizz', 19, 'Buzz',
'Fizz', 22, 23, 'Fizz', 'Buzz', 26, 'Fizz', 28, 29, 'Fizz Buzz',
31, 32, 'Fizz', 34]
... |
7cbcccade555018b2f92eeac59409872f5d05960 | alexcarcar/WebLayout | /app/src/main/assets/jsexamples/py/ch17/exercises.py | 1,070 | 4.21875 | 4 | # Exercise 17-2
class Point(object):
"""Represents a point in 2D.
attributes: x, y
"""
def __init__(self, x=0, y=0):
(self.x, self.y) = (x, y)
# Exercise 17-3 (p 194)
def __str__(self):
return '(%g, %g)' % (self.x, self.y)
# Exercise 17-4 (p 194)
def __add__(self, other):
# Exercise 17-5 (p 196)
if i... |
23e11f96672fa67d81c50353dfb0236a7ed109a8 | liuwanping/leetcode-problems-python-solutions | /array/Pascal's Triangle.py | 1,041 | 3.734375 | 4 | # Given numRows, generate the first numRows of Pascal's triangle.
# For example, given numRows = 5,
# Return
# [
# [1],
# [1,1],
# [1,2,1],
# [1,3,3,1],
# [1,4,6,4,1]
# ]
class Solution(object):
#solution1:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List... |
a50ff6a649fc8bbe69e39e5cc67956905debefed | highshoe/PYTHON | /python-02-exercise2/src/.svn/text-base/exercise04.py.svn-base | 261 | 3.75 | 4 | '''
Created on 2009-10-11
@author: selfimpr
'''
if __name__ == '__main__':
input = raw_input('Please input a number')
while input != 'q':
result = int(input)
print result, type(result)
input = raw_input('Please input a number') |
80ff3147d7e4b2fba8b97849c3d798bc98572eab | cemathey/aoc_2020 | /day18/day18.py | 1,848 | 3.625 | 4 | import sys
import string
from collections import defaultdict, deque
OPERATORS = ("+", "-", "*")
def tokenize(raw_expression):
"""Split the given string expression into discrete tokens ignoring whitespace."""
token = []
discrete_tokens = ("(", ")", "+", "-", "*")
for char in raw_expression:
... |
fb1db281a702c7f0c428ae8e318c92db192acef0 | gautambedi1998/5.2-embedded- | /5.2code.py | 1,636 | 3.546875 | 4 | from tkinter import *
import tkinter.font
from gpiozero import LED
import RPi.GPIO
RPi.GPIO.setmode(RPi.GPIO.BCM)
### hardware
led1 = LED(17)
led2 = LED(27)
led3 = LED(23)
win = Tk()
win.title("LED Toggler")
myFont = tkinter.font.Font(family = "Helvetica", size = 12, weight = "bold")
### defininf func... |
bf1dcc25cf10be1eb5ae99068ef36373eb40076a | yashaswiniyashu/Weakavl-tree | /bstmain.py | 1,226 | 3.59375 | 4 | import bst
import wavl
b=bst.BST()
b.insert(5)
b.insert(1)
b.insert(7)
b.insert(2)
b.insert(6)
b.insert(12)
b.insert(4)
b.insert(0)
b.insert(11)
b.insert(13)
b.insert(14)
b.insert(15)
b.insert(16)
b.insert(17)
b.insert(18)
b.insert(19)
b.inorder()
print("bst test")
ch='y'
while ch == 'y' or ch == 'Y':
print("enter the... |
994dba146cfcb8da30a39704078b3362d9143bcb | chrismgeorge/Curriculum | /past_iterations/02_Homewood_Y/02_drawing/02_rectangles2.py | 608 | 4.1875 | 4 | from tkinter import *
def draw(canvas, width, height):
# draw these on a piece of paper before you run the code
canvas.create_rectangle(0,0,50,50, fill="maroon")
canvas.create_rectangle(100,100,200,200, fill="pink")
canvas.create_rectangle(50,50,150,150, fill="turquoise")
# challenge rectangle! (add it to yo... |
185c528cfc0a69b71ae6fd6eeea7198d46d2f25a | sebarias/python_classes_desafioltm | /clase_6/letra_o.py | 352 | 4.125 | 4 | # La función letra_o(n) , la cual al ser llamada, retornará una cadena de texto que al ser
# imprimida con print, dibujará una letra "o" según el ejemplo
def letra_o(n):
linea = "*" * n
columna = ""
for i in range(n-2):
columna += "*" + ((n-2) * " ") + "*" + "\n"
return linea + "\n" + columna +... |
074d9ff930449fd4c22820cfd73f981495e08e57 | ondrasouk/face-recognition-project | /draw_tool.py | 648 | 3.5625 | 4 | import cv2
'''
Set of function for marking objects direct into frame
We used lot more of draw functions, but finally we need only these two:
-draw_point(frame, center, colorKey)
used for marking center of face and reference point
-draw_circle(frame, center_coordinates, radius)
used for face marking
'''
def dr... |
c91475008717afbad4dda8424cf6df52cc531c01 | lhansford/project-euler | /python/problem_51.py | 769 | 4.03125 | 4 | import itertools
def is_prime(number):
if number > 1:
if number == 2:
return True
if number % 2 == 0:
return False
for current in range(3, int(number**0.5 + 1), 2):
if number % current == 0:
return False
return True
return False
def prime_gen(num=2):
while True:
if is_prime(num):
yield n... |
d3faba91f6b66a974321bdc542ba69d4973d5037 | devdjan/Basic_python | /Courses/Introduction to CS MITx/Week 2/Functions/power_recursion.py | 558 | 3.890625 | 4 | # Let's split problem
# firstly it should return us base * recursion(base, epx-1)
# while exp will equal to 1
# Then we write if statement
# If exp == 1, obviously we will return base (e.x. (2,0) ==> 2
# if exp == 0 return 1
# else return base * recursion(base, epx-1)
#
def recurPower(base, exp):
'''
:param b... |
330f77ea6f1a4442a684ad074297860c163037a0 | brigitteunger/katas | /test_insert_delete_get_random.py | 1,798 | 4.03125 | 4 | import unittest
import random
from typing import List
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.ran_set = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not al... |
7b8d57094c56583726fe8763cb825bb9fa73b5d6 | inuishan/miscellaneous-codes | /spoj/PRIME1.py | 466 | 3.8125 | 4 | import math
def isPrime(n):
flag=0
for i in xrange(3,int(math.sqrt(n)+1),2):
if(n%i==0):
flag=1
if(flag==0):
print n
canMul(n)
def canMul(k):
i=2
while k*i<=n:
dic[k*i]=3
i+=1
t=int(raw_input())
while t:
t-=1
dic={}
# m=int(raw_input())
# n=int(raw_input())
m,n=map(int,raw_input().split())
... |
135e42a9199c15ea5a8ebb85ef168609ef93681c | luochonglie/tf | /data_structure/searcher.py | 1,414 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/05/02 13:40
# @Author : c0l0121
# @File : searcher.py
# @Desc :
def binary_search(array, value):
""" 查找所给数值在有序数组中的位置,找不到则返回-1
:param array: 数组
:param value: 待查找的数值
:return: 找到则返回数值在数组中的下标,否则返回-1
"""
ret = -1
start = 0
... |
77d9f7f1b19ff3d378532ed894c0e60a5d51838b | 4nu81/python_trainee | /test.py | 252 | 3.890625 | 4 | alist = {
'name' : 'Max',
'schule' : 'Saengerstadt',
}
for element in alist:
key = element
value = alist [ element ]
print "{key} : {value}".format (key = key, value = value)
def add(a,b):
c = a+b
return c
print add(1,5)
|
fdfd1f22720b8dc0d4ca503378dac4991410590c | Hogs-Co/Firebase-Location-Emulation-MandP-subproject | /tag_creation_and_manip.py | 3,137 | 3.578125 | 4 | from datetime import date
from random import randint, uniform
from collections import OrderedDict
class Tag:
def __init__(self, name: str, author: str = "EmulationApp",
creation_date: str = str(date.today()), users=None):
self.author = author
self.name = name.replace("#", "")
... |
17ca9fec0c020c9567be346876e242769c16c7dd | rriolo/cscs-531-pd-tournament | /src/pd/agents.py | 9,749 | 3.609375 | 4 | '''
@date 20131124
@author: mjbommar
'''
# Standard imports
import random
# PD imports
import world
from world import *
class Agent(object):
'''
The Agent class is a base class, meant to be extended by
our individual players in the PD world.
The Agent class defines a shared set of methods and vari... |
30a0b583a05110bd9041709769bc977e608f30e5 | qqqclark/Python-Foundation-Suda | /苏大上机代码/python_project/03_历年真题期末期中/RealExercise2/py22_exercise03_matrixMultiply.py | 696 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 18:23:03 2020
@author: douzi
"""
def matrixMul(A, B):
if len(A[0]) == len(B): # A列数 == B行数
res = [[0] * len(B[0]) for i in range(len(A))] # A行 x B列
for i in range(len(A)):
for j in range(len(B... |
b613dd8ec65ff4e735b7b5e44f6869733b9cd3c0 | Warthog710/Computer-Networking-Fundamentals | /Web_Server/web_server.py | 1,388 | 3.546875 | 4 | #Import socket
from socket import *
#Prepare a server socket at this address
serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 1234
serverSocket.bind(('',serverPort))
#Queue up to a maximum of 1 request
serverSocket.listen(1)
while True:
try:
#Print that the server is ready to service requests
... |
64d76de515d44a3232f53b76d90b87d1a6dba649 | AvneetSandhu1/Python | /types.py | 508 | 3.671875 | 4 | print("45e5 is a ", type(45e5))
print(45e5)
x = 1+4j
print(x)
print(type(x))
# setting types:
x = float(1)
print(x)
x = int(35.67)
print(x)
x = list((1, 4, 6, 8, 9))
print(x)
print(type(x))
x = tuple((1, 4, 6, 8, 9))
print(x)
print(type(x))
x = dict(apple = 5, pear = 6)
print(x)
print(type... |
39f8fa11d45be0130161bb1a49a4f2feb527da83 | pedrohgmuniz/computational_linguistics_2018.1_exercises | /exercicio-2/palindromocomplexo.py | 1,552 | 4.46875 | 4 | # palindromocomplexo.py
# Programa que testa uma palavra, frase ou expressao
# eh um palindromo: se a inversao de seus caracteres
# gera a mesma palavra, frase ou expressao
# Por: Pedro Muniz, Joao Vieira, Brenda Souza
def main ():
print ("Cheque se uma palavra/termo/frase é a mesma coisa ao contrário!")
palav... |
58e69e82a652944b64167d3b96e82313c116e20f | vanden/code_challenges | /leetcode/sort_colours.py | 1,966 | 3.59375 | 4 | # https://leetcode.com/problems/sort-colors/description/
# Ugly, complex, and fast: 36ms beating 100% of Py3 solutions
class Solution:
def swap(self, nums, idx1, idx2):
nums[idx1], nums[idx2] = nums[idx2], nums[idx1]
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype... |
8176936ae95d6156a1b416b567892d463e52586d | k-dx2/Non_Linear_regression | /non_linear_regr.py | 1,530 | 3.546875 | 4 | import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
def sigmoid(x, Beta_1, Beta_2):
y = 1 / (1 + np.exp(-B... |
c4afdc0729ba126f76c47e42894834f7faf02264 | test12345-coder/Python | /OOP3-inheritance.py | 474 | 3.671875 | 4 | class Human:
name = ''
surname = ''
length = 0
def printVar(self):
print(f'{self.name} {self.surname} {self.length}')
class Student(Human):
grade = 0
def printVar(self):
print(f'{self.name} {self.surname} {self.length} {self.grade}')
if __name__ == '__main__... |
e494905c2b892755985470ca5d22ba8d8ac1a3ca | kame3niku9/atcoder | /ABC159/B/main.py | 290 | 3.625 | 4 | import math
def resolve():
S = input()
N = len(S)
pre = S[0:math.floor((N-1)/2)]
post = S[math.floor((N+3)/2 - 1):]
if S == S[::-1] and pre == pre[::-1] and post == post[::-1]:
print('Yes')
else:
print('No')
if __name__ == "__main__":
resolve() |
3e1bed927199bd943ac13420e87953d57e093a4b | bartoszmaleta/dojos_katas_exercise_bank | /katas_codewars/sort_and_star.py | 811 | 4.09375 | 4 | # You will be given an vector of string(s). You must sort it alphabetically (case-sensitive!!) and then return the first value.
# The returned value must be a string, and have "***" between each of its letters.
# You should not remove or add elements from/to the array.
array = ["bitcoin", "take", "over", "the", "wor... |
39d63136d4de97ca84eb562674c0294432382897 | PythonCodes1/CodeWars | /7 kyu/Python/Reverselt.py | 298 | 3.75 | 4 | def reverse_it(data):
if isinstance(data,bool):
return data
elif isinstance(data,int):
return int(str(data)[::-1])
elif isinstance(data,str):
return data[::-1]
elif isinstance(data,float):
return float(str(data)[::-1])
else:
return data
|
bd484410f0acf02d76c4dc3adaca6385a13c67a1 | komalupatil/30-Day-LeetCoding-Challenge | /July2020/Week1/Prison Cells After N Days.py | 2,001 | 4.09375 | 4 | #Problem3
#There are 8 prison cells in a row, and each cell is either occupied or vacant.
#Each day, whether the cell is occupied or vacant changes according to the following rules:
#If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
#Otherwise, it becomes vacan... |
7ea2872aa58ff71e9139efd073e542a0f242e03a | alirezabayatmk/pacman-AI | /search.py | 4,253 | 3.59375 | 4 |
import util
class SearchProblem:
def getStartState(self):
util.raiseNotDefined()
def isGoalState(self, state):
util.raiseNotDefined()
def getSuccessors(self, state):
util.raiseNotDefined()
def getCostOfActions(self, actions):
util.raiseNotDefined()
def tinyM... |
865d26a91722e70067590c5ecf8047d9ab279c0f | YaroslavaMykhailenko/datasciencepandasplotly | /lesson1/map.py | 513 | 4.21875 | 4 | # The map function is used to apply a particular operation to every element in a sequence. Like filter(), it also takes 2 parameters:
sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = map (lambda x: x*x, sequences)
print(type(filtered_result))
print(list(filtered_result))
# or
def f(x):
return x*x
filtere... |
3c56fe9d8c4b0d328b0ec8c7faac7ce807374f95 | oberlin-io/html-quick-scrape | /get-content.py | 887 | 3.640625 | 4 | from bs4 import BeautifulSoup as soup
# Get the html saved in the txt file
with open('html.txt', 'r') as f:
text = f.read()
# Make soup widit
soup = soup(text, 'html.parser')
#<div class="entry-content">
# Find desired content by tag
tags = soup.find_all('h3')
list = []
# Get the text. ... |
4811b5b3be418becfe20a6fd8660fdb51efd13dd | atrivedi8988/DSA-Must-Do-Questions | /08_Bubble sort/Ideal Solutions/bubbleSort.py | 583 | 4.46875 | 4 |
# Swap the elements of array present in first and second location.
def swap(arr, first, second):
arr[first], arr[second] = arr[second], arr[first]
# Bubble Sort Function which will sort the given input array of length N.
def bubbleSort(arr, N):
for i in range(N-1):
for j in range(0, N-i-1):
# If adjacent... |
f1f50df63a896023bfe64eddd4560f7c0cf57f86 | yangh-zzf-itcast/Python_heima_Study | /02多任务-多进程-多线程/08-多线程共享全局变量-args参数.py | 843 | 3.75 | 4 | import threading
import time
# 多线程共享全局变量会有一个问题:同时对一个变量进行操作时,发生资源竞争
# 定义一个全局变量
g_nums = [11, 22]
# 主线程和子线程之间是共享全局变量的
def test1(temp):
temp.append(33)
print("------------in test1 g_nums = %s -----------" % str(temp))
def test2(temp):
print("------------in test1 g_nums = %s -----------" % str(temp... |
caedbb337dfafe1344b03f4df2d5ef4988f062a5 | jakobkhansen/KattisSolutions | /iforaneye/iforaneye.py | 1,300 | 3.625 | 4 | import sys
subs = {
"at":"@",
"and":"&",
"one":"1",
"won":"1",
"to":"2",
"too":"2",
"two":"2",
"for":"4",
"four":"4",
"bea":"b",
"be":"b",
"bee":"b",
"sea":"c",
"see":"c",
"eye":"i",
"oh": "o",
"owe": "o",
"are": "r",
"you": "u",
"why": "y... |
73a59f6af37e9d676e32a0fc0e06909f9a6ff282 | GinaCha/MLLab-OpenFaas-CS | /functions/calculator/multiply/handler.py | 695 | 4.03125 | 4 | """Author: Gina Chatzimarkaki"""
#test-calculator-multiply.py
def handle(str):
"""
Multiple two numbers and return the result. If there are more
just take the first two
Parameters
----------
str : String
the provided input
Returns
-------
... |
0357dbfb9852dcb8198a5fdf8d45bad3cc2003ee | susanahidalgo/python_class | /06-Strings-The-Basics/string-slicing-II-slicing-by-steps.py | 1,480 | 4.46875 | 4 | alphabet = "abcdefghijklmnopqrstuvwxyz"
print(alphabet[0:10:2])
print(alphabet[:26:3])
print(alphabet[::3])
print(alphabet[-20:-8:5])
print(alphabet[::-3])
print("\n")
print("---Exercises String Slicing---")
print("\n")
# Define a first_three_characters function that accepts a string argument.
# The function shoul... |
0e7c9e5b71fde2ec0e7e3a17ff13530c3a432dc8 | jvillamarino/python | /Platforms_courses/DataCamp/Learn_python_list/chapter_3_manipulation_list.py | 5,101 | 4.15625 | 4 | # INFORMATION ======================================================================
'''
You should copy list with reference or without reference
'''
print("*" * 10, " With Reference ", "*" * 10)
person_names = ["Jesús", "Humberto", "Sara", "Ronald"]
students = person_names
del person_names[3]
# If you print per... |
0976a5d00c906d986f6695601eae92ec6bb400b6 | vladislav-ero/lesson2 | /string_challenges.py | 1,608 | 4.125 | 4 | # Вывести последнюю букву в слове
word = 'Архангельск'
lenght_of_word = len(word)
print(f"Last char of word '{word}' is '{word[lenght_of_word - 1]}'.")
# Вывести количество букв "а" в слове
word = 'Архангельск'
count_chars = word.lower().count("а")
print(f"Word '{word.lower()}' has {count_chars} chars 'a'.")
# Вывест... |
cde24e11df5a100fc47a83c36613b38fa4e78ae6 | jbobo/leetcode | /tracking_feature_requests.py | 702 | 3.765625 | 4 | #!/usr/bin/env python3
from heapq import heappop, heappush
def get_most_requested_features(features, feature_requests, target_count):
"""TODO: Do the thing.
"""
top_features = []
frequency_heap = []
print(heappush(frequency_heap, (1, "A")))
return top_features
if __name__ == "__main__":
... |
7c373a0708f8176efd6708c77a6310eb232d00fa | Liam-McQueen04/Password-Locked-Ticket-Prices | /password tickets.py | 467 | 3.890625 | 4 | #Liam McQ - Password Locked Ticket Prices
print("Please log in...")
password = str("sesame")
enter = True
tp = int("10")
while enter == True:
test = input("Enter your password.\n")
if test == password:
enter = False
print("You have been logged in.")
else:
enter = True
... |
b18cfcb33c497b1464e6f906c5cfd12936326c06 | pythohshop/pythonintro | /loop/while2.py | 161 | 3.75 | 4 | s = "Do you have any questions?"
len_of_s = len(s)
# print each characters of s in new line
count = 0
while count < len_of_s:
print(s[count])
count += 1 |
4f559a67ea7956f6bd1f0393d0eaf24dd9e59687 | NO0N3-17/ShapeAI_netsec | /hash.py | 122 | 3.53125 | 4 | import hashlib
text=input("Enter Input :")
res = hashlib.md5(text.encode())
print("This is md5 Hash :",res.hexdigest()) |
694695bf590b81f6af821f85256df49f4e526725 | kefirzhang/algorithms | /leetcode/python/medium/p142_detectCycle.py | 691 | 3.65625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersect(self, head: ListNode):
hare = head
tortoise = head
while hare and hare.next:
hare = hare.next.next
tortoise... |
9c1db4306e7bc06903f3e230ccf6e9e9f2bdd56f | Vieiraork/Python-Learn | /Ex083.py | 272 | 4 | 4 | soma = p1 = p2 = 0
expressao = str(input('Digite a expressão matemática: '))
for p in expressao:
if p == '(' or p == ')':
soma += 1
if soma % 2 == 0 and soma != 0:
print('Expressão válida!')
else:
print('Expressão inválida, tente novamente!')
|
6fe1f7d52746668ce3d773eed7cbd7e0bbe742f7 | virgilraj/python-interview | /string/anagram.py | 983 | 4.1875 | 4 |
def is_anagram(X,Y):
# if X's length is not same as Y's, they can't be anagram
if len(X) != len(Y):
return False
#Create empty dict
freq = {}
# maintain count of each character of X in the dict
for i in range(len(X)):
freq[X[i]] = freq.get(X[i],0) + 1
for i in rang... |
df1fca697e75bd79304c2ada043492491dcfd6ab | prasunchakra/Happy-Coder | /Chamber Of Arrays/InfiniteArraySearch.py | 952 | 4.0625 | 4 | """
Find position of an element in a sorted array of infinite numbers
"""
def binarySearch(arr,l,h, key):
# print(l,h,arr)
if h >= l:
mid = (l+h)//2
# print(mid)
if arr[mid]==key:
return mid
elif arr[mid]>key:
return binarySearch(arr,l,mid-1,key)
... |
91ca4a143dba178286f57a427826f19713d224bf | GavinPHR/code | /phase1/14.py | 636 | 3.65625 | 4 | # Longest Common Prefix
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs == []:
return ""
i = 0
while True:
try:
tmp = [x[i] for x in strs]
except Exception:
return str... |
dc0e34241ad99cbabcc6068a8be8de2fa470a659 | SophiaPankeyeva/data-structures | /Task7.py | 800 | 3.609375 | 4 | from os import system
#----------- Функція для знаходження кількості всіх входжень підрядка в рядок
def my_matches_count(text, pattern):
count = 0
for i in range(len(text) - len(pattern) + 1):
result = True
for j in range(len(pattern)):
if text[i+j] != pattern[j]:
... |
b9f10ab076b81a42e08c8532f21eafe643ededd5 | PaulRaUnite/parall-distr-systems | /count triangles/mapper.py | 230 | 3.59375 | 4 | import sys
def flip(x: int, y: int) -> (int, int):
if x < y:
return y, x
return x, y
for line in sys.stdin:
v1, v2 = line.split()
if v1 != v2:
v1, v2 = flip(v1, v2)
print(f"{v1}\t{v2}")
|
61269f6c768d5965e50de89834b6d89fad9c88b1 | RidaATariq/ITMD_413 | /Assignment-2/Module-3_Lopping/while-loop-2.py | 462 | 4.1875 | 4 | '''
This program demonstrates the concept of while loop.
'''
import random
# Generate a random number to be guessed
number = random.randint(0, 100)
print("Guess a magic number between 0 and 100")
guess = -1
while guess != number:
guess = eval(input("Enter your guess: "))
if guess == number:
print("... |
00061c95740367e698163568bc2f03d4da2b1a26 | apillalamarri/python_exercises | /lesson04_csvtolist.py | 637 | 4.5 | 4 | # Challenge level: Beginner
# Goal: Using the code from Lesson 3: File handling and dictionaries, create a function that will open a CSV file and return the result as a nested list.
def csv_to_list(csv_file):
"Takes a csv file (csv_file) and returns a nested list version of it"
lines = csv_file.read().split("\n")
... |
bba719f97f4f4fcb6153593a82693f7c64b6c5f5 | dicao425/algorithmExercise | /LintCode/binaryTreePathSum.py | 1,003 | 3.859375 | 4 | #!/usr/bin/python
import sys
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: the root of binary tree
@param: target: An integer
@return: all valid paths
"""
def bi... |
10a90cd40f0209cbef0f30e4a5c934634ac2d1e7 | FadhlihHasanSetiawan/Praktikum-Algopro | /kegiatan praktikum 12/L200194209/cgi-bin/prisma.py | 1,051 | 3.671875 | 4 | def hitung_luas(X,Y,Z):
L = 2 * X + Y * Z
return L
print("<!DOCTYPE html>\n")
print("""<html>
<head>
<title> Kegiatan 3 </title>
</head>
<body>
<table border="0">
<tr>
<td colspan="4"><p align="center"><b> Bangun Geometri </b></p></td>
</tr>
<tr>
<td> Nama Bangun... |
0a920c44eb61b9173ef01aa49e3761ed84728b1e | luckspt/prog2 | /fichas/6_csv/main.py | 5,331 | 3.984375 | 4 | import csv
def ler_csv(nome_ficheiro, delimiter=','):
"""Ler um ficheiro CSV
Args:
nome_ficheiro (str): O nome do ficheiro
Returns:
list[list][str]: O conteúdo do ficheiro.
Cada elemento da lista contém uma linha do ficheiro CSV.
Cada string corresponde a um valor ... |
73122032ef13e27a80e77ff4d35f290c337db5b1 | glycoinfo/GlyCovid | /PSICQUIC/uri_list/treat_uri_list.py | 1,873 | 3.59375 | 4 | import csv
def csv_to_dict():
# 両末端のスペースを取る?
csv_dict = dict()
with open("uri_list/object_uri_list.csv") as f1:
reader = csv.reader(f1, delimiter=",")
next(reader)
for row in reader:
csv_dict[row[0]] = dict()
csv_dict[row[0]]['uri'] = row[1]
try:
... |
18a0d7eaba5b7be0f53f4401ddc7df50d9263705 | aman-saurabh/python-basics | /sec5-variable-scope/part3_global_scope.py | 3,089 | 4.71875 | 5 | """
A variable declared in the main body of the Python file(or module) is called global variable and
belongs to global scope. Global variables are available anywhere within the file i.e inside any function
as well as outside any function, but we can't modify a global variable inside a function directly.
For such requir... |
31c3693d2c7f445bb4273a19a4fb9761334f2412 | docxed/codeEjust | /Ascending.py | 397 | 3.8125 | 4 | """main"""
def slide(num):
"""slide sording"""
for i in range(len(num)):
small = i
for j in range(i+1, len(num)):
if num[small] > num[j]:
small = j
num[i], num[small] = num[small], num[i]
return num
def main():
"""main"""
num = [int(input()) for ... |
13059b8ff84e9a26b134b6fab4570def98b1bb23 | d3zd3z/euler | /python3/sieve.py | 3,043 | 3.65625 | 4 | #! /usr/bin/env python3
"""
A simple prime number sieve.
"""
from collections import namedtuple
# Using bitarray will use a lot less memory, but is actually slower.
Factor = namedtuple('Factor', ['prime', 'power'])
class Sieve:
def __init__(self):
self._fill(8192)
def _fill(self, limit):
... |
0e3501669e3f6560f1d694ab4c737df25849ff9d | AngrySamaritan/ilearningTask1 | /src/project/model/person.py | 322 | 3.765625 | 4 | """Module for class Person"""
class Person:
"""
Class for person record
"""
def __init__(self, name, number, address):
self.name = name
self.number = number
self.address = address
def __str__(self):
return self.name + " | " + self.address + " | " + self.number + "\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.