blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4e43fa920b2b5f733f1d80d7088e256d6831a8a4 | Maxington20/Python-Udemy-Course | /BasicLessons/Tkinter-helloworld.py | 293 | 3.703125 | 4 | from tkinter import * # This imports everything from tkinter
root = Tk() # object of tk class called root
label1 = Label(root, text="Hello World") # object of label class, pass in root, and text to display
label1.pack()
root.mainloop() # causes window to only close when we tell it to |
b7b32021faa1e5ab3441843e18a8f06d518a6704 | WorryingWonton/Monopoly | /tiles.py | 20,641 | 3.90625 | 4 | import attr
import monopoly
import ownable_item
from math import floor
from auction import Auction
class Structure(ownable_item.OwnableItem):
"""
My code will handle buying and selling Structures in the following ways:
-Buying Structures:
-The Option to buy a structure should only appear ... |
28c6b1981327cbb56e65d23ac856c8205739ffb6 | rouemma1/dd-adapter-exercice | /sdk/eventlogger.py | 735 | 3.546875 | 4 |
class StringEvent(object):
def __init__(self, msg, timestamp):
"""
:param msg (string): A message that happened
:param timestamp (int): The time at which this message happened
"""
self.timestamp = timestamp
self.msg = msg
class EventLogger(object):
"""
Even... |
55d72af9652fd818c96f237767bffe4c70b5073d | VishalGohelishere/Python-tutorials-1 | /programs/gcd.py | 303 | 4.09375 | 4 | # GCD is we take two numbers and check that the highest number which divides both the values is called as GCD
v1 = input("Enter 1st value ")
v2 = input("Enter 2nd value ")
v1 = int(v1)
v2 = int(v2)
i=1
while i<v1 and i<v2:
if v1%i==0 and v2%i==0:
gcd = i
i = i+1
print("GCD is ",gcd) |
cf25197bdec395ea48e7481dabdda10b09accd53 | wesenu/Data-Structures-2 | /Data Hiding.py | 614 | 3.78125 | 4 | '''
class Demo:
def __init__(self,v):
self._tu = v
self.__tum = 20 #hidden
obj = Demo(10)
print(obj._tu)
#print(obj.__tum)
#We can print hidden variables
print(obj._Demo__tum) #Fully qualified name (FQN)
'''
'''
class SEQ:
_x = 949 #static member
__h = 666 #static. h... |
cfc49875f4f2d91fe2947ccb82494f39ef893dfb | EduChancafe/T08_Chancafe.carrion | /longitud.py | 1,569 | 3.546875 | 4 | #ejercicio1
nombre="eduardo"
longitud=len(nombre)
print("la longitud de la cadena es :",longitud)
#ejercicio2
apellido="chancafe"
longitud=len(apellido)
print("la longitud de la cadena es:",longitud)
#ejercicio3
deporte="futbol"
longitud=len(deporte)
print("la longitud de la cadena es:",longitud)
#ejercicio4
curs... |
1b02e74940d6979bfbf21442423e9131dc359e43 | dinuionica08/Projects.py | /Basics/operators.py | 310 | 4.40625 | 4 | # arithmetic operators
print (1 + 2)
print (1 - 2)
print (1 * 2)
print (1 / 2)
print (1 ** 2)
print ( 1 % 2)
# logical operators
if 2 == 2 and 3 > 1:
print("True")
if 2 == 2 or 3 == 3:
print("True")
if not (2 < 3):
print("False")
#comparation operator
if 4 < 2 :
print("4 is the greater") |
798595f5a595150edbe5c9496c45c5ad4d412822 | dwhagar/AveryThesisProcessor | /speaker/speaker.py | 2,237 | 3.8125 | 4 | from .age import Age
class Speaker:
"""A class to store information about a speaker."""
def __init__(self, sid = None, role = None, name = None, sex = None, age = None, language = None):
self.sid = sid.strip()
self.role = role.replace("_", " ").strip()
# Some names are not filled in, re... |
dcd7cbac66a820aeddf02e430bdbde80af351a9c | lokendra7512/Project-Euler-Solutions | /problem_30.py | 437 | 3.625 | 4 | '''
4*(9**5) = 236196
5*(9**5) = 295245
6*(9**5) = 354394
7*(9**5) = 413343 #So the highest possible sum of a 7-digit no is 6 digits
(which is less than the original 7 digit no) so the upper limit is 6
'''
def sum_powers(n,power):
sums = 0
while n > 0:
remainder = n % 10
n = n / 10
sum... |
e63262cb548ff309671c4dc7e5d147b37ee30bfb | marcelo-py/Exercicios-Python | /exercicios-Python/desaf105.py | 474 | 3.5625 | 4 | def notas(*n, sit = False):
notas = dict()
notas['total'] = len(n)
notas['maior'] = max(n)
notas['menor'] = min(n)
notas['média'] = sum(n)/len(n)
if sit:
if notas['média'] >= 7:
notas['situação'] = 'Boa'
if notas['média'] >= 5:
notas['situação'] = 'Razoáve... |
401d9f8aa09b89dc7fdf298bdafd773774fdfca5 | vc2000/python-pandas-basic | /ud-101.py | 622 | 3.9375 | 4 | import pandas
df1 = pandas.read_csv("supermarkets.csv")
df1 = df1.set_index("Address")
#print(df1)
#df1_lim =df1.loc["735 Dolores St":"1056 Sanchez St","ID":"City"]
#print(df1_lim)
#df1_intercep = df1.loc["1056 Sanchez St","State"]
#print(df1_intercep)
"""
#only want everything in country
df1_US... |
6f000685064cf3e9b58ccde393b7be69e0390db3 | Vivianhuan/Python | /data/sitka_deathvalley_comparison.py | 1,725 | 3.515625 | 4 | import csv
from datetime import datetime
def get_weather_data(filename,dates,highs,lows,date_index,high_index,low_index):
with open (filename) as f:
reader = csv.reader(f)
header_row = next(reader)
for row in reader:
current_date = datetime.strptime(row[date_index],'%Y-%m-%d')
try:
high = int(ro... |
bbb4bd252024758f166f12b814e2311e1124c863 | SirSilver/crocobot | /game.py | 6,087 | 3.59375 | 4 | import random
import sqlite3
class Game:
def __init__(self, dbfile):
self.connection = sqlite3.connect(dbfile)
self.cursor = self.connection.cursor()
self.create_tables()
self.words_file = 'categories/words.txt'
self.celebrities_file = 'categories/celebrities.txt'
... |
c7bb3801635cdf2e2db0de322819cfbed38b89da | oylumseriner/Codes | /python exercise6 (Ackermann Function).py | 544 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#We try to compute the Ackermann Function A(m,n) with m,n. Now, we can use the this formula:
#if m=0,then use n+1
#if m>0 and n=0, then use A(m-1,1)
#if m>0 and n>0, then use A(m-1,A(m,n-1))
def A(m,n):
if m == 0:
return (n+1)
elif m > 0 and n == 0:
... |
97a36c47f899388dc0ff134b4b63b301cb265b2a | M-Amin-Mamdouhi/python-class | /Ex 7.py | 1,335 | 4 | 4 | '012'
a=input('please enter your first number: ')
b=input('please enter your second number: ')
if a>b:
print(a,b)
else:
print(b,a)
'013'
a=int(input('please enter your number: '))
if a<20:
print('thank you')
else:
print('too much')
'014'
a=int(input('please enter your number: '))
if a<=20 and a>=10:
... |
5a7af9626f1d5e84e382e8226461f3ffd6715a52 | ram5550/Luminardjango | /Luminarproject/flowcontrols/maximumnumber.py | 185 | 4.15625 | 4 |
num1=int(input("enter num1"))
num2=int(input("enter num2"))
if(num1>num2):
print("num1 is maximum")
elif(num2>num1):
print("num2 is maximum")
else:
print("both are equal") |
946ec975c2641f08318d4c7be3090eeb2f67b037 | chiheblahouli/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 237 | 3.640625 | 4 | #!/usr/bin/python3
"""
checks if the object is an instance of, or if the object is an instance
"""
def inherits_from(obj, a_class):
""" returns true if object is a subclass of a class """
return(issubclass(type(obj), a_class))
|
2b224a6004b8f26b68c8d14867ecb60c5e156591 | davidknoppers/interview_practice | /dynamic_programming/coin_change.py | 1,389 | 4.28125 | 4 | #!/usr/bin/python3
"""
Computes the total number of ways a value can be made with the given coins
It is assumed that there are infinite coins for each given denomination
Not properly tested for coin lists which exclude 1-cent coins
@coins is a list of coin denominations and @value is the $ value you're making change fo... |
46fbdc21b1eea9838e48eb4651634412ec6e3d2b | Newester/MyCode | /Py/Python/Debug.py | 980 | 3.96875 | 4 | #!/usr/bin/env python3
#使用 print 将变量打印出来,简单粗暴
def foo(s):
n = int(s)
print('>>> n = %d ' % n)
return 10 / n
def main():
foo('0')
#main()
#使用断言 assert
#如果断言失败会抛出 AssertionError
def foo_2(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main_2():
foo('0')
#main_2()
#可以使用 -0 参... |
99f0171f860694ccdd16715b8df6e419a363ae26 | Madhupreetha98/Python-Programming | /Beginner Level/prime range.py | 143 | 3.703125 | 4 | start=int(input())
end=int(input())
for num in range(start,end+1):
if num>1:
for i in range(2,num):
if num%i==0:
break
else:
print(num)
|
5bc96feabc3696f00e7b60bb3a33713e3a4d22a9 | iamOuko/pythonbasics | /numbers.py | 281 | 3.6875 | 4 | from math import *
print(2)
print(2.97)
print(3 + 4.5)
print(3 * 4 + 5)
print(10 % 3)
my_num = -5
print(my_num)
print(str(my_num) + " my favorite number.")
print(abs(my_num))
print(pow(4, 2))
print(max(4, 6))
print(min(7, 5))
print(round(3.7))
print(floor(3.7))
print(sqrt(36))
|
bb5d8b13189a9f773a610fc8b2760afe8a62352e | github5507/geeksforgeeks | /intro_to_tensorflow/basic1.py | 385 | 3.6875 | 4 | # importing tensorflow
import tensorflow as tf
# creating nodes in computation graph
node1 = tf.constant(3, dtype=tf.int32)
node2 = tf.constant(5, dtype=tf.int32)
node3 = tf.add(node1, node2)
# create tensorflow session object
sess = tf.Session()
# evaluating node3 and printing the result
print("Sum of node1 and ... |
c13f91578b17836fc193b32aa282aa63761974b6 | Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way | /ex03fp.py | 1,090 | 4.21875 | 4 | # statement
print "I will now count my chickens:"
#statement, followed by math (order of operations places multiplication BEFORE additon)
print "Hens", 25 + 30 / 6
#statement, followed by math (order of operations places multiplication & modulo BEFORE subtraction
#reading from left to right, multiplication comes first... |
34b32c1ea8146aae5b6cc1755b5ecd1376897a49 | thomas-hennessy-work/python-exercizes | /easy/isbn.py | 976 | 3.8125 | 4 | isbn = input("Please input the first 12 digits of the ISBN \n")
isbnList = []
isbnListClean =[]
total = int(0)
count = int(-1)
# https://www.geeksforgeeks.org/python-split-string-into-list-of-characters/
isbnList = [char for char in isbn]
# for x in isbnList:
# if x != "-":
# if int(x)%2 == 0:
# ... |
fb897fb0f89a729e8aef9ec9a2caa805620f2385 | hse-labs/PY111-template | /Tasks/f0_binary_search_tree.py | 1,060 | 3.78125 | 4 | """
You can do it either with networkx ('cause tree is a graph)
or with dicts (smth like {'key': 0, value: 123, 'left': {...}, 'right':{...}})
"""
from typing import Any, Optional, Tuple
# import networkx as nx
def insert(key: int, value: Any) -> None:
"""
Insert (key, value) pair to binary search tree
... |
3ddc01fc256f29865f3b45678309113313c90fbd | cyh1582081321/python_fuxi | /闰年.py | 398 | 3.875 | 4 | '''
闰年的判断
'''
year = int(input('请输入要判断的年份:'))
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
print("您要查询的年份是闰年!!")
else :
print("您查询的年份是平年!!")
else :
print("您要查询的年份是闰年!!")
else :
print("您查询的年份是平年!!")
|
60933470da20830620ad8b6e20223c360cb79827 | jihye-woo/algorithm-practice | /sort/K번째수.py | 298 | 3.515625 | 4 | def solution(array, commands):
answer = []
for i, j, k in commands:
target_array = []
for idx in range(i - 1, j):
target_array.append(array[idx])
target_array.sort()
kth_num = target_array[k - 1]
answer.append(kth_num)
return answer |
28a5568242905f7877d745686d940306cd1385f8 | dimasiklrnd/python | /highlighting numbers, if, for, while/List of squares.py | 890 | 4.15625 | 4 | '''По данному натуральному числу N распечатайте все квадраты натуральных чисел, не превосходящие N ,
в порядке возрастания.
ВАЖНО! В данной задаче необходимо использовать цикл.
Формат входных данных
На вход программе передается целое число N , не превышающее 10000.
Формат выходных данных
Программа должна распечатать... |
8cf16623f31c94326d903ff73caeb78a3acb4bf4 | offero/algs | /inversioncount.py | 2,061 | 3.9375 | 4 | """ Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k]
form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total
number of inversions of size 3.
"""
from binary_indexed_tree import BIT
def three_inversions_ctlower(arr):
"""
Count the number of 3 inversions by counting th... |
9db4e984fbcb644f2770dd4e71bbf634e607d71c | mihir20/HackerRank-algo | /catAndMouse.py | 559 | 3.734375 | 4 | #!/bin/python3
import sys
def greaterOF( a, b ):
if a>b:
return a
else:
return b
def catAndMouse(x, y, z):
ac = greaterOF(x-z,z-x)
bc = greaterOF(y-z,z-y)
if ac == bc :
return "Mouse C"
elif ac > bc:
return "Cat B"
else:
return "Cat A"
if __name__... |
4454863977c63df6e4358172d51c43dfaa23ca78 | DonkeyZhang/Python | /stage1/day02/game2.py | 971 | 3.90625 | 4 | #-*-coding:utf-8-*-
# way01:
import random
all_choice = ['石头', '剪刀', '布']
win_list = [['石头','剪刀'], ['剪刀','布'],['布', '石头']]
computer = random.choice(all_choice)
player = input('请出拳(石头/剪刀/布):')
print(('你出拳: %s , 电脑出拳: %s') % (player, computer))
if computer == player:
print('平局')
elif [player, computer] in win_list... |
b53ef35c271b457020ec88022cf1e2b112256485 | SamyakLuitel/Data_Structure_and_Algorithms | /Groking 's Algorithms/Chapter1/binarySearch.py | 433 | 3.875 | 4 | def binary_search(arr, item):
'''This function returns position of item in the list if found'''
low = 0
high = len(arr)-1
while low <= high:
mid = (low+high)//2
guess = arr[mid]
if guess == item:
return mid
if guess < item:
low = mid
else:... |
512b9c0b288e922fb210f70e4784ae6d687cbfda | Zatyi94/gyakorlas | /3.py | 430 | 4.09375 | 4 | # készíts programot ami kettő számot kér be és abból egy két dimenziós listát csinál
# pl: 2,3 -> [[0,1,2], [0,1,2]]
outer_list_length = int(input('ird be az elso szamot: '))
inner_list_length = int(input('ird be a masodik szamot: '))
nums = []
inner_nums = []
for num in range(0, inner_list_length):
inner_... |
e0ef267f32a3c5008ad3d8e4dfc04981691db5b6 | dacharat/python-practice | /code/ox_game/main.py | 338 | 3.640625 | 4 | from player import Player
from table import Table
size = int(input('Enter table size: '))
nb_of_players = int(input('Enter number of players: '))
sym_list = [input(f'Enter player{i+1} symbol: ') for i in range(nb_of_players)]
table = Table(size, nb_of_players, sym_list)
who_win = table.play()
print(f'Player"... |
93397fe881721e3554aa13c557ba82daa8e5b480 | Ronak912/Programming_Fun | /Bloomberg/SortStringByFrequency.py | 428 | 4 | 4 | #Give a string like "BBBCADDDD", return "DDDDBBBCA" with characters sorted by frequency.
def sortByFrequency(instr):
hashmap = {}
for char in instr:
hashmap[char] = hashmap.get(char, 0) + 1
outstr = ''
for key, value in sorted(hashmap.items(), key=lambda x: x[1], reverse=True):
outst... |
52e3612528fd4ef1ff7b1286ffc76db28676f69a | XiaoshuaiGeng/Python-Intro | /Section3/Tuples.py | 285 | 4.09375 | 4 | # Tuples
# Tuples are immutable with only 2 methods associated with them
newTuple = (1,1,2,3)
print(newTuple)
# Tuple methods
print('The index of number 3 is {}'.format(newTuple.index(3)))
print('The number of times that value 1 showing in the tuple is {}'.format(newTuple.count(1)))
|
1a2a3df6af1ae24aa36efccd49a7aa32132b8c72 | mjnorona/codingDojo | /Python/python_fundamentals/compareArrays.py | 761 | 3.953125 | 4 | def compArr(arr1, arr2):
if (len(arr1) != len(arr2)):
print "The lists are not the same"
else:
boo = True
for i in range(0, len(arr1)):
if arr1[i] != arr2[i]:
boo = False
break
if boo is True:
print "The lists are t... |
2f0f907c3e94c0f24dc04cba6e994ab1a8f21bae | JBielan/leetcode-py-js | /python/keyboard_row.py | 1,197 | 4 | 4 | class Solution:
def findWords(self, words):
first_row = ('Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p')
second_row = ('A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', ... |
c7f53112bc0c39fa1875fcbdb6b88f07124634fe | BartoszKopec/wsb-pios-python | /src/2020-05-28_raport.py | 2,245 | 4.3125 | 4 | list = ['a', 'b', 'c', 'c'] # stworzenie kolekcji która ma 4 elementy
print(list)
setFromList = set(list) # stworzenie zbioru z kolekcji który ma 3 elementy, ponieważ zostały zignorowane dane powtarzające się
print(setFromList)
setFromList.add('d')
print(setFromList)
setFromList.remove('a')
print(setFromList) # dodanie... |
86afc8bcf86640189d4b3f0a953183f37e080e7d | Mayur01/Python-Fun | /L3_1_identifyelement.py | 266 | 3.859375 | 4 | from collections import *
def countfreq(list):
return Counter(list)
print("Enter list of variavbles:")
list = [int(x) for x in input().split()]
freq = countfreq(list)
sortedDict = dict(sorted(freq.items(), key=lambda x: x[1]))
print(next(iter(sortedDict)))
|
94ce852d3acdc47817916f0b220dcd4e878279f1 | dlaststark/machine-learning-projects | /Programming Language Detection/Experiment-2/Dataset/Train/Python/middle-three-digits-1.py | 1,481 | 4.03125 | 4 | >>> def middle_three_digits(i):
s = str(abs(i))
length = len(s)
assert length >= 3 and length % 2 == 1, "Need odd and >= 3 digits"
mid = length // 2
return s[mid-1:mid+2]
>>> passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345]
>>> failing = [1, 2, -1, -10, 2002, -2002, 0]
>>> for x ... |
39c203625a93b204b5b1ce1ff70729d7741e31e8 | sistemasmarcelocastro/pruebas-python | /cursoPython1/s7l17-py.py | 393 | 3.625 | 4 | # diccionarios
"""
gato = {'tamaño': 'gordo', 'color': 'blanco', 'animo': 'apapachero'}
print(gato['tamaño'])
for k, v in gato.items():
print(k + ' contiene ' + v)
"""
import pprint
mensaje = 'Qué lehabrán hacho mis manos, qué le habrán hecho...'
cuenta = {}
for letra in mensaje.upper():
cuenta.setdefault(let... |
0812161b3c7d83389f91c33e0a47e418170f45c7 | lavhaleakshay/datastructures-python | /linked-list/reverse_linked_list.py | 1,979 | 4.03125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
... |
f508b7ed12649dd075a012e2da9c4372bf56f460 | TGathman/Codewars | /7 kyu/Isograms/Isograms.py | 166 | 3.734375 | 4 | # Python 3.8, 20 March 2020.
def is_isogram(string):
for i in string.lower():
if string.lower().count(i) > 1:
return False
return True
|
b18213c864bf7f55e357f3c840ea188cd31d5e65 | ontheone04/dc-cohort-week-1 | /day2/Calculator.py | 452 | 4.1875 | 4 | First_num = input('Enter first number:\n')
symbol = input('Enter Operation (+, -, *, /):\n')
Second_num = input('Enter Second Number:\n')
First_num = float(First_num)
Second_num = float(Second_num)
out = None
if symbol == '+':
out = First_num + Second_num
elif symbol == '-':
out = First_num - Second_num
elif... |
d06d85d049b5e9608090a2e70f95ac4877f12c3d | faheelsattar/Python-for-fun | /recursion/allpossiblepalindromicpartitions.py | 696 | 3.640625 | 4 | def partitions(value ,array:list):
if len(value) == 0:
print(array)
return
else:
holder=''
for val in value:
holder+=val
if palindrome(holder):
array.append(holder)
value=value[1 : : ]
partitions(value, array)
de... |
5c70b4e5f613c91985f2c468e4f166c3841f601c | KarateJB/Python.Practice | /src/TensorFlow/venv/Lab/Tutorials/Basic/zip.py | 137 | 3.640625 | 4 | a = [11,22,33,44,55,66,77,88,99]
b = [1,2,3,4,5,6,7,8,9]
print(list(zip(a,b)))
print(*zip(range(0, len(a), 2), range(2, len(a)+1, 2)))
|
d6cd9ae6fbe46ba677d31368ffade1a3a608f44d | vMorane/Excerc-cios | /Exercícios/Ex13.py | 193 | 3.9375 | 4 | a = int (input("Digite o 1º nº:"))
b = int (input("Digite o 2º nº:"))
if (a > b):
print("Primeiro maior")
elif: (a = b):
print("São iguais")
else:
print("Segundo maior") |
3dd184f72d35c0868cd5066cb720d89b8a2568ca | AlexanderPort/NNToolkit | /gui/VisualElements/utils.py | 632 | 3.71875 | 4 | import math
def curve(x1: int, y1: int, x2: int, y2: int) -> list:
mx = (x2 - x1) / 2
my = (y2 - y1) / 2
c1 = [x1, y1 + my]
c2 = [x2, y2 - my]
steps = 0.001
points = []
angle = 1.5 * math.pi
goal = 2 * math.pi
while angle < goal:
x = c1[0] + mx * math.cos(angle)
y ... |
4f029613989461e81e71f0590b41eadd473c3585 | chatton/ProgrammingChallengeQuestions | /python/sort-the-odd.py | 685 | 4.25 | 4 | """
Description:
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
"""
def sort_... |
45991f492cffdb79a6b1c978671c3e27c23b806f | go2bed/python-functions | /com.go2bed.functions/Functions.py | 541 | 4.09375 | 4 | def my_fun(string):
print(string)
my_fun('Hello')
def greeting(name):
print("Hello " + name)
greeting('Jose')
def add_num(num1, num2):
return num1 + num2
x = add_num('goo', 'gle')
y = add_num(2, 3)
print(x)
print(y)
def is_prime(num):
"""
This function checks for prime numbers
:param... |
94a311fc5b660db843de5fc391cd1106a47b3738 | CaioHRombaldo/PythonClasses | /Ex019 v2.py | 422 | 4.125 | 4 | from random import choice
print('=--Student name picker--=')
print('How many students do you want to register?')
nStudents = int(input('Number of students: '))
students = []
index = 0
while index < nStudents:
studentName = input('Enter the name of student number {} '.format(index + 1))
students.append(studen... |
c26d2da341500f1dd8513081a00a0de6981da65e | alvinzhu33/6.0002 | /PSet 2/graph.py | 5,045 | 4 | 4 | # 6.0002 Problem Set 2
# Graph Optimization
# Name: Alvin Zhu
# Collaborators:
# Time: 4
#
# A set of data structures to represent the graphs that you will be using for this pset.
#
class Node(object):
"""Represents a node in the graph"""
def __init__(self, name):
self.name = str(name)
def get_na... |
be0716adeb8791ae142c7c8cec389fa890c9c273 | potatoHVAC/leetcode_challenges | /algorithm/988.2_smallest_string_starting_from_leaf.py | 1,353 | 3.765625 | 4 | # Smallest String Starting From Leaf
# https://leetcode.com/problems/smallest-string-starting-from-leaf/
# Completed 5/6/19
# I added dynamic
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def to_letter... |
ce6c764e50e7c800706f9ba27941d4d389734d37 | ntupenn/exercises | /medium/356.py | 851 | 3.671875 | 4 | """
Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given set of points.
Example 1:
Given points = [[1,1],[-1,1]], return true.
Example 2:
Given points = [[1,1],[-1,-1]], return false.
Follow up:
Could you do better than O(n2)?
Hint:
Find the smallest and largest x-va... |
ec344f6af3391c9c20ae74fe055c446fac0ecf0d | Arnabsaha6/Chess-with-Python | /Chess Game/board.py | 50,564 | 3.703125 | 4 | #Initiliazes the global variables to keep up with the states in chess
KingcastlingStateWhite = True
KingcastlingStateBlack = True
QueencastlingStateBlack = True
QueencastlingStateWhite = True
whiteUnderCheck = False
blackUnderCheck = False
whiteMoveMade = False
checkMate = False
class Board:
#initialize the board a... |
7f1fcf06375b00e37d2392f156dca1eed924db7e | PengchongLiu/Algorithms | /w2_grundy_table.py | 1,296 | 3.59375 | 4 | #! python3
def mex(nums) -> int:
'''
Find the smallest non-negative integer in a list by create a Python set
'''
tmp = set(nums)
cnt = 0
for t in tmp:
if t != cnt:
return cnt
cnt += 1
return cnt
def findGrundy(G: list, V: int, W: int) -> list:
for v in ran... |
f05c03f1e56759cf3a119d27dfaee4806b197b2f | leonhanimichi/Evangelion | /references/basicStockTrader.py | 17,739 | 3.671875 | 4 | #!/usr/bin/python
'''
Created on Aug 15, 2017
@author: Leon (Jobs), Junaid (Woz)
'''
import pandas as pd
import numpy as np
import random as rrand
import math as math
from pandas_datareader import data as dreader
from pylab import * #Used to calculate Mean and maybe more stuff didn't check, can probably replace/get ... |
e758cfe3685fd64fc3bd2e1466e6b278350d5fed | hwang033/job_algorithm | /py/Balanced_Binary_Tree.py | 1,001 | 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:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
if not root:
return True
... |
1a3110962c2ad63820ff69b0774eb7ba586e8f91 | SanGReaL53/Class | /OddEvenSeparator.py | 343 | 3.640625 | 4 | class OddEvenSeparator:
def __init__(self):
self._odd = []
self._even = []
def add_number(self, num):
if num % 2 == 1:
self._odd.append(num)
else:
self._even.append(num)
def even(self):
print(self._even)
def odd(self):
... |
f23d8c51b7fa1e32ca57e9416719a10fc5efcbd1 | storans/as91896-virtual-pet-GBarrand7 | /death_checker.py | 1,835 | 4.28125 | 4 | # Function to check if the cat has died or is near death
# Parameters:
# Weight - weight of pet
# Low - lowest possible weight
# High - highest possible weight
# Boundary - range above the lowest weight or below the highest weight that if the cat's weight is in it is near being too low or high
def death_checker(weight,... |
aa98b3d9a66da7bf667e87fc26d4fa85dc114528 | mspontes360/Programacao-Python-Geek-University | /section5/exercicio20.py | 892 | 4.09375 | 4 | """
Dados três valores, A, B, C, verificar se eles podem ser valores dos lados de um
triângulo e, se é um triângulo escaleno, equilátero ou isóscele, considerando os
seguintes conceitos:
# O comprimento de cada lado de um triângulo é menor do que a soma dos outros
dois lados.
# Chama-se equilátero o triân... |
c4326c4fb16248380e2aa0b857828a6d1e6dbd91 | vzamyati/piscine_django | /d01/ex05/all_in.py | 1,418 | 3.9375 | 4 | import sys
def look_for_state(trim_param, states, capital_cities):
trim_param = trim_param.lower()
trim_param = trim_param.title()
if not states.get(trim_param):
return 0
elif capital_cities.get(states[trim_param]):
return(capital_cities[states[trim_param]])
else:
return 0
def look_for_capital(trim_param... |
35656a3598781b8da855b8d0c4dd34ffa22a0b4b | dbmccoy/data | /pdx/generators.py | 2,154 | 3.96875 | 4 | def count_above_threshold(filename, threshold=6, column_number=2):
with open(filename) as fi:
headers = next(fi)
return sum(1 for line in fi if float(line.split(",")[column_number]) > threshold)
## CHALLENGE 1: Generate a small CSV and prove to yourself that the above works.
from random import normalvar... |
e13be476a189c97c2dd425c604492f6aaef62ac2 | jeffwright13/codewars | /multiple_split.py | 1,239 | 4.5 | 4 | def main():
print multiple_split.__doc__
def multiple_split(str, delimiters=[]):
"""
Give me a multiple_split
=================
https://www.codewars.com/kata/split-string-by-multiple-delimiters
=============================================
Your task is to write function which takes string a... |
de1874dbdd0006c0660df5d8643cbed7566a0916 | Volodymyr-SV/Python_367 | /ClassWork1.py | 362 | 3.90625 | 4 | a=int(input("a="))
b=int(input("b="))
if a<b:
print(b,">",a,", b bilshe")
elif a>b:
print(a,">",b,", a bilshe")
else: print(a,"=",b,", rivni")
#######################
c=int(input("c="))
if c % 2 == 0 :
print("parne")
else: print("neparne")
########################
d=int(input("d="))
f=1
for i in ran... |
8b0589ae4e32d42cdf071154b7ad1542f93c556a | HighHopes/codewars | /6kyu/Transform To Prime.py | 1,390 | 4.1875 | 4 | """Given a List [] of n integers , find minimum mumber to be inserted in a list, so that sum of all elements of list should equal the closest prime number .
Notes
List size is at least 2 .
List's numbers will only positives (n > 0) .
Repeatition of numbers in the list could occur .
The newer list's sum should equal... |
e33cfea21759fb6adabf13f6ffc36b79e3f18f9b | sehammuqil/python- | /day34.py | 743 | 4.3125 | 4 | def my_function(food):
for x in food :
print(x)
fruits = ["apple","banana","cherry"]
my_function(fruits)
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
def my_function(child3, child2 , child1):
print("the youngest child is " ... |
fc6b2246556488a48b9ff4b0b75ddfdc82decca3 | officialstephero/codeforces | /Codeforces solutions/Bit++.py | 213 | 3.59375 | 4 | n = input()
operations = []
for i in range(int(n)):
k = input()
operations.append(k)
operations = "".join(operations)
plus = operations.count('++')
minus = operations.count('--')
x = plus - minus
print(x)
|
7d69a3f5fd473da6799f368d38bff6943b9b29de | kkotha4/Machine-Learning | /models/Softmax.py | 2,984 | 3.984375 | 4 | import numpy as np
class Softmax():
def __init__(self):
"""
Initialises Softmax classifier with initializing
weights, alpha(learning rate), number of epochs
and regularization constant.
"""
self.w = None
self.alpha = 0.2
self.epochs = 300
self... |
f3d31e42f7df36016d2fca4153b2188cb2b82566 | RodolpheBeloncle/100-days-Python | /oop-coffee-machine-start/main.py | 2,375 | 3.515625 | 4 | import coffee_maker
import menu
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
# Data
MyCoffeeMachine = CoffeeMaker()
Latte_Item = MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5)
Espresso_Item = MenuItem(name="espresso", water=50, milk=0, ... |
67390dc60c286926f88a6a6c94a127bf6bf928a8 | ajpiter/CodeCombat | /Forest/ThumbBitter.py | 447 | 3.78125 | 4 | # If-statement code only runs when the if’s condition is true.
# In a condition, == means "is equal to."
if 2 + 2 == 4:
hero.say("Hey!")
if 2 + 2 == 5:
hero.say("Yes, you!")
# Change the condition here to make your hero say "Come at me!"
if 3 + 4 == 7: # ∆ Make this true.
hero.say("Come at me!")
if 2 + 1... |
e2f785930ffc5a05a99780d4e502b7299f601416 | V2xray1024/pyHack | /流程控制.py | 1,150 | 4.25 | 4 | '''
Description: python 流程控制练习
Author: yrwang
Date: 2021-08-30 18:25:59
LastEditTime: 2021-09-02 21:39:16
LastEditors: yrwang
'''
# 单分支/双分支
age = int(input("your age is:"))
if age < 25:
print("you are a little boy!")
else:
print("you are old boy!")
# 多分支
'''
if
elif
else
'''
girl_age = 30
count = 0
while coun... |
717d1e282f411a8bf9113fb6aa9dd8fc6de4f9af | kcnti/schoolWorks | /hackerrank/findingPercentage.py | 351 | 3.53125 | 4 | nums = int(input('how many: '))
lstName = []
for i in range(nums):
_all = input("Put name and number: ")
name = _all
name = lstName.append(_all[0])
number = [int(x) for x in _all.split() if x.isdigit()]
query_name = str(input("Who: "))
print(number)
print(lstName)
if query_name in lstName:
print... |
3e8c12e94ea0cb5dcdac63cf5eb76589f168cae0 | SonawaneMayur/Algorithms_using_Data_Structures | /Python Code/Find Kth char.py | 495 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 17:52:11 2017
@author: Mayur
"""
#code
def getKthBit(bin_digit, blockId, offset):
seed_value = int(bin_digit[blockId])
if seed_value:
return (1^(bin(offset).count('1') % 2))
else:
return ((bin(offset).count('1')) % 2)
for i in rang... |
89d24d1adb7792c3b7a6da995ba0361f7d5fac33 | Manib92/Codewars | /5 Kyu/Weight for weight.py | 2,229 | 4.0625 | 4 | """
Weight for weight
My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried
because each month a list with the weights of members is published and each
month he is the last on the list which means he is the heaviest.
I am the one who establishes the list so I told him: "Don't worry any mor... |
e571171f78b0069b529c1e429f8c0a1250323096 | gbrayhan/Learn-Python | /Advance_3.py | 549 | 4.15625 | 4 | #Decalracion y conjuntos
print('\n' *100)
conjunto=set('8794')
conjunto2={'3','2','4'}#Conjunto definido
print(conjunto)
print(conjunto2)
#operaciones con conjuntos
print(conjunto & conjunto2)#operacion interseccion
print(conjunto.intersection(conjunto2))#Otra forma
print(conjunto.union(conjunto2))# no se repit... |
b47ddca4fb16bc61585d6def82a0e704f8215a58 | darrencheng0817/AlgorithmLearning | /Python/interview/practiceTwice/KthNumber.py | 209 | 3.796875 | 4 | '''
Created on 2015年12月1日
https://leetcode.com/problems/kth-largest-element-in-an-array/
@author: Darren
'''
def findKthLargest( nums, k):
pass
nums=[3,1,4,5,6,2,8,7]
print(findKthLargest(nums, 3)) |
23991770683bfebf659e30db197d5c12b35bb945 | Chalmiller/competitive_programming | /python/algorithms/arrays/sort/block_swap.py | 399 | 3.734375 | 4 | def swap(arr, index1, index2):
temp = arr[index1]
arr[index1] = arr[index2]
arr[index2] = temp
def leftRotate(arr, d, n):
if (d == 0 or d == n):
return
i = d
j = n - d
while ( i != j):
if (i < j):
swap(arr, d - i, d + j - i, i)
j -= i
else:
... |
49ffeaa0641c89b71674ec43a9294a5abdebdb50 | peter-tang2015/cplusplus | /PetersPyProjects/PetersPyProjects/Dictionary/DictionaryTrie.py | 3,645 | 3.671875 | 4 | import sys
class DictionaryTrie(object):
"""DictionaryTrie class"""
def __init__(self):
self.value = None
self.children = dict()
for idx in range(0, 26):
self.children[ord('a') + idx] = None
def GetChildren(self):
return self.children
def GetValue(self... |
1e44b3da8ab5626dcf427a3ee3e9967df60f7cd7 | Angelpacman/codecademy-py3 | /Unit 05 Lists & Dictionaries/02 A Day at the Supermarket/1 Looping and lists/1-beFOR we begin.py | 1,117 | 4.8125 | 5 | """BeFOR We Begin
Before we begin our exercise, we should go over the Python for loop one more time. For now, we are only going to go over the for loop in terms of how it relates to lists and dictionaries. We'll explain more cool for loop uses in later courses.
for loops allow us to iterate through all of the elements... |
50d370309add178cdcc66fdc5880e60c1351f407 | cs-fullstack-2019-fall/python-review2-cw-dekevion-hamida | /Dekevion.py | 1,734 | 4.625 | 5 | # Create a task list. A user is presented with the text below.
#Congratulations! You're running [YOUR NAME]'s Task List program.
# What would you like to do next?
# 1. List all tasks.
# 2. Add a task to the list.
# 3. Delete a task.
# 0. To quit the program
# Let them select an option to list all of their tasks, add ... |
183ed6ab72e9d462ef70605f7df6f085bff96a99 | 1992kly/grab-test | /first1.py | 377 | 3.546875 | 4 | def sumto(nums, tar):
if len(nums):
dic = {}
for num in nums:
dic[num] = num
for num in nums:
diff = tar - num
if diff in dict.keys():
print("[%d,%d]" % (num, diff))
else:
print("no exit")
else:
print... |
20cb3eac9f9dbff9c1f13773d28d5949462f9d74 | ztxcyk/python_test | /python100/20190527/def2.py | 955 | 3.703125 | 4 | # def gcd(x, y):
# (x, y) = (y, x) if x > y else (x, y)
# for factor in range(x, 0, -1):
# if x % factor == 0 and y % factor == 0:
# return factor
#def lcm(x, y):
# return x * y // Mygcd(x, y)
#
#
#def Mygcd(x, y):
# (x, y) = (y, x) if x > y else (x, y)
# a=1
# for factor in ra... |
229159b871beb70d22781a6503d06696e2608689 | KlimchukNikita/Software_Engineering | /Lab 4/Sketch 7.py | 859 | 4 | 4 | #«Второй максимум»
# Ввести последовательность S и вывести второй максимум этой последовательности,
# т. е. элемент a∈S : ∃ b∈S : b>a и a⩾c ∀c∈S, c≠b
# Если второго максимума нет, вывести NO
# Пользоваться функциями наподобие max() или sorted() нельзя
mas = [7, 7, 7, 7, 7, 7]
maximum = mas[0]
for i in range(1, len(m... |
85425de022e851591a1d0417744e30942b11a7a9 | MaroderKo/Labs | /Kolokvium/Dopolnitelnie/39.py | 711 | 3.71875 | 4 | """39. Дані про температуру повітря і кількості опадів за декаду квітня
зберігаються в масивах. Визначити кількість опадів, що випали у вигляді дощу і у
вигляді снігу за цю декаду."""
import random
A = list()
rain = 0
snow = 0
for n in range(10):
nap = random.randint(0, 1)
if nap == 1:
A.append([True, r... |
f18ff381f42d2735fb8d58a6620bf4b23d1435f0 | VamshiPriyaVoruganti/HackerRank | /Programs/Introduction to Regex/hex color code.py | 162 | 3.609375 | 4 | import re
for _ in range(int(raw_input())):
color = "\n".join(re.findall(r':?.(#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3})',raw_input()))
if color!='': print(color)
|
6023187ab4a68a4a76cceafa9d64fe11d583b858 | mdolancode/Intro-To-Pytest | /tests/test_accum.py | 5,844 | 3.578125 | 4 | """
This module contains basic unit tests the the accum module.
Their purpose is to show how to use the pytest framework by example
"""
# ------------------------------------------------------------------
# imports
# ------------------------------------------------------------------
import pytest
from stuff.accum im... |
e8497fb8b6f1614a01ff5387157a0acfb5049950 | dsubhransu/pythonbeginner | /Day3_assingment/square_number.py | 184 | 4.03125 | 4 | def square_number_in_dictonary():
elements = int(input("Enter the elements"))
for i in range(1,elements+1):
print('{}:{}'.format(i,i*i))
square_number_in_dictonary()
|
9166772718b968ef75ab357a5199e81c128ca4c5 | irfanmaulana126/hacktiv8_py43 | /part_2/contoh_kondisi_2.py | 155 | 3.578125 | 4 | a = input("masukan angka: ")
a = eval(a) # ini langsung menentukan tipe data
if a % 2 == 0 and a > 5:
print("masukan kedalam kondisi")
else:
pass |
b756a91132488a7f03327ed64a443a42aa9e6647 | StreamlitTest1/TeamPurple_Movie-Recommender-App | /views/main.py | 1,796 | 3.546875 | 4 | import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data
import numpy as np
import pandas as pd
import random
class MainView(object):
def __init__(self):
self.load_data()
def load_data(self):
movies_df = pd.read_csv(
... |
0de29b2cf3730aeb6f7f498f568fe06d13f8bd49 | songjiabin/PyDemo | /2爬虫/1、urllib爬虫网页.py | 1,558 | 3.609375 | 4 | import urllib.request
# 向指定的url地址发起请求 ,并返回服务器响应的数据(文件的对象)
respose = urllib.request.urlopen("http://www.jjmima.top")
"""
这中读取方式不是很常用
# 得到二进制的数据 读取的事网页中的全部内容 会把读取到的内容赋值给一个字符串变量
data = respose.read()
# 得到 指定编码的数据 data =respose.read().encode("utf-8")
# 将得到的 data存储到文件中
path = r"E:\py_project_path\2爬虫\res\file.html"
... |
a6132b53c2c9df1071b97ea449342d4de1d2ee93 | dada99/python-learn | /builtin/string1.py | 353 | 4.03125 | 4 | str1 = '"Isn\'t," she said.'
print(str1)
s = 'First line.\nSecond line.' # \n means newline
print(s) # with print(), \n produces a new line
format_str = "this is {}'s books".format("Chris")
print(format_str)
print(format_str.capitalize())
print(format_str.count("s"))
first_name = "Chris"
last_name = "Liu"
print(f'... |
451bcef21f5541df1f3c7e84f9e986642442fe93 | Carbocarde/learn-python | /1 - Hello World/unittests.py | 741 | 3.859375 | 4 | """
Check if your script is correct using this file.
Run in the command line by typing:
python unittests.py
If you are in the PyCharm IDE, run this file by clicking the green arrow next to the main method:
if __name__ == "__main__":
"""
import unittest
from helloworld import hello
class TestHello(unittest.T... |
17d8c454ae1a1735bd95513d20557c50bbf55121 | MridulGangwar/Leetcode-Solutions | /Python/Easy/543. Diameter of Binary Tree.py | 729 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def dfs(node):
nonlocal ... |
84e0dc5fbd9764c6e7c08154c2d3b5d2fb7eddb6 | ryfeus/lambda-packs | /Pdf_docx_pptx_xlsx_epub_png/source/pptx/compat/python3.py | 812 | 3.75 | 4 | # encoding: utf-8
"""
Provides Python 3 compatibility objects
"""
from io import BytesIO # noqa
def is_integer(obj):
"""
Return True if *obj* is an int, False otherwise.
"""
return isinstance(obj, int)
def is_string(obj):
"""
Return True if *obj* is a string, False otherwise.
"""
... |
62d96ca31a2b08d8b1670be007b5c9e471f1a796 | vishnupsatish/CCC-practice | /2012/J5/J5.py | 3,278 | 3.9375 | 4 | """
Problem: CCC 2012 S4/J5
Name: Vishnu Satish
Solution: For each list, find all of the possible moves then perform a BFS for all of
the possible moves. Eventually, either return IMPOSSIBLE or the current level
"""
# Find all of the possible moves
def get_possible_moves(original):
possible_moves = []
# Itera... |
478e763acf55aa5d3b95eeb64476d42e34a445b1 | SoumyaDey1994/JS-Exercises | /Python/OOP Concepts/Class & Object/self parameter.py | 1,036 | 3.59375 | 4 | class ITCEmployees:
companyName="ITC Infotech"
def set_EmployeeDetails(self,name,designation,department,grade):
self.name=name;
self.designation=designation;
self.department=department;
self.grade=grade;
def print_EmployeeDetails(self):
print("Employee Name: " +self.... |
3cb1035408cfe7d536cc1bebf991d5d407aacce0 | LakshmiManasaNuthalapati/manas | /Largest.py | 209 | 4.09375 | 4 | num1=input("")
num2=input("")
num3=input("")
if(num1 >= num2) and (num1>=num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else
largest = num3
print(largest)
|
787868ef0259be160061bd8f980304bcb5c919b9 | gucky92/loris | /loris/app/wiki/utils.py | 1,836 | 3.671875 | 4 | """
"""
import re
from flask import url_for
def clean_url(url):
"""
Cleans the url and corrects various errors. Removes multiple
spaces and all leading and trailing spaces. Changes spaces
to underscores and makes all characters lowercase. Also
takes care of Windows style folders ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.