blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
27b0b0069b44272f4c950d1c5ecffcfe77c3e1cc | EmreCenk/Breaking_Polygons | /Storing_High_Scores/handling_csv.py | 1,652 | 3.8125 | 4 | def add_to_csv(name, score,pre_path=""):
folder = open(pre_path+"/high_scores.csv", "a+")
folder.write(name + "," + str(score) + "\n")
folder.close()
def read_csv(pre_path=""):
folder = open(f"{pre_path}/high_scores.csv", "r")
information = folder.read()
folder.close()
# print('I',information)
return information
def parse_csv(pre_path=""):
# Parsing the csv file that was saved:
info = read_csv(pre_path=pre_path).split("\n")
updated = []
if len(info)<=1:
return []
for i in range(len(info) - 1):
try:
a = info[i].split(",")
updated.append([a[0], int(a[1])])
except:
pass
return updated
def insert_person(csv_array, person):
index = len(csv_array) - 1
for i in range(len(csv_array)):
if csv_array[i][1] < person[1]:
# The person is greater than the array at this index, we do not need to look at anything else
index = i
break
inserted = []
for i in range(len(csv_array)):
if i == index:
inserted.append(person)
inserted.append(csv_array[i])
return inserted
def automate_insertion(person,pre_path=""):
info = parse_csv(pre_path=pre_path)
inserted_array = insert_person(info, person)
if inserted_array == []:
inserted_array = [person]
folder = open(f"{pre_path}/high_scores.csv", "w")
for name in inserted_array:
folder.write(name[0] + "," + str(name[1]) + "\n")
folder.close()
if __name__ == "main":
print(parse_csv())
|
ceac412b95ddfc03f70b09946ee5ddd20c38d124 | VivakaNand/COMPLETE_PYTHON_3 | /COMPLETE PYTHON-3 COURSE/Chapter-07-DICTIONARY/data_entry_project.py | 355 | 4.15625 | 4 | for i in range(1, 3):
name = input("Enter Name : ")
age = input("Enter age : ")
gender = input("Enter gender : ")
marks = input("Enter marks : ")
school = input("Enter school : ")
data = {}
data["name"] = name
data["age"] = age
data["gemder"] = gender
data["marks"] = marks
data["school"] = school
print(data) |
d3e0b7b9bc8d41203d988bc14d5101024fd51fe8 | jainvardhman/HackerRank | /python/maximize-xor.py | 768 | 3.53125 | 4 | totalLanes = 0
testCases = 0
lanesWidth = []
def initializeGlobals():
global totalLanes,testCases,lanesWidth
totalLanes,testCases = input().split()
totaLanes,testCases = int(totalLanes),int(testCases)
lanesWidth = input().split()
for i in range(0,len(lanesWidth)):
lanesWidth[i] = int(lanesWidth[i])
def findMaxVehicleWidth(entry,exit):
min = lanesWidth[entry]
for i in range(entry,exit+1):
if lanesWidth[i] < min:
min = lanesWidth[i]
else:
min = min
return min
def main():
initializeGlobals()
for i in range(0,testCases):
entry,exit = input().split()
entry,exit = int(entry),int(exit)
print(str(findMaxVehicleWidth(entry,exit)))
main() |
a28e1fb1a8c5a24acfead91ceeca0a7ac1d8e2fb | sharadbhat/Competitive-Coding | /LeetCode/Calculate_Money_In_Leetcode_Bank.py | 420 | 3.59375 | 4 | # leetcode
# https://leetcode.com/problems/calculate-money-in-leetcode-bank
class Solution:
def totalMoney(self, n: int) -> int:
total = 0
for i in range((n // 7) + 1):
days_in_week = 7 if n >= 7 else n
n -= 7
total += self.calcSum(days_in_week + i) - self.calcSum(i)
return total
def calcSum(self, n: int) -> int:
return (n * (n + 1)) // 2
|
27a69edb744fbfdbe07ed4700c2a99ef05915ae9 | MCaldwell-42/Prep | /something.py | 1,160 | 3.6875 | 4 | import sys
name = sys.stdin
def FizzBuzz(T, *args):
i = 0
while i < T + 1:
for instances in args:
instance = list(range(1, instances+1))
for number in instance:
if number % 3 == 0 and number % 5 == 0:
print('FizzBuzz')
elif number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print('Buzz')
else:
print(number)
i += 1
FizzBuzz(name)
t = int(input())
s = input()
def swapping_cases(t, s):
i=0
while i < t+1:
for case in s:
q=0
while q < len(case):
word = []
if case[0].isupper():
case[0].islower()
word.append(case[0])
for letter in case:
if letter.isupper():
word.append("_")
word.append(letter)
else:
word.append(letter)
q += 1
i += 1
print(word)
swapping_cases(t, s) |
0dd9b13f3f42ebb4929ba93efb919ded4a40b3fe | azunic/pyhton-tasks | /vjezba_6_ponovno/zad_6_1.py | 590 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 15:40:16 2020
@author: Ana
"""
#Napišite program u kojem korisnik unosi broj N. Program
# tražiti od korisnika da unese N cijelih brojeva i ispisati
#njihovu aritmetičku sredinu.
#Koristite funkciju „ArtimetickaSredina” koja prima broj i vraća rezultat.
def aritmetickasredina(N):
suma = 0
for i in range(0, N):
broj = int(input("Unesite brojeve"))
suma += broj
print(suma)
sredina = suma / N
return(sredina)
N = int(input("Unesite broj "))
print(aritmetickasredina(N)) |
ab1ac0b217a00b9f8e9cf312e18a326a70e6ec17 | Shaheen0611/UiA-Work | /assignment_2_1/main.py | 825 | 3.796875 | 4 |
count = 0
num = []
sum = 0
avg = 0
sort = []
result = []
med = 0
j = 0
while num != 0:
j = int(input())#FUNCTION TO CALCULATE AVERAGE
if j == 0:
break
num = j
sort.append(num)
sum += num
count += 1
avg = sum / count
for x in range(len(sort)): #FUNCTION TO SORT NUMBERS IN DECENDING ORDER
y = max(sort)
sort.remove(y)
result.append(y)
z = ' '.join(str(num) for num in result)
print("Average :",avg)
c = int(count) #FUNCTION TO FIND OUT THE MEDIAN
m = 0
if (c % 2) == 0:
n = int(c/2)
m = (result[n-1] + result[n])/2
print("Median :" ,round(m,2))
if (c % 2) == 1:
n = (c/2) + 0.5
t = int(n)
m = result[t - 1]
print("Median :" ,round(m,2))
print("Descending :",z)
|
61cb58a86e6fea647fd2651a55871d4b1aa6829b | anannya03/zip-file-cracker | /ab.py | 773 | 3.859375 | 4 | import zipfile
wordlist = 'rockyou.txt'
zip_file = 'secret.zip'
flag = False
# initialize the Zip File object
zip_file = zipfile.ZipFile(zip_file)
# count the number of words in this wordlist
num_words = len(list(open(wordlist, "rb")))
# print the total number of passwords
print "Total passwords to test: " + str(num_words)
#try the passwords one by one against the zip file
with open(wordlist, "rb") as wordlist:
for word in wordlist:
print 'trying password: ' + word
try:
zip_file.extractall(pwd=word.strip())
except Exception:
continue
else:
print "[+] Password found: " + word.decode().strip()
flag = True
break
if(flag == True):
print "Succesful"
else:
print "[!] Password not found, try other wordlist." |
48d9b449d6f330b23627207238ae8395d7bc37bc | farmkate/asciichan | /test.py | 274 | 3.671875 | 4 | #def testEqual(fuctionResult, expected):
# if functionResult == expected:
# result = 'Pass'
# else:
# result = 'Fail'
# return result
def testEqual(a, b):
if a == b:
print('Pass:', a, '==', b)
else:
print('Fail:', a, '!=', b)
|
0d389c71122fd2e8e98ef5bed6dcf1d4599571e1 | kjspgd/aoc2020 | /21/aoc21_part1.py | 2,481 | 3.65625 | 4 | #!/usr/local/bin/python3
ingredients = {}
allergyMap = {}
tempList = []
debug = 0
allergenCulprits = {}
inverseAllergenCulprits = {}
allCulprits = []
allIngredients = []
for line in open('input.txt'):
tempList.append(line.rstrip())
for i in range(0,len(tempList)):
ingredients.update({int(i):tempList[i].split("(")[0].split()})
lineAllergens = []
lineAllergens= (tempList[i].split("(")[1].replace(")","").replace("contains ","").split(", "))
for allergen in lineAllergens:
if debug: print("------------")
if debug: print(str(i) + " " + str(allergen))
updater=[]
try:
if debug: print(allergyMap[allergen])
updater = allergyMap[allergen] + [int(i)]
if debug: print("no exception")
except:
if debug: print("Exception on " + str(i) + " " + str(allergen))
updater = [int(i)]
if debug: print(updater)
pass
if debug: print(updater)
allergyMap.update({allergen:updater})
if debug: print(allergyMap)
#print(ingredients)
#print(allergyMap)
for allergen in allergyMap.keys():
print("-----------")
print("Processing " + str(allergen))
culprits = []
recipeList = allergyMap[allergen]
#print(recipeList)
for i in range(0,len(recipeList)):
#culprits=[]
#print(recipeList[i])
#recipe = ingredients[i]
#print(int(i))
#print("*-(")
if int(i) == 0: culprits = ingredients[recipeList[i]]
for recipeNo in allergyMap[allergen]:
#print("Recipe No")
#print(recipeNo)
#print("Ingredients")
#print(ingredients[int(recipeNo)])
#print(set(culprits))
#print("Vs")
#print(ingredients[int(recipeNo)])
culprits = list(set(culprits) & set(ingredients[int(recipeNo)]))
print("Culprits for " + str(allergen) + " are " + str(culprits))
allergenCulprits.update({allergen:culprits})
##ADD INVERSE CULPRITS FOR LINE HERE?
for culpritItem in culprits:
allCulprits.append(culpritItem)
for recipe in ingredients.values():
for ingredient in recipe:
allIngredients.append(ingredient)
safeIngredients = []
for ingredient in allIngredients:
if ingredient not in allCulprits:
safeIngredients.append(ingredient)
print(allergenCulprits)
print(allCulprits)
print(allIngredients)
print(safeIngredients)
print(len(safeIngredients))
|
43e7007ffaef8677fc4be0cf33758f4e2d134c58 | Zahidsqldba07/python_course_exercises | /TEMA 5_FICHEROS/Ficheros_2/escribe_csv.py | 1,015 | 3.78125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import lee_csv
def dicacsv(fichero,lista):
"""Recibe un fichero y una lista de diccionarios que fue creada a partir de un CSV
en dicho fichero se escribirán los datos de todos los diccionarios"""
with open(fichero,'w') as fman:
# con la primera linea saco las cabeceras, cogiendo las claves de cualquier diccionario de la lista
cabeceras = (';'.join(lista[0].keys())) + '\n'
fman.write(cabeceras)
# para cada diccionario, escribo los valores
for diccionario in lista:
fman.write((';'.join(diccionario.values())) + '\n')
return()
# ### PROBANDO
if __name__ == "__main__":
try:
listadic = csvadic("Estaciones.csv")
pasaracsv = dicacsv("pruebadic.csv",listadic)
print('Datos escritos correctamente')
except FileNotFoundError:
print("Fichero no encontrado")
except PermissionError:
print("No tienes permiso para leer el fichero") |
9435c4fbefec4e546bb43173535945beafad6543 | grkheart/Python-class-homework | /homework_3_task_6.py | 440 | 4.0625 | 4 | # Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
word = input("Введите слово в строчном формате: ")
def int_func(word):
return word.title()
print (int_func(word))
|
e4d73e8ac451265838a878d516e47382d1a212a6 | leotalorac/SpidersAndFlies | /main.py | 2,850 | 3.515625 | 4 | from graphics import *
import spider as sp
import fly as fl
import random as random
import time
import matplotlib.pyplot as plt
height = 600
wight = 1000
def main():
# setup
series = list()
s =0
spy =list()
fli = list()
nspiders = 80
nflies = 170
#import the points
flyform = open("./forms/fly.form",'r')
flypoints = flyform.readlines()
spiderform = open("./forms/spider.form","r")
spiderspoints = spiderform.readlines()
#define world
spiders = list()
flies = list()
#put init
for i in range(nspiders):
spiders.append(sp.spider(random.randint(0,wight),random.randint(0,height)))
for i in range(nflies):
flies.append(fl.fly(random.randint(0,wight),random.randint(0,height)))
while(True):
series.append(s)
s+=1
spy.append(len(spiders))
fli.append(len(flies))
# clear(win)
# drawspiders(spiders,win,spiderspoints)
# drawflies(flies,win,flypoints)
moveflies(flies)
spidereat(spiders,flies)
reproducespiders(spiders)
reproduceflies(flies)
print("Flies population:" + str(len(flies)))
print("Spiders population: " + str(len(spiders)))
if(len(flies) ==0 or len(spiders) == 0 or len(flies) >=30000):
if len(flies) <=0:
for i in range(nflies):
flies.append(fl.fly(random.randint(0,wight),random.randint(0,height)))
elif len(spiders) <=0:
for i in range(nspiders):
spiders.append(sp.spider(random.randint(0,wight),random.randint(0,height)))
else:
break
# time.sleep(.01)
win = GraphWin("Spider and Flyes",wight,height)
series.append(s)
s+=1
spy.append(len(spiders))
fli.append(len(flies))
print(spy)
print(fli)
# plt.subplot(211)
# plot
plt.plot(series,fli,label="Flies")
plt.plot(series,spy,label="Spiders")
plt.legend(bbox_to_anchor=(.8,1),loc=2,borderaxespad=0 )
plt.show()
# draw final
clear(win)
drawflies(flies,win,flypoints)
drawspiders(spiders,win,spiderspoints)
win.getMouse()
win.close()
def clear(window):
for i in window.items[:]:
i.undraw()
window.update()
def drawspiders(elements,window,points):
for i in elements:
i.simpledraw(window)
# i.putspider(window,points)
def drawflies(elements,window,points):
for i in elements:
i.simpledraw(window)
def moveflies(elements):
for i in elements:
i.move(wight,height)
def spidereat(spiders, flies):
for i in spiders:
i.eat(flies)
def reproducespiders(spiders):
for i in spiders:
i.reproduce(spiders,i)
def reproduceflies(flies):
for i in flies:
i.reproduce(flies,i)
main() |
943e410dd308e561a8fba82f696c4a4994998688 | vikramzsingh/Python | /for_loop3.py | 146 | 4.25 | 4 | #Display table of a given number by user
n=int(input("Enter the number: "))
for i in range(1,11,1):
t=n*i
print(n,"*",i,"=",t)
|
0e5a74b168b2d587c6ef94e5ccae46bc019566d8 | TJMcButters/workspace-vscode | /Python/Personal/cardGames/99/Player.py | 1,025 | 3.625 | 4 | import ninetynine as nn
class Player:
def __init__(self, hand, p_num):
self.hand = hand
self.p_num = p_num
def play_card(self):
x = ''
keep_going = True
while keep_going:
print("Player {}: what would you like to play: ".format(self.p_num))
print("\t1. {}\n\t2. {}\n\t3. {}\n\t4. {}\n\t5. {}".format(self.hand[0], self.hand[1], self.hand[2], self.hand[3], self.hand[4]))
opt = int(input())
if opt <= len(self.hand):
x = self.hand.pop(opt - 1)
return x
else:
print("Invalid Input")
continue
print("New Hand: " + str(self.hand))
return x
def get_hand(self):
for i in self.hand:
print(i, end=" ")
print("\n")
def draw(self, deck):
self.hand.append(deck[0])
def get_pnum(self):
return self.p_num
if __name__ == '__main__':
nn.main() |
6a3b65b8e42a135f435151b90b5f413eb41a4a4c | rauljordan/PythonInterviewPractice | /interviewquestions.py | 18,870 | 4.03125 | 4 | def binary_search(l, value):
low = 0
high = len(l)-1
while low <= high:
mid = (low+high)//2
if l[mid] > value: high = mid-1
elif l[mid] < value: low = mid+1
else: return mid
return -1
#=======================================================================
# Author: Isai Damier
# Title: Radix Sort
# Project: geekviewpoint
# Package: algorithms
#
# Statement:
# Given a disordered list of integers, rearrange them in natural order.
#
# Sample Input: [18,5,100,3,1,19,6,0,7,4,2]
#
# Sample Output: [0,1,2,3,4,5,6,7,18,19,100]
#
# Time Complexity of Solution:
# Best Case O(kn); Average Case O(kn); Worst Case O(kn),
# where k is the length of the longest number and n is the
# size of the input array.
#
# Note: if k is greater than log(n) then an nlog(n) algorithm would
# be a better fit. In reality we can always change the radix
# to make k less than log(n).
#
# Approach:
# radix sort, like counting sort and bucket sort, is an integer based
# algorithm (i.e. the values of the input array are assumed to be
# integers). Hence radix sort is among the fastest sorting algorithms
# around, in theory. The particular distinction for radix sort is
# that it creates a bucket for each cipher (i.e. digit); as such,
# similar to bucket sort, each bucket in radix sort must be a
# growable list that may admit different keys.
#
# For decimal values, the number of buckets is 10, as the decimal
# system has 10 numerals/cyphers (i.e. 0,1,2,3,4,5,6,7,8,9). Then
# the keys are continuously sorted by significant digits.
#=======================================================================
def radixsort( aList ):
RADIX = 10
maxLength = False
tmp , placement = -1, 1
while not maxLength:
maxLength = True
# declare and initialize buckets
buckets = [list() for _ in range( RADIX )]
# split aList between lists
for i in aList:
tmp = i / placement
buckets[tmp % RADIX].append( i )
if maxLength and tmp > 0:
maxLength = False
# empty lists into aList array
a = 0
for b in range( RADIX ):
buck = buckets[b]
for i in buck:
aList[a] = i
a += 1
# move to next digit
placement *= RADIX
"""
Find the most frequent integer in an array
"""
def most_freq(xs):
occurences = {}
for i in xs:
if i in occurences.keys():
occurences[i] += 1
else:
occurences[i] = 0
v = list(occurences.values())
k = list(occurences.keys())
print k[v.index(max(v))]
"""
Find pairs in an integer array whose sum is equal to 10
"""
"""
Given 2 integer arrays, determine of the 2nd array is a rotated
version of the 1st array
"""
"""
Write fibbonaci iteratively and recursively
"""
def memoize(fn, arg):
memo = {}
if arg not in memo:
memo[arg] = fn(arg)
return memo[arg]
def fib(n):
if n == 1 or n == 2:
return 1
else:
return fib(n - 2) + fib(n - 1)
"""
Given a function rand5() that returns a random int between 0 and 5, implement rand7()
How does it work? Think of it like this: imagine printing out this double-dimension array on paper, tacking it up to a dart board and randomly throwing darts at it. If you hit a non-zero value, it's a statistically random value between 1 and 7, since there are an equal number of non-zero values to choose from. If you hit a zero, just keep throwing the dart until you hit a non-zero. That's what this code is doing: the i and j indexes randomly select a location on the dart board, and if we don't get a good result, we keep throwing darts.
"""
import random
def rand5():
return random.randint(1,5)
def rand7():
values = [
[1,2,3,4,5],
[6,7,1,2,3],
[4,5,6,7,1],
[2,3,4,5,6],
[7,0,0,0,0]
]
result = 0
while result == 0:
i = rand5()
j = rand5()
result = values[i - 1][j - 1]
return result
"""
Newtons method for sq roots
"""
def check(x, guess):
return (abs(guess*guess - x) < 0.001)
def newton(x, guess):
while not check(x, guess):
guess = (guess + (x/guess)) / 2.0
return guess
""" String Questions"""
"""
Find the first non-repeated character in a String
"""
def first_non_repeated(s):
repeated = set()
for letter in s:
if letter in repeated:
return letter
else:
repeated.add(letter)
"""
Reverse a String iteratively and recursively
"""
def rev_iterative(s):
reversed = []
for letter in s:
reversed.insert(0,letter)
return ''.join(reversed)
def rev_recursive(s):
if s == "":
return s
else:
return rev_recursive(s[1:]) + s[0]
"""
Determine if 2 Strings are anagrams
"""
def anagrams(s1, s2):
bools = []
for letter1, letter2 in zip(s1, s2):
if (letter1 in s2) and (letter2 in s1):
bools.append(True)
else:
bools.append(False)
return False not in bools
"""
Check if String is a palindrome
"""
def palindrome(s):
return s == rev_recursive(s)
def permute_string(s):
from itertools import permutations
string_list = permutations(list(s))
for item in string_list:
print ''.join(item)
"""
Implement a Queue using two stacks
"""
class Queue2Stack(object):
def __init__(self):
from datastructures import Stack
self.inbox = Stack()
self.outbox = Stack()
def push(self,item):
self.inbox.push(item)
def pop(self):
if self.outbox.isEmpty():
while not self.inbox.isEmpty():
self.outbox.push(self.inbox.pop())
return self.outbox.pop()
"""
Given an image represented by an NxN matrix, write a method to rotate the
image by 90 degrees. Can you do this in place?
"""
def rotate_mat(mat):
return [list(row) for row in zip(*mat)[::-1]]
print rotate_mat([[1,2],[3,4]])
"""
Pythonic fibbonaci
"""
def fib(n):
fibValues = [0,1]
for i in range(2,n+1):
fibValues.append(fibValues[i-1] + fibValues[i-2])
return fibValues[n]
"""
Hanoi
"""
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
# move disk from source peg to target peg
if source:
target.append(source.pop())
# move tower of size n-1 from helper to target
hanoi(n - 1, helper, source, target)
#=======================================================================
# Author: Isai Damier
# Title: Longest Increasing Subsequence
# Project: geekviewpoint
# Package: algorithms
#
# Statement:
# Given a sequence of numbers, find a longest increasing subsequence.
#
# Time Complexity: O(n^2)
#
# Sample Input: [8,1,2,3,0,5]
# Sample Output: [1,2,3,5]
#
# DEFINITION OF SUBSEQUENCE:
# A sequence is a particular order in which related objects follow
# each other (e.g. DNA, Fibonacci). A sub-sequence is a sequence
# obtained by omitting some of the elements of a larger sequence.
#
# SEQUENCE SUBSEQUENCE OMISSION
# [3,1,2,5,4] [1,2] 3,5,4
# [3,1,2,5,4] [3,1,4] 2,5
#
# SEQUENCE NOT SUBSEQUENCE REASON
# [3,1,2,5,4] [4,2,5] 4 should follow 5
#
# STRATEGY:
# Illustrating by finding a longest increasing subsequence
# of [8,1,2,3,0,5]:
#
# - Start by finding all subsequences of size 1: [8],[1],[2],[3],[0],[5];
# each element is its own increasing subsequence.
#
# - Since we already have the solutions for the size 1 subsequences,
# we can use them in solving for the size two subsequences. For
# instance, we already know that 0 is the smallest element of an
# increasing subsequence of size 1, i.e. the subsequence [0].
# Therefore, all we need to get a subsequence of size 2 is add an
# element greater than 0 to [0]: [0,5]. The other size 2
# subsequences are: [1,2], [1,3], [1,5], [2,3], [2,5], [3,5].
#
# - Now we use the size 2 subsequences to get the size 3 subsequences:
# [1,2,3], [1,2,5], [1,3,5], [2,3,5]
#
# - Then we use the size 3 subsequences to get the size 4 subsequences:
# [1,2,3,5]. Since there are no size 5 solutions, we are done.
#
# SUMMARY:
# Instead of directly solving the big problem, we solved a smaller
# version and then 'copied and pasted' the solution of the subproblem
# to find the solution to the big problem. To make the 'copy and paste'
# part easy, we use a table (i.e. array) to track the subproblems
# and their solutions. This strategy as a whole is called Dynamic
# Programming. The tabling part is known as memoization, which means
# writing memo.
#
# To recognize whether you can use dynamic programming on a problem,
# look for the following two traits: optimal substructures and
# overlapping subproblems.
#
# Optimal Substructures: the ability to 'copy and paste' the solution
# of a subproblem plus an additional trivial amount of work so to
# solve a larger problem. For example, we were able to use [1,2]
# itself an optimal solution to the problem [8,1,2] to get [1,2,3]
# as an optimal solution to the problem [8,1,2,3].
#
# Overlapping Subproblems: Okay. So in our approach the solution grew
# from left to right: [1] to [1,2] to [1,2,3] etc. But in reality
# we could have solved the problem using recursion trees so that
# for example [1,2] could be reached either from [1] or from [2].
# That wouldn't really be a problem except we would be solving for
# [1,2] more than once. Anytime a recursive solution would lead to
# such overlaps, the bet is dynamic programming is the way to go.
#
# [1] [2]
# / | \ / | \
# / | \ / | \
# / | \ / | \
# [1,2] [1,3] [1,5] [1,2] [2,3] [2,5]
#
# Dynamic Programming = Optimal Substructures + Overlapping Subproblems
# Divide and Conquer = Optimal Substructures - Overlapping Subproblems
# see merge sort: http://www.geekviewpoint.com/python/sorting/mergesort
#
# Alternate coding: Not really much difference here, just another code
# that some readers will find more intuitive:
#
# m = [1]*len(A)
#
# for x in range(len(A)):
# for y in range(x):
# if m[y] >= m[x] and A[y] < A[x]:
# m[x]+=1
#
# max_value = max(m)
#
# result = []
# for i in range(m-1,-1,-1):
# if max == m[i]:
# result.append(A[i])
# max-=1
#
# result.reverse()
# return result
#=======================================================================
"""
def LIS( A ):m = [0] * len( A ) # m = [1]*len(A) not important here
for x in range( len( A ) - 2, -1, -1 ):
for y in range( len( A ) - 1, x, -1 ):
if A[x] < A[y] and m[x] <= m[y]:
m[x] += 1 # or use m[x] = m[y] + 1
#===================================================================
# Use the following snippet or the one line below to get max_value
# max_value=m[0]
# for i in range(m):
# if max_value < m[i]:
# max_value = m[i]
#===================================================================
max_value = max( m )
result = []
for i in range( len( m ) ):
if max_value == m[i]:
result.append( A[i] )
max_value -= 1
return result
"""
def knapsack(items, maxweight):
"""
Solve the knapsack problem by finding the most valuable
subsequence of `items` subject that weighs no more than
`maxweight`.
`items` is a sequence of pairs `(value, weight)`, where `value` is
a number and `weight` is a non-negative integer.
`maxweight` is a non-negative integer.
Return a pair whose first element is the sum of values in the most
valuable subsequence, and whose second element is the subsequence.
>>> items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)]
>>> knapsack(items, 15)
(11, [(2, 1), (6, 4), (1, 1), (2, 2)])
"""
# Return the value of the most valuable subsequence of the first i
# elements in items whose weights sum to no more than j.
@memoized
def bestvalue(i, j):
if i == 0: return 0
value, weight = items[i - 1]
if weight > j:
return bestvalue(i - 1, j)
else:
return max(bestvalue(i - 1, j),
bestvalue(i - 1, j - weight) + value)
j = maxweight
result = []
for i in xrange(len(items), 0, -1):
if bestvalue(i, j) != bestvalue(i - 1, j):
result.append(items[i - 1])
j -= items[i - 1][1]
result.reverse()
return bestvalue(len(items), maxweight), result
def pascals_triangle(n_rows):
results = [] # a container to collect the rows
for _ in range(n_rows):
row = [1] # a starter 1 in the row
if results: # then we're in the second row or beyond
last_row = results[-1] # reference the previous row
# this is the complicated part, it relies on the fact that zip
# stops at the shortest iterable, so for the second row, we have
# nothing in this list comprension, but the third row sums 1 and 1
# and the fourth row sums in pairs. It's a sliding window.
row.extend([sum(pair) for pair in zip(last_row, last_row[1:])])
# finally append the final 1 to the outside
row.append(1)
results.append(row) # add the row to the results.
return results
"""
TSP Problem!
"""
from itertools import permutations
def distance(point1, point2):
"""
Returns the Euclidean distance of two points in the Cartesian Plane.
>>> distance([3,4],[0,0])
5.0
>>> distance([3,6],[10,6])
7.0
"""
return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5
def total_distance(points):
"""
Returns the length of the path passing throught
all the points in the given order.
>>> total_distance([[1,2],[4,6]])
5.0
>>> total_distance([[3,6],[7,6],[12,6]])
9.0
"""
return sum([distance(point, points[index + 1]) for index, point in enumerate(points[:-1])])
def travelling_salesman(points, start=None):
"""
Finds the shortest route to visit all the cities by bruteforce.
Time complexity is O(N!), so never use on long lists.
>>> travelling_salesman([[0,0],[10,0],[6,0]])
([0, 0], [6, 0], [10, 0])
>>> travelling_salesman([[0,0],[6,0],[2,3],[3,7],[0.5,9],[3,5],[9,1]])
([0, 0], [6, 0], [9, 1], [2, 3], [3, 5], [3, 7], [0.5, 9])
"""
if start is None:
start = points[0]
return min([perm for perm in permutations(points) if perm[0] == start], key=total_distance)
def optimized_travelling_salesman(points, start=None):
"""
As solving the problem in the brute force way is too slow,
this function implements a simple heuristic: always
go to the nearest city.
Even if this algoritmh is extremely simple, it works pretty well
giving a solution only about 25% longer than the optimal one (cit. Wikipedia),
and runs very fast in O(N^2) time complexity.
>>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
[[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
>>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
[[0, 0], [6, 0], [10, 0]]
"""
if start is None:
start = points[0]
must_visit = points
path = [start]
must_visit.remove(start)
while must_visit:
nearest = min(must_visit, key=lambda x: distance(path[-1], x))
path.append(nearest)
must_visit.remove(nearest)
return path
points = [[0, 0], [1, 5.7], [2, 3], [3, 7],
[0.5, 9], [3, 5], [9, 1], [10, 5]]
print("""The minimum distance to visit all the following points: {}
starting at {} is {}. The optimized algoritmh yields a path long {}.""".format(
tuple(points),
points[0],
total_distance(travelling_salesman(points)),
total_distance(optimized_travelling_salesman(points))))
def numIslands(grid):
if not grid: return 0
m, n, c= len(grid), len(grid[0]), 0
visited= [[False for i in xrange(n)]for i in xrange(m)]
for i in xrange(m):
for j in xrange(n):
if not visited[i][j] and grid[i][j]==1:
dfs(grid, visited, i, j, m, n)
c += 1
return c
def dfs(grid, visited, i, j, m, n):
visited[i][j]= True
if i+1<m and grid[i+1][j]==1 and not visited[i+1][j]:
dfs(grid, visited, i+1, j, m, n)
if i-1>=0 and grid[i-1][j]==1 and not visited[i-1][j]:
dfs(grid, visited, i-1, j, m, n)
if j+1<n and grid[i][j+1]==1 and not visited[i][j+1]:
dfs(grid, visited, i, j+1, m, n)
if j-1>=0 and grid[i][j-1]==1 and not visited[i][j-1]:
dfs(grid, visited, i, j-1, m, n)
a = [[1,0,1],[0,0,0],[0,0,0]]
print numIslands(a)
_dp = [0]
def numSquares(self, n):
dp = self._dp
while len(dp) <= n:
dp += min(dp[-i*i] for i in range(1, int(len(dp)**0.5+1))) + 1,
return dp[n]
def klargest(k, xs):
if k > len(xs):
raise Exception("k is larger than size of list")
maximum = None
while k > 0:
maximum = max(xs)
xs = [x for x in xs if x != maximum]
k -= 1
return maximum
def minimumEditDistance(s1,s2):
if len(s1) > len(s2):
s1,s2 = s2,s1
distances = range(len(s1) + 1)
for index2,char2 in enumerate(s2):
newDistances = [index2+1]
for index1,char1 in enumerate(s1):
if char1 == char2:
newDistances.append(distances[index1])
else:
newDistances.append(1 + min((distances[index1],
distances[index1+1],
newDistances[-1])))
distances = newDistances
return distances[-1]
print(minimumEditDistance("kitten","sitting"))
print(minimumEditDistance("rosettacode","raisethysword"))
"""
Permutations
"""
def permutations(string, step = 0):
# if we've gotten to the end, print the permutation
if step == len(string):
print "".join(string)
# everything to the right of step has not been swapped yet
for i in range(step, len(string)):
# copy the string (store as array)
string_copy = [character for character in string]
# swap the current index with the step
string_copy[step], string_copy[i] = string_copy[i], string_copy[step]
# recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)
permutations(string_copy, step + 1)
|
b09eaf732235660df644474829ad62d30cda20b5 | Louvani/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 561 | 4.0625 | 4 | #!/usr/bin/python3
"""Module learn how to Search and update in a file"""
def append_after(filename="", search_string="", new_string=""):
"""function to inserts a line of text to a file,
after each line containing a specific string """
cp_line = []
with open(filename, encoding='utf-8') as f:
for line in f:
cp_line.append(line)
if search_string in line:
cp_line.append(new_string)
with open(filename, mode="w", encoding='utf-8') as f:
for line in cp_line:
f.write(line)
|
77d77de31824605f5fad5e4b756696d84bd4a31d | XianYX/Python- | /Snake game with frame.py | 2,368 | 3.734375 | 4 | from Tkinter import *
import random
class SnakeGame:
def __init__(self):
# moving step for snake and food
self.step=15
# game score
self.gamescore=0
# to initialize the snake in the range of (x1,y1,x2,y1)
r=random.randrange()
self.snakeX=[]
self.snakeY=[]
# to initialize the moving direction
self.snakeDirection = ' '
self.snakeMove = []
# to draw the game frame
window = Tk()
window.geometry("600x400+10+10")
window.maxsize(600,400)
window.minsize(600,400)
window.title("Snake game")
self.frame1=Frame(... ...)
self.frame2=Frame(... ...)
self.canvas=Canvas(... ...)
self.score_label=Label(... ...)
self.frame1.pack()
self.frame2.pack(fill=BOTH)
self.score_label.pack(side=LEFT)
self.canvas.pack(fill=BOTH)
self.draw_wall()
self.draw_score()
self.draw_food()
self.draw_snake()
self.play()
window.mainloop()
"=== View Part ==="
def draw_wall(self):
pass
def draw_score(self):
self.score() # score model
self.score_label.config(... ...) # score view
def draw_food(self):
self.canvas.delete("food")
self.foodx,self.foody=self.random_food() #food model
self.canvas.create_rectangle(... ...,fill=... ,tags="food") #food view
def draw_snake(self):
self.canvas.delete("snake")
x,y=self.snake() # snake model
for i in range(len(x)): # snake view
self.canvas.create_rectangle(... ..., fill=...,tags='snake')
"=== Model Part ==="
# food model
def random_food(self):
pass
# snake model
def snake(self):
pass
#score model
def score(self):
pass
"=== Control Part ==="
def iseated(self):
pass
def isdead(self):
pass
def move(self,event):
pass
def play(self):
pass
def gameover(self):
pass
def restart(self,event):
pass
SnakeGame()
|
835ebccf51c229885b577cb81095e695095d54fe | gsudarshan1990/Training_Projects | /Classes/class_example134.py | 416 | 3.78125 | 4 | #This is python program on Multiple Inheritance
class GrandParent:
def height(self):
print('I have inherited height from Grand Parent')
class Parent(GrandParent):
def intelligence(self):
print('I have inherited intelligence from Parent')
class Child(Parent):
def experience(self):
print('I have my experience of my own')
c = Child()
c.height()
c.experience()
c.intelligence() |
c515d2b428fabbcebbbfc37d85ffcb7ebbdda34c | WIC-ING/AllPython | /IntroductiontoAlgorithms/dynamicProgramming/Fibonacci sequence.py | 936 | 4.25 | 4 | # -*- coding: utf-8 -*-
import time
# 函数名称:fibonacciSequence
# 函数功能:自底向上 -- 产生斐波切纳数列中的某一位
# 输入参数:int
# 返回参数:int
def fibonacciSequence(n):
if n<=2: return 1
seq = [1, 1]
for i in range(2, n):
seq.append(seq[-1] + seq[-2])
return seq[-1]
# 函数名称:fibonacciSequence_up_to_buttom
# 函数功能:自顶向下 -- 产生斐波切纳数列中的某一位
# 输入参数:int
# 返回参数:int
def fibonacciSequence_up_to_buttom(n):
if n<=2: return 1
return fibonacciSequence_up_to_buttom(n-1) + fibonacciSequence_up_to_buttom(n-2)
n = 35
startTime = time.time()
print (fibonacciSequence(n))
endTime = time.time()
print ('共耗时:{}s\n\n'.format(endTime-startTime))
startTime = time.time()
print (fibonacciSequence_up_to_buttom(n))
endTime = time.time()
print ('共耗时:{}s'.format(endTime-startTime))
|
3b0c7c590154dd6fface0f9b3930ffe3a44b824b | foxtype/python | /wiki_scraper/wiki_scraper.py | 2,430 | 3.59375 | 4 | #import Dependencies
#BS helps with parsing data from the web.
from bs4 import BeautifulSoup
#python Lybrary, used for deailing with HTML CSS and other web technologies
import requests
# Helps us perform regular expressions
import re
#a wrapper around functions that already exist in python ie. addition subtraction
import operator
#help parse our json
import json
#creates nice table in terminal
from tabulate import tabulate
#system calls to take user input
import sys
#words that don't matter in natural laguage like 'the', and 'to'
from stop_words import get_stop_words
#get Data from wikipedia
#create link to wiki api
wikipedia_api_link = "https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srsearch="
wikipedia_link = "https://en.wikipedia.org/wiki/"
if (len(sys.argv) < 2):
print("Enter Valid String")
exit()
#get the search word
string_query = sys.argv[1]
if (len(sys.argv) > 2):
search_mode = True
else:
search_mode = False
#create url
url = wikipedia_api_link + string_query
try:
response = requests.get(url)
data = json.loads(response.content.decode('utf-8'))
#format this data
wikipedia_page_tag = data['query']['search'][0]['title']
#create our new url
url = wikipedia_link + wikipedia_page_tag
page_word_list = getWordList(url)
#create table of word counts
page_word_count = CreateFrequencyTable(page_word_list)
sorted_word_frequency_list = sorted(page_word_count.items(), key = operator.itemgetter(1), reverse = True)
#remove stop words
if(search_mode):
sorted_word_frequency_list = remove_stop_words(sorted_word_frequency_list)
#sum total words to calculate frequencies
total_words_sum = 0
for key, value in sorted_word_frequency_list:
total_words_sum += value
#get top 20 words to display in table
if len(sorted_word_frequency_list) > 20 :
sorted_word_frequency_list = sorted_word_frequency_list[:20]
#create our final list, words + frequency counts + percentage
final_list = []
for key, vale in sorted_word_frequency_list:
percentage_value = float(value * 100) / total_words_sum
final_list.append(key, value, round(percentage_value, 4))
print_headers = ['Word', 'Frequency', 'Frequency Percentage']
#print the table with tabulate
print(tabulate(final_list, headers=print_headers, tablefmt='orgtbl'))
#throw an exception in case it breaks
except requests.exceptions.Timeout:
print("The server didn't respond. Please, try again later.") |
d50ee114e5abc13a3579a4f609f186720216f9aa | idloea/manfred-jobs | /web_scrapping.py | 520 | 3.515625 | 4 | from bs4 import BeautifulSoup
import requests
def get_href_to_list(url):
"""
Get all the href elements of a URL to a list
:param url: URL of the website to extract the href elements
:return: list of href elements
"""
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
text_list = []
href_list = []
for element in soup.findAll('a'):
text_list.append(element.contents[0])
href_list.append(element['href'])
return text_list, href_list
|
336de1cf555630e4b375801fc543b3d440712e5b | gururajks/algos | /check_permutation.py | 650 | 3.75 | 4 | import unittest
from collections import Counter
def check_permutation(input1, input2):
c1 = Counter(input1)
c2 = Counter(input2)
for k, v in c1.items():
if c2[k] != v:
return False
return True
class check_permutation_unit_test(unittest.TestCase):
def test_check_permutation(self):
input1 = "abba"
input2 = "bbaa"
self.assertEqual(check_permutation(input1, input2), True)
def test_check_permutation_fail(self):
input1 = "abbc"
input2 = "bbcaa"
self.assertEqual(check_permutation(input1, input2), False)
if __name__ == '__main__':
unittest.main()
|
156a8186cff7973b1532bd0adf7ef863512085eb | ShubhamJha21/python-rough-work | /Object Introspection.py | 761 | 3.765625 | 4 | class Mobiephones():
def __init__(self):
self.brand = ["mi","nokiya","lenovo"]
self.battery_capacity =["3000mhz","4000mhz","6000mhz"]
def rint_details(self):
return f"mobile brands {self.brand} have {self.battery_capacity} battery capacity"
def ispe(self,str,classstr):
self.object = str
namre =self.class1 = classstr
import inspect
return f"All members of mobiles object are \n {inspect.getmembers(self.object)} \n is it a class if yes than return trues else false\n {inspect.isclass(self.object)}\n all members of main class Mobile_phone are \n {inspect.getmembers(namre)} "
mobiles = Mobiephones()
print(mobiles.rint_details())
print(mobiles.ispe("mobiles","Mobilephones"))
|
17080120ff48422589779a7970b8f2c418bdab02 | eepgwde/godel-program-converter | /src/encode_program/encode_program.py | 3,182 | 3.859375 | 4 | from typing import Generator, Tuple
from src.godel_utils import encode_pair, sequence_to_godel_number
from .constants import ADD_REGEX, GOTO_REGEX, MINUS_REGEX, NOOP_REGEX
def encode_label(label: str) -> int:
"""
Encodes a label into a number
If there is no label, the number is 0.
Othewise, the number is the index in the sequence:
```
A1, B1, C1, D1, E1, A2, B2, C2, ...
```
A, B, C, D, E are interpretted as A1, B1, C1, D1, E1, respectively.
"""
if not label:
return 0
# part after letter if it has a number, otherwise 1
index = int(label[1:]) if len(label) > 1 else 1
# A = 1, B = 2, ... E = 5
offset = ord(label[0]) - ord("A") + 1
# compute label number
return (index - 1) * 5 + offset
def encode_var(variable: str) -> int:
"""
Encodes a label into a number
Returns the index of the variable in the sequence:
```
Y, X1, Z1, X2, Z2, X3, Z3, ...
```
X and Z are interpretted as X1 and Z1, respectively.
"""
if variable == "Y":
return 1
index = int(variable[1:]) if len(variable) > 1 else 1
offset = {"X": 0, "Z": 1}[variable[0]]
return index * 2 + offset
def convert_instruction(instruction: str) -> Tuple[int, int, int]:
"""
Determine the a, b, and c values for a given instruction as a string
a = 0 for unlabeled instructions, otherwise a = #(L) where L is the instruction label
b represents the type of instruction:
- NOOP: b = 0
- ADD: b = 1
- SUB: b = 2
- GOTO: b = #(L) + 2 where L is the target label
c = #(V) - 1 where V is the variable in the instruction
"""
# NOOP
if match := NOOP_REGEX.match(instruction):
instruction_type = 0
# ADD
elif match := ADD_REGEX.match(instruction):
instruction_type = 1
# MINUS
elif match := MINUS_REGEX.match(instruction):
instruction_type = 2
# GOTO
elif match := GOTO_REGEX.match(instruction):
instruction_type = encode_label(match.group("TARGET")) + 2
# No match
else:
raise ValueError(f"Unrecognized instruction: {instruction}")
# get a and c from the label and variable capture groups
label = encode_label(match.group("LABEL"))
variable = encode_var(match.group("VAR")) - 1
return label, instruction_type, variable
def encode_instruction(instruction: str) -> int:
"""
Encodes a given instruction into a number
An instruction number is the pair encoding of `<a, <b, c>>` where `a` represents
the label, `b` represents the instruction type, and `c` represents the variable
"""
a, b, c = convert_instruction(instruction)
return encode_pair(a, encode_pair(b, c))
def encode_program_as_sequence(program: str) -> Generator[int, None, None]:
"""
Encodes a program into a sequence of numbers
Each instruction is encoded into a number and yielded
"""
instructions = program.split("\n")
# yield each instruction number for every non-empty line
return (encode_instruction(i) for i in instructions if i != "")
def encode_program_as_number(program: str) -> int:
"""
Encodes a program into a program number
First, the program is encoded as a sequence of instruction numbers
Then, the sequence is converted into a program number using its Gödel number - 1
"""
return sequence_to_godel_number(encode_program_as_sequence(program)) - 1
|
f0cef96d25892e261438ff813eb0ed5cf0712b53 | JaimeyHolm/Programming | /Opdracht 9.1.py | 324 | 3.65625 | 4 | def sum():
total = 0
aantalKeer = 0
while True:
nextInt = (input('next int: '))
if nextInt == '0':
break
else:
total += int(nextInt)
aantalKeer += 1
return aantalKeer, total
x, y = sum()
print('Er zijn', x, 'getallen ingevoerd, de som is:', y) |
95909bec400f2a893038405ed1115d4cc8843045 | holsky/stralg12 | /stralgsearch.py | 2,532 | 3.546875 | 4 | #!bin/python
from __future__ import print_function
import sys
import random
import time
def calc_border_array(string):
"""
>>> calc_border_array("aaba")
[0, 1, 0, 1]
>>> calc_border_array("bbba")
[0, 1, 2, 0]
>>> calc_border_array("abaabaab")
[0, 0, 1, 1, 2, 3, 4, 5]
"""
border = [0] * len(string)
border[0] = 0
for i in xrange(1, len(string)):
b = border[i-1]
while b > 0 and not (string[i] == string[b]):
b = border[b-1]
if string[i] == string[b]:
border[i] = b+1
else:
border[i] = 0
return border
def search_ba(string, pattern):
"""
>>> search_ba("aba", "ab")
[0]
>>> search_ba("abaaabaabaa", "ab")
[0, 4, 7]
>>> search_ba("mississippi", "ss")
[2, 5]
"""
border = calc_border_array(pattern + '$' + string)
m = len(pattern)
results = []
for i, b in enumerate(border):
if b == m:
results += [i - 2*m]
return results
def search_kmp(string, pattern):
"""
>>> search_kmp("aba", "ab")
[0]
>>> search_kmp("abaaabaabaa", "ab")
[0, 4, 7]
>>> search_kmp("mississippi", "ss")
[2, 5]
>>> search_kmp("acc", "ac")
[0]
"""
border = calc_border_array(pattern)
shift = [0] + [x+1 for x in border]
i = 0
j = 0
m = len(pattern)
results = []
while i <= len(string) - m + j:
while j < m and (string[i] == pattern[j]) :
i = i + 1
j = j + 1
if j == m:
results += [i-m]
if j==0:
i = i + 1
else:
j = shift[j] - 1
return results
def open_file_and_search(search_function, text_file, pattern):
try:
with file(text_file) as f:
text = f.read()
results = search_function(text, pattern)
for r in results:
print(str(r) + " " , end='')
except IOError:
print ("file not found:" + text_file)
def benchmark_searches(search_function):
text = "A"*100
pattern_start = 5
pattern_max = 60
steps = 20
for i in xrange(1,steps + 1):
pattern = "A" * (i*(pattern_max/steps) - 1) + "B"
t_start = time.time()
t = 0
for j in xrange(2000):
search_function(text, pattern)
t += time.time() - t_start
print("{} {}".format(len(pattern), t)) |
9e7e03df37bd8be14ad1b826dc2fea46455e63bf | Parker609/leetcode | /ptoffer58_2.py | 521 | 4.125 | 4 | """
剑指 Offer 58 - II. 左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数
将返回左旋转两位得到的结果"cdefgab"。
"""
"""
其实还是栈堆的知识,就不赘述了。
"""
def reverseLeftWords(s: str, n: int) -> str:
return s[n:] +s[:n]
if __name__ == '__main__':
res = reverseLeftWords("abcde",1)
print(res) |
e968f87951840d6f088c0b4ef87dbed2141a602b | daizutabi/machine-learning | /docs/tensorflow/b1_チュートリアル/p1_初級/c01_KerasによるMLの基本/s05_過学習と学習不足.py | 5,123 | 3.65625 | 4 | # # 過学習と学習不足
# # (https://www.tensorflow.org/tutorials/keras/overfit_and_underfit)
import matplotlib.pyplot as plt
import numpy as np
from tensorflow import keras
# ## IMDBデータセットのダウンロード
NUM_WORDS = 10000
(train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(
num_words=NUM_WORDS
)
def multi_hot_sequences(sequences, dimension):
# 形状が (len(sequences), dimension)ですべて0の行列を作る
results = np.zeros((len(sequences), dimension))
for i, word_indices in enumerate(sequences):
results[i, word_indices] = 1.0 # 特定のインデックスに対してresults[i] を1に設定する
return results
train_data = multi_hot_sequences(train_data, dimension=NUM_WORDS)
test_data = multi_hot_sequences(test_data, dimension=NUM_WORDS)
# -
plt.plot(train_data[0])
# ## 過学習のデモ
# ### 比較基準を作る
baseline_model = keras.Sequential(
[
# `.summary` を見るために`input_shape`が必要
keras.layers.Dense(16, activation="relu", input_shape=(NUM_WORDS,)),
keras.layers.Dense(16, activation="relu"),
keras.layers.Dense(1, activation="sigmoid"),
]
)
baseline_model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy", "binary_crossentropy"],
)
baseline_model.summary()
# -
baseline_history = baseline_model.fit(
train_data,
train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2,
)
# ### より小さいモデルの構築
smaller_model = keras.Sequential(
[
keras.layers.Dense(4, activation="relu", input_shape=(NUM_WORDS,)),
keras.layers.Dense(4, activation="relu"),
keras.layers.Dense(1, activation="sigmoid"),
]
)
smaller_model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy", "binary_crossentropy"],
)
smaller_model.summary()
# -
smaller_history = smaller_model.fit(
train_data,
train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2,
)
# ### より大きなモデルの構築
bigger_model = keras.models.Sequential(
[
keras.layers.Dense(512, activation="relu", input_shape=(NUM_WORDS,)),
keras.layers.Dense(512, activation="relu"),
keras.layers.Dense(1, activation="sigmoid"),
]
)
bigger_model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy", "binary_crossentropy"],
)
bigger_model.summary()
# -
bigger_history = bigger_model.fit(
train_data,
train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2,
)
# ### 訓練時と検証時の損失をグラフにする
def plot_history(histories, key="binary_crossentropy"):
plt.figure(figsize=(12, 8))
for name, history in histories:
val = plt.plot(
history.epoch,
history.history["val_" + key],
"--",
label=name.title() + " Val",
)
plt.plot(
history.epoch,
history.history[key],
color=val[0].get_color(),
label=name.title() + " Train",
)
plt.xlabel("Epochs")
plt.ylabel(key.replace("_", " ").title())
plt.legend()
plt.xlim([0, max(history.epoch)])
plot_history(
[
("baseline", baseline_history),
("smaller", smaller_history),
("bigger", bigger_history),
]
)
# ## 過学習防止の戦略
# ### 重みの正則化を加える
l2_model = keras.models.Sequential(
[
keras.layers.Dense(
16,
kernel_regularizer=keras.regularizers.l2(0.001),
activation="relu",
input_shape=(NUM_WORDS,),
),
keras.layers.Dense(
16, kernel_regularizer=keras.regularizers.l2(0.001), activation="relu"
),
keras.layers.Dense(1, activation="sigmoid"),
]
)
l2_model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy", "binary_crossentropy"],
)
l2_model_history = l2_model.fit(
train_data,
train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2,
)
# -
plot_history([("baseline", baseline_history), ("l2", l2_model_history)])
# ### ドロップアウトを追加する
dpt_model = keras.models.Sequential(
[
keras.layers.Dense(16, activation="relu", input_shape=(NUM_WORDS,)),
keras.layers.Dropout(0.5),
keras.layers.Dense(16, activation="relu"),
keras.layers.Dropout(0.5),
keras.layers.Dense(1, activation="sigmoid"),
]
)
dpt_model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy", "binary_crossentropy"],
)
dpt_model_history = dpt_model.fit(
train_data,
train_labels,
epochs=20,
batch_size=512,
validation_data=(test_data, test_labels),
verbose=2,
)
# -
plot_history([('baseline', baseline_history),
('dropout', dpt_model_history)])
|
bb8d535cf65dcf71a0b83b533ccbf8999b0878aa | PeterSchell11/Python---Beginnings | /#Two Dimensional Lists.py | 692 | 4.0625 | 4 | #Two Dimensional Lists
students=[['Joe', 'Kim'],['Sam','Sue'],['Kelly','Chris']]
print(students)
print(students[0])
print(students[1])
print(students[2])
def main():
#Create a two dimensional list
values=[[1,2,3],
[10,20,30],
[100,200,300]]
for row in values:
for element in row:
print(element)
main()
import random
rows=3 cols=4
def main1():
values=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for r in range(rows):
for c in range(cols):
values[r][c]=random.randint(1, 100)
print (values)
main1()
import random
rows=2 cols=2
values=[[0,0],
[0,0]]
for r in range(rows):
for c in range(cols):
values[r][c]=random.randint(1, 10)
print (values)
|
502781ec19a7c858460dc52afa9461e801462d10 | davidyuanyue/Mars-Rover | /model/Rover.py | 2,587 | 3.515625 | 4 | from .Plateau import Plateau
from constants import INSTRUCTION_LEFT_TURN, INSTRUCTION_RIGHT_TURN, INSTRUCTION_MOVE, NORTH, WEST, SOUTH, EAST
_DIRECTIONS_TURN_LEFT = {NORTH: WEST, SOUTH: EAST, WEST: SOUTH, EAST: NORTH}
_DIRECTIONS_TURN_RIGHT = {NORTH: EAST, SOUTH: WEST, WEST: NORTH, EAST: SOUTH}
_DELTA = {NORTH: (0, 1), SOUTH: (0, -1), WEST: (-1, 0), EAST: (1, 0)}
class Direction:
def __init__(self, symbol):
if symbol not in _DIRECTIONS_TURN_LEFT.keys():
raise Exception('invalid direction {}'.format(symbol))
self._symbol = symbol
def left(self):
return Direction(_DIRECTIONS_TURN_LEFT[self._symbol])
def right(self):
return Direction(_DIRECTIONS_TURN_RIGHT[self._symbol])
def delta(self):
return _DELTA[self._symbol]
def __repr__(self):
return self._symbol
class Rover:
def __init__(self, name):
self._name = name
self._plateau = None
self._x_position = None
self._y_position = None
self._direction = None
def land(self, plateau: Plateau, landing_x: int, landing_y: int, direction : str):
if not plateau.is_valid_position(landing_x, landing_y):
raise Exception("Not able to land because of valid landing for {}, {}".format(landing_x, landing_y))
self._plateau = plateau
self._x_position = landing_x
self._y_position = landing_y
self._direction = Direction(direction)
def _left_turn(self):
self._direction = self._direction.left()
def _right_turn(self):
self._direction = self._direction.right()
def _move(self):
delta_x, delta_y = self._direction.delta()
proposed_move_x, proposed_move_y = self._x_position + delta_x, self._y_position + delta_y
if not self._plateau.is_valid_position(proposed_move_x, proposed_move_y):
raise Exception("Not able to make the move because of valid landing for {}, {}".format(proposed_move_x, proposed_move_y))
self._x_position = proposed_move_x
self._y_position = proposed_move_y
def send_move_instructions(self, instructions):
for instruction in instructions:
if instruction is INSTRUCTION_LEFT_TURN:
self._left_turn()
elif instruction is INSTRUCTION_RIGHT_TURN:
self._right_turn()
elif instruction is INSTRUCTION_MOVE:
self._move()
def get_position_and_direction(self):
return '{}:{} {} {}'.format(self._name, self._x_position, self._y_position, self._direction)
|
6ec1bee818b74f8641e4c4e93edf4cbc735785fb | k-r-jain/misc | /algorithms_assignment_1/multiplication.py | 4,838 | 3.75 | 4 | from random import randint
from timeit import timeit
# from memory_profiler import profile
import matplotlib.pyplot as plt
from sys import getsizeof
def gen_rand_ints(digit_size = 8, list_size = 1000):
'''Returns a list of m integers each of n digits where m = list_size and n = digit_size'''
list_of_ints = []
for i in range(list_size):
digit = str(randint(1, 9)) # So that the most significant digit is not set to zero effectively making the result of size n - 1
for j in range(1, digit_size):
digit += str(randint(0, 9)) # String concatenation
list_of_ints.append(int("".join(digit)))
return list_of_ints
# @profile
def multiply(operand_a, operand_b):
'''Returns an integer which is the product of two arguments passed. Works only for unsigned decimal numbers'''
# Generating a fixed size matrix using python's multiplication operator (*)
elementary_multiplication_matrix = [[0 for i in range(10)] for j in range(10)]
for i in range(10):
for j in range(10):
elementary_multiplication_matrix[i][j] = i * j # To generate all 100 combinations of multiplications from 0x0 = 0 to 9x9 = 81
# Convert the two integers into list and reverse them (for ease of calculation)
a = list(map(int, list(str(operand_a))))[::-1]
b = list(map(int, list(str(operand_b))))[::-1]
result = 0
# Cache is of size 10. It is used to store the result of operand_a * p where p is a single digit [0, 9]
cache = [-1 for j in range(10)]
cache[0] = 0 # Since operand_a * 0 = 0
for b_index in range(len(b)): # Grab one digit at a time from the second operand
if(cache[b[b_index]] == -1): # Set cache if unavailable to save time later on
tmp_result = 0
for a_index in range(len(a)): # Grad one digit at a time from the first operand
# p * q (where p and q are both [0, 9]) is looked up in the elementary_multiplication_matrix. The number of the zeros appended depends on the position of digit with first operand
# For example, if q is a digit in the tens' place in operand_a, one zero will be appended
tmp_result += int(str(elementary_multiplication_matrix[b[b_index]][a[a_index]]) \
+ ''.join(['0' for i in range(a_index)]))
cache[b[b_index]] = tmp_result # Save the result in cache
result += int(str(cache[b[b_index]]) + ''.join(['0' for i in range(b_index)])) # Same drill of appending zeros as above but w.r.t. the second operand
# Returning sum of sizes of all the variables in this function to analyze space complexity
# Using this technique since various memory profilers indicated O(1) which is, obviously, incorrect
total_size = getsizeof(elementary_multiplication_matrix) + getsizeof(cache) + getsizeof(result) + getsizeof(operand_a) + getsizeof(operand_b) + \
getsizeof(a) + getsizeof(b) + getsizeof(tmp_result)
total_size /= (1024) # To return output in Kilobytes
return result, total_size
def wrapper_multiply(): # Since timeit doesn't accept functions with parameters
for i in range(number_of_observations):
result, total_size = multiply(operand_a_list[i], operand_b_list[i])
if __name__ == "__main__":
sizes = [4, 8, 16, 32, 64, 128, 256, 512]
number_of_observations = 1000 # Number of random tests for each size
time_list = []
operand_a_list = []
operand_b_list = []
memory_list = []
for size in sizes:
operand_a_list = gen_rand_ints(digit_size = size, list_size = number_of_observations)
operand_b_list = gen_rand_ints(digit_size = size, list_size = number_of_observations)
time = timeit(wrapper_multiply, number = 1)
avg_memory_used = 0
# Running the same operations for the second time since timeit function dumps the multiply function's return values (which we need to calculate memory usage)
for i in range(number_of_observations):
result, total_size = multiply(operand_a_list[i], operand_b_list[i])
avg_memory_used += total_size
avg_memory_used /= number_of_observations
print("For size", size, ", Time:", time, "Space:", avg_memory_used)
time_list.append(time)
memory_list.append(avg_memory_used)
# Plotting results
fig, ax = plt.subplots()
ax.plot(sizes, time_list, color = 'b', label = "Time (in seconds)")
ax.plot(sizes, memory_list, color = 'g', label = "Space (in Kilobytes)")
ax.scatter(sizes, time_list, s = 35, c = 'b')
ax.scatter(sizes, memory_list, s = 35, c = 'g')
ax.legend(loc = 'upper left', shadow = True)
plt.xlabel("Input size (n digits)")
plt.ylabel("Cost")
plt.title("Custom multiplication results")
plt.show() |
45a85781f95c5f5dae59740ef1b254e42834a7ee | junyechen/Basic-level | /1009 说反话.py | 706 | 4.34375 | 4 | #给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
#输入格式:
#测试输入包含一个测试用例,在一行内给出总长度不超过 80
#的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。
#输出格式:
#每个测试用例的输出占一行,输出倒序后的句子。
#输入样例:
#Hello World Here I Come
#输出样例:
#Come I Here World Hello
sentence = str(input())
sentence = sentence.split(' ')
sentence = list(reversed(sentence))
print(' '.join(sentence)) |
960a52f2941291206cfe9f2a659b84849008e975 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/521a9e43970a4d4f99807829cb74ac18.py | 1,191 | 3.65625 | 4 | import datetime
import calendar
WEEKLIST = list(calendar.day_name)
def meetup_day(year, month, dayOfWeek, dayType):
weekday_index = WEEKLIST.index(dayOfWeek.title())
num_days = calendar.monthrange(year, month)[1]
days = []
for day in range(1, num_days + 1):
if datetime.date(year, month, day).weekday() == weekday_index:
days.append(day)
if dayType.lower() == 'teenth':
for day in days:
if 12 < day < 20:
return datetime.date(year, month, day)
if dayType.lower() == '1st' or dayType.lower() == 'first':
return datetime.date(year, month, days[0])
if dayType.lower() == 'last':
return datetime.date(year, month, days[-1])
if dayType.lower() == '2nd' or dayType.lower() == 'second':
return datetime.date(year, month, days[1])
if dayType.lower() == '3rd' or dayType.lower() == 'third':
return datetime.date(year, month, days[2])
if dayType.lower() == '4th' or dayType.lower() == 'fourth':
return datetime.date(year, month, days[3])
if dayType.lower() == '5th' or dayType.lower() == 'fifth':
return datetime.date(year, month, days[4])
|
61a58875482fafc9e606efa729b7f1a23819247e | JoshBasham/Cosc499GithubGroup | /scripts/median.py | 234 | 3.734375 | 4 | ##the median of the array
def median(nums):
n = len(nums)
if n%2 == 0:
median1 = nums[n//2]
median2 = nums[n//2-1]
median = (median1 + median2)/2
else:
median = nums[n//2]
return median |
806d1fa8c6b57b9d01460a496ab06b003c9cbef8 | gus-an/algorithm | /2020/05-3/recursive_13699.py | 539 | 3.65625 | 4 | my_hash = {}
def rec(n):
if n == 0:
return 1
else:
a = 0
for i in range(n):
if i in my_hash:
l = my_hash[i]
else:
l = rec(i)
my_hash[i] = l
if (n-1-i) in my_hash:
r = my_hash[n-1-i]
else:
r = rec(n-1-i)
my_hash[n-1-i] = r
a += l * r
return a
if __name__ == "__main__":
N = int(input())
result = rec(N)
print(result)
print(x) |
5f1690caa34b6ddeb1c7a2020b6b307f1b97717c | BerlinTokyo/Python_new | /nvod_while.py | 11,725 | 4.15625 | 4 | #Для получения данных в программах используется функция input().
#Цикл while в языке Python позволяет выполнять программу, пока некоторое условие остается истинным.
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
#В этом примере продемонстрирован один из способов построения длинных строк. Первая часть длинного сообщения сохраняется в переменной prompt. Затем оператор += объединяет текст, хранящийся в prompt, с новым фрагментом текста.
#Использование int() для получения числового ввода
#При работе с числовыми данными может пригодиться оператор вычисления остатка (%), который делит одно число на другое и возвращает остаток:
print(4 % 3)
#1
#Четные числа всегда делятся на 2. Следовательно, если остаток от деления на 2 равен 0 (number % 2 == 0), число четное, а если нет — нечетное.
#Циклы while
#Цикл for получает коллекцию элементов и выполняет блок кода по одному разу для каждого элемента в коллекции. В отличие от него, цикл while продолжает выполняться, пока остается истинным некоторое условие.
#Цикл while может использоваться для перебора числовой последовательности.
#Например, следующий цикл считает от 1 до 5:
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1 #(Оператор += является сокращенной формой записи для current_number = current_number + 1.)
#Программа может выполняться, пока пользователь не захочет остановить ее, — для этого бульшая часть кода заключается в цикл while. В программе определяется признак завершения, и программа работает, пока пользователь не введет нужное значение:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
#while message != 'quit':
#message = input(prompt)
#print(message)
#Программа работает неплохо, если не считать того, что она выводит слово 'quit', словно оно является обычным сообщением. Простая проверка if решает проблему:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
#while message != 'quit':
#message = input(prompt)
#if message != 'quit':
#print(message)
#Флаги
#В предыдущем примере программа выполняла некоторые операции, пока заданное условие оставалось истинным. А что если вы пишете более сложную программу, выполнение которой может прерываться по нескольким разным условиям? Например, компьютерная игра может завершаться по разным причинам: у игрока кончились все «жизни»; прошло отведенное время; все города, которые он должен был защищать, были уничтожены и т. д. Игра должна завершаться при выполнении любого из этих условий. Попытки проверять все возможные условия в одной команде while быстро усложняются и становятся слишком громоздкими.
#Если программа должна выполняться только при истинности нескольких условий, определите одну переменную-флаг.
#Добавим флаг в программу parrot.py из предыдущего раздела. Этот флаг, который мы назовем active (хотя переменная может называться как угодно), управляет тем, должно ли продолжаться выполнение программы:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
#while active:
#message = input(prompt)
#if message == 'quit':
#active = False
#else:
#print(message)
#Команда break и выход из цикла
#Чтобы немедленно прервать цикл while без выполнения оставшегося кода в цикле независимо от состояния условия, используйте команду break.
#Команда continue и продолжение цикла
#Вместо того чтобы полностью прерывать выполнение цикла без выполнения оставшейся части кода, вы можете воспользоваться командой continue для возвращения к началу цикла и проверке условия. Например, возьмем цикл, который считает от 1 до 10, но выводит только нечетные числа в этом диапазоне:
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
#Если ваша программа зациклилась, нажмите Ctrl+C или просто закройте терминальное окно с выводом программы.
#DZ
x = "Vedi pervoe dopolnenie: "
x += "\nIli vedi: o "
x += "\n"
w = ""
while w != 2:
w = str(input(x))
if w != 'o':
print(w + " dobavlen")
else:
print("OK")
break
skaz = "Napishi svoi age: "
age = int(input(skaz))
while isinstance(age, int):
if age < 3:
print("Price 0$")
elif 3 <= age <= 12:
print("Price 10$")
else:
print("Price 15$")
break
#Использование циклов while со списками и словарями позволяет собирать, хранить и упорядочивать большие объемы данных для последующего анализа и обработки. Возьмем список недавно зарегистрированных, но еще не проверенных пользователей сайта. Как переместить пользователей после проверки в отдельный список Использование цикла while со списками и словарями 131 проверенных пользователей? Одно из возможных решений: используем цикл while для извлечения пользователей из списка непроверенных, проверяем их и включае в отдельный список проверенных пользователей. Код может выглядеть так:
# Начинаем с двух списков: пользователей для проверки
# и пустого списка для хранения проверенных пользователей.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Проверяем каждого пользователя, пока остаются непроверенные
# пользователи. Каждый пользователь, прошедший проверку,
# перемещается в список проверенных.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: " + current_user.title())
confirmed_users.append(current_user)
# Вывод всех проверенных пользователей.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
#Удаление всех вхождений конкретного значения из списка
#В главе 3 функция remove() использовалась для удаления конкретного значения из списка. Функция remove() работала, потому что интересующее нас значение встречалось в списке только один раз. Но что если вы захотите удалить все вхождения значения из списка? Допустим, имеется список pets, в котором значение 'cat' встречается многократно. Чтобы удалить все экземпляры этого значения, можно выполнять цикл while до тех пор, пока в списке не останется ни одного экземпляра 'cat':
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
#Заполнение словаря данными, введенными пользователем
#При каждом проходе цикла while ваша программа может запрашивать любое необходимое количество данных. Напишем программу, которая при каждом проходе цикла запрашивает имя участника и его ответ. Собранные данные будут сохраняться в словаре, потому что каждый ответ должен быть связан с конкретным пользователем:
responses = {}
# Установка флага продолжения опроса.
polling_active = True
while polling_active:
# Запрос имени и ответа пользователя.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# Ответ сохраняется в словаре:
responses[name] = response
# Проверка продолжения опроса.
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
# Опрос завершен, вывести результаты.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(name + " would like to climb " + response + ".")
sandwich_orders = ['a', 'b', 'x']
finished_sandwiches = []
while sandwich_orders:
sandwich_order = sandwich_orders.pop()
print("I made your tuna sandwich " + sandwich_order)
finished_sandwiches.append(sandwich_order)
for finished_sandwiche in finished_sandwiches:
print(finished_sandwiche) |
873dc9aa5fb75cf4954ed6c21f766b7ed4b964bd | buzsb/PythonExample | /HundredYears.py | 654 | 4.09375 | 4 | # Simple program that ask you age and show year that you will turn 100
# years old
from datetime import date
def calculate_years(age):
if not isinstance(age, int):
return False
if age <= 0 or age >= 100:
return False
now = date.today().year
calculate = (now - age) + 100
return calculate
def say_when():
age = raw_input("Enter your age: ")
add_age = calculate_years(age)
if add_age == False:
print "No! print your age, not some shit, age you understand?"
say_when()
else:
print "100 years you will celebrate in " + str(add_age)
if __name__ == '__main__':
say_when()
|
f677760fc4426aa4612e48a0a587ac3e33b08aaf | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4174/codes/1752_3090.py | 241 | 3.96875 | 4 | N = int(input("movimentos da lagartixa:"))
cont = 0
while(0 < N < 7):
somatorio = N + 7
if(somatorio = 0):
mensagem = ("Abaixo")
cont = cont + 1
else:(somatorio < 0)
mensagem = ("Acima")
cont = 1 *(-1)
print(mensagem)
|
2149ecdbfd0fd32b6288be3f702ad1eaf65e12e2 | bharat-kadchha/tutorials | /python-pandas/Python_Pandas/dataframe/CreateDfFromDictofTuples.py | 434 | 3.65625 | 4 | import pandas as pd
d = {('a', 'b'): {('A', 'B'): 1, ('A', 'C'): 2},
('a', 'a'): {('A', 'C'): 3, ('A', 'B'): 4},
('a', 'c'): {('A', 'B'): 5, ('A', 'C'): 6},
('b', 'a'): {('A', 'C'): 7, ('A', 'B'): 8},
('b', 'b'): {('A', 'D'): 9, ('A', 'B'): 10}
}
df = pd.DataFrame(data=d)
# You can automatically create a MultiIndexed frame by passing a tuples dictionary.
print("DataFrame from Dict of Tuples : ")
print(df) |
7c0cef370aac4a94b1dd0926655f495a3bd59cbc | jaychsu/algorithm | /lintcode/600_smallest_rectangle_enclosing_black_pixels.py | 1,356 | 3.5625 | 4 | class Solution:
def minArea(self, image, x, y):
"""
:type image: list[str]
:type x: int
:type y: int
:rtype: int
"""
if not image or not image[0]:
return 0
m, n = len(image), len(image[0])
top = self.binary_search(image, 0, x, self.is_empty_row)
bottom = self.binary_search(image, m - 1, x, self.is_empty_row)
left = self.binary_search(image, 0, y, self.is_empty_col)
right = self.binary_search(image, n - 1, y, self.is_empty_col)
return (bottom - top + 1) * (right - left + 1)
def binary_search(self, image, start, end, is_empty):
check = None
if start < end:
check = lambda start, end: start + 1 < end
else:
check = lambda start, end: start - 1 > end
while check(start, end):
mid = (start + end) // 2
if is_empty(image, mid):
start = mid
else:
end = mid
return end if is_empty(image, start) else start
def is_empty_row(self, image, x):
for col in image[x]:
if col == '1':
return False
return True
def is_empty_col(self, image, y):
for row in image:
if row[y] == '1':
return False
return True
|
22f295a737603420ed849c25ddce576e7ca07f46 | saumonarticho/Project-Euler | /Problem 2.py | 404 | 4.09375 | 4 | #finds the sum of even-valued terms from the Fibonacci sequence whose values do
#not exceed "n"
def fibo(n):
x = 1
y = 2
liste = [x,y]
z = x+y
while z < n:
z = x+y
if z % 2 == 0:
liste.append(z)
x = y
y = z
else:
x = y
y = z
print(liste)
print(sum(liste))
|
aa848c9083552aa7ccfe07e85ed366cbc65ace4d | gabriellaec/desoft-analise-exercicios | /backup/user_004/ch75_2019_06_06_18_52_27_826626.py | 690 | 3.515625 | 4 | def primo(n):
if n == 1:
return False
elif n == 2:
return True
elif n == 5:
return False
elif n == 3:
return True
elif n % n == 0 and n % 1 == 0 and n % 2 == 0:
return False
elif n % n == 0 and n % 1 == 0 and n % 5 == 0:
return False
elif n % n == 0 and n % 1 == 0 and n % 3 == 0:
return False
else:
return True
def verifica_primos(lista):
dic = {}
i = 0
while i < len(lista):
if primo(lista[i]) == True:
dic[lista[i]] = True
else:
dic[lista[i]] = False
i += 1
return dic
print(verifica_primos([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) |
e6b9ad39d889d48b1e68c22586074b7ed0a29515 | Yaya7/hornets-scrape | /hornets-scrape.py | 1,717 | 3.546875 | 4 | import urllib2
import re
import sys
from bs4 import BeautifulSoup
import csv
import os
import itertools
from itertools import izip
import datetime
from datetime import datetime
from datetime import date
my_url = "http://www.nba.com/hornets/schedule/"
scheduleHTML = urllib2.urlopen(my_url)
# Now we create a beautifulsoup object by passing through html to the BeautifulSoup()
soup = BeautifulSoup(scheduleHTML, "html.parser")
daysofweek = []
weekdays = soup.findAll('span', attrs={'class': 'desktop'})
for day in weekdays:
weekday = str(day.string)
daysofweek.append(weekday)
print len(daysofweek) #89
newdaysofweek = []
for dd in daysofweek:
if(dd == "Sunday"):
dd = "Monday"
newdaysofweek.append(dd)
elif(dd == "Monday"):
dd = "Tuesday"
newdaysofweek.append(dd)
elif(dd == "Tuesday"):
dd = "Wednesday"
newdaysofweek.append(dd)
elif(dd == "Wednesday"):
dd = "Thursday"
newdaysofweek.append(dd)
elif(dd == "Thursday"):
dd = "Friday"
newdaysofweek.append(dd)
elif(dd == "Friday"):
dd = "Saturday"
newdaysofweek.append(dd)
elif(dd == "Saturday"):
dd = "Sunday"
newdaysofweek.append(dd)
gamedates = []
dates = soup.findAll('span', attrs={'class': 'date etowah-schedule__event_datetime__date etowah-schedule__event--game__datetime__date'})
for date in dates:
gameday = str(date.span.next_sibling)
gameday = gameday.strip()
gamedates.append(gameday)
print len(gamedates) #89
rows = zip(newdaysofweek, gamedates)
# Create column headers
headers = ['Weekday', 'Date']
with open("hornets_schedule_2016.csv", 'w') as w:
writer = csv.writer(w)
writer.writerow(headers)
for row in rows:
writer.writerow(row)
# Open the file
os.system("open hornets_schedule_2016.csv")
|
4807df700a19023b3498b9b5756e62704a8c49f2 | collin-yamada/UVa | /Super Easy/hajj/hajj.py | 445 | 3.671875 | 4 | from sys import stdin
case = 0
while True:
hajj = stdin.readline()
hajj = hajj.strip()
case += 1
if hajj == "Hajj":
print("Case ", end = "")
print(case, end = "")
print(": ", end = "")
print("Hajj-e-Akbar")
elif hajj == "Umrah":
print("Case ", end = "")
print(case, end = "")
print(": ", end = "")
print("Hajj-e-Asghar")
else:
break |
77f565f2a37aa3e6d46b60c396334edcf20c73dc | GabrielaVilaro/Ejercicios_Programacion | /POO_2.py | 931 | 3.859375 | 4 | #coding=UTF-8
#Ejercicio de objetos Python, del curso de "Pildoras Informáticas."
class vehiculos(): #herencia
def __init__(self, marca, modelo):
self.marca = marca
self.modelo = modelo
self.enMarcha = False
self.acelera = False
self.frena = False
def arrancar (self):
self.enMarcha = True
def acelerar (self):
self.acelera = True
def frenar (self):
self.frena = True
def estado (self):
print "Marca: " , self.marca, "\nModelo: ", self.modelo, "\nEn marcha: ",
self.enMarcha, "\nAcelerando: ", self.acelera, "\nFrenando: ", self.frena #\n salto de línea
class moto(vehiculos):#hacemos que moto herede todas las propiedades anteriores de vehiculos.
pass
miMoto = moto("Honda", "CBR") #le pasamos los parametros de vehiculos (el constructor de objetos)
miMoto.estado() #hereda las características
raw_input("Oprima ENTER para finalizar.") |
173a0b5f6b11ab7b2b3430d4d5695de3f83ee233 | GalyaBorislavova/SoftUni_Python_Fundamentals_January_2021 | /10_Exams/Exam03.04.2021/Third.py | 1,477 | 3.859375 | 4 | mail = {}
capacity = int(input())
command = input()
while not command == "Statistics":
command = command.split("=")
action = command[0]
if action == "Add":
username = command[1]
sent = int(command[2])
received = int(command[3])
if username not in mail:
mail[username] = {"Sent": sent, "Received": received, "All": sent + received}
elif action == "Message":
sender = command[1]
receiver = command[2]
if sender in mail and receiver in mail:
if mail[sender]["All"] + 1 >= capacity or mail[receiver]["All"] + 1 >= capacity:
if mail[sender]["All"] + 1 >= capacity:
del mail[sender]
print(f"{sender} reached the capacity!")
if mail[receiver]["All"] + 1 >= capacity:
del mail[receiver]
print(f"{receiver} reached the capacity!")
else:
mail[sender]["Sent"] += 1
mail[sender]["All"] += 1
mail[receiver]["Received"] += 1
mail[receiver]["All"] += 1
elif action == "Empty":
username = command[1]
if username == "All":
mail = {}
elif username in mail:
del mail[username]
command = input()
print(f"Users count: {len(mail)}")
for person, mails in sorted(mail.items(), key=lambda x: (-x[1]["Received"], x[0])):
print(f"{person} - {mails['All']}")
|
f90d926fb7c1f0523e77a2d263d42058766c5d1c | guanfuchen/CodeTrain | /SwordOffer/Algorithm/Python/link_list_copy.py | 1,022 | 3.609375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead is None:
return None
pCloneHead = RandomListNode(None)
pCloneList = pCloneHead
random_dict = {}
next_dict = {}
while pHead:
pCloneList.next = RandomListNode(pHead.label)
random_dict[id(pCloneList.next)] = id(pHead.random)
next_dict[id(pHead.next)] = pCloneList.next
pCloneList = pCloneList.next
pHead = pHead.next
pCloneList = pCloneHead.next
while pCloneList:
id_random = random_dict[id(pCloneList)]
pCloneList.random = next_dict[id_random]
pCloneList = pCloneList.next
return pCloneHead.next
if __name__ == '__main__':
# {1, 2, 3, 4, 5, 3, 5, # ,2,#}
pass
|
38d999eef7c9eeece480368abcdf3ad8acb24761 | lumbduck/euler-py | /archive/p046.py | 2,150 | 3.59375 | 4 | """
Goldbach's Other Conjecture
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×1^2
15 = 7 + 2×2^2
21 = 3 + 2×3^2
25 = 7 + 2×3^2
27 = 19 + 2×2^2
33 = 31 + 2×1^2
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
"""
from itertools import count
from math import sqrt
import time
from timeit import timeit
from prime import is_prime, primes, sieve_primes
start_time = time.time()
def is_pass(n, remove_prime_first=False):
"""Return True if n passes the criteria for the given conjecture."""
if remove_prime_first:
for p in primes():
if p > n:
return False
elif sqrt((n - p) / 2).is_integer():
return True
else:
for i in range(1, n // 2):
if is_prime(n - 2 * i**2):
return True
def gen_odd_composites():
step_size = 10000
sieve_primes(step_size) # Cache primes
# Avoiding lower limit. This avoids running an unnecessary filter for each caching step
for j in range(9, step_size + 1, 2):
if not is_prime(j):
yield j
for i in count(2):
sieve_primes(i * step_size + 1) # Cache primes
for j in range(step_size * (i - 1) + 1, step_size * i + 1, 2):
if not is_prime(j):
yield j
def find_first_failure(remove_prime_first=False):
for n in gen_odd_composites():
if not is_pass(n, remove_prime_first):
return n
break
print("First failure: {}".format(find_first_failure()))
print("Execution time: {}".format(time.time() - start_time))
# NOTE: Performance when canceling prime factors first (using :param remove_prime_first:) is dramatically worse.
# Backwards from what I expected. Possibly an issue with primes() generator...?
print(timeit('find_first_failure()', globals={'find_first_failure': find_first_failure}, number=100))
print(timeit('find_first_failure(True)', globals={'find_first_failure': find_first_failure}, number=100))
|
bb56d5c67f3c1b4ba84fd67b8ff14004fb36fa31 | minnonong/Codecademy_Python | /17.Advanced Topics in Python/17_05.py | 176 | 3.578125 | 4 | # 17_05
# 리스트 내포(list comprehension): new_list = [x for x in range() if 조건문]
even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]
print even_squares
|
7251cde04154919a03ac74cabc6ad09039b258f8 | xiangcao/Leetcode | /python_leetcode_2020/Python_Leetcode_2020/241_differents_ways_to_add_parentheses.py | 1,376 | 4.0625 | 4 | """
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 2:
Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
"""
# same algorithm as leetcode 95 Unique BST trees II
class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
self.memoization = {}
return self.allResults(input)
def allResults(self, input: str):
if input in self.memoization:
return self.memoization[input]
if input.isdigit():
return [int(input)]
result = []
for i,c in enumerate(input):
if c in '+-*':
leftResults = self.allResults(input[:i])
rightResults = self.allResults(input[i+1:])
for l in leftResults:
for r in rightResults:
if c == '+':
result.append(l + r)
elif c == '-':
result.append(l - r)
else:
result.append(l * r)
self.memoization[input] = result
return result
|
b638deb5ca9eca81c6af7bad8a5dcb9d57cd4b02 | haanguyenn/python_learning | /simple_coffee_chatbot/utils.py | 1,483 | 4.28125 | 4 | def print_message():
print('We\'re sorry, we did not understand your selection. Please enter the corresponding letter for your response.')
def get_drink_type():
res = input('What type of drink would you like?\n[a] Brewed Coffee \n[b] Mocha \n[c] Latte \n>')
if res.lower() == 'a':
return 'Brewed Coffee'
elif res.lower() == 'b':
return order_mocha()
elif res.lower() == 'c':
return order_latte()
else:
print_message()
return get_drink_type()
def get_size():
res = input('What size drink can I get for your? \n[a] Tall \n[b] Grande \n[c] Venti \n>')
if res.lower() == 'a':
return 'Tall'
elif res.lower() == 'b':
return 'Grande'
elif res.lower() == 'c':
return 'Venti'
else:
print_message()
return get_size()
def order_latte():
res = input('And what kind of milk for your latte?\n[a] 2% milk \n[b] Non-fat milk \n[c] Soy milk \n>')
if res.lower() == 'a':
return 'Latte with 2% milk'
elif res.lower() == 'b':
return 'Latte with Non-fat milk'
elif res.lower() == 'c':
return 'Latte with Soy milk'
else:
print_message()
return order_latte()
def order_mocha():
while True:
res = input('Would you like to try our limited-edition peppermint mocha?\n[a] Sure! \n[b] Maybe next time!\n>')
if res.lower() == 'a':
return 'peppermint mocha'
elif res.lower() == 'b':
return 'Mocha'
print_message()
def get_name():
res = input('Can we get your name? :')
return res
|
8b1ae241b9555318cd904f83515e913e4c88dba0 | tochukwuokafor/my_chapter_7_solution_gaddis_book_python | /driver_license_exam.py | 1,085 | 3.578125 | 4 | def main():
correct_answers = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']
open_file = open('driver_license_exam.txt', 'r')
student_answers = []
for answer in open_file:
answer = answer[:-1]
student_answers.append(answer)
open_file.close()
#print(student_answers)
grading = []
for i in range(20):
if student_answers[i] == correct_answers[i]:
grading.append(True)
else:
grading.append(False)
if grading.count(True) >= 15:
print('The student passed the exam.')
else:
print('The student failed the exam.')
print('The total number of correctly answered questions is', grading.count(True))
print('The total number of incorrectly answered questions is', grading.count(False))
incorrect_question = []
for index, value in enumerate(grading):
if value == False:
index = index + 1
incorrect_question.append(index)
print(incorrect_question)
main() |
9d4948c3f6d958da0e6eca9e72a801bb87ff8740 | vumeshkumarraju/class | /strings activity assesment 2/code7.py | 263 | 4.3125 | 4 | #converting to title case
print("\n\t<<<....WELCOME TO THE PROGRAM....>>>")
print("converting your entered string into title mode.\n")
string=input("enter the string :- ")
print("showing you the entered string in title mode ",end=":- ")
print(string.title())
|
22460ac6a8359e67184906fe4e925ac1bc599c14 | arbalest339/myLeetCodeRecords | /main43strMultiply.py | 478 | 3.78125 | 4 | class Solution:
def multiply(self, num1: str, num2: str) -> str:
num1 = [int(n) for n in num1]
num2 = [int(n) for n in num2]
multi = 0
for n1 in range(1, len(num1)+1):
for n2 in range(1, len(num2)+1):
multi += num1[-n1]*num2[-n2]*pow(10, n1-1)*pow(10, n2-1)
return str(multi)
if __name__ == "__main__":
solution = Solution()
num1 = "123"
num2 = "456"
print(solution.multiply(num1, num2))
|
f6dd75bc3bf434f21494b4511f673be19ae805b1 | XiangSugar/Python | /verification/verf_cli.py | 1,314 | 3.5 | 4 | # coding = utf-8
'''This is a cilent program to test the comunication which is encrypted'''
import rsa
import socket
import time
HOST = '127.0.0.1'
PORT = 9997
BUFSIZE = 2048
ADDR = (HOST, PORT)
key = rsa.newkeys(1024) #生成随机秘钥
privateKey = key[1] #私钥
publicKey = key[0] #公钥
n = publicKey.n
e = publicKey.e
str_n = str(n)
str_e = str(e)
# 创建套接字
tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
tcpCliSock.connect(ADDR)
# 接收欢迎消息:
print(tcpCliSock.recv(BUFSIZE).decode('utf-8'))
tcpCliSock.send(str_n.encode('utf-8'))
time.sleep(1)
tcpCliSock.send(str_e.encode('utf-8'))
time.sleep(1)
# tcpCliSock.send(b'start')
while True:
try:
data = input('>')
#byte_data = data.encode()
#crypted_data = rsa.encrypt(byte_data, publickey)
tcpCliSock.send(data.encode())
if data == 'exit':
break
# 接收加密之后的数据
encrypt_data = tcpCliSock.recv(BUFSIZE)
print('encrypted_data: %s' % encrypt_data.decode('utf-8', errors='ignore'))
decrypt_data = rsa.decrypt(encrypt_data, privateKey)
print(decrypt_data.decode())
except Exception as e:
print('Error: %s' % e)
tcpCliSock.close() |
2ae7942e916b76da8baca8da487ad755015a1ab5 | SpiceGhost/telegram-csgo-server-status-bot | /apps/timer.py | 1,159 | 3.578125 | 4 | import datetime
import time
class DropReset:
def get_time(self):
wanted_day = 'wednesday'
wanted_time = 00
list = [['monday', 0],['tuesday', 1],['wednesday', 2],['thursday', 3],['friday', 4],['saturday', 5],['sunday', 6]]
for i in list:
if wanted_day == i[0]:
number_wanted_day = i[1]
today = datetime.datetime.today().weekday() # delivers the actual day
delta_days = number_wanted_day - today # describes how many days are left until the wanted day
actual_time = time.localtime(time.time()) # delivers the actual time
if wanted_time > actual_time[3]:
delta_hours = wanted_time - actual_time[13]
delta_mins = 59 - actual_time[4]
delta_secs = 59 - actual_time[5]
else:
delta_days = delta_days - 1
delta_hours = 23 - actual_time[3] + wanted_time
delta_mins = 59 - actual_time[4]
delta_secs = 59 - actual_time[5]
if delta_days < 0:
delta_days = delta_days + 7
return delta_days, delta_hours, delta_mins, delta_secs
|
06866720c30f1e9cc2e875da50b9ddc9ca4ddc06 | JarryChung/Python-Learn | /python_1.py | 229 | 4.125 | 4 | # -*- coding: utf-8 -*-
name = input("Enter you name:")
print("hello",name,".")
height = input("Enter your height:")
weight = input("Enter your weight:")
print("Height: %s, Weight: %s" % (height,weight))
print("Number: %d" % 5) |
f1102f2291cc6414ec2f1ce97b3984e0d0333fb6 | SkotarenkoEvgeny/Softformance_scool | /Modul_3_1/Task_3_1_max.py | 4,165 | 3.90625 | 4 | import random
# 1 Створити програму для вгадування числа. Програма запитує користувача число,
# яке він повинен відгадати. Якщо користувач відповів не вірно, програма виводить
# підказку, повідомляє чи число є більшим чи меншим за те, яке потрібно вгадати і
# запитує ще раз. Програма повинна працювати доки користувач не введе вірну
# відповідь.
def game():
number = random.randint(0, 100)
print(number)
atempt = 5
while atempt > 0:
response = int(input('Input a number '))
if response > number:
print('need less')
elif response < number:
print('nees more')
else:
print('you win')
break
atempt -= 1
if atempt == 0:
print('you loose')
print('game over')
#game()
# 2 Створити програму яка згенерує послідовність Фібоначчі для заданого числа N
n = 20
def fib(n, i =0, list = [0, 1]):
if list[i+1] >= n:
return list
else:
list.append(list[i]+list[i+1])
i += 1
return fib(n, i, list)
print(fib(n))
# 3 Реалізувати алгоритм сортування обміном.
mixed_list = [random.randint(0, 30) for i in range(l)]
print('mixed list ', mixed_list)
def simple_buble(mixed_list):
'''
:param mixed_list:
:return: Створити програму сортування списку чисел методом обміну в сервісі scratch.
'''
iter_value = 0
for i in range(len(mixed_list)):
for j in range(len(mixed_list) - 1):
if mixed_list[j + 1] < mixed_list[j]:
temp = mixed_list[j]
mixed_list[j] = mixed_list[j + 1]
mixed_list[j + 1] = temp
iter_value += 1
print('simple iter ', iter_value)
return mixed_list
print('sorted list (simple)', simple_buble(mixed_list))
# 4 Реалізувати алгоритм сортування вибором.
mixed_list = [random.randint(0, 30) for i in range(l)]
print('mixed list ', mixed_list)
def sort_by_choice(mixed_list):
'''
:param mixed_list:
:return: сортування списку чисел методом вибору
'''
k = 0
min = mixed_list[0]
while k < len(mixed_list) - 1:
for i in range(k, len(mixed_list)):
if mixed_list[i] <= min:
min = mixed_list[i]
temp_i = i
temp = mixed_list[k]
mixed_list[k] = min
mixed_list[temp_i] = temp
k += 1
min = mixed_list[k]
return mixed_list
print('List sorted by choice ', sort_by_choice(mixed_list))
# 5 Спробувати самостійно розібратись із алгоритмом обходження графа. Зокрема,
# методом обходу в ширину.
def search(dad, sonn, dl, vay=[]):
vay = vay+[sonn]
if dad == sonn:
return "Yes"
elif sonn not in dl.keys():
return "No"
shortkey = "No"
for d in dl[sonn]:
if d not in vay:
new_search = search(dad, d, dl, vay=[])
if new_search:
if new_search == "Yes":
return "Yes"
shortkey = new_search
return shortkey
a = int(input())
dl = {}
for i in range(a):
s = [f for f in input().split(" : ")]
if len(s) == 1:
dl[s[0]] = s[0] # chek variants
else:
dl[s[0]] = s[1].split()
b = int(input())
for i in range(b):
ansver = input().split()
g = search(ansver[0], ansver[1], dl, vay=[])
print(g)
'''
https://stepik.org/lesson/24462/step/7?unit=6768
завдання
15
G : F
A
B : A
C : A
D : B C
E : D
F : D
X
Y : X A
Z : X
V : Z Y
W : V
Q : P
Q : R
Q : S
9
A G
A Z
A W
X W
X QWE
A X
X X
1 1
Q
Відпвіді:
Yes
No
Yes
Yes
No
No
Yes
No
Yes
''' |
aaace78556f84b94af0304fd6ff839d37b9906ed | seweissman/advent_of_code_2017 | /day2_corruption_checksum.py | 987 | 3.625 | 4 | """
Day 2: Corruption Checksum
"""
def string_to_spreadsheet(s):
rows = [[int(s) for s in row.split()] for row in s.split("\n")]
return rows
def checksum(ss):
rows = string_to_spreadsheet(ss)
checksum = sum(max(row) - min(row) for row in rows)
return checksum
s1 = """5 1 9 5
7 5 3
2 4 6 8"""
# print(string_to_spreadsheet(s1))
assert(checksum(s1) == 18)
def checksum_dividend(ss):
rows = string_to_spreadsheet(ss)
checksum = 0
for row in rows:
for i, val in enumerate(row):
for val2 in row[i+1:]:
if val % val2 == 0:
checksum = checksum + val//val2
if val2 % val == 0:
checksum = checksum + val2//val
return checksum
s2 = """5 9 2 8
9 4 7 3
3 8 6 5"""
assert(checksum_dividend(s2) == 9)
file = open("day2.input.txt")
INPUT = file.read()
INPUT = INPUT.strip()
if __name__ == "__main__":
print(checksum(INPUT))
print(checksum_dividend(INPUT))
|
0b335abb5a0aa332bcb27bd4f3705bb5ae607ada | joaothomaz23/Basic_Python_Journey | /verificador_notas.py | 539 | 3.75 | 4 | v = []
aux = 1
acima = 0
sete = 0
while aux > 0:
nota = float(input('Entre com o valor da nota: '))
aux = nota
v.append(nota)
v.pop()
print('Número de valores lidos: ',len(v))
print(v)
v.reverse()
print(v)
print('Soma dos valores: ',sum(v))
print('Media dos valores: ',sum(v)/len(v))
for i in v:
if i > sum(v)/len(v):
acima += 1
print('Número de valores acima da media: ',acima)
for i in v:
if i < 7:
sete += 1
print('Número de valores abaixo de sete: ',sete)
print('Sifude')
|
7694b0ff31d33818d151294a03437a5b28e8634e | andywillcock/political-analysis-cc | /src/donation-analytics.py | 3,376 | 3.515625 | 4 | from data_checks import *
from extract_repeat_donors import *
import argparse
import numpy as np
import pandas as pd
def find_repeat_donors(input_file,percentile_file,output_file):
"""
Uses the provided files to pull relevant data from pipe-delimited file of FEC donation records. Writes out rows
containing information defined in the output directions of the Insight_Readme.md file.
:param input_file: Filepath of file containing rows of 21 pipedelimited filed as defined by the FEC
:param percentile_file: File containing one number 1-100 defining what percentile to use in calculations
:param output_file: Filepath for output file for results of analysis to be written to
:return: None
"""
records_names = ['CMTE_ID','NAME','ZIP_CODE','TRANS_DT', 'TRANS_AMT', 'OTHER_ID']
# Open input file and read in as stream of data line by line
with open(percentile_file,'r') as percent:
percentile = float(percent.read())
with open(input_file, 'r') as data:
donors = pd.DataFrame(columns=records_names)
holder = {'CMTE_ID':'','NAME':'','ZIP_CODE':'','TRANS_DT':0000,'TRANS_AMT':0,'COUNT':0}
final_set = pd.DataFrame(data = holder,index=[0])
outfile = open(output_file, 'w')
for row in data:
record_data = data_check(row)
#find indices of all repeat donations in the current table (all rows read in)
if record_data != False:
previous_donations = map(int,donors.index[(donors['NAME'] == record_data['NAME']) &
(donors['ZIP_CODE']== record_data['ZIP_CODE'])].tolist())
# Check if all the subsequent donations by the same donor came after the first donation's date
if previous_donations != []:
if donors.iloc[previous_donations[0]]['TRANS_DT'] <= record_data['TRANS_DT']:
# Adds the most recent donation by a given donor to the dataset that will be used to calculate
# the aggregate donation data
for i in previous_donations[-1:]:
repeaters, final_set = extract_repeat_donors(record_data,final_set,percentile)
# Write line of aggregated donations with total amount, percentile, and count for each
# Candidate, zipcode, and year
repeaters.tofile(outfile,sep='|',format='%s')
outfile.write('\n')
donors = donors.append(record_data, ignore_index=True)
outfile.close()
data.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('input_file',
help='filepath containing political donors input data')
parser.add_argument('percentile',
help='filepath containing percentile to be used in calculations')
parser.add_argument('output_file',
help='filepath to store output data')
args = parser.parse_args()
input_filepath = args.input_file
percentile_filepath = args.percentile
output_filepath = args.output_file
find_repeat_donors(input_filepath,percentile_filepath,output_filepath)
|
f4582db26d49786722a6e9d51a62ebbcdef52f3d | BaeKyoungYoung/education-automation-robot | /robotEnv/DegreeLibrary.py | 512 | 3.578125 | 4 | from Degree import Degree, DegreeChangeError
class DegreeLibrary(object):
def __init__(self):
self._deg = Degree()
self._result = 0
def degree_change_C(self, degree):
self._result = self._deg._change_C(degree)
def degree_change_F(self, degree):
self._result = self._deg._change_F(degree)
def result_should_BE(self, expected):
if self._result != float(expected):
raise AssertionError('%s != %s' % (self._result, expected))
|
5116e717b0981e9f4c00b1a16e5800099678cd7a | RodolfoSocrepa/projetos_LetsCode | /projeto_1_JogoDaForca/Projeto_JogoDaForca.py | 5,301 | 3.8125 | 4 | import random # Biblioteca para usar o 'choice' para selecionar a palavra aleatória
import os #Biblioteca para ulitizar o comando cls para limpar o terminal
#Função para ilustrar a forca
#Imprime na tela o boneco conforme os erros
def forca(erro):
os.system('cls')
print('---------- JOGO DA FORCA ----------')
if erro == 0:
print('+---+')
print('| |')
print('|')
print('|')
print('|')
elif erro == 1:
print('+---+')
print('| | ', [l.upper() for l in letrasIncorretas])
print('| O')
print('|')
print('|')
elif erro == 2:
print('+---+')
print('| | ', [l.upper() for l in letrasIncorretas])
print('| O')
print('| |')
print('|')
elif erro == 3:
print('+---+')
print('| | ', [l.upper() for l in letrasIncorretas])
print('| O')
print('| /|')
print('|')
elif erro == 4:
print('+---+')
print('| | ', [l.upper() for l in letrasIncorretas])
print('| O')
print('| /|\\')
print('|')
elif erro == 5:
print('+---+')
print('| | ', [l.upper() for l in letrasIncorretas])
print('| O')
print('| /|\\')
print('| / ')
elif erro == 6:
print('+---+')
print('| | ', [l.upper() for l in letrasIncorretas])
print('| X')
print('| VOCÊ FOI ENFORCADO ! GAME OVER')
print('| /|\\ A PALAVRA ERA: ', ''.join(palavra).upper())
print('| / \\')
# Função para validar as letras digitadas
def validacaoLetra(letra):
letra = str(input('Digite uma letra: ')).lower()
while len(letra) != 1:# Valida se tem mais de uma letra ou apenas espaço
if len(letra) == 0:
letra = str(input('Digite uma letra: ')).lower()
else:
letra = str(input('Digite apenas UMA letra: ')).lower()
while (letra in letrasIncorretas) or (letra in letrasCorretas):# Valida se a letra ja foi digitada
letra = str(input('VOCÊ JA DIGITOU ESSA LETRA ! Digite OUTRA letra: ')).lower()
while len(letra) != 1:
if len(letra) == 0:
letra = str(input('Digite uma letra: ')).lower()
else:
letra = str(input('Digite apenas UMA letra: ')).lower()
while not 97 <= ord(letra) <= 122: # Valida se o caracter digitado é valido
letra = str(input('\nCOMANDO INVALIDO! Digite uma letra: ')).lower()
while len(letra) != 1:
if len(letra) == 0:
letra = str(input('Digite uma letra: ')).lower()
else:
letra = str(input('Digite apenas UMA letra: ')).lower()
return letra
# Função para validar o palpite/chute
def palpite(opçao):
while opçao != 's' and opçao != 'n':
opçao = str(input('Digite uma opção valida! Você gostaria de chutar? [S/N]')).lower()
if opçao == 's':
chute = list(input('Digite o seu palpite: '))
if chute == palavra:
print('PARABENS VOCÊ GANHOU! A PALAVRA ERA :', ''.join(palavra).upper())
return chute
else:
print('VOCÊ ERROU ! TENTE NOVAMENTE')
listaPalavras = ['mesa''cadeira', 'banco','exceto','mister', 'vereda', 'apogeu', 'utopia', 'escopo','casual',
'pressa','alheio', 'nocivo', 'infame', 'hostil', 'idiota','legado', 'gentil', 'adorno','aferir', 'astuto',
'difuso', 'formal', 'apreço', 'solene', 'limiar', 'ocioso', 'julgar', 'outrem', 'ensejo', 'eficaz','alento',
'escusa', 'dispor', 'embora', 'larica', 'safado', 'abster','perene', 'acento', 'isento', 'nuance', 'objeto',
'sisudo', 'acesso', 'receio', 'remoto', 'mazela', 'avidez', 'vulgar', 'axioma', 'buscar', 'ciente', 'desejo',
'alocar', 'asseio', 'anseio','eximir']
palavra = ''
erro = 0
letrasCorretas = []
letrasIncorretas = []
letra = ''
opçao = 'n'
chute = ''
palavra = random.choice(listaPalavras)
for i in range(0, len(palavra)): #cria uma lista com os "_" para posteriormente ser prenchida com as letras
letrasCorretas.append('_')
os.system('cls')
forca(erro)
print(letrasCorretas)
print('\n')
while erro < 6:
letra = validacaoLetra(letra)
if letra not in palavra:
erro += 1
letrasIncorretas.append(letra)
os.system('cls')
forca(erro)
print([l.upper() for l in letrasCorretas])
if erro < 6:
print('VOCÊ ERROU ! TENTE NOVAMENTE')
print('\n')
else:
for index in range(0, len(palavra)):
if letra == palavra[index]:
letrasCorretas[index] = letra
os.system('cls')
forca(erro)
print([l.upper() for l in letrasCorretas])
print('\n')
if letrasCorretas == list(palavra):
print('PARABENS VOCÊ GANHOU! A PALAVRA ERA :', ''.join(palavra).upper())
break
opçao = str(input('Você gostaria de chutar? [S/N]')).lower()
chuteCerto = palpite(opçao)
if chuteCerto == palavra:
break
print('FIM')
|
680643a392a615408ba8079d433566543d767c5a | gabriellaec/desoft-analise-exercicios | /backup/user_091/ch121_2020_10_06_00_24_28_049671.py | 105 | 3.65625 | 4 | def subtracao_de_listas(lista1,lista2):
lista=[x for x in lista1 if x not in lista2]
return lista |
f2e2788fbf086d53967fc07741cf56ad54627ae1 | sotomaque/Cracking-the-Coding-Interview | /Chapter 1/stringRotation.py | 641 | 4.03125 | 4 | '''
problem: 1.9 - string rotation
assume you have a method 'isSubstring' which checks if a word is a substring of another.
given two strings, s1 and s2, write a function that checks if s2 is a rotation of s1 using
only one call to isSubstring
i.e. 'waterbottle' is a rotation of erbottlewat
'''
def isSubstring(string1, string2):
return(string2 in string1)
def isRotation(str1, str2):
newString = str2*2
return(len(str1) == len(str2) and isSubstring(newString, str1))
def main():
stirng1 = 'erbottlewat'
string2 = 'waterbottle'
if (isRotation(stirng1, string2)):
print(stirng1, ' is a rotation of ', string2)
main()
|
2af4a0e0ad67159a05fe5cb023aa2c7aa866bec2 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_95/1588.py | 616 | 3.625 | 4 | #!/usr/bin/python
# google code jam - c.durr - 2012
# Speaking in Tongues
# trouver un couplage sur {a...z}
from string import *
def readint(): return int(raw_input())
clear = """a zoo
our language is impossible to understand
there are twenty six factorial possibilities
so it is okay if you want to just give up"""
cyph = """y qee
ejp mysljylc kd kxveddknmc re jsicpdrysi
rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd
de kr kd eoya kw aej tysr re ujdr lkgc jv"""
t = maketrans(clear+cyph, cyph+clear)
for test in range(readint()):
print "Case #%i:"% (test+1), raw_input().translate(t)
|
bb51910f2f8118fd6aea1e92ad3faeb9f889fea6 | J-RAG/DTEC501-Python-Files | /Lab 4-1-3 Challenge Lab.py | 2,095 | 4.125 | 4 | # Lab 4-1-3 Challenge Lab
# By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.
EQUAL_RESULT = "an equilateral"
ISO_RESULT = "an isosceles"
SCALENE_RESULT = "a scalene"
INVALID_INPUT_MSG = "One or more of the sides was not valid."
ZERO_INPUT_MSG = "You can't have a triangle with a side of 0."
ZERO_INPUT = 0
VALID_CHAR = "+" #inputs with this char (as a leadingspace) are valid
side_one = input("Enter the length of side 1: ").strip().lstrip(VALID_CHAR)
side_two = input("Enter the length of side 2: ").strip().lstrip(VALID_CHAR)
side_three = input("Enter the length of side 3: ").strip().lstrip(VALID_CHAR)
# input validation check
if not all([side_one.isdigit(),
side_two.isdigit(),
side_three.isdigit()]):
# selfnote: All negative numbers are False when using isdigit() since "-" is
# a non-digit char, aswell as "+" char but we lstrip() it so it is valid for
# this case since the lab input allows numbers with "+". We do not need to remove
# "-" char in this case since we cannot have negative inputs on side lengths.
# print("TestCheck: Input(s) is invalid.")
print(INVALID_INPUT_MSG)
elif any([int(side_one) == ZERO_INPUT,
int(side_two) == ZERO_INPUT,
int(side_three) == ZERO_INPUT]):
# print("TestCheck: Inputs are valid but a Zero input has been made.")
print(ZERO_INPUT_MSG)
else:
# print("TestCheck: all Inputs are valid!")
# initialize comparisson list for readablitly
compare_size = [int(side_one) == int(side_two),
int(side_one) == int(side_three),
int(side_two) == int(side_three)]
if all(compare_size):
# print("TestCheck: Result is an Equilateral Triangle.")
print(f"A triangle with sides {side_one}, {side_two} and {side_three} is {EQUAL_RESULT} triangle.")
elif not any(compare_size):
# print("TestCheck: Result is a Scalene Triangle.")
print(f"A triangle with sides {side_one}, {side_two} and {side_three} is {SCALENE_RESULT} triangle.")
else:
# print("TestCheck: Result is an Isosceles Triangle.")
print(f"A triangle with sides {side_one}, {side_two} and {side_three} is {ISO_RESULT} triangle.") |
7309de992f9cc77d7196c5f94320d1693bab0903 | fagan2888/leetcode-6 | /solutions/647-palindromic-substrings/palindromic-substrings.py | 1,009 | 4.125 | 4 | # -*- coding:utf-8 -*-
# Given a string, your task is to count how many palindromic substrings in this string.
#
# The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
#
# Example 1:
#
#
# Input: "abc"
# Output: 3
# Explanation: Three palindromic strings: "a", "b", "c".
#
#
#
#
# Example 2:
#
#
# Input: "aaa"
# Output: 6
# Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
#
#
#
#
# Note:
#
#
# The input string length won't exceed 1000.
#
#
#
#
class Solution(object):
def countStartOne(self, s):
r=0
for i in xrange(len(s)):
t=s[:i+1]
if t==t[::-1]:
r+=1
return r
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
r=0
l=len(s)
for i in xrange(l):
t1=s[i:]
r+=Solution.countStartOne(self, t1)
return r
|
da62b68e9ff378f5c79c515bf613f5ea5b26d2a2 | kellysan/learn | /python/day4/homework10_打印菱形.py | 192 | 3.765625 | 4 | #! /usr/bin/env python
# @Author : sanyapeng
i = 1
while i <= 9:
j = 1
while j <= i:
print("{} * {} = {}".format(j, i, i * j), end='\t')
j += 1
print()
i += 1 |
44ee4d8dad44570e7a379e2ef81eff05de072ed5 | vineel2014/Pythonfiles | /python_exercises/17exercises/16_search.py | 677 | 4 | 4 | # Search element in a sorted list
def search(list1,elem):
return bsearch(list1,elem,0,len(list1)-1)
def bsearch(list1,elem,low,high):
if (high - low) < 2:
if list1[high] == elem:
print 'position = ',high+1
elif list1[low] == elem:
print 'position = ',low+1
else:
print 'element is not present'
return
mid = low + (high - low)/2
if list1[mid] == elem:
print 'position = ',mid
return
elif list1[mid] < elem:
return bsearch(list1,elem,mid+1,high)
elif list1[mid] > elem:
return bsearch(list1,elem,low,mid-1)
|
95afa0448ff53b67261a04bb4378f87772638fad | alijangjoo/rpi-course | /session7/Stepper_Motor.py | 1,358 | 3.5625 | 4 | ######################################################################
# Stepper_Motor.py
#
# This program control the speed and direction of a stepper motor
# that connected to gpio
######################################################################
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
coilA1Pin = 18
coilA2Pin = 23
coilB1Pin = 24
coilB2Pin = 17
GPIO.setup(coilA1Pin, GPIO.OUT)
GPIO.setup(coilA2Pin, GPIO.OUT)
GPIO.setup(coilB1Pin, GPIO.OUT)
GPIO.setup(coilB2Pin, GPIO.OUT)
forwardSeq = ['1010', '0110', '0101', '1001']
reverseSeq = list(forwardSeq) # to copy the list
reverseSeq.reverse()
def Forward(delay, steps):
for i in range(steps):
for step in forwardSeq:
SetStep(step)
time.sleep(delay)
def Backward(delay, steps):
for i in range(steps):
for step in reverseSeq:
SetStep(step)
time.sleep(delay)
def SetStep(step):
GPIO.output(coilA1Pin, step[0] == '1')
GPIO.output(coilA2Pin, step[1] == '1')
GPIO.output(coilB1Pin, step[2] == '1')
GPIO.output(coilB2Pin, step[3] == '1')
while True:
SetStep('0000')
delay = raw_input("Delay between steps (milliseconds)?")
steps = raw_input("How many steps forward? ")
Forward(int(delay) / 1000.0, int(steps))
SetStep('0000')
steps = raw_input("How many steps backwards? ")
Backward(int(delay) / 1000.0, int(steps))
|
0315e63470993b4158d5549358ccd318b7888609 | lungen/algorithms | /chapter-3/349_01_InfixToPostfixConversion.py | 1,980 | 4.09375 | 4 | """
1. Create an empty stack called op_stack for keeping operators. Create an empty list for
output.
2. Convert the input infix string to a list by using the string method split.
3. Scan the token list from left to right.
• If the token is an operand, append it to the end of the output list.
• If the token is a left parenthesis, push it on the op_stack.
• If the token is a right parenthesis, pop the op_stack until the corresponding left
parenthesis is removed. Append each operator to the end of the output list.
• If the token is an operator, *, /, +, or −, push it on the op_stack. However, first
remove any operators already on the op_stack that have higher or equal precedence
and append them to the output list.
When the input expression has been completely processed, check the op_stack. Any
operators still on the stack can be removed and appended to the end of the output list.
"""
from Stack import *
def infix_to_postfix(string):
op_stack = Stack()
postfix_list = []
token_string = string.split()
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
for token in token_string:
if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '0123456789':
postfix_list.append(token)
elif token == '(':
op_stack.push(token)
elif token == ')':
top_token = op_stack.pop()
while top_token != '(':
postfix_list.append(top_token)
top_token = op_stack.pop()
else:
while (not op_stack.is_empty()) \
and (prec[op_stack.peek()] >= prec[token]):
postfix_list.append(op_stack.pop())
op_stack.push(token)
while not op_stack.is_empty():
postfix_list.append(op_stack.pop())
print("String: ", string, "\nConverion: ", end='')
return " ".join(postfix_list)
#print(infix_to_postfix("( A + B ) * ( C + D )"))
print(infix_to_postfix("( A + B ) * C"))
|
1207418ea3ef4e123c136d9e621b707b0d7ed0e7 | Allen-Maharjan/Sudoku_Queens | /queen_1.py | 264 | 3.640625 | 4 | import numpy as np
grid = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
num = 4
def main ():
point = []
for i in range (0,4):
point.append([0,i])
point.append([i,0])
m = grid.diagonal()
print (m)
main() |
c9c1d307005fcf3cc2f9e899f1e6a821dd134941 | schouten76/raspberrypi_workshop | /python/simonIncomplete.py | 1,732 | 3.609375 | 4 | import RPi.GPIO as GPIO # importeer de GPIO bibliotheek.
import time # importeer de 'time' bibliotheek.
import random # Import 'random' bibliotheek
# Constanten declaratie
leds = [20,16,12,7] # array met pinnummers van de leds
buttons = [21,6,13,19] # array met pinnummers van de buttons
aantal = len(leds) # totaal aantal buttons en leds
wacht = 0.5 # de tijd in seconden tussen een led aan en uit.
# Setup
GPIO.setmode(GPIO.BCM) # je kan kiezen tussen BOARD and BCM pin-nummering.
for pin in leds: GPIO.setup(pin, GPIO.OUT) ## Setup the leds to OUT(PUT)
for pin in buttons: GPIO.setup(pin, GPIO.IN) ## Setup the buttons to IN(PUT)
# Methode om alle leds een x aantal keer te laten knipperen
def blinkAll(times):
for x in range(0,times):
for pin in leds: GPIO.output(pin, GPIO.HIGH)
time.sleep(wacht)
for pin in leds: GPIO.output(pin, GPIO.LOW)
time.sleep(wacht)
# Methode om een led 1x te laten knipperen
# Color is gelijkt aan de index van de array: 0 ..3
def blink(color):
GPIO.output(leds[color], GPIO.HIGH)
time.sleep(wacht)
GPIO.output(leds[color], GPIO.LOW)
time.sleep(wacht)
# GAME START
blinkAll(1)
print "Het spel is begonnen, herhaal de steeds langer wordende reeks. Succes!"
sequence = []
gameOn = True
# GAME LOOP
while gameOn:
# voeg een willekeurige led (kleur) toe aan de sequence (0, 1, 2 of 3)
# <schrijf hier uw code>
# speel de sequence af
# <schrijf hier uw code>
# Lees de spelers input (buttons), laat de bijbehorende led branden en controleer de input.
# <schrijf hier uw code>
# GAME END
blinkAll(3)
print "Game over!"
print "Score: ", len(sequence)-1
GPIO.cleanup() ## clean up all the ports that were used
|
1848d132b2e8ab1851455e501447ffbb46e80a9f | matthaigh27/python-challenges | /primes.py | 340 | 3.828125 | 4 | def isprime(x):
for i in range(2, int((x ** 0.5)) + 1):
if x % i == 0:
return False
return True
def isgprime(real,imag):
return (
(real == 0 and imag % 4 == 3)
or (imag == 0 and real % 4 == 3)
or isprime(real ** 2 + imag ** 2)
)
if __name__ == "__main__":
print(isprime(4))
|
70406cc678ae57c81fd269211cbd9f22b7ea6aba | Israa-Saleh/hackerrank | /Diagonal_Difference.py | 781 | 4.0625 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
# Write your code here
sum1,sum2=0,0
j=len(arr)
k,l=0,-1
for i in arr:
sum1+=i[k]
sum2+=i[l]
k+=1
l-=1
abSum=abs(sum1-sum2)
return abSum
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
67d0aff8ecfe93a6a200447989566ecd675f69d9 | asperaa/back_to_grind | /Heap/k_nearly_sorted_array.py | 853 | 3.765625 | 4 | """We are the captains of our ships, and we stay 'till the end. We see our stories through.
"""
"""https://practice.geeksforgeeks.org/problems/nearly-sorted-algorithm/0
"""
from heapq import heapify, heappop, heappush
def k_nearly_sorted(nums, k):
min_heap = []
heapify(min_heap)
sorted_arr = []
for num in nums:
heappush(min_heap, num)
if len(min_heap) > k:
min_element_so_far = heappop(min_heap)
sorted_arr.append(min_element_so_far)
for i in range(k):
min_element_so_far = heappop(min_heap)
sorted_arr.append(min_element_so_far)
return sorted_arr
if __name__ == "__main__":
t = int(input())
while t > 0:
n, k = [int(i) for i in input().split()]
nums = [int(i) for i in input().split()]
print(k_nearly_sorted(nums, k))
t -= 1
|
5678c4cc738d442a749822805f0bcf09315104fe | ndiekema/CPE202 | /Labs/lab1/location_tests.py | 715 | 3.5625 | 4 | import unittest
from location import *
class TestLab1(unittest.TestCase):
def test_repr(self):
loc = Location("SLO", 35.3, -120.7)
self.assertEqual(repr(loc),"Location('SLO', 35.3, -120.7)")
def test_eq(self):
loc1 = Location("SLO", 35, -120)
loc2 = Location("SLO", 35, -120)
self.assertTrue(loc1 == loc2)
def test_eq2(self):
loc1 = Location("SLO", 25, -120)
loc2 = Location("CHI", 78, -45)
self.assertFalse(loc1 == loc2)
def test_repr2(self):
loc3 = Location("SEA", 67, -118)
self.assertEqual(repr(loc3), "Location('SEA', 67, -118)")
if __name__ == "__main__":
unittest.main()
|
bfd9aa024962448e409b318fbce340735bba4b91 | Huymemee/genetics | /sudoku/positions.py | 6,136 | 3.71875 | 4 | """
This package is used to compute positions of elements in grids depending on grid size obviously.
Created on 15/11/2018
@author: nidragedd
"""
from random import shuffle
def retrieve_row_id_from_position_and_size(position, size):
"""
Given a position in the objects values, determine the id of the row (starting at 0)
:param position: (int) position in the objects values (starting at 0)
:param size: (int) the size of the objects (i.e number of elements per row/column/grid)
:return: (int) id of the row (starting at 0)
"""
return position // size
def retrieve_column_id_from_position_and_size(position, size):
"""
Given a position in the objects values, determine the id of the row (starting at 0)
:param position: (int) position in the objects values (starting at 0)
:param size: (int) the size of the objects (i.e number of elements per row/column/grid)
:return: (int) id of the column (starting at 0)
"""
return position % size
def retrieve_grid_id_from_row_and_col(row_id, col_id, grid_size):
"""
Given a position by it row and column id (starting at 0), determine the id of the grid (also starting at 0)
:param row_id: (int) self-explained, the row id (starting at 0)
:param col_id: (int) self-explained, the column id (starting at 0)
:param grid_size: (int) self-explained, the size of one objects grid (which equals to the square root of the
objects size, which is the number of elements per row/column/grid)
:return: (int) id of the grid (starting at 0)
"""
return int(col_id // grid_size + ((row_id // grid_size) * grid_size))
def retrieve_range_rows_from_grid_id(grid_id, grid_size):
"""
Retrieve range of rows (indexes) linked to the given grid id (starting at 0) for a given grid size
Be careful, this method returns the upper row index included because it is a 'range' in the Python sense and
the range (start, end) does not include the 'end' element while looping with 'for' or 'enumerate'. For example,
for a grid size=3 and grid_id=0 (the first one), the range returned will be (0, 3) so that the loop will take row 0,
1 and 2
:param grid_id: (int) the grid id (starting at 0) for which we want to get the range of rows
:param grid_size: (int) size of one grid (not the objects size, its square root)
:return: a range of rows indexes
"""
start = int(grid_id / grid_size) * grid_size
return range(start, start + grid_size)
def retrieve_range_columns_from_grid_id(grid_id, grid_size):
"""
Retrieve range of columns (indexes) linked to the given grid id (starting at 0) for a given grid size.
Be careful, this method returns the upper column index included because it is a 'range' in the Python sense and
the range (start, end) does not include the 'end' element while looping with 'for' or 'enumerate'. For example,
for a grid size=3 and grid_id=0 (the first one), the range returned will be (0, 3) so that the loop will take column
0, 1 and 2
:param grid_id: (int) the grid id (starting at 0) for which we want to get the range of columns
:param grid_size: (int) size of one grid (not the objects size, its square root)
:return: a range of columns indexes
"""
start = int(grid_id % grid_size) * grid_size
return range(start, start + grid_size)
def retrieve_row_id_from_grid_id_and_position(grid_id, grid_position, grid_size):
"""
Given a position by it grid id and position in the grid (both starting at 0), determine the id of row (also
starting at 0)
:param grid_id: (int) self-explained, the grid id (starting at 0)
:param grid_position: (int) the position of the element in this grid (starting at 0)
:param grid_size: (int) self-explained, the size of one objects grid (which equals to the square root of the
objects size, which is the number of elements per row/column/grid)
:return: (int) id of the row (starting at 0)
"""
row_in_grid = retrieve_row_id_from_position_and_size(grid_position, grid_size)
delta_row = grid_size * (retrieve_row_id_from_position_and_size(grid_id, grid_size))
return delta_row + row_in_grid
def retrieve_column_id_from_grid_id_and_position(grid_id, grid_position, grid_size):
"""
Given a position by it grid id and position in the grid (both starting at 0), determine the id of column (also
starting at 0)
:param grid_id: (int) self-explained, the grid id (starting at 0)
:param grid_position: (int) the position of the element in this grid (starting at 0)
:param grid_size: (int) self-explained, the size of one objects grid (which equals to the square root of the
objects size, which is the number of elements per row/column/grid)
:return: (int) id of the column (starting at 0)
"""
col_in_grid = retrieve_column_id_from_position_and_size(grid_position, grid_size)
delta_col = grid_size * (retrieve_column_id_from_position_and_size(grid_id, grid_size))
return delta_col + col_in_grid
def fill_with_some_valid_values(array_to_fill, length):
"""
Based on a given array containing '0' and non-zero values, return a new array filled with distinct and authorized
values randomly placed where there were '0'.
:param array_to_fill: (array) represents a grid, column or row and contains non-zero values if they are known or
zero otherwise
:param length: (int) size of the objects
:return: (array) new array filled with distinct and authorized values randomly placed where there were '0'.
"""
# Get fixed values
fixed_values = [value for value in array_to_fill if value > 0]
# Get fixed values and their index
fixed_index_values = [(pos, value) for pos, value in enumerate(array_to_fill) if value > 0]
# Determine what are the available values based on fixed values
available_values = [x for x in range(1, length + 1) if x not in fixed_values]
shuffle(available_values)
# Add fixed values in the shuffled array
for index, val in fixed_index_values:
available_values.insert(index, val)
return available_values
|
27917945244de8a9fab3686f1f9fd6f75452233c | SocioProphet/CodeGraph | /kaggle/python_files/sample987.py | 8,341 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# <table>
# <tr>
# <td>
# <center>
# <font size="+1">If you haven't used BigQuery datasets on Kaggle previously, check out the <a href = "https://www.kaggle.com/rtatman/sql-scavenger-hunt-handbook/">Scavenger Hunt Handbook</a> kernel to get started.</font>
# </center>
# </td>
# </tr>
# </table>
#
# ___
#
# ## Previous days:
#
# * [**Day 1:** SELECT, FROM & WHERE](https://www.kaggle.com/rtatman/sql-scavenger-hunt-day-1/)
#
# ____
#
# # GROUP BY... HAVING and COUNT
#
# Now that we know how to select the content of a column, we're ready to learn how to group your data and count things within those groups. This can help you answer questions like:
#
# * How many of each kind of fruit has our store sold?
# * How many species of animal has the vet office treated?
#
# To do this, we're going to learn about three new techniques: GROUP BY, HAVING and COUNT. Once again, we're going to use this 100% made up table of information on various pets, which has three columns: one with the unique ID number for each pet, one with the name of the pet and one with the species of the animal (rabbit, cat or dog).
#
# 
#
# ### COUNT
# ___
#
# COUNT(), as you may have guessed from the name, returns a count of things. If you pass it the name of a column, it will return the number of entries in that column. So if we SELECT the COUNT() of the ID column, it will return the number of ID's in that column.
#
# SELECT COUNT(ID)
# FROM `bigquery-public-data.pet_records.pets`
#
# This query, based on the table above, will return 4 because there are 4 ID's in this table.
#
# ### GROUP BY
# ___
#
# GROUP BY takes the name of one or more column and tells SQL that we want to treat rows that have the same value in that column as a single group when we apply aggregate functions like COUNT().
#
# > An **aggregate function** takes in many values and returns one. Here, we're learning about COUNT() but there are other aggregate functions like SUM() and AVERAGE().
#
# Note that because it tells SQL how to apply aggregate functions, it doesn't make sense to use GROUP BY without something like COUNT().
#
# Let's look at an example. We want to know how many of each type of animal we have in our table. We can get this information by using GROUP BY to group together rows that have the same value in the “Animal” column, while using COUNT() to find out how many ID's we have in each group. You can see the general idea in this image:
#
# 
#
# The query that will get us this information looks like this:
#
# SELECT Animal, COUNT(ID)
# FROM `bigquery-public-data.pet_records.pets`
# GROUP BY Animal
#
# This query will return a table with two columns (Animal & COUNT(ID)) three rows (one for each distinct Animal).
#
# One thing to note is that if you SELECT a column that you don't pass to 1) GROUP BY or 2) use as input to an aggregate function, you'll get an error. So this query won't work, because the Name column isn't either passed to either an aggregate function or a GROUP BY clause:
#
# # NOT A VALID QUERY! "Name" isn't passed to GROUP BY
# # or an aggregate function
# SELECT Name, Animal, COUNT(ID)
# FROM `bigquery-public-data.pet_records.pets`
# GROUP BY Animal
#
# If make this error, you'll get the error message `SELECT list expression references column (column's name) which is neither grouped nor aggregated at`.
#
# ### GROUP BY ... HAVING
# ___
#
# Another option you have when using GROUP BY is to specify that you want to ignore groups that don't meet certain criteria. So this query, for example, will only include groups that have more than one ID in them:
#
# SELECT Animal, COUNT(ID)
# FROM `bigquery-public-data.pet_records.pets`
# GROUP BY Animal
# HAVING COUNT(ID) > 1
#
# The only group that this query will return information on is the one in the cells highlighted in blue in this figure:
#
# 
#
# As a result, this query will return a table with only one row, since this there only one group remaining. It will have two columns: one for "Animal", which will have "Cat" in it, and one for COUNT(ID), which will have 2 in it.
# ## Example: Which Hacker News comments generated the most discussion?
# ___
#
# Now we're ready to work through an example on a real dataset. Today, we're going to be using the Hacker News dataset, which contains information on stories & comments from the Hacker News social networking site. I want to know which comments on the site generated the most replies.
#
# First, just like yesterday, we need to get our environment set up. I already know that I want the "comments" table, so I'm going to look at the first couple of rows of that to get started.
# In[ ]:
# import package with helper functions
import bq_helper
# create a helper object for this dataset
hacker_news = bq_helper.BigQueryHelper(active_project="bigquery-public-data",
dataset_name="hacker_news")
# print the first couple rows of the "comments" table
hacker_news.head("comments")
# By looking at the documentation, I learned that the "parent" column has information on the comment that each comment was a reply to and the "id" column has the unique id used to identify each comment. So I can group by the "parent" column and count the "id" column in order to figure out the number of comments that were made as responses to a specific comment.
#
# Because I'm more interested in popular comments than unpopular comments, I'm also only going to return the groups that have more than ten id's in them. In other words, I'm only going to look at comments that had more than ten comment replies to them.
# In[ ]:
# query to pass to
query = """SELECT parent, COUNT(id)
FROM `bigquery-public-data.hacker_news.comments`
GROUP BY parent
HAVING COUNT(id) > 10
"""
# Now that our query is ready, let's run it (safely!) and store the results in a dataframe:
# In[ ]:
# the query_to_pandas_safe method will cancel the query if
# it would use too much of your quota, with the limit set
# to 1 GB by default
popular_stories = hacker_news.query_to_pandas_safe(query)
# And, just like yesterday, we have a dataframe we can treat like any other data frame:
# In[ ]:
popular_stories.head()
# Looks good! From here I could do whatever further analysis or visualization I'd like.
#
# > **Why is the column with the COUNT() data called f0_**? It's called this because COUNT() is the first (and in our case, only) aggregate function we used in this query. If we'd used a second one, it would be called "f1\_", the third would be called "f2\_", and so on. We'll learn how to name the output of aggregate functions later this week.
#
# And that should be all you need to get started writing your own kernels with GROUP BY... WHERE and COUNT!
# # Scavenger hunt
# ___
#
# Now it's your turn! Here's the questions I would like you to get the data to answer:
#
# * How many stories (use the "id" column) are there of each type (in the "type" column) in the full table?
# * How many comments have been deleted? (If a comment was deleted the "deleted" column in the comments table will have the value "True".)
# * **Optional extra credit**: read about [aggregate functions other than COUNT()](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#aggregate-functions) and modify one of the queries you wrote above to use a different aggregate function.
#
# In order to answer these questions, you can fork this notebook by hitting the blue "Fork Notebook" at the very top of this page (you may have to scroll up). "Forking" something is making a copy of it that you can edit on your own without changing the original.
# In[ ]:
# Your code goes here :)
# Please feel free to ask any questions you have in this notebook or in the [Q&A forums](https://www.kaggle.com/questions-and-answers)!
#
# Also, if you want to share or get comments on your kernel, remember you need to make it public first! You can change the visibility of your kernel under the "Settings" tab, on the right half of your screen.
|
ee5529f234f5ad4f088620a01dda105fd2d44160 | appdutao/python | /python/com/dutao/spider/sigle_thread.py | 460 | 3.53125 | 4 | '''
Created on 2015-12-18
@author: dutao
'''
from time import ctime,sleep
def music(music_name):
for i in range(2):
print("I was listening to %s. %s" % (music_name,ctime()))
sleep(1)
def move(movie_name):
for i in range(2):
print("I was at the %s! %s" % (movie_name,ctime()))
sleep(5)
if __name__ == '__main__':
music('月亮之上')
move('火星救援')
print("all over %s" %ctime()) |
c30ef29642aad3ba26ad140dcd81883ed0a75dc4 | mdziubin/leet | /22.py | 499 | 3.515625 | 4 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []
# Backtracking?
def helper(left, right, tempStr):
if right < left:
return
if not right and not left:
res.append(tempStr)
return
if left:
helper(left-1, right, tempStr + "(")
if right:
helper(left, right-1, tempStr + ")")
helper(n, n, "")
return res
|
cb726ee71c81ef694e364fd019efb66f32b6b5e3 | jan-nemec/LPTHW | /ex42_objects_and_classes.py | 5,951 | 4.15625 | 4 | # Is-A, Has-A, Objects, and Classes
# An important concept that you have to understand is the difference between a class and an object.
# The problem is, there is no real "difference" between a class and an object.
# They are actually the same thing at different points in time.
# What is the difference between a fish and a salmon?
# A salmon is a kind of fish, so I mean it's not different.
# But at the same time, a salmon is a particular type of fish so it's actually different from all other fish.
# That's what makes it a salmon and not a halibut.
# You know a salmon is a kind of fish and that there are other kinds of fish.
# Let's take it one step further. Let's say you have a bucket full of three salmon and because you are a nice person,
# you have decided to name them Frank, Joe, and Mary. Now, think about this question:
# What is the difference between Mary and a salmon?
# You know that Mary is a salmon, so she's not really different. She's just a specific "instance" of a salmon.
# Joe and Frank are also instances of salmon. What do I mean when I say instance?
# I mean they were created from some other salmon and now represent a real thing that has salmon-like attributes.
# Now for the mind-bending idea: Fish is a class, and Salmon is a class, and Mary is an object.
# There you have it: Mary is a kind of salmon that is a kind of fish---object is a class is a class.
# I will show you two tricks to help you figure out whether something is a class or an object.
# is-a
# A phrase to say that something inherits from another,
# as in a "salmon" is-a "fish."
# has-a
# A phrase to say that something is composed of other things or has a trait,
# as in "a salmon has-a mouth."
# The instantiation operation (“calling” a class object) creates an empty object.
# Many classes like to create objects with instances customized to a specific initial state.
# Therefore a class may define a special method named __init__(), like this:
# def __init__(self):
# self.data = []
# Of course, the __init__() method may have arguments for greater flexibility.
# In that case, arguments given to the class instantiation operator are passed on to __init__().
# class Complex:
# def __init__(self, realpart, imagpart):
# self.r = realpart
# self.i = imagpart
## Animal is-a object
class Animal(object):
def __init__(self, sound):
self.sound = sound
self.number_of_legs = None
def welcome(self):
print("Welcome to the nature!")
## ?? | Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
## ?? | Dog has-a name
self.name = name
# 3. Python then looks to see if you made a "magic" __init__ function, and if you have it calls that function to initialize your newly created empty object.
# 4. In the MyStuff function __init__ I then get this extra variable self, which is that empty object Python made for me, and I can set variables on it just like you would with a module, dictionary, or other object.
# 5. In this case, I set self.tangerine to a song lyric and then I've initialized this object.
## ?? | Person is-a object
class Person(object):
def __init__(self, name):
## ?? | Person has-a name
self.name = name
## Person has-a pet of some kind
self.pet = None
# That makes sure that the self.pet attribute of that class is set to a default of None.
## ?? | Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## ??
super(Employee, self).__init__(name)
# That's how you can run the __init__ method of a parent class reliably.
# Note that the syntax changed in Python 3.0: you can just say super().__init__()
# instead of super(ChildB, self).__init__() which IMO is quite a bit nicer.
## ?? | Employee has-a salary
self.salary = salary
## ?? | Fish is-a object
class Fish(object):
pass
## ?? | Salmon is-a Fish
class Salmon(Fish):
pass
## ?? | Halibut is-a Fish
class Halibut(Fish):
pass
## Cat is-a Animal
class Cat(Animal):
def __init__(self, sound, name):
super(Cat, self).__init__(sound)
self.name = name
## rover is-a Dog
rover = Dog("Rover")
## ?? | satan is-a Cat
satan = Cat("Miau", "Satan")
## ?? | mary is-a Person
mary = Person("Mary")
## ??
mary.pet = satan
## ??
frank = Employee("Frank", 120000)
## ??
frank.pet = rover
## ?? | flipper is-a Fish
flipper = Fish()
## ?? | crouse is-a Fish
crouse = Salmon()
## ?? | harry is-a Fish
harry = Halibut()
# About class Name(object)
# class is-a object" comes in.
# They decided that they would use the word "object," lowercased,
# to be the "class" that you inherit from to make a class. Confusing, right?
# A class inherits from the class named object to make a class but it's not an object really it's a class,
# but do not forget to inherit from object.
# assume that Python always requires (object) when you make a class
# New-style classes inherit from object, or from another new-style class.
class NewStyleClass(object):
pass
class AnotherNewStyleClass(NewStyleClass): # if a new-style class inherits from another new-style class, then by extension, it inherits from object
pass
# Old-style classes don't.
class OldStyleClass():
pass
# Python 3.x:
# class MyClass(object): = new-style class
# class MyClass: = new-style class (implicitly inherits from object)
# When defining base classes in Python 3.x, you’re allowed to drop the object from the definition.
# However, this can open the door for a seriously hard to track problem…
# "Multiple inheritance"
# avoid it if you can
# Study Drills
print("-" * 25)
print(f"The dog name is {rover.name}.")
rover.welcome()
print(mary.pet.name, satan.name)
rover.number_of_legs = 4
print(f"Rover has {rover.number_of_legs} legs.")
print(satan.name, satan.sound)
print(frank.name, frank.salary)
|
72651e56e608d9fd25f0cfd5908c08647d2382d8 | valgerdur-asgeirsdottir/Python_verkefni_git | /numbers.py | 301 | 3.515625 | 4 |
for i in range(10, 100):
num1 = i // 10
num2 = i % 10
sum_num = num1 + num2
if (sum_num ** 2) == i:
print(i)
count_div = 0
for i in range(10,100):
for b in range(1,100):
if i % b == 0:
count_div = count_div +1
if count_div == 10:
print(i) |
c8fbfa72135f465358196b6a8b912a105e95de1d | TiredOfThisAll/SmartCalculator | /main.py | 1,460 | 4.03125 | 4 | from calculator import calculate
from parse_brackets import parse_brackets
from my_dictionary import show_variable_value, add_variable_to_dictionary
HELP_MESSAGE = """Type your expression in the next format:
x + y * ( c + ( s + z ) )
Calculator supports addition, subtraction, multiplication,
division, alphabetic variables and brackets
To use alphabetic variables you should type 'variable' = 'value'
-> then you can use your variable in the expression
The variable name must be written in English with a lowercase
letter
You can also set the value of a new variable using an existing one
"""
while True:
expression = input("Type your expression\n")
if expression == "":
continue
elif expression == "/exit":
print("Bye!")
exit()
elif expression == "/help":
print(HELP_MESSAGE)
continue
elif expression[0] == "/":
print("Unknown command")
continue
elif expression.isalpha():
show_variable_value(expression)
continue
if "(" in expression or ")" in expression:
result = parse_brackets(expression)
print(result)
continue
if "=" not in expression:
result = calculate(expression)
print(result)
continue
else:
add_variable_to_dictionary(expression)
continue
|
f9eba7fc6357e4fb32a52de80e63722baafd35d7 | lilyhuong/TD3-S1-Info-2018-2019 | /EX1.1.TD3.Nguyen Thi Huong.py | 176 | 3.78125 | 4 | def function(x):
print ("F(x) = 1 / (x * x)")
Fx = 1 / (x * x)
return Fx
Fx = function(5)
print(Fx)
def f(x):
return 1/ x ** 2
print(f(2))
|
2bdc4e84ae9f968ad447a5dd2b52d353372c7e90 | kannanmavila/coding-interview-questions | /interview_cake/5_ways_to_make_change.py | 714 | 4.0625 | 4 | def ways_to_make_change_bottom_up(n, denominations):
"""O(Nk) solution - uses the coins bottom-up.
Start with a particular coin, update all amounts
up till n, and never come back to that coin again.
"""
ways = [1] + [0] * n
for coin in denominations:
# For amounts higher than coin
for amount in xrange(coin, n+1):
# No. of ways you can make amount
# using coins used so far, plus
# new ways by using this'coin' and
# making the remainder in its own ways
ways[amount] += ways[amount-coin]
return ways[n]
print ways_to_make_change_bottom_up(5, [1, 3, 5]) # 3
print ways_to_make_change_bottom_up(4, [1, 3, 5]) # 2
print ways_to_make_change_bottom_up(4, [1, 3, 2]) # 4
|
c7144342329fb1ce3c1ee7b0a416905e56331907 | dhlife09/pyschool | /20201130_환전.py | 442 | 3.625 | 4 | def exchange(c, m):
m = m/1000
if c == 1:
m = str(m*0.9) + '$(달러)'
elif c == 2:
m = str(m*0.8) + '€(유로)'
elif c == 3:
m = str(m*5.6) + '¥(위안)'
elif c == 4:
m = str(m*91.8) + '¥(엔)'
else:
m = 'ERROR'
return m
print('[1] 달러 [2] 유로 [3] 위안 [4] 엔')
c = int(input('환전 코드: '))
m = int(input('환전 금액: '))
r = exchange(c, m)
print(r)
|
d4c65034f48c4c69d1eff001d41780247d49fcc3 | tcsfremont/curriculum | /python/pygame/maze/maze_generator.py | 1,782 | 3.65625 | 4 | import random
import time
mx = 12; my = 12 # width and height of the maze
maze = [[0 for x in range(mx)] for y in range(my)]
dx = [0, 1, 0, -1]; dy = [-1, 0, 1, 0] # 4 directions to move in the maze
color = [(0,0, 0), (255, 255, 255)] # RGB colors of the maze
# start the maze from a random cell
cx = random.randint(0, mx - 1)
cy = random.randint(0, my - 1)
maze[cy][cx] = 'S'
stack = [(cx, cy, 0)] # stack element: (x, y, direction)
target_random_tile = random.randint(0, int((mx * my)/2))
print(target_random_tile)
visited = 1
while len(stack) > 0:
symbol = 1
if visited == target_random_tile:
print(visited)
symbol = "E"
(cx, cy, cd) = stack[-1]
# to prevent zigzags:
# if changed direction in the last move then cannot change again
if len(stack) > 2:
if cd != stack[-2][2]: dirRange = [cd]
else: dirRange = range(4)
else: dirRange = range(4)
# find a new cell to add
nlst = [] # list of available neighbors
for i in range(4):
nx = cx + dx[i]; ny = cy + dy[i]
if nx >= 0 and nx < mx and ny >= 0 and ny < my:
if maze[ny][nx] == 0:
# of occupied neighbors must be 1
ctr = 0
for j in range(4):
ex = nx + dx[j]; ey = ny + dy[j]
if ex >= 0 and ex < mx and ey >= 0 and ey < my:
if maze[ey][ex] in [1, 'S', 'E']: ctr += 1
if ctr == 1: nlst.append(i)
# if 1 or more neighbors available then randomly select one and move
if len(nlst) > 0:
ir = nlst[random.randint(0, len(nlst) - 1)]
cx += dx[ir]; cy += dy[ir]; maze[cy][cx] = symbol
stack.append((cx, cy, ir))
else:
stack.pop()
visited += 1
print(maze)
|
78b48e86a00128fad0c82900d358f30feb97e2f3 | daniel-reich/turbo-robot | /dBBhtQqKZb2eDERHg_5.py | 841 | 4.25 | 4 | """
Write a **recursive** function that accepts an integer `n` and return a
sequence of `n` integers as a string, descending from `n` to 1 and then
ascending back from 1 to `n` as in the examples below:
### Examples
number_sequence(1) ➞ "1"
number_sequence(2) ➞ "1 1"
number_sequence(3) ➞ "2 1 2"
number_sequence(4) ➞ "2 1 1 2"
number_sequence(9) ➞ "5 4 3 2 1 2 3 4 5"
number_sequence(10) ➞ "5 4 3 2 1 1 2 3 4 5"
### Notes
* Only use recursion.
* No auxiliary data structures like list and tuple are allowed.
"""
def numberSequence(n, d = 1, ans = ''):
if n <= 0: return '-1'
if d == 1:
ans = '1' if n%2 else '1 1'
else:
ans = str(d) + ' ' + ans + ' ' + str(d)
return ans if n == (len(ans) + 1)//2 else numberSequence(n, d + 1, ans)
|
9af43523b581d7cdb6764156585e497c7c7565a9 | VVKot/coding-competitions | /leetcode/python/101_symmetric_tree.py | 918 | 4.0625 | 4 | """
T: O(N)
S: O(N)
Start with left and right children of the root. For a tree to be symmetric
both of them should either have same value or both be emptry. If that condition
holds, check their children in mirrored fashion - first left with second right
and first right with second left.
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root):
if not root:
return True
stack = [(root.left, root.right)]
while stack:
first, second = stack.pop()
if first and second:
if first.val != second.val:
return False
stack.append((first.left, second.right))
stack.append((first.right, second.left))
elif first or second:
return False
return True
|
bf2a9ae252fb937ebcd9dfdac3a4ee2fc8651e1a | gtripti/PythonBasics | /Decorators/Sample.py | 891 | 4.09375 | 4 | def func():
return 1
func()
def hello():
return 'Hello!!!'
hello()
greet = hello
greet()
# Return Functions
def hello1(name = 'Jose'):
print('The hello1() function is executed')
def greet():
return '\t This is the greet function inside hello'
def welcome():
return '\t this is welcome function inside hello'
# print(greet())
# print(welcome())
# print('This is the end of hello function')
print('I am going to return a function')
if name == 'Jose':
return greet
else:
return welcome
new_funct = hello1('Jose')
new_funct()
def cool():
def supercool():
return 'I am very cool'
return supercool
some_funct = cool()
some_funct
some_funct()
# Pass function as argument
def hello2():
return 'Hi Jose'
def other(some_def_funct):
print('Other code')
print(some_def_funct)
other(hello2)
|
f5603aa68a8a4d7bb85acb024bd3046024d3006a | antariandel/eliq | /common.py | 15,739 | 3.609375 | 4 | import platform
import types
from typing import Union
from abc import ABC, abstractmethod
import tkinter as tk
from tkinter import ttk
from images import icons
def float_or_zero(value) -> float:
try:
return float(value)
except ValueError:
return float(0)
def center_toplevel(toplevel: tk.Toplevel) -> None:
toplevel.nametowidget('.').eval('tk::PlaceWindow %s center' % toplevel.winfo_toplevel())
def round_digits(value: Union[int, float], digits: int) -> float:
return int(float(value) * pow(10, digits)) / pow(10, digits)
class VerticalScrolledFrame(ttk.Frame):
# source: https://stackoverflow.com/questions/16188420/python-tkinter-scrollbar-for-frame
# Source edited to make compatible with Python 3 and added mousewheel support
'''
A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Can only be used with grid
* This frame only allows vertical scrolling
'''
def __init__(self, parent, *args, **kw):
ttk.Frame.__init__(self, parent, *args, **kw)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=1)
# create a canvas object and a vertical scrollbar for scrolling it
vscrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)
vscrollbar.grid(row=0, column=1, sticky=tk.NS)
canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, yscrollcommand=vscrollbar.set)
canvas.grid(row=0, column=0, sticky=tk.EW + tk.NS)
vscrollbar.config(command=canvas.yview)
# reset the view
canvas.xview_moveto(0)
canvas.yview_moveto(0)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = ttk.Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior, anchor=tk.NW)
def _bound_to_mousewheel(event):
if platform.system() != 'Linux':
canvas.bind_all('<MouseWheel>', _on_mousewheel)
else:
canvas.bind_all('<Button-4>', _on_mousewheel)
canvas.bind_all('<Button-5>', _on_mousewheel)
interior.bind('<Enter>', _bound_to_mousewheel)
def _unbound_to_mousewheel(event):
if platform.system() != 'Linux':
canvas.unbind_all('<MouseWheel>')
else:
canvas.bind_all('<Button-4>', _on_mousewheel)
canvas.bind_all('<Button-5>', _on_mousewheel)
interior.bind('<Leave>', _unbound_to_mousewheel)
def _on_mousewheel(event):
if platform.system() != 'Darwin':
canvas.yview_scroll(int(-1 * (event.delta / 120)), 'units')
else:
canvas.yview_scroll(int(-1 * event.delta), 'units')
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion='0 0 %s %s' % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
class FloatValidator:
'''
Used to validate tkinter entry widgets accepting only input that still results in a float.
Inherit this to add the validate_float_entry method to your class.
'''
def validate_float_entry(self, action: str, value: str,
widget_obj_name: str, min_value_or_attrname: str, max_value_or_attrname: str) -> bool:
'''
More on entry validation:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html
Example:
import tkinter as tk
class MyClass(FloatValidator):
def some_method(self):
field = tk.Entry()
validator = field.register(self.validate_float_entry)
field.configure(validate='all')
field.configure(validatecommand=(validator, '%d', '%P', 'field', 0, 100))
Note:
All parameters are coerced to string by tkinter. Therefore widget_obj_name must be
a string, so it's 'field' in the above example.
min_value_or_attrname can max_value_or_attrname can be numbers (will be coerced),
a string that can be converted to a float or a name of an instance attribute.
If the attribute is a method, it will be called without any parameters and the return
value will be used as the min or max value respectively. Lambdas obviously work, too.
'''
entry_widget = getattr(self, widget_obj_name)
# Try to convert to float to see if it's a value, if can't, treat it as an attribute name
# and get it with getattr from self.
try:
min_value = float(min_value_or_attrname)
except ValueError:
min_value = getattr(self, min_value_or_attrname)
try:
max_value = float(max_value_or_attrname)
except Exception:
max_value = getattr(self, max_value_or_attrname)
# If the values are in fact callables, call them.
if callable(min_value):
min_value = min_value()
if callable(max_value):
max_value = max_value()
# Raise error if min or max is still not a number, like if calling didn't return a number
if not isinstance(min_value, (float, int)):
raise TypeError('min_value_or_attrname can\'t be resolved to a number')
if not isinstance(max_value, (float, int)):
raise TypeError('max_value_or_attrname can\'t be resolved to a number')
# Update field to min_value if unfocused when blank or value is smaller than min_value.
# This essentially prevents entering values smaller than min_value while enabling
# proper deletion of the input and entering numbers initially smaller than min_value.
if action == '-1': # focus change action
if not value or float_or_zero(value) < float(min_value):
entry_widget.delete(0, tk.END)
entry_widget.insert(0, float(min_value))
# Return validation result
# Will only let changes to the entry field that still result in a float.
# The number also has to be within min/max bounds.
if value:
try:
float(value)
if float(value) > float(max_value):
# Only prevent values over max_value.
# Validating against min_value will happen above.
return False
else:
return True
except (TypeError, ValueError):
return False
else:
# Allow empty string, so we can delete the contents completely
return True
class CreateToolTip:
# Source: https://stackoverflow.com/questions/3221956/how-do-i-display-tooltips-in-tkinter
''' Create a tooltip for a given widget. '''
def __init__(self, widget: tk.Widget, text='widget info'):
self.waittime = 500 # ms
self.wraplength = 180 # pixels
self.widget = widget
self.text = text
self.widget.bind('<Enter>', self.enter)
self.widget.bind('<Leave>', self.leave)
self.widget.bind('<ButtonPress>', self.leave)
self.id = None
self.tw = None
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.waittime, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox('insert') # pylint: disable=W0612
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.hidetip() # added this as a comment suggested
self.tw = tk.Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry('+%d+%d' % (x, y))
label = tk.Label(self.tw, text=self.text, justify='left', background='#ffffff',
relief='solid', borderwidth=1, wraplength=self.wraplength)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tw
self.tw = None
if tw:
tw.destroy()
class BaseDialog(ABC):
''' Abstract Base Class for dialogs. '''
def __init__(self, parent: tk.Widget, callback: types.FunctionType, window_title: str,
text: str, destroy_on_close: bool = True, iconbitmap=icons['titlebar'], **kwargs):
self.parent = parent
self.toplevel = tk.Toplevel(self.parent)
self.toplevel.withdraw()
self.toplevel.title(window_title)
self.toplevel.iconbitmap(iconbitmap)
self.toplevel.resizable(False, False)
self.toplevel.protocol('WM_DELETE_WINDOW', lambda: self.close(False, **kwargs))
self.toplevel.focus()
self.callback = callback
self.destroy_on_close = destroy_on_close
self.frame = ttk.Frame(self.toplevel)
self.frame.grid(padx=20, pady=5)
self.label = ttk.Label(self.frame, text=text, justify=tk.CENTER)
self.label.grid(row=0, column=0, columnspan=2, pady=10)
self.ok_button = ttk.Button(self.frame, text='OK',
command=lambda: self.close(True, **kwargs))
self.ok_button.grid(row=10, column=0, pady=16, sticky=tk.EW)
self.toplevel.bind('<Return>', lambda event: self.close(True, **kwargs))
self.toplevel.bind('<Escape>', lambda event: self.close(False, **kwargs))
self.configure_widgets(**kwargs)
center_toplevel(self.toplevel)
def configure_widgets(self, **kwargs) -> None:
'''
Override this to add and reconfigure widgets in the dialog. Use self.frame as parent.
Use the grid geometry manager. Row 0 is the main label, row 10 is the buttons' row.
Column 0 in row 10 is the self.ok_button.
'''
pass
@abstractmethod
def close(self, ok_clicked: bool = False, **kwargs) -> None:
'''
Override this to call self.callback somehow.
Then super().close(ok_clicked, **kwargs) to close the dialog.
'''
if self.destroy_on_close:
self.toplevel.destroy()
else:
self.toplevel.withdraw()
class OkDialog(BaseDialog):
def close(self, ok_clicked: bool, **kwargs) -> None:
super().close()
self.callback(ok_clicked, **kwargs)
class YesNoDialog(BaseDialog):
def configure_widgets(self, **kwargs) -> None:
self.ok_button.configure(text='Yes', width=15)
self.no_button = ttk.Button(self.frame, text='No', width=15,
command=lambda: self.close(False, **kwargs))
self.no_button.grid(row=10, column=1, sticky=tk.E)
self.ok_button.grid(row=10, column=0, sticky=tk.W)
def close(self, ok_clicked: bool, **kwargs) -> None:
super().close()
self.callback(ok_clicked, **kwargs)
class FloatEntryDialog(BaseDialog, FloatValidator):
def configure_widgets(self, **kwargs) -> None:
self.entry_value = tk.StringVar()
self.entry_value.set(kwargs['default_value'])
self.entry = ttk.Entry(self.frame, textvariable=self.entry_value, width=30)
self._entry_validator = self.entry.register(self.validate_float_entry)
self.entry.configure(validate='all',
validatecommand=(self._entry_validator, '%d', '%P', 'entry',
kwargs['min_value'], kwargs['max_value']))
self.entry.grid(row=1, columnspan=2, pady=10)
self.entry.focus()
self.ok_button.configure(text='OK')
self.no_button = ttk.Button(self.frame, text='Cancel', width=10,
command=lambda: self.close(False))
self.no_button.grid(row=10, column=1, sticky=tk.EW)
def close(self, ok_clicked: bool, **kwargs) -> None:
super().close()
if ok_clicked:
self.callback(float(self.entry.get()))
class StringDialog(BaseDialog):
def configure_widgets(self, max_length=100, **kwargs):
self.entry_value = tk.StringVar()
self.entry_value.set(kwargs['default_value'])
self.default_value = kwargs['default_value']
self.entry = ttk.Entry(self.frame, textvariable=self.entry_value, width=30)
self._entry_validator = self.entry.register(self.validate_entry)
self.entry.configure(validate='all',
validatecommand=(self._entry_validator, '%d', '%P', max_length))
self.entry.grid(row=1, columnspan=2, pady=10)
self.entry.focus()
self.ok_button.configure(text='OK')
self.no_button = ttk.Button(self.frame, text='Cancel', width=10,
command=lambda: self.close(False))
self.no_button.grid(row=10, column=1, sticky=tk.EW)
def validate_entry(self, action: str, value: str, max_length: int) -> bool:
if action == '-1':
if self.entry_value.get() == self.default_value:
self.entry_value.set('')
elif not self.entry_value.get():
self.entry_value.set(self.default_value)
if len(value) < float_or_zero(max_length):
return True
else:
return False
def close(self, ok_clicked: bool, **kwargs) -> None:
super().close()
if self.entry_value.get() == '':
self.entry_value.set(self.default_value)
if ok_clicked:
self.callback(self.entry_value.get())
class TextDialog(BaseDialog):
def configure_widgets(self, **kwargs):
self.text = tk.Text(self.frame, width=50, height=15)
self.text.configure(font=('Calibri', 11))
self.text.grid(row=1, columnspan=2, pady=10)
self.text.focus()
self.default_value = kwargs['default_value']
if 'text_content' in kwargs:
if kwargs['text_content'].strip():
self.text.insert('0.0', kwargs['text_content'].strip())
else:
self.text.insert('0.0', self.default_value)
else:
self.text.insert('0.0', self.default_value)
self.ok_button.configure(text='OK')
self.no_button = ttk.Button(self.frame, text='Cancel', width=10,
command=lambda: self.close(False))
self.no_button.grid(row=10, column=1, sticky=tk.EW)
self.toplevel.unbind('<Return>')
self.toplevel.unbind('<Escape>')
def close(self, ok_clicked: bool, **kwargs) -> None:
super().close()
if not self.text.get('0.0', tk.END).strip():
self.text.insert('0.0', self.default_value)
if ok_clicked:
self.callback(self.text.get('0.0', tk.END).strip())
|
287420ddfbb5cfb1dfdda1aeadc5da74c9f8a7c2 | aravind1910/Algorithmic-Toolkit-Course-UC-SanDiego | /Algorithmic toolkit/week4_divide_and_conquer/2_majority_element/majority_element.py | 930 | 3.9375 | 4 | # Uses python3
import sys
def findCandidate(A):
maj_index = 0
count = 1
for i in range(len(A)):
if A[maj_index] == A[i]:
count += 1
else:
count -= 1
if count == 0:
maj_index = i
count = 1
return A[maj_index]
# Function to check if the candidate occurs more than n/2 times
def isMajority(A, cand):
count = 0
for i in range(len(A)):
if A[i] == cand:
count += 1
if count > len(A)/2:
return True
else:
return False
def get_majority_element(A):
# Find the candidate for Majority
cand = findCandidate(A)
# Print the candidate if it is Majority
if isMajority(A, cand) == True:
print("1")
else:
print("0")
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
get_majority_element(a)
|
de3212366871ec7ca1842e1ea2854c4099141a69 | MaximOksiuta/for-dz | /dz3/5.py | 890 | 3.8125 | 4 | def splitter(u_str):
u_str = u_str.split()
for i in range(0, len(u_str)):
u_str[i] = int(u_str[i])
return u_str
def summer(u_str):
result = sum(u_str)
print(result)
return result
itog_sum = 0
while True:
u_str = input("Для сложения введите числа через пробел для выхода введите 'Q' ")
if u_str[len(u_str) - 1].upper() == 'Q':
try:
u_str = splitter(u_str[:-1])
except ValueError:
print('Введите число!!!')
itog_sum += summer(u_str)
print(f'Общая сумма - {itog_sum}')
break
try:
u_str = splitter(u_str)
except ValueError:
print('Введите число!!!')
try:
itog_sum += summer(u_str)
except ValueError:
pass
print(f'Общая сумма - {itog_sum}') |
db2c7c0a09ab89ef321901c8ea7667e75af23003 | ursstaud/PCC-Basics | /ada_lovelace.py | 477 | 3.921875 | 4 | #name = 'ada lovelace'
#print(name)
#print(name.title())
#name_upper = name.upper()
#print(name_upper)
#print(name_upper.lower())
first_name = 'ada'
last_name = 'lovelace'
full_name = f"{first_name} {last_name}"
#print(full_name)
#print(full_name.title())
print(f"Hello, " + full_name.title() +"! How are you today?")
message = f"...um what was this chick's name again? {last_name} {first_name}"
new_message = message.title()
print("Who was this " +new_message + "?") |
d190ead0af51f82dbd5746e8ade4a83d360d4f56 | Apurva-10/Python-Basics | /swapno.py | 121 | 3.8125 | 4 | a = 100
b = 157
print(a,b) #It will give output as: 10 15
a,b = b,a
print(a,b) #It will give output as: 15 10 |
c6630e815b33a3a733fbdfb66be6cf0a8a858e04 | mrpsharp/comp-phys | /turtle1.py | 825 | 4.03125 | 4 | import math
from turtle import *
dt = 0.0
class Particle(Turtle):
"""Subclass of Turtle representing a body.
Extra attributes:
mass : mass in kg
ax, ay: x, y accelerations in m/s^2
vx, vy: x, y velocities in m/s
px, py: x, y positions in m
"""
mass = None
vx = vy = 0
px = 0.
py = 0.
def move(self, dt):
self.vx += self.ax * dt
self.vy += self.ay * dt
self.px += self.vx * dt
self.py += self.vy * dt
if self.py<0:
self.py = -self.py
self.vy = -self.vy
self.goto(self.px*50, self.py*50)
self.dot(3)
ball = Particle()
ball.hideturtle()
ball.mass = 1
ball.vx = 2
ball.vy = 10
ball.ax = 0
ball.ay = -9.81
ball.getscreen().delay(0)
while(True):
ball.move(0.05)
ball.getscreen().exitonclick()
|
9170eb406b6b048c0bf2c86d3138d73edfc131b0 | kcc3/hackerrank-solutions | /problem_solving/python/algorithms/strings/pangrams.py | 1,153 | 4.375 | 4 | def pangrams(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/pangrams/problem
Roy wanted to increase his typing speed for programming contests. His friend suggested that he type the sentence
"The quick brown fox jumps over the lazy dog" repeatedly. This sentence is known as a pangram because it contains
every letter of the alphabet.
After typing the sentence several times, Roy became bored with it so he started to look for other pangrams.
Given a sentence, determine whether it is a pangram. Ignore case.
Args:
s (str): String to check to see if it's a pangram or not
Returns:
str: Return "pangram" or "not pangram" based on the results of the string
"""
letters = {}
for i in s.lower():
if i not in letters.keys() and i != " ":
letters[i] = 1
if len(letters.keys()) == 26:
return "pangram"
return "not pangram"
if __name__ == "__main__":
assert pangrams("We promptly judged antique ivory buckles for the next prize") == "pangram"
assert pangrams("We promptly judged antique ivory buckles for the prize") == "not pangram" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.