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 |
|---|---|---|---|---|---|---|
927cc97d115602ca74d6cdd9c76f85978e6e5a47 | adalloul0928/Leetcode_Hell | /Archive/test.py | 547 | 3.5 | 4 | class Solution:
def waitingTime(self, tickets, p):
# Write your code here
total = tickets[p]
half_1 = tickets[:p]
half_2 = tickets[p + 1:]
for n in half_1:
if n < tickets[p]:
total += n
else:
total += tickets[p]
... |
92061ea5cfe06ac053c0237a2d883b064b829b09 | adalloul0928/Leetcode_Hell | /Archive/climbingStairs.py | 736 | 3.8125 | 4 | class Solution:
# Recursive Slow Solution
# def climbStairs(self, n: int) -> int:
# sum = self.climbStairsHelper(n)
# return sum
#
# def climbStairsHelper(self, n):
# if n == 0:
# return 1
# elif n < 0:
# return 0
# else:
# retu... |
89151e72cbc23129d50a7dfe3f84e38bd2300793 | adalloul0928/Leetcode_Hell | /Archive/reverseList_206.py | 905 | 3.90625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
curr = head
while curr:
nextNode = curr.next
curr.next = prev
... |
91c428e358738e5f124022248a7867b912930c63 | adalloul0928/Leetcode_Hell | /Archive/Facebook/Dynamic/fibBottomUp.py | 274 | 3.59375 | 4 | class Solution:
def fibBottomUp(self, n):
memo = [1,1]
if n <=1:
return memo[n]
for i in range(2,n+1):
memo.append(memo[i-1] + memo[i-2])
return memo[n]
sol = Solution()
input = 10
print(sol.fibBottomUp(input)) |
96cb3de212f80af3a2835f6f69b4eefe39ed3543 | adalloul0928/Leetcode_Hell | /Archive/Facebook/Trees & Graphs/numIslands.py | 927 | 3.5 | 4 | class Solution:
def numIslands(self, grid) -> int:
count = 0
if not grid:
return count
lenRows = len(grid)
lenCols = len(grid[0])
def helperCounter(row, col, grid):
if row < 0 or col < 0 or row > lenRows - 1 or col > lenCols - 1 or grid[row][col] == '... |
0b8c92b44e7e653407cc755e8e7426f61e30e14e | mtj6/class_project | /glossary2.py | 467 | 3.59375 | 4 | from collections import OrderedDict
glossary = OrderedDict()
glossary['index'] = 'position of an item in a list'
glossary['list'] = 'a collection of items in a particuar order'
glossary['loop'] = 'a way to perform an action on every item in a list'
glossary['indentation errors'] = 'mistakes in levels of indentation'
... |
c38f26e312ac93bef4e99826e906506a9b23c363 | mtj6/class_project | /city_country.py | 262 | 4.0625 | 4 | def city_country(city, country):
"""Return a city and its country."""
full_name = city + ', ' + country
return full_name.title()
print(city_country('berlin', 'germany'))
print(city_country('london', 'england'))
print(city_country('paris', 'france')) |
c4aaaaa193fb7ee3b670371978dcea295c908fbe | mtj6/class_project | /users.py | 1,199 | 4.125 | 4 | """A class related to users."""
class User():
"""Describe some users."""
def __init__(self, first_name, last_name, age, sex, race, username):
"""initialize user attributes"""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.sex = sex
se... |
2433420fd3505d49227af3dd39e25994d7cda480 | mtj6/class_project | /vacation.py | 422 | 3.890625 | 4 | vacation = []
polling_active = True
while polling_active:
response = input('\nIf you could visit one place in the world, where would you go? ')
vacation.append(response)
repeat = input('Would you like to let another person respond? (yes/no) ')
if repeat == 'no':
polling_active = False
print('\nT... |
92e39cbf993106f6dffdf7a7a4cf24e45b992b3b | cameron-powell/advent-of-code-2018 | /day5-2.py | 1,005 | 3.578125 | 4 | import string
polymer = ''
with open('day5.txt') as polymer_file:
polymer = polymer_file.readline().strip()
low_alpha = list(string.ascii_lowercase)
up_alpha = list(string.ascii_uppercase)
def react(poly):
l_alpha = list(string.ascii_lowercase)
u_alpha = list(string.ascii_uppercase)
while True:
... |
b4fc1bf66885910a67d3dcd114eab79447be38cb | hpamei247/Udacity-Project-Movie-Trailer-Website | /media.py | 1,061 | 3.640625 | 4 | import webbrowser
class Movie(): #Google Style Guide for Python suggests that names of classes should start in UpperCase
"""This class provides a way to store movie related information""" #Triple quotes is used to add documentation for the file
def __init__(self,movie_title,movie_storyline,pos... |
bd79a4fb7cddc39b605984b0608ad19f6ff064dd | sahiilll/Python-Scripts | /prac1.py | 1,252 | 3.75 | 4 | def getleft(index):
return index * 2
def getright(index):
return index * 2 + 1
def min_heapify(arr, i):
left = getleft(i)
right = getright(i)
smallest = i
if (len(arr) > left) and (arr[left] < arr[i]):
smallest = left
if(len(arr) > right) and (arr[right] < arr[i]):
... |
4136dca4f01815f52f8bbde93413601d8cd48689 | deuzeman/Bloodhu0nd | /MkDirTree.py | 586 | 3.875 | 4 | #!/usr/bin/env python
import os
def mkdirtree(newdir):
"""Works the way a good mkdir should
- Directory already exists: silently complete
- Regular file in the way: raise an exception
- Parent directory doesn't exist: create recursively"""
if os.path.isdir(newdir):
pass
elif os.path.isfil... |
93d36aa606c700c2019797570b32e01436fc825c | psoren/small-python-projects | /caesarCipher.py | 1,328 | 3.921875 | 4 | def caesar(phrase, amt):
caesarTxt = ''
for c in phrase:
newChar = ord(c) + amt
if newChar > ord('z'):
newChar -= 26
caesarTxt += chr(newChar)
return caesarTxt
def altCaesar(plaintext, shift):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
shifted_alphabet... |
848f19970cb202bb190d3495b10810a6d2487a82 | KonradWasikiewicz/Pure-Python-Projects | /Hangman/Hangman.py | 2,691 | 4.09375 | 4 | import random #word choice
import string #uppercase letters in english dict
from ThousandMostPopularWords import words #imported list of 1000 most popular english nouns
from gallows import gallows
def get_valid_word(words): #excluding any words that might not be valid
word = random.choice(words)
wh... |
f1ab20d4eebdbddda94de673206edee24ee84712 | pugmomsf/oh-no-broken-code | /birthday.py | 1,228 | 4.3125 | 4 | from datetime import datetime
number_endings = {
1: 'st',
2: 'nd',
3: 'rd',
}
today = datetime.now()
todays_day = today.day
# get the right ending, e.g. 1 => 1st, 2 => 2nd
# but beware! 11 => 11th, 21 => 21st, 31 => 31st
# test your code by forcing todays_day to be something different
todays_day = 9
e... |
a2328f49694cf5f19841f11aab86772df2267023 | vishwanaik15/DAA_PROJECT | /insertionsort.py | 475 | 3.78125 | 4 | #insertionsort
import time
from time import sleep
def insertionSort(nlist):
start_time=time.time()
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
p... |
0c488f05f1cc8584f6990029db70f18c8b9a2a66 | anarkia7115/google-foobar | /gearing_up_for_destruction.py | 2,204 | 3.53125 | 4 | from fractions import Fraction
def answer(pegs):
r0_frac = compute_r0(pegs)
if r0_frac <= 1:
return [-1, -1]
else:
ratio_list = compute_r(pegs, r0_frac)
for i in range(len(ratio_list) - 1):
r = ratio_list[i]
r_next = ratio_list[i+1]
p = pegs[i]
... |
3c5d3674ea3d693969e7506308cd58946233a490 | gamer0/python_challenge | /challenge3.py | 487 | 4.1875 | 4 | #! /usr/python3
import sys
import string
import re
def find_pattern(file):
with open(file,'r') as f:
f_gen = (line for line in f.readlines())
my_pattern = re.compile(r'[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]')
match_list = [ my_pattern.search(line) for line in f_gen]
match_list = [ match.group(1) ... |
817dc53b3ccaa18016b499e534dac8b2e5342c0e | sjunhong/CovidGame | /Country.py | 1,296 | 3.96875 | 4 | #Country class with information
class Country:
#constructor
def __init__(self, countryName, population, infectedNum):
self.name = countryName
self.population = population
self.infectedNum = infectedNum
#getters
def getName(self):
return self.name
def getPopulation(s... |
b96019740718f1c20bdf6ee47885310dd117cab8 | ChristoGH/voice2text | /NLP.py | 5,410 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 08:56:40 2019
@author: Christo Strydom
"""
import os
os.chdir('/home/lnr-ai/github_repos/pyAudioAnalysis/')
#%%
import speech_recognition
# Gentle Start to Natural Language Processing using Python
# What is NLP ?
# Natural language processin... |
54fd66d20812cff23fd843539113592bef031310 | LoaDy588/py_brno_prestupky | /raw_data_cleaner.py | 2,013 | 3.5625 | 4 | """
Clean up the files(delete empty or short/incomplete lines),
change the formatting a bit and join the files together.
"""
import csv
def join_files(files, out_file):
"""Join two files together."""
# setup output file
file_out = open(out_file, "w", encoding="cp1250")
csv_writer = csv.writer(file_ou... |
578e293283ddfa972b79d8bcfec5cf3f2e99e176 | mathias-madsen/information_theory | /demo_huffman_coin_flips.py | 6,077 | 4.1875 | 4 | """
HUFFMAN CODING DEMO
-------------------
This script constructs a binary Huffman code for the coin flipping sequences
of length n, and then visualizes that code as a tree. It was used in lecture 2
of the 2018 NASSLLI course on information theory.
For more information, see the course website on
https://www.cmu... |
49db76b26f50ea1e0e934e7880800fbc59557f25 | mathias-madsen/information_theory | /demo_coding.py | 2,771 | 3.78125 | 4 | """
LIVE CODING DEMO
----------------
This script constructs a code for an uppercase Latin alphabet, using
reasonable estimates for the letter probabilities, and then allows the
uses to watch text be encoded as it is typed into a text field.
This script was used in the 2018 NASSLLI course on information theory,
... |
c85d00f3a21fd14b378d43fe20297bdd7517e8b9 | dabiri1377/DS_proj_nom2 | /pojc_stack.py | 6,963 | 4.03125 | 4 | import time
def get_maze_from_user(x_of_maze_for_get_maze):
"""
get maze from user and return it
:return:
maze matrix
"""
# guide user
print("for wall enter 1")
print("for exit point enter $")
print("for empty way enter 0")
print("for start point enter *")
# get maze fro... |
e92393319be738fc32c0319cedece455567b6709 | Skyfallk/Lesson_7 | /personal_bill_utils.py | 1,751 | 3.75 | 4 | import os
def top_up(money, summ):
money += summ
print('Счет пополнен на', summ)
return money
def chek_input(question):
while True:
x = input(question + '\n')
try:
x = float(x)
if x >= 0:
return x
break
else:
... |
8befcd622b8173a4dd831fbefd8f73fb60fe394b | Silversmithe/InferenceEngine | /part3.py | 3,921 | 4.0625 | 4 | """
FILE: CNF Conversion
AUTHOR: Alexander S. Adranly
A group of functions that help convert any type of propositional logic into CNF form
CNF -Conjunctive Normal Form-
: a conjunction of disjunctions -aka- and AND of ORs
:
CONVERTING TO CNF
1. Biconditional Elimination
2. Implication Elimination
3. Move negatio... |
199dd572e403b6da3c3a09525f06b1914a556951 | tannh/Py | /Day3/bai2.py | 147 | 4 | 4 | a = -1
if a == 0:
print('this is zero')
elif a < 0:
print('this is negative number')
elif a > 0:
print('this is positive number')
print('exit')
|
71608521f38f1c337f1d64dc2c3ffba6fadb84a0 | Dodobirds/blackhat | /vig.py | 1,866 | 3.5 | 4 | import sys
import english
file_name = './Emails/email2'
with open(file_name, 'r') as f:
cy = f.readline()
NORMAL_FREQ = english.normal_freqs
FREQ_SQR = 0
for n in NORMAL_FREQ:
FREQ_SQR += NORMAL_FREQ[n] ** 2
def shiftBy(a, n):
return chr(((ord(a) - ord('a') + n) % 26) + ord('a'))
def findFreq(text):
... |
dd7e6f9f16d72acd47a15a4fc73f1405641be2e7 | reginashay/cs102 | /homework01/caesar.py | 1,369 | 4.40625 | 4 | def encrypt_caesar(plaintext):
"""
Encrypts plaintext using a Caesar cipher.
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("0123456")
'0123456'
>>> encrypt_caesar("@#^&*${}><~?")
'@#^&*${}><~?'
>>> encrypt_caesar("")
''
... |
623c20a5a52c71516f933420931d52acab7ed7e5 | Hazemmasry/hazemm | /opfile.py | 224 | 3.59375 | 4 | def main():
x = open("fe.txt","r")
return x
x = main()
#for i in range(100):
#e=input("what is your name")
# x.write("hi"+str(i)+"\r\n")
if x.mode=="r":
contents= x.read()
print(contents)
x.close()
|
47e3b6cf04dfb2aa3681161395599a53958dcff0 | chuy2412/cse491-numberz | /sieve_iter/test3.py | 671 | 4.0625 | 4 | ################################################################
#Test3: move the iterator to the next prime number 3 times
# check if the value is equal to 7
################################################################
import sieve
def test3():
s = sieve.sieve() #create an object of type sieve
i = iter(s)... |
3efb89278c9308d351616058389b52e016482b0f | mptrepanier/coding-cookbook | /python/python-practice-master/practice/DirectoryRecurse.py | 706 | 3.765625 | 4 | import itertools
class Directory:
def __init__(self, name, contents=[]):
self.name = name
self.contents = contents
class File:
def __init__(self, name):
self.name = name
def flatmap(func, *iterable):
return itertools.chain.from_iterable(map(func, *iterable))
d... |
9deb255910fb39d0d499b1a8e59081c1824f5750 | YenneV/Periodic_Membrane_Skeleton | /Assembly/PMS_PY/Making_Rings/Point_Particle/Single_Spec.py | 3,312 | 3.84375 | 4 | # Monte Carlo Type Simulation for a Single, Structureless Spectrin Tetramer in a 2D Cartesian Space
#from random import randint
import random
import math
import numpy as np
import matplotlib.pyplot as plt
random.seed(10)
# Function 'step' does a single step given an initial position and a set of allowed coordinates
#... |
61d861e33e9f60bc2c412b38e55b708c85393d7e | arikpamnani/cpg-workshop | /EXTEUCLID.py | 366 | 3.6875 | 4 | def egcd(A, B):
"""return (g, x, y) such that a*x + b*y = g = gcd(x, y)"""
if(B == 0):
return (A, 1, 0)
else:
g, x, y = egcd(B, A%B)
return (g, y, x - (A//B) * y)
a = int(input())
b = int(input())
c = int(input())
(g, x, y) = egcd(a, b)
if(c%g!=0):
print("NO")
else:
print("... |
2a1b822407b558eda90301a1bfec1f5c159c21cc | alexandermedv/Prof_python7 | /main.py | 1,502 | 4.25 | 4 |
class Stack():
"""Класс, реализующий стек"""
def __init__(self):
"""Инициализация класса"""
self.stek = ''
def isEmpty(self):
"""Проверка, пустой ли стек"""
if self.stek == '':
return True
else:
return False
def push(self, element):
... |
eb0dcf84ec5a86cdec6cd068fcfe5d0c940bada5 | LoganEerdmans/it-python | /banner.py | 526 | 3.8125 | 4 | def banner(subject, author):
subject_length = len(subject)
by_line = f"By {author}"
by_line_length = len(by_line)
banner_length = max(subject_length, by_line_length) + 4
print(f"{'=' * banner_length}")
print(f"{subject:^{banner_length}}")
print(f"{by_line:^{banner_length}}")
print(f"{'=... |
c983b6f14ff55a610975b90e942443482f96a355 | n3n/CP2014 | /CodePython/pythonDuke/Prime_v1.py | 215 | 4 | 4 | from math import sqrt
def isPrime(n):
if n == 1:
return False
for num in range(1, int(sqrt(n)), 2)[1:]:
if n%num == 0:
return False
return True
n = input()
print isPrime(n)
|
5cc17cb4ef19a0f7823b773e710864151f417d4e | n3n/CP2014 | /CodePython/python_file/GCD.py | 214 | 3.578125 | 4 | num1, num2 = input(), input()
i = 1
while i <= num1 or i <= num2:
if (num1 % 2 == 0 and num2 % 2 == 0) and (num1 % i == 0 and num2 % i == 0):
n1 = i
#print n1,i
i += 2
#print 'Come in',i
#print i
print n1
|
a7289bb90f09042b15b937414410db4abcdc7284 | n3n/CP2014 | /CodePython/Divide3Or5.py | 99 | 3.796875 | 4 | summ = 0
for i in xrange(input()+1):
if i % 3 == 0 or i % 5 == 0:
summ += i
print summ
|
5021a1a0d069b623edb5aee3f6cde1beeb987891 | n3n/CP2014 | /CodePython/python_file/Python_Test/palindrome.py | 339 | 4.0625 | 4 | def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if first(word) != last(word):
return False
elif len(word) <= 2:
return True
else:
return is_palindrome(middle(word))
text = raw_input("Press message: ")
print "Is palindrome?", is... |
1f42fee28a9c8be9c611ea1c45a86c50e46643fb | n3n/CP2014 | /CodePython/Gram2.py | 369 | 3.5 | 4 | message = raw_input()
list_Word = []
for index in xrange(len(message)-1):
list_Word.append(message[index]+message[index+1])
max_Val = 0
for word in list_Word:
if list_Word.count(word) > max_Val:
max_Val = list_Word.count(word)
for word2 in list_Word:
if list_Word.count(word2) == max_Val:
... |
24723f5618bcc30b3a03729ac316b4b202e32f70 | n3n/CP2014 | /CodePython/PreMidterm09_Manga.py | 218 | 3.71875 | 4 | def manga(alist):
emptylist = []
for i in alist[::-1]:
if type(i) == list:
emptylist.append(manga(i))
else:
emptylist.append(i)
return emptylist
print manga(input())
|
dbb932df1414dff17f8459c31b4c9366ae592fec | n3n/CP2014 | /CodePython/pythonDuke/Prime_v2.py | 344 | 4.0625 | 4 | from math import sqrt
def isPrime(n):
if n == 1 or (n%2 == 0 and n != 2):
return False
for num in range(1, int(sqrt(n))+2, 2)[1:]:
if n%num == 0:
return False
return True
n = input()
total = 0
for i in range(1, n+1):
if isPrime(i):
total += 1
... |
4f482ab15467090ac178a195199811f85f63eb64 | n3n/CP2014 | /CodePython/Python/3n+1.py | 140 | 3.734375 | 4 | while True:
n = input()
if n == 0:
break
c = 1
while n != 1:
if n % 2 == 0:
n /= 2
else:
n = ( 3 * n ) + 1
c += 1
print c |
635e58ad8801cef8e7978c210b22f10ca648e3e5 | n3n/CP2014 | /CodePython/python_file/ReverseWord2.py | 169 | 3.515625 | 4 | message = raw_input().split()
for i in message:
if i == ' ':
message.pop(message.index(i))
print ' '.join(message[::-1])
#print ' '.join(raw_input().split()[::-1])
|
7499fe8e2f101bb234d5b1e829c9daf7a48c176f | n3n/CP2014 | /CodePython/Count.py | 176 | 3.609375 | 4 | cnt_odd = 0
cnt_even = 0
for i in xrange(input()):
n = input()
if n % 2 == 0:
cnt_even += 1
else:
cnt_odd += 1
print "%d\n%d" % (cnt_even, cnt_odd)
|
3c120e662397c960b61c9646880c875978db9e2e | n3n/CP2014 | /CodePython/python_file/GCD2.py | 97 | 3.84375 | 4 | num1, num2 = input(),input()
while num1:
num = num1
num1 = num2 % num1
num2 = num
print num2
|
05957777be30a5c0393833cc939e2ca58226a9d8 | n3n/CP2014 | /CodePython/Python/Zero.py | 81 | 3.5625 | 4 | summ = 0
while True:
tmp = input()
if tmp == 0:
break
summ += tmp
print summ |
1e8a9a681fe0942306a04c58733536852a96727e | n3n/CP2014 | /CodePython/python_file/test232.py | 289 | 3.671875 | 4 | message = open("../wordlist.txt")
string = "fracne"
word = "hello"
cnt = 0
for i in string:
for j in message:
#print "J: "
for k in j:
#print "K: "
if i in j and k in string:
cnt += 1
if cnt == len(word):
print "Was found! : " + j
break
print "not found"
|
da9074d6cd449470174fb11436f39d7372c05d27 | n3n/CP2014 | /CodePython/Frequency.py | 562 | 3.859375 | 4 | def histogram(string):
''' string -> dictionary
'''
d = {}
for i in string:
if i not in d:
d[i] = 1
else:
d[i] += 1
return d
def frequency(string):
'''
string -> string
return ...
'''
alist = []
frequency_str = histogram(string... |
e0183b16ae8b69ef1520684bcc0e287cad87719b | n3n/CP2014 | /CodePython/python_file/sum_of_squares_of_digits.py | 368 | 4.03125 | 4 | def sum_of_squares_of_digits(n):
'''check input digits , return number of digits'''
count,num = 0,0
i, m = 10, 10
n = abs(n)
while n/i > 0:
count += 1
i *= 10
while i >= 10:
i = m**count
c = n/i
n = n-(c*i)
num = num + (c**2)
count -= 1
... |
de20c16a86deb256c73c6dc1ede05730cb93dc35 | rogue0137/general | /online_practice_sites/leetcode/two_sum.py | 1,757 | 3.921875 | 4 | # Python 2.7
# Given an array of integers,
# return indices of the two numbers such that
# they add up to a specific target.
# You may assume that each input would have exactly one solution,
# and you may not use the same element twice.
# Given nums = [2, 7, 11, 15], target = 9,
#
# Because nums[0] + nums[1] = 2 + 7... |
de5fafb6037886e513d9010d28f0a6bbd80280db | MikeSmvl/google-online-quiz | /task1.py | 1,989 | 3.828125 | 4 | from itertools import combinations, product
def read_int(file) -> int:
"""Read int function.
Args:
file: A file where the next line will be read.
Returns:
Int: A line stripped and converted to an integer.
"""
return int(file.readline().rstrip())
def parse_file(filepath: str) -> dict:
... |
2e047601c56d68034306dd80f28e8639942cdb11 | fuston05/Graphs | /OLD_projects/ancestor/ancestor.py | 2,354 | 3.953125 | 4 | class Stack():
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
def earliest_ancestor... |
146e082b36aadbb8e30d800f23721273f219a76b | cqann/PRGM | /Python/project_euler/015_Lattice_paths.py | 346 | 3.5625 | 4 | #((2*n)!)/((n!)**2)
import math
size = 3
count = 0
print(math.factorial(40)/(math.factorial(20)**2))
def go(x,y):
global count
x_check = x==size
y_check = y==size
if x_check and y_check:
count += 1
return
if not x_check:
go(x+1,y)
if not y_check:
go(x,y... |
a04e29c2fde228fd1a960b479ff20252f8b57eda | cqann/PRGM | /Python/project_euler/003_Largest_prime_factor.py | 489 | 3.625 | 4 | import math
def is_prime(num):
for i in range(2,math.ceil(math.sqrt(num))+1):
if(num/i == num//i and num != i):
return False
return True
def is_in(n,l):
for i in range(len(l)):
if n == l[i]:
return True
return False
n = 600851475143
list_of_primes = []
varying... |
0c6de66d0ba25ab6ce3301f93d9fd2c88743f39f | cqann/PRGM | /Python/code_comp/Codechef/260120_Encoding_Jan/triangle.py | 671 | 3.734375 | 4 |
t = int(input())
dic = {}
for i in range(t):
a,b,c = [int(x) for x in input().split(" ")]
if (a,b,c) in dic:
print(dic[(a,b,c)])
else:
if a + b + c == 180 and a != 0 and b != 0 and c != 0:
dic[(a,b,c)] = "YES"
dic[(b,c,a)] = "YES"
dic[(c,a,b)] = "YES"
... |
171746f206db0efdcab48a2b43729da2af04c57a | tyrionzt/new_web | /test.py | 1,382 | 3.65625 | 4 | import re
class Solution: # judge sudoku is avaiable
def isValidSudoku(self, board):
for i in range(9):
locals()["sudoku" + str(i)] = []
for i in range(9):
row = []
col = []
for j in range(9):
if board[i][j] and not re.match(r'^[1-9]{1... |
5dceb18dc692e599c2c749383c5021b734d0e0d7 | nioanna/python-helper-functions | /array/min.py | 218 | 3.75 | 4 | # Funkcija trazi najmanju vrednost niza
def min(array):
minValue = array[0]
for item in array:
if item < minValue:
minValue = item
return minValue
# print(min([40, 30, 1, -20, 30, -6])) |
948419723ef3a82602abe37d14b03338b9569450 | doyosaedog/TIL | /day01/hello.py | 535 | 3.75 | 4 | # greeting 이라는 변수에 '안녕하세요' 라는 문자를 할당한다.
greeting = '안녕하세요.'
# 주석처리 하는법 : ctrl + /
# greeting 변수가 담고있는 값을 출력한다.
# print(greeting)
# 반복문을 통해서 인사를 여러번 해보도록 하자.
# while
count=0
while count<4:
print(greeting)
count += 1
# for
# 0~ n-1 까지의 숫자들을 만들어주는 range()
# range(5) -> 0,1,2,3,4
# i -> 0~4까지의 값을 반복해서 넣는다.
f... |
6b413e7405349a27c5c4f9765d291a134e58e7f6 | ryan258/vampire_pizzas | /VampirePizzaAttack.py | 854 | 3.5625 | 4 | #import libraries
import pygame
from pygame import *
# initialize pygame
pygame.init()
WINDOW_WIDTH = 1100
WINDOW_HEIGHT = 600
WINDOW_RES = (WINDOW_WIDTH, WINDOW_HEIGHT)
# create window
GAME_WINDOW = display.set_mode(WINDOW_RES)
# add window caption
display.set_caption('Attack of the Vampire Pizzas!')
# set up enemy... |
6263c14525505c149480f22bca529d5e8a950b09 | yz500223/AID1811 | /binary_re.py | 566 | 3.984375 | 4 | def binary(value,key):
left=0
right=len(value)-1
while left<=right:
middle=(left+right)//2
if value[middle]==key:
return middle
#如果大于中间值
elif value[middle]<key:
left=middle+1
#如果小于中间值
else:
right=middle-1
return -1
... |
529580fc4ec8b6b092e82c0f2b8511e22d165828 | EliJaghab/QueryJSON | /driver.py | 1,140 | 3.53125 | 4 | from tools import *
import os
import pathlib
class driver:
def URL2File():
while True:
inputURL = input(str("Enter the URL of the JSON Object: "))
JSONfunc = queryJSON(inputURL)
if JSONfunc.saveData(inputURL) == True:
return JSONfunc.saveData(inputURL)
... |
6af524150bc02834270d10badd10b910495b663e | amarmulyak/Python-Core-for-TA | /hw04/pnago/task_1.py | 403 | 3.625 | 4 | # • Знайти всі чотирьохзначні числа, сума цифер яких рівна заданому числу.
# Задаємо число:
num = int(input("Provide a number:"))
for a in range(1, 9):
for b in range(9):
for c in range(9):
for d in range(9):
if a+b+c+d == num:
print(int(str(a)+str(b)+str(c)... |
b0cb0e88002fec44cf48ace9565f4a03c046e439 | amarmulyak/Python-Core-for-TA | /hw05/akhomi/Task5.py | 513 | 3.75 | 4 | # Дана матриця. Знайти в ній рядок з максимальною сумою елементів, а також стовпець.
from random import random
matrix = []
matrix_row = []
for i in range(5):
row = []
for j in range(5):
row.append(int(random()*10))
matrix.append(row)
print(row)
for item in range(len(matrix)):
x = sum(matri... |
4cf6941fe5aeab772c8d7c39946bec10ddf1f9f9 | amarmulyak/Python-Core-for-TA | /hw04/akhomi/Task2.py | 322 | 4.09375 | 4 | x = int(input("Please enter positive digit: "))
count = 0
if x <= 1:
print("It's not prime number")
for i in range(1, x+1):
# print(x, i)
if x % i == 0:
count = count + 1 # count += 1
#print("count", count)
#print(a, b)
if count == 2:
print("Prime number")
else:
print("Not prime... |
96e2565447ee94ec6cb21f72b8c268778329b01b | amarmulyak/Python-Core-for-TA | /lessons/lesson08/examlpe08.py | 2,755 | 3.953125 | 4 | # class A:
# pass
#
# class A():
# pass
#
# class A(object): #for python 2
# pass
# class Class:
# """
# is class
# """
# name = ""
# size = 0
#
#
# def print(self):
# print(f"name:{self.name} size:{self.size}")
#
#
# c = Class()
# c.print()
# c.name = "r9111"
# c.size = 10
... |
ec1df6e378a91407058badc98aa480f7356a0073 | amarmulyak/Python-Core-for-TA | /hw05/pnago/task_9.py | 609 | 3.71875 | 4 | # В даному списоку визначити значення яке(і) найбільше зустрічається.
from random import random
a = [int(random() * 5) for i in range(50)]
print(a)
x = 0
for i in range(5):
count_i = a.count(i)
if count_i > x:
elem = i
x = count_i
print("The most frequent value is %s:" % elem, "It occurs %s t... |
0ed2dae9f0521887bbf376947e7e28c4d9708336 | amarmulyak/Python-Core-for-TA | /lessons/lesson12/run.py | 2,148 | 3.53125 | 4 | # import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('sqlite:///library.db', echo=True)
from sqlalchemy.orm import mapper, relation, backref
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, text
metadata = MetaData()
authors_table = Table('authors',
... |
a203760073f2019d6e500c097c807782befe0179 | amarmulyak/Python-Core-for-TA | /hw02/ashep/Task1.py | 1,269 | 3.546875 | 4 | python_philosophy = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality be... |
32197a9d260623de1d6b2b98e3c1930f8a35115e | amarmulyak/Python-Core-for-TA | /hw06/uhavir/hw06_task1.py | 902 | 4.5625 | 5 | # Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence
# n - length of Fibonacci sequence.
# NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements
# --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
# EXAMPLE OF Inputs/Ouputs when using t... |
657e7493a8557179b3327a7a1345ee5794fd0024 | amarmulyak/Python-Core-for-TA | /hw05/amarm/task4.py | 1,769 | 3.890625 | 4 | """
Вводиться нормалізований текст, який крім слів може містити певні знаки
пунктуації. Програма будує список слів, знаки пунктуації виключаються.
Під нормалізованим текстом будемо розуміти текст, в якому пробіл ставиться
після знаків пунктуації, за винятком відкриває дужки (пробіл перед нею).
str = input("Write down ... |
f7fa1e213ddd43ea879957bc309c5026addb905e | amarmulyak/Python-Core-for-TA | /hw06/amarm/task1.py | 634 | 4.375 | 4 | """
Provide full program code of fibo(n) function which returns array with
elements of Fibonacci sequence
n - length of Fibonacci sequence.
NOTE: The Fibonacci sequence it's a sequence where some element it's a
sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
EXAMPLE OF Inputs/Ouputs when using this... |
17e555d24c9b10c7748c183a1ac62960f9328ba5 | amarmulyak/Python-Core-for-TA | /hw03/pnago/task_2.py | 777 | 4.1875 | 4 | year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
day = int(input("Enter a day: "))
short_months = [4, 6, 9, 11]
# Check if it is a leap year
is_leap = False
if year % 4 != 0:
is_leap
elif year % 100 != 0:
is_leap = True
elif year % 400 != 0:
is_leap
else:
is_leap = True
# Dat... |
24a2cc20d192b5e6cdd66f090469963c51a5487c | amarmulyak/Python-Core-for-TA | /hw04/ashep/task4.py | 222 | 3.734375 | 4 | #Знайти суму кубів цифер заданого натурального числа.
n = int(input("Enter number "))
suma_x = 0
while n > 0:
x = (n % 10)**3
suma_x += x
n //= 10
print(suma_x)
|
30fda1f94c4538fb59875b908a9fa8bfbf752a82 | amarmulyak/Python-Core-for-TA | /hw07-10/uhavir/entity/group.py | 1,232 | 3.96875 | 4 | # Група з полями назва, студенти(list).
# Перевизначити методи __init__, __str__, __repr__
# Визнасити метод add_student, print_students, is_contain(Людина)
# додати у класи Людина, Група, Викладач, Заняття обробітники винятків у необхідні методи
# визначити в модулі run.py можливість роботи з програмую через терміна... |
9fed667624813e14437a577d8374f2e306578a61 | amarmulyak/Python-Core-for-TA | /hw03/arusova/leap.py | 256 | 4.03125 | 4 | check_year = int(input("Enter year "))
if check_year % 4 != 0:
print("It's not a leap year")
elif check_year % 400 == 0:
print("It's a leap year")
elif check_year % 100 == 0:
print("It's a leap year")
else:
print("It's a leap year")
|
b08dfa9c61ea32b40594f424dfb140002764f5a5 | amarmulyak/Python-Core-for-TA | /hw06/arus/fibo_func.py | 583 | 4.4375 | 4 | """Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence
n - length of Fibonacci sequence.
NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
"""
def fibo_func(n):
i = 1
i1 =... |
5f0a74b243d2a0d0ed6d504936a19ede39175284 | amarmulyak/Python-Core-for-TA | /hw05/yvasya/hw05_5.py | 995 | 4.125 | 4 | # Дана матриця. Знайти в ній рядок з максимальною сумою елементів, а також стовпець.
from random import random
matrix = []
for i in range(5):
row = []
for j in range(5):
row.append(int(random()*10))
matrix.append(row)
for row in matrix:
print(row)
# sum of the row
biggest_row = []
for row i... |
f0b6079899e1dc932f96f197420108d8c2abe549 | amarmulyak/Python-Core-for-TA | /hw04/pnago/task_5.py | 449 | 3.984375 | 4 | # • Заданий текст, вивести всі слова які починаються на певну послідовність символів.
import re
your_text = input("Enter some text:")
seq = input("Enter the search phrase:")
text_arr = re.split(', |_|-|!|\.| |\"| \(|\)', your_text)
words = []
for i in text_arr:
if i.startswith(seq):
if i not in words:
... |
8b5bc86614f4e8dcecf7fc2f42233c6e8de9cf26 | amarmulyak/Python-Core-for-TA | /hw07-10/akhomi/services/human_service.py | 493 | 3.59375 | 4 | from entity.human import Human, HumanException
def create_human():
created = True
while created:
try:
name = input("Please enter name: ")
age = int(input("Please enter age: "))
sex = input("Please enter sex: ")
human = Human(name, age, sex)
c... |
987e8a5653b66047b97c6c73b22d8b83414009a4 | amarmulyak/Python-Core-for-TA | /hw07-10/amarm/entity/group.py | 918 | 3.578125 | 4 | from entity.human import Human
class Group:
def __init__(self, group_name, students):
self.group_name = group_name
if not isinstance(students, list):
raise Exception("'students' is not a list")
self.students = students
def __str__(self):
return f"Group name: {self... |
f14bac7c286ea83f0101f63906df08c4d79e2b68 | amarmulyak/Python-Core-for-TA | /hw02/dlobo/002_Task2.py | 1,217 | 3.890625 | 4 | # Записати в стрічку філософію Пайтона
# Знайти в заданій стрічці кількість входжень слів (better, never, is)
# Вивести весь текст у верхньому регістрі (всі великі літери)
# Замінити всі входження символу “і” на “&”
# Задано чотирицифрове натуральне число.
# Знайти добуток цифр цього числа.
# Записати число в реверсно... |
11479ff5ed3027796c3c54b35c4edbc9609ffeac | amarmulyak/Python-Core-for-TA | /hw03/amarm/task1.py | 310 | 4.28125 | 4 | from calendar import monthrange
var_year = int(input("Type the year to found out if it's leap year: "))
february = monthrange(var_year, 2) # Here 2 means second month in the year
february_days = february[1]
if february_days == 29:
print("It's a leap year!")
else:
print("This is not a leap year!")
|
ecf282a34fda241d3d590b2cff58799c30cf0d26 | amarmulyak/Python-Core-for-TA | /hw02/pnago/task_2.py | 461 | 3.609375 | 4 | # Задано чотирицифрове натуральне число.
num = 7854
# * Знайти добуток цифр цього числа.
toString = str(num)
n = 1
for i in toString:
n *= int(i)
print(n)
# * Записати число в реверсному порядку.
print(toString[::-1])
# * Посортувати цифри, що входять в дане число
sortedString = ''.join(sorted(toString))
print(... |
23a51ec7bb62bb9200a9372264e1619acea3c7a6 | amarmulyak/Python-Core-for-TA | /hw04/amarm/task4.py | 194 | 4.53125 | 5 | print("This program calculates the sum of each number exponented by 3")
number = input("Type your number: ")
result = 0
for digit in number:
result = result + int(digit) ** 3
print(result)
|
9f297271754dd3a00a5b65763bd0a2387d2c2a5e | amarmulyak/Python-Core-for-TA | /hw04/akhomi/Task3.py | 116 | 3.765625 | 4 | n = int(input("Please enter number: "))
f = [ 0, 1]
for i in range(2, n + 1):
f.append(f[i-1] + f[i-2])
print(f) |
aeb22296008b03565e0e2328d2acc8aad56947f5 | amarmulyak/Python-Core-for-TA | /hw05/ashep/task1.py | 514 | 3.796875 | 4 | #Генерується список випадкових цілих чисел. Визначається, скільки в ньому парних чисел, а скільки непарних.
import random
a = []
b = []
c = []
for i in range(10):
a.append(int(random.random() * 100))
for x in a:
if x%2 == 0 and x!=0:
b.append(x)
else:
c.append(x)
print(a)
print("Paired nu... |
8c9320a9c918a667a1e308dc73b7cda9d1b7aa0b | amarmulyak/Python-Core-for-TA | /hw06/yvasya/hw06_01.py | 673 | 4.28125 | 4 | """
Provide full program code of fibo(n) function which returns array with elements of Fibonacci sequence
n - length of Fibonacci sequence.
NOTE: The Fibonacci sequence it's a sequence where some element it's a sum of two
previous elements --> 1, 1, 2, 3, 5, 8, 13, 21, 34,...
EXAMPLE OF Inputs/Ouputs when using this fu... |
00ee5af22cb11217d71e71f69f5902d782ed0c7c | aiqbal-hhs/python-programming-91896-JoshuaPaterson15 | /coin_flipping_v2.py | 651 | 3.6875 | 4 | basic.show_string("Hello!, to start, please answer the following math question.")
basic.show_string("10+10 (Button a is 20 and button b is 100).")
def on_forever():
if input.button_is_pressed(Button.A):
basic.show_icon(IconNames.DIAMOND)
basic.show_icon(IconNames.SMALL_DIAMOND)
basic.show_... |
c4cc1df080077fd565d9afbbb3a6c1129a00501c | aiqbal-hhs/python-programming-91896-JoshuaPaterson15 | /print_statement.py | 384 | 4.21875 | 4 | print("Hello and Welcome to this Digital 200 print statement.")
print("Here is string one." + "Here is string two.")
print("Here is string one times 5." * 5)
name = input("What is your name? ")
print("Welcome to Digital 200 {}.".format(name))
print("Line one \nLine two \nLine three")
print("""This is line one
... |
b3239c18f75f46b98029017a2dab5230bf760a7d | natedidit/pythonWork16 | /ex02.py | 298 | 3.890625 | 4 | # Student: Nate Canney
# Programming Exercise: 02
import InputBox
import MessageBox
import InputBox
InputBox.ShowDialog("How much do you weigh in pounds?")
f = InputBox.GetInput()
w = (float(f) * 0.45359237)
import MessageBox
MessageBox.Show("You weigh" + " " + (str(w)) + " " + "kg")
|
945c5226a8b258adfc543c7dcca792a934e6f5f0 | natedidit/pythonWork16 | /ex03.py | 340 | 3.90625 | 4 | # Student: Nate Canney
# Programming Exercise: 03
import InputBox
import MessageBox
import InputBox
InputBox.ShowDialog("Enter the atomic mass of silicon in grams:")
f = InputBox.GetInput()
w = (float(f) / 28.09 * (6.022*(10**23)))
import MessageBox
MessageBox.Show("This sample has" + " " + (str(w)) + ... |
2cb85f40c51d869ecb558e1c71bfca68a7e388bc | kitfair/kitspython | /airline.py | 7,329 | 3.921875 | 4 | """
Model for aircraft fligths
"""
from pprint import pprint as pp
class Flight:
def __init__(self, number, aircraft):
# 1) Pos 0-1 Must be alpha and Capital Letters
if not number[:2].isalpha():
raise ValueError("No airline code in '{}'".format(number))
if not number[:2].isuppe... |
bd5748fcfb73e50653d94f0bdc4c9f789d49c018 | bemyself1214/c_to_f | /c_to_f.py | 93 | 3.5 | 4 | temp = input('請輸入攝氏溫度:')
print('華氏溫度為:', float(temp)* 9 / 5 + 32) |
336dc2fe84d34d3865e0209e77ea4d00e6cc9d31 | K4bl0-Skat3R/exercicios-02-2014 | /exercicio 05.py | 302 | 4.125 | 4 |
# algoritimo verificar se o numero e par ou impar
# aluno Genilson
# professor Habib
# exercicio 05
n1= input("digite um numero: ")
if n1 == 0:
print "Neutro" #usei essa opcao para testar o elif(zero e par porem nulo )
elif n1 %2 == 0:
print "este numero e par"
else:
print "este numero e impar"
|
21917380c17d255bd53aafada3c0b29c7cf28286 | rec/test | /python/plur.py | 617 | 3.71875 | 4 | from numbers import Number
from typing import Sequence, Union
Arg = Union[Number, Sequence, str]
DEFAULT_PLURAL = 's'
def plur(word: str, plural: str, *args: Tuple[Arg, ...], zero=None) -> str:
if not args or isinstance(args[-1], str):
return partial(plur, word, plural, *args, zero=zero)
*plurals, ... |
9983dfeaea5f2838c7ba92f986e3a58348956010 | rec/test | /python/multiple_inheritance.py | 395 | 3.796875 | 4 | class Foo:
def __init__(self):
print('Foo.__init__')
def one(self):
return 'Foo.self'
class Bar:
def __init__(self):
print('Bar.__init__')
def one(self):
return 'Bar.self'
class Baz(Foo, Bar):
def two(self):
print(Foo.one(self), Bar.one(self), self.one()... |
fdd901f17aeb92480cbf3e7b8237bcdd03767454 | rec/test | /python/erato.py | 254 | 3.65625 | 4 | def eratosthenes(n):
is_prime = [False, False] + [True] * (n-2)
for idx in range(n):
if is_prime[idx]:
for i in range(2*idx, n, idx):
is_prime[i] = False
return [idx for idx, p in enumerate(is_prime) if p]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.