blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
f5c58e281c315b60b44426eff8ccb551624691a1 | KIMZI0N/bioinfo-lecture-2021-07 | /src/028.py | 738 | 3.75 | 4 | #! /usr/bin/env python
seq = "ATGTTATAG"
'''
#1 if๋ฌธ
list=[]
for i in range(len(seq)):
if seq[i] == 'A':
list.append('T')
elif seq[i] == 'T':
list.append('A')
elif seq[i] == 'G':
list.append('C')
elif seq[i] == 'C':
list.append('G')
l = ''.join(list)
print(l)
'''
#2 ๊ฐ์ฌ๋
comp_seq=""
comp_data = {"A":"T", "T":"A", "G":"C", "C":"G"}
for s in seq:
comp_seq += comp_data[s]
print(seq)
print(comp_seq)
for i in range(len(seq)):
s = seq[i]
cs = comp_seq[i]
bond = "โก"
if s == "A" or s == "T":
bond = "="
print(f"{s}{bond}{cs}")
'''
#3 replace์ด์ฉ
Seq = s.replace('A','t').replace('T','a').replace('G','c').replace('C','g')
print(Seq.upper())
'''
|
a36002de7981c81dc1f4170809a47c37b2cca0d5 | pnads/advent-of-code-2020 | /day_06.py | 3,730 | 4.0625 | 4 | """--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much
larger plane, customs declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you
need to do is identify the questions for which anyone in your group answers
"yes". Since your group is just you, this doesn't take very long.
However, the person sitting next to you seems to be experiencing a language
barrier and asks if you can help. For each of the people in their group, you
write down the questions for which they answer "yes", one per line. For
example:
abcx
abcy
abcz
In this group, there are 6 questions to which anyone answered "yes": a, b, c,
x, y, and z. (Duplicate answers to the same question don't count extra; each
question counts at most once.)
Another group asks for your help, then another, and eventually you've collected
answers from every group on the plane (your puzzle input). Each group's answers
are separated by a blank line, and within each group, each person's answers are
on a single line. For example:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
The first group contains one person who answered "yes" to 3 questions: a, b,
and c.
The second group contains three people; combined, they answered "yes" to 3
questions: a, b, and c.
The third group contains two people; combined, they answered "yes" to 3
questions: a, b, and c.
The fourth group contains four people; combined, they answered "yes" to only 1
question, a.
The last group contains one person who answered "yes" to only 1 question, b.
In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11.
For each group, count the number of questions to which anyone answered "yes".
What is the sum of those counts?
"""
with open('input_files/input_day_06.txt', 'r') as f:
lines = [line.rstrip("\n") for line in f.readlines()]
def part1():
grouped_lines = {0: ''}
idx = 0
for line in lines:
if line == '':
idx += 1
grouped_lines[idx] = ''
else:
grouped_lines[idx] += line
total = 0
for _, grouped_line in grouped_lines.items():
total += len(set(grouped_line))
print(total)
"""--- Part Two ---
As you finish the last group's customs declaration, you notice that you misread
one word in the instructions:
You don't need to identify the questions to which anyone answered "yes"; you
need to identify the questions to which everyone answered "yes"!
Using the same example as above:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
In the first group, everyone (all 1 person) answered "yes" to 3 questions: a,
b, and c.
In the second group, there is no question to which everyone answered "yes".
In the third group, everyone answered yes to only 1 question, a. Since some
people did not answer "yes" to b or c, they don't count.
In the fourth group, everyone answered yes to only 1 question, a.
In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b.
In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6.
For each group, count the number of questions to which everyone answered "yes".
What is the sum of those counts?
"""
# with open('input_files/input_day_06.txt', 'r') as f:
# groups = f.read().split("\n\n")
# Sandy again:
from functools import reduce
import string
def part2():
with open('input_files/input_day_06.txt', 'r') as input: print(sum(len(reduce(lambda sofar, next_answers: sofar.intersection(set(next_answers)), group.strip().split('\n'), set(string.ascii_lowercase))) for group in input.read().split('\n\n')))
part2() |
049494c7eb2cd4b110164def15827503b616ef2e | sprotg/2020_3h | /algoritmer_og_datastrukturer/heap.py | 968 | 3.5625 | 4 | from random import randint
class Heap():
def __init__(self):
self.a = [randint(1,100) for i in range(10)]
self.heap_size = len(self.a)
def left(self, i):
return 2*i + 1
def right(self, i):
return 2*i + 2
def parent(self, i):
return (i-1)//2
def max_heapify(self, i):
l = self.left(i)
r = self.right(i)
if l < self.heap_size and self.a[l] > self.a[i]:
largest = l
else:
largest = i
if r < self.heap_size and self.a[r] > self.a[largest]:
largest = r
if largest != i:
self.a[i], self.a[largest] = self.a[largest], self.a[i]
self.max_heapify(largest)
def build_max_heap(self):
self.heap_size = len(self.a)
for i in reversed(range(len(self.a))):
self.max_heapify(i)
def heapsort(self):
pass
h = Heap()
print(h.a)
h.build_max_heap()
print(h.a)
|
f7179afa985135e89d3f83e772db20440c361106 | sprotg/2020_3h | /algoritmer_og_datastrukturer/sorting.py | 848 | 3.9375 | 4 | from random import randint
import time
import matplotlib.pyplot as plt
antal = []
tid = []
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
n = 100
for n in range(1000,20000,1000):
a = [randint(0,100) for i in range(n)]
starttid = time.time()
bubbleSort(a)
sluttid = time.time()
total = sluttid - starttid
antal.append(n)
tid.append(total)
plt.plot(antal,tid)
plt.show()
|
e3cdc173691a2ccdcdda891e41258f4fcc970b4c | sprotg/2020_3h | /databaser/database_start.py | 2,168 | 3.703125 | 4 | import sqlite3
#Her oprettes en forbindelse til databasefilen
#Hvis filen ikke findes, vil sqlite oprette en ny tom database.
con = sqlite3.connect('start.db')
print('Database รฅbnet')
try:
con.execute("""CREATE TABLE personer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
navn STRING,
alder INTEGER)""")
print('Tabel oprettet')
except Exception as e:
print('Tabellen findes allerede')
c = con.cursor()
c.execute('INSERT INTO personer (navn,alder) VALUES (?,?)', ("Hans", 38))
c.execute('INSERT INTO personer (navn,alder) VALUES (?,?)', ("Kim", 37))
#Efter at have รฆndret i databasen skal man kalde funktionen commit.
con.commit()
#Denne variabel bruges til at modtage input fra brugeren
inp = ''
print('')
print('Kommandoer: ')
print(' vis - Viser alle personer i databasen')
print(' sรธg - Find personer i en bestemt alder')
print(' ny - Opret ny person')
print(' q - Afslut program')
while not inp.startswith('q'):
inp = input('> ')
if inp == 'vis':
c = con.cursor()
c.execute('SELECT navn,alder FROM personer')
for p in c:
print('{} er {} รฅr'.format(p[0], p[1]))
elif inp == 'ny':
n = input('Indtast navn: ')
a = input('Indtast alder: ')
c = con.cursor()
c.execute('INSERT INTO personer (navn,alder) VALUES (?,?)', (n, a))
con.commit()
elif inp == 'ven':
c = con.cursor()
c.execute("SELECT id, navn FROM personer;")
for p in c:
print("{}: {}".format(p[0],p[1]))
n1 = input("Vรฆlg fรธrste person: ")
n2 = input("Vรฆlg anden person: ")
c.execute("INSERT INTO venner (person1, person2) VALUES (?,?)",[n1,n2])
con.commit()
elif inp == 'venneliste':
c = con.cursor()
c.execute("SELECT navn FROM personer;")
for p in c:
print("{}".format(p[0]))
n = input("Vรฆlg person: ")
c.execute("SELECT p1.navn, p2.navn FROM venner JOIN personer p1 ON venner.person1 = p1.id JOIN personer p2 on venner.person2 = p2.id WHERE p1.navn = ?",[n])
for ven in c:
print("{} er ven med {}".format(ven[0],ven[1]))
|
74bda556d528a9346da3bdd6ca7ac4e6bcac6654 | adaoraa/PythonAssignment1 | /Reverse_Word_Order.py | 444 | 4.4375 | 4 | # Write a program (using functions!) that asks the user for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
user_strings = input('input a string of words: ') # prompts user to input string
user_set = user_strings.split() # converts string to list
print(user_set)
backwards_list = user_set[::-1] # makes user_set list print backwards
print(backwards_list)
|
7b35393252d51e721ffddde3007105546240e5df | adaoraa/PythonAssignment1 | /List_Overlap.py | 1,360 | 4.3125 | 4 | import random
# Take two lists, say for example these two:...
# and write a program that returns a list that
# contains only the elements that are common between
# the lists (without duplicates). Make sure your program
# works on two lists of different sizes.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
common_list=list(set(a).intersection(b)) # intersection: finds commonalities
print(common_list)
num1=int(input('How many numbers do you want list1 to have? '
'enter a number between 5 and 12: '))
num2=int(input('How many numbers do you want list2 to have? '
'enter a number between 5 and 12: '))
range_list1= int(input('Starting at 1, at what integer do '
'you want your list to end?: '))
range_list2= int(input('Starting at 1, at what integer do '
'you want your list to end?: '))
x=random.sample(range(range_list1),num1)
y=random.sample(range(range_list2),num2)
print(x)
print(y)
common_elements=list(set(x).intersection(y))
print(common_elements)
# variable x generates random list given range the user inputs
# variable y does the same as variable x
# The varaible common_elements prints the common elements between the random lists
# Sometimes there will be no common elements which is why this is impractical |
8b396545767f1cd2d9cd925bd6006542116cbc4c | Mercy435/python--zero-to-mastery | /Advanced Python Object Oriented Programming.py | 8,816 | 4.34375 | 4 | # OOP
# 1.
class BigObject: # creating your class
pass
obj1 = BigObject() # instantiate means creating object
obj2 = BigObject() # instantiate
obj3 = BigObject() # instantiate
print(type(obj1))
# 2. gaming company
class PlayerCharacter: # make it singular
membership = True # class object attribute (to play the game u must be a member)
# Init/ constructor function, whatever is after self(i.e, name is a parameter). it can take default characters
def __init__(self, name='anonymous', age=0): # default parameters
if self.membership: # if PlayerCharacter.membership- membership is an attribute of PlayerCharacter
# if age > 18:
self.name = name # self is used to refer to the class you create
self.age = age # class attributes
def run(self): # method
print(f'my name is {self.name}')
# return 'done'
player1 = PlayerCharacter('Cindy', 44) # object
player2 = PlayerCharacter('Tom', 21) # object
player2.attack = 50
print(player1.name)
print(player1.age)
print(player2.name)
print(player2.age)
print(player1.run()) # when a function doesnt return anything, we get none
# print(player1.attack) this returns an error cos player1 has no attribute attack
print(player2.attack)
# help(player1) # this gives the entire blueprint of the object
# help(list) # shows the blueprint
# print(player1.membership)
# print(player2.membership)
print(player1.run())
print(player2.run())
# 3.cat exercise
# Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
Cat1 = Cat('Cat1', 22)
Cat2 = Cat('Cat2', 12)
Cat3 = Cat('Cat3', 2)
# 2 Create a function that finds the oldest cat
def oldest_cat(*args):
return max(args)
x = oldest_cat(Cat1.age, Cat2.age, Cat3.age)
# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2
print(f'The oldest cat is {x} years old')
# 4. class method
class PlayerCharacter:
membership = True
def __init__(self, name='anonymous', age=0):
self.name = name
self.age = age
@classmethod
def add_things(cls, num1, num2): # cls stands for class
# return num1 + num2
return cls('Teddy', num1 + num2) # cls can be used to instantiate, teddy rep name and the sum the age
@staticmethod
def add_things2(num1, num2):
return num1 + num2
player1 = PlayerCharacter()
# print(player1.name)
# print(player1.add_things(2, 3))
player3 = PlayerCharacter.add_things(6, 3) # method on the actual class(class method) to create another player
print(player3.age)
print(player1.add_things2(3,4))
# 5 summary of oop
class NameOfClass: # classical oop-i.e use of classes, uses camelcase)
class_attribute = 'value'
def __init__(self, param1, param2): # to instantiate objects
self.param1 = param1
self.param2 = param2
def method(self): # instance method
# code
pass
@classmethod
def cls_method(cls, param1, param2): # class method
# code
pass
@staticmethod # static method
def stc_method(param1, param2):
# code
pass
# all of this is to create our data type that models the real world
# 6 inheritance example
class User(object): # class User: everything in python is from the base object
def sign_in(self):
print('logged in')
def attack(self): # polymorphism: doing wizard1.attack() overrides this cos the method is in the wizard class
print('do nothing')
class Wizard(User):
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
User.attack(self)
print(f'attacking with power of {self.power}')
class Archer(User):
def __init__(self, name, num_arrows):
self.name = name
self.num_arrows = num_arrows
def attack(self):
print(f'attacking with arrows: arrows left- {self.num_arrows}')
wizard1 = Wizard('Merlin', 50)
archer1 = Archer('Arthur', 500)
wizard1.sign_in()
# polymorphism
wizard1.attack()
archer1.attack()
def player_attack(char):
char.attack()
player_attack(wizard1)
player_attack(archer1)
for char in [wizard1, archer1]:
char.attack()
# isinstance a builtin function to check for inheritance (instance, class)
print(isinstance(wizard1, Wizard)) # True
print(isinstance(wizard1, User)) # True
print(isinstance(wizard1, object)) # True
# 7. calling a method from a subclass of the parent class
class Gamer(object):
def __init__(self, email):
self.email = email
def sign_in(self):
print('logged in')
class Wiz(Gamer):
def __init__(self, name, power, email):
super().__init__(email) # this is a better alt to the code below, it doesnt take self
# Gamer.__init__(self, email) # here
self.name = name
self.power = power
wiz1 = Wiz("Merlin", 60, "[email protected]")
print(wiz1.email)
# 8. exercise pets everywhere
class Pets(object):
animals = []
def __init__(self, animals):
self.animals = animals
def walk(self):
for animal in self.animals:
print(animal.walk())
class Cat():
is_lazy = True
def __init__(self, name, age):
self.name = name
self.age = age
def walk(self):
return f'{self.name} is just walking around'
class Simon(Cat):
def sing(self, sounds):
return f'{sounds}'
class Sally(Cat):
def sing(self, sounds):
return f'{sounds}'
# 1 Add another Cat
class Susan(Cat):
def sing(self, sounds):
return f'{sounds}'
# 2 Create a list of all of the pets (create 3 cat instances from the above)
my_cats = [Simon('Simon', 2), Sally('Sally', 3), Susan('Susan', 12)]
# 3 Instantiate the Pet class with all your cats use variable my_pets
my_pets = Pets(my_cats)
# 4 Output all of the cats walking using the my_pets instance
my_pets.walk()
# INTROSPECTION
print(dir(wizard1)) # gives all of the methods and attributes an object has
# dunder methods
class Toy:
def __init__(self, color, age):
self.color = color
self.age = age
self.my_dict = {'name': 'Yoyo', 'has_pets': False}
def __str__(self): # modifying dunder mthd str for object to behave in a certain way
return f'{self.color},{self.age}'
def __len__(self): # modifying len to suit ur function
return 5
def __del__(self):
# print('deleted')
pass
def __call__(self): # it's used to call a function
return ('yes??')
def __getitem__(self, i):
return self.my_dict[i]
action_figure = Toy('red', 10)
print(action_figure) # this calls str
print(action_figure.color)
print(action_figure.__str__())
print(str('action_figure'))
print(len(action_figure))
# del action_figure
print(action_figure()) # this does the call function
print(action_figure['name'])
# exercise extending list
# to make superlist have all of the attributes of list in python, use inheritance, that is superlist(list),
# list becomes the parent class
class SuperList(list): # class
def __len__(self):
return 1000
super_list1 = SuperList() # object
print(len(super_list1))
super_list1.append(5)
print(super_list1)
print(super_list1[0])
print(issubclass(SuperList, list))
print(issubclass(list, object))
print(issubclass(list, SuperList))
# multiple inheritance
class U:
def log_in(self):
print('logged in')
class W(U):
def __init__(self, name, power):
self.name = name
self.power = power
def attack(self):
print(f'attacking with power of {self.power}')
class A(U):
def __init__(self, name, arrows):
self.name = name
self.arrows = arrows
def check_arows(self):
print(f'{self.arrows} remaining')
def run(self):
print('ran really fast')
class HybridBorg(W, A): # multiple inheritance
def __init__(self, name, power, arrows):
A.__init__(self, name, arrows)
W.__init__(self, name, power)
hb1 = HybridBorg('chudi', 30, 100)
print(hb1.run)
print(hb1.check_arows())
print(hb1.attack())
print(hb1.log_in())
# MRO method resolution order - a rule python follows when u run a method, which to run first ..
# when there is a complicated multiple inheritance structure, mro is followed
class C:
num = 10
class D(C):
pass
class E(C):
num = 1
class F(D, E):
pass
print(F.mro()) # shows u the order with which it checks, it uses the algorithmn depth first search
print(F.num) # 1
print(F.__str__)
class X: pass
class Y: pass
class Z: pass
class G(X, Y): pass # A
class H(Y, Z): pass # B
class M(H, G, Z): pass
print(M.__mro__)
|
1cd49270025286ef2a143bde60119ff410c4fb63 | Mercy435/python--zero-to-mastery | /Testing_in_python/testing_exercise.py | 988 | 3.71875 | 4 | import unittest
import random_game_testing
class TestGame(unittest.TestCase):
# 1
def test_input(self):
answer = 5
guess = 5
result = random_game_testing.run_guess(answer, guess)
self.assertTrue(result)
def test_inputw(self):
answer = 15
guess = 5
result = random_game_testing.run_guess(answer, guess)
self.assertFalse(result)
# 2
# 2
def test_input2(self):
result = random_game_testing.run_guess(5, 5)
self.assertTrue(result)
def test_input_wrong_guess(self):
result = random_game_testing.run_guess(5, 0)
self.assertFalse(result)
# 3
def test_input_wrong_number(self):
result = random_game_testing.run_guess(5, 12)
self.assertFalse(result)
# 4
def test_input_wrong_type(self):
result = random_game_testing.run_guess(5, '12')
self.assertFalse(result)
if __name__ == '__main__':
unittest.main()
|
ed46bde96311d2f53554158365edc3c8280f4a34 | kgupta1542/interviewQs | /Daily-Coding-Problem/dcp004.py | 669 | 3.78125 | 4 | #Refer to Daily Coding Problem #3
def findMissingInt(x):#find lower and upper, checks if in x, declares as missing, finds smallest missing
missing = 0
temp = -1
for i in range(len(x)):
if x[i] >= 1:
lower = x[i] - 1
upper = x[i] + 1
if upper in x or lower in x:#Fulfills last three reqs
temp = upper*(upper not in x) + lower*(lower not in x)
else:
temp = lower*(lower != 0) + upper*(lower == 0)
if (temp < missing or missing == 0) and temp != 0:
missing = temp
if temp == -1:
missing = 1
return missing
numList = [1,3,6,4,2]#Missing Integer should be 2
missingInt = findMissingInt(numList)
print(missingInt)
|
c8174a43df4b0e5dab7d954db25f41a3c604094a | Liangmiaomiao123/yiyuan | /demo02.py | 500 | 3.78125 | 4 | #็ผฉ่ฟindent
a=int(input('่ฏท่พๅ
ฅๆฐๅญ๏ผ'))
if a>0:
print('aๅคงไบ้ถ')
else:
print('aๅฐไบ้ถ')
#ๅญ็ฌฆไธฒ
i="i'm fine"
print(i)
#ๆฅ็ๅญ็ฌฆ็ผ็
print(ord('a'))
print(ord('A'))
#ๅญ็ฌฆไธฒ
name=input('่ฏท่พๅ
ฅๆจ็ๅๅญ:')
age=input('่ฏท่พๅ
ฅๆจ็ๅนด้พ:')
print('ๆๅซ%s,ไปๅนด%dๅฒ'%(name,int(age)))
#ๅๅปบๅ่กจ
classmates=['zhang1','zhang2','zhang3','zhang4','zhang5']
print(classmates)
name=classmates[-5]
print(name)
print('ๅ่กจ้ฟๅบฆ= ',len(classmates))
|
97ab0921063f3db55af7f5dbcbea99cf5409489a | HuXuzhe/algorithm008-class02 | /Week_09/541.ๅ่ฝฌๅญ็ฌฆไธฒ-ii.py | 840 | 3.515625 | 4 | '''
@Descripttion:
@version: 3.X
@Author: hu_xz
@Date: 2020-06-23 15:03:24
@LastEditors: hu_xz
@LastEditTime: 2020-06-23 15:33:23
'''
#
# @lc app=leetcode.cn id=541 lang=python
#
# [541] ๅ่ฝฌๅญ็ฌฆไธฒ II
#
# @lc code=start
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
res = ''
for i in range(0, len(s), 2*k):
res += s[i:i+k][::-1] + s[i+k:i+2*k]
return res
# @lc code=end
#%%
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
res, flag = "", True
for i in range(0, len(s), k):
res += s[i:i + k][::-1] if flag else s[i:i+k]
flag = not flag
return res
# %%
|
2d7c7a182da252c7ace81b792290ddc36b3b6447 | HuXuzhe/algorithm008-class02 | /Week_03/236.ไบๅๆ ็ๆ่ฟๅ
ฌๅ
ฑ็ฅๅ
.py | 985 | 3.546875 | 4 | '''
@Descripttion:
@version: 3.X
@Author: hu_xz
@Date: 2020-05-06 14:27:39
@LastEditors: hu_xz
@LastEditTime: 2020-05-08 11:52:57
'''
#
# @lc app=leetcode.cn id=236 lang=python
#
# [236] ไบๅๆ ็ๆ่ฟๅ
ฌๅ
ฑ็ฅๅ
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root == p or root == q:
return root
left = right = None
if root.left:
left = self.lowestCommonAncestor(root.left, p, q)
if root.right:
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
else:
return left or right
# @lc code=end
|
7036212232a843fe184358c1b41e5e9cb096d31d | andrew5205/MIT6-006 | /ch2/binary_search_tree.py | 1,377 | 4.21875 | 4 |
class Node:
# define node init
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# insert into tree
def insert(self, data):
# if provide data exist
if self.data:
# 1 check to left child
# compare with parent node
if data < self.data:
# 1.1 if left child not yet exist
if self.left is None:
self.left = Node(data)
# 1.2 if left child exist, insert to the next level(child)
else:
self.left.insert(data)
# 2 check to right child
# compare with parent node
elif data > self.data:
# 2.1 if right child not yet exist
if self.right is None:
self.right = Node(data)
# 2.2 if right child exist, insert to the next level(child)
else:
self.right.insert(data)
else:
self.data = data
# print func
def print_tree(self):
if self.left:
self.left.print_tree()
print(self.data),
if self.right:
self.right.print_tree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.print_tree()
|
6141ec333d44e99c0c1968f7a21a9d6d83f56c3d | aliazani/python-exercise | /fun.py | 306 | 3.6875 | 4 | from random import randint
answer = 209
guess = randint(1, 2000)
print(guess)
mini = 1
maxi = 2000
count = 0
while guess != answer:
guess = randint(mini, maxi)
if guess > answer:
maxi = guess
elif guess < answer:
mini = guess
count += 1
print(guess)
print(count)
|
eed8a14cb453e976317a8e2ecbce711e627ebe83 | aliazani/python-exercise | /review.py | 388 | 3.71875 | 4 | class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
class Temperature:
celsius = Celsius()
def __init__(self, initial_f):
self.fahrenheit = initial_f
t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)
|
05588ff773753216a4345b4a3fd7ad903f7aec3f | aliazani/python-exercise | /getter&setter.py | 359 | 3.90625 | 4 | class Circle:
def __init__(self, diameter):
self.diameter = diameter
@property
def radius(self):
return self.diameter / 2
@radius.setter
def radius(self, radius):
self.diameter = radius * 2
small_one = Circle(10)
small_one.radius = 20
print(small_one.diameter)
print(small_one.radius)
print(small_one.diameter)
|
aea31ea7e2069290e0fc0931d00e0d57018cca75 | aliazani/python-exercise | /class_number_string.py | 1,343 | 4.03125 | 4 | class NumberString:
def __init__(self, value):
self.value = str(value)
def __str__(self):
return f"{self.value}"
def __int__(self):
return int(self.value)
def __float__(self):
return float(self.value)
def __add__(self, other):
if '.' in self.value:
return float(self) + other
else:
return int(self) + other
def __radd__(self, other):
return self + other
def __mul__(self, other):
if '.' in self.value:
return float(self) * other
else:
return int(self) * other
def __rmul__(self, other):
return self * other
def __sub__(self, other):
if '.' in self.value:
return float(self) - other
else:
return int(self) - other
def __rsub__(self, other):
return other - float(self)
def __truediv__(self, other):
if '.' in self.value:
return float(self) / other
else:
return int(self) / other
def __rtruediv__(self, other):
return other / float(self)
five = NumberString(5)
print(five)
print(int(five))
print(float(five))
print(str(five))
print(five + 2)
print(2.2 + five)
print(five * 2)
print(10 * five)
print(five - 2)
print(20 - five)
print(five / 2)
print(10 / five)
|
6d3c2605deadcf5d437323ee455866506b42dabd | khaiduong/lpy | /Learn_Project/6th_day/6.3.py | 688 | 3.875 | 4 | """
Write a python script which write to file 64out.txt, each line contains line
index, month, date of month (Feb 28days).
E.g::
1, January, 31
2, February, 28
"""
import calendar
from sys import argv
def write_days_monthname_to_file(year=2016, filename=None):
try:
std_int = int(year)#raw_input(std_int))
except ValueError:
print("Please input the year you want to looking for days and months")
exit(1)
n = 1
with open('./64out.ext', 'w') as f:
for i in range(1, 13):
content = str(n) + ', ' + str(calendar.month_name[i]) +', ' +str(calendar.monthrange(year,i)[1]) + '\n'
print(content)
f.write(str(content))
n +=1
write_days_monthname_to_file(2012)
|
f8e3c787070297a6a7554baaf61eef82fb9c0f67 | Picik-picik/Python | /Chapter 03. ํ๋ก๊ทธ๋จ ์ฌ์ฉ์๋ก๋ถํฐ์ ์
๋ ฅ ๊ทธ๋ฆฌ๊ณ ์ฝ๋์ ๋ฐ๋ณต/03-2 ์
๋ ฅ๋ฐ์ ๋ด์ฉ์ ์ซ์๋ก ๋ฐ๊พธ๋ ค๋ฉด.py | 3,596 | 3.515625 | 4 | Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # 03-2 ์
๋ ฅ๋ฐ์ ๋ด์ฉ์ ์ซ์๋ก ๋ฐ๊พธ๋ ค๋ฉด
>>>
>>> # ํ๋ก๊ทธ๋จ ์ฌ์ฉ์๋ก๋ถํฐ '๋ฌธ์์ด'์ด ์๋ '์'๋ฅผ ์
๋ ฅ๋ฐ์ผ๋ ค๋ฉด ์ด๋ป๊ฒ ํด์ผ ํ ๊น?
>>> # ํ์ด์ฌ์ ์๋ฅผ ์
๋ ฅ๋ฐ๋ ํจ์๋ฅผ ์ ๊ณตํ์ง ์๋๋ค. ๋์ ์ ๋ฌธ์์ด์ ๋ด์ฉ์ ์๋ก ๋ฐ๊ฟ ๋
>>> # ์ฌ์ฉํ ์ ์๋ ํจ์๋ฅผ ์ ๊ณตํ๊ณ ์๋ค.
>>>
>>> year = input("This year : ")
This year : 2020
>>> year = eval(year) # year์ ์ ์ฅ๋ ๋ด์ฉ์ ์ฐ์ ์ฐ์ฐ์ด ๊ฐ๋ฅํ '์'๋ก ๋ฐ๊พผ๋ค.
>>> year = year + 1
>>> print("Next year :", year)
Next year : 2021
>>>
>>> # ์ ์์์๋ ๋ค์๊ณผ ๊ฐ์ด eval ํจ์๋ฅผ ํธ์ถํ์๋ค.
>>>
>>> # year = eval(year)
>>>
>>> # ์ด ๋ฌธ์ฅ์ด ์คํ๋๊ธฐ ์ year์ ์ ์ฅ๋ ๋ด์ฉ์ ๋ฌธ์์ด "2020"์ด์๋ค. ๊ทธ๋ฐ๋ฐ ์ด๋ฅผ eval ํจ์์
>>> # ์ ๋ฌํ์๊ณ , ๊ทธ ๊ฒฐ๊ณผ eval ํจ์๋ 2020์ด๋ผ๋ ์๋ฅผ ๋ฐํํ์๋ค.
>>> # ์ฆ ์ ๋ฌธ์ฅ์์ eval ํจ์๊ฐ ํธ์ถ๋ ์ดํ์ ์ํ๋ ๋ค์๊ณผ ๊ฐ๋ค.
>>>
>>> # year = 2020
>>>
>>> # ๊ทธ๋์ ๋ค์๊ณผ ๊ฐ์ด ๋ง์
์ ํตํด์ year์ ์ ์ฅ๋ ๊ฐ์ 1 ์ฆ๊ฐ์ํฌ ์ ์์๋ค.
>>> # ์? year์ ์ ์ฅ๋ ๊ฒ์ '์(number)'์ด๋๊น.
>>>
>>> # year = year + 1
>>>
>>> # ๊ทธ๋ฐ๋ฐ ์ฒ์๋ถํฐ ์๋ฅผ ์
๋ ฅ๋ฐ๋ ๊ฒ์ด ๋ชฉ์ ์ด์๋ค๋ฉด ๋ค์์ ๋ ๋ฌธ์ฅ์,
>>>
>>> # year = input("This year : ")
>>> # year = eval(year)
>>>
>>> # ๋ค์๊ณผ ๊ฐ์ด ํ ๋ฌธ์ฅ์ผ๋ก ๊ตฌ์ฑํ ์๋ ์๋ค.
>>>
>>> # year = eval(input("This year : "))
>>>
>>> # ์์ ๊ฒฝ์ฐ input ํจ์๊ฐ ๋จผ์ ํธ์ถ๋๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ก ๋ฐํ๋๋ ๊ฐ์ด eval ํจ์์ ์ ๋ฌ๋๋ค.
>>> # ๋ฐ๋ผ์ ์ด๋ ๊ฒ ์ค์ฌ์ ํํํ ์ ์๋ค. ๊ทธ๋ฆฌ๊ณ ๋น์ฐํ ์๊ธฐ๋ก ๋ค๋ฆฌ๊ฒ ์ง๋ง
>>> # eval ํจ์๋ ์์์ ์ดํ์ ๊ฐ์ ๊ฐ๋ ์ค์๋ฅผ ๋์์ผ๋ก๋ ์ ๋์ํ๋ค.
>>>
>>> rad = eval(input("radius : "))
radius : 2.5
>>> area = rad * rad * 3.14 # ์ด๋ ์์ ๋์ด ๊ณ์ฐ ๊ณต์์ ์ ์ฉํ ๋ฌธ์ฅ์
๋๋ค.
>>> print(area)
19.625
>>>
>>> # ์์ ์์์๋ ์์ ๋์ด๋ฅผ ๊ตฌํ๊ณ ์๋๋ฐ, ๊ทธ๋ณด๋ค๋ '์
๋ ฅ๋ฐ์ ๊ฐ์ผ๋ก ๊ณฑ์
์ ํ๋ค.'
>>> # ๋ ์ฌ์ค์ ์ฃผ๋ชฉํด์ผ ํ๋ค. ๊ณฑ์
์ ํ๋ค๋ ๊ฒ์ eval ํจ์๊ฐ 2.5๋ผ๋ ์๋ฅผ ๋ฐํํ๋ค๋ ๋ป์ด๋๊น ๋ง์ด๋ค.
>>>
>>> # [์ฐ์ต๋ฌธ์ 03-2]
>>> str1 = eval(input("์ฒซ ๋ฒ์งธ ์
๋ ฅ : "))
์ฒซ ๋ฒ์งธ ์
๋ ฅ : 1.24
>>> str2 = eval(input("๋ ๋ฒ์งธ ์
๋ ฅ : "))
๋ ๋ฒ์งธ ์
๋ ฅ : 3.12
>>> print("๋ ์
๋ ฅ์ ํฉ :" + str1 + str2)
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
print("๋ ์
๋ ฅ์ ํฉ :" + str1 + str2)
TypeError: can only concatenate str (not "float") to str
>>> print("๋ ์
๋ ฅ์ ํฉ :" + (str1 + str2))
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
print("๋ ์
๋ ฅ์ ํฉ :" + (str1 + str2))
TypeError: can only concatenate str (not "float") to str
>>> str3 = str1 + str2
>>> print("๋ ์
๋ ฅ์ ํฉ :" + str3)
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
print("๋ ์
๋ ฅ์ ํฉ :" + str3)
TypeError: can only concatenate str (not "float") to str
>>> print("๋ ์
๋ ฅ์ ํฉ :", str3)
๋ ์
๋ ฅ์ ํฉ : 4.36
>>> str1 = eval(input("์ฒซ ๋ฒ์งธ ์
๋ ฅ : "))
์ฒซ ๋ฒ์งธ ์
๋ ฅ : 1.24
>>> str2 = eval(input("๋ ๋ฒ์งธ ์
๋ ฅ : "))
๋ ๋ฒ์งธ ์
๋ ฅ : 3.12
>>> print("๋ ์
๋ ฅ์ ํฉ :", str1 + str2)
๋ ์
๋ ฅ์ ํฉ : 4.36
>>> |
bfee9aead792afa056a6254d96037a18856d594c | mariamingallonMM/AI-ML-W3-LinearRegression | /p37/ridge_regression.py | 7,425 | 3.921875 | 4 | ๏ปฟ"""
This code implements a linear regression per week 3 assignment of the machine learning module part of Columbia University Micromaster programme in AI.
Written using Python 3.7
"""
# builtin modules
import os
#import psutil
import requests
import sys
import math
# 3rd party modules
import pandas as pd
import numpy as np
import plotly.graph_objects as go
def vis_data(data_x, data_y):
fig = go.Figure()
for col in data_x.columns:
fig.add_trace(go.Scatter(x=data_x[col], y=data_y,
mode='markers',
name="{}".format(col)))
return fig.show()
def vis_regression_(X, y):
#TODO: fix dimensionality of dataframe plotted per column as above for actual curve
fig = go.Figure()
for col in data_x.columns:
fig.add_trace(go.Scatter(x=data_x[col], y=data_y,
mode='markers',
name="{}".format(col)))
return fig.show()
def get_data(source_file):
# Define input and output filepaths
input_path = os.path.join(os.getcwd(),'datasets','in', source_file)
# Read input data
df = pd.read_csv(input_path)
return df
def split_data(df, ratio:float = 0.7):
"""
Splits the data set into the training and testing datasets from the following inputs:
df: dataframe of the dataset to split
ratio : percentage by which to split the dataset; ratio = training data / all data;
e.g. a ratio of 0.70 is equivalent to 70% of the dataset being dedicated to the training data and the remainder (30%) to testing.
Outputs: X_train, y_train, X_test, y_test
X_train: Each row corresponds to a single vector xi . The last dimension has already been set equal to 1 for all data.
y_train: Each row has a single number and the i-th row of this file combined with the i-th row of "X_train" constitutes the training pair (yi,xi).
X_test: The remainder of the dataset not included already in the X_train dataframe. Same format as "X_train".
y_test: The remainder of the dataset not included already in teh y_train dataframe. Same format as "y_train".
"""
rows, cols = df.shape
rows_split = int(ratio * rows)
# split the dataset into train and test sets
# drop last column of X which will become 'y' vector
df_X_train = df[df.columns[:-1]].loc[0 : rows_split]
df_X_test = df[df.columns[:-1]].loc[rows_split : rows]
# get the last column of X as the 'y' vector and split it into train and test sets
df_y_train = df[df.columns[cols - 1]].loc[0 : rows_split]
df_y_test = df[df.columns[cols - 1]].loc[rows_split : rows]
# add a column of '1' to the X matrix
df_X_train['Ones'] = np.ones((rows_split + 1), dtype = int)
df_X_test['Ones'] = np.ones((rows - rows_split), dtype = int)
return df_X_train, df_X_test, df_y_train, df_y_test
def RidgeRegression(X, y, l:int = 2):
"""
This function implements the โ2 -regularized least squares linear regression algorithm (aka ridge regression) which takes the form:
wRR=argminw(โฅyโXwโฅ^2 ) + ฮป * โฅwโฅ^2.
Inputs:
y : vector 'y' from the split dataset
X : matrix 'X' from the split dataset
l : an arbitray value for lambda "ฮป"
Outputs:
wRR : calculated as expressed above
deg_f : degrees of freedom as a function of lambda
"""
n, m = X.shape
I = np.identity(m)
cov_matrix = np.linalg.inv(np.dot(X.T, X) + l * I)
wRR = np.dot(np.dot(cov_matrix, X.T), y)
_, S, _ = np.linalg.svd(X)
deg_f = np.sum(np.square(S) / (np.square(S) + l))
return wRR, cov_matrix, deg_f
def update_posterior(X, y, xx_old, xy_old, l:int = 2, sigma2:int = 3):
n, m = X.shape
I = np.identity(m)
xx_old = np.dot(X.T, X) + xx_old # XoXoT + XiXiT
xy_old = np.dot(X.T, y) + xy_old # Xoyo + Xiyi
new_cov = np.linalg.inv(l * I + (1 / sigma2) * xx_old) # new covariance ฮฃ, captures uncertainty about w as Var[wRR]
new_mean = np.dot((np.linalg.inv(l * sigma2 * I + xx_old)),xy_old) # new ยต
return new_cov, new_mean, xx_old, xy_old
def activeLearning(X, y, X_test, l:int = 2, sigma2:int = 3):
n, m = X.shape
I = np.identity(m)
X_indexes = []
# set up an xx_old and xy_old to zero to start with
xx_old = np.zeros((m, m))
xy_old = np.zeros(m)
new_cov, new_mean, xx_old, xy_old = update_posterior(X, y, xx_old, xy_old, l, sigma2)
#Select the 10 data points to measure as per the assignment requirements
for i in range(10):
# Pick x0 for which sigma20 is largest
cov_matrix = np.dot(np.dot(X_test, new_cov), X_test.T)
row_largest = np.argmax(np.diagonal(cov_matrix))
# update x and y values
# first reset indexes for X_test dataframe so you can call it from its row index number using 'row_largest'
X_test = X_test.reset_index(drop=True)
# then get x0 and pass it onto the X matrix
x0 = X_test.iloc[[row_largest]].to_numpy()[0]
X.loc[row_largest] = x0
# calculate y0 and update the y vector
y0 = np.dot(X, new_mean)
y = y0
#row, _ = X_test.shape
#X_index = list(range(row))[row_largest]
X_indexes.append(row_largest)
# Remove x0
X_test = X_test.drop(index = row_largest)
# Update the posterior distribution
new_cov, new_mean, xx_old, xy_old = update_posterior(X, y, xx_old, xy_old, l, sigma2)
# Create 1-based indexes
X_indexes = [i + 1 for i in X_indexes]
return X_indexes
def write_csv(filename, a):
# write the outputs csv file
filepath = os.path.join(os.getcwd(),'datasets','out', filename)
df = pd.DataFrame(a)
df.to_csv(filepath, index = False, header = False)
return print("New Outputs file saved to: <<", filename, ">>", sep='', end='\n')
def main():
"""
## $ python3 hw1_regression.py lambda sigma2 X_train.csv y_train.csv X_test.csv
"""
#take string for input data csv file
#in_data = str(sys.argv[1])
#uncomment the following when ready to bring in lambda_input and sigma2_input
#lambda_input = int(sys.argv[1])
#sigma2_input = float(sys.argv[2])
#in_data = 'forestfires.csv'
in_data = 'winequality-red.csv'
df = get_data(in_data)
# split the dataset
df_X_train, df_X_test, df_y_train, df_y_test = split_data(df, ratio = 0.7)
#vis_data(df_X_train, df_y_train)
write_csv('X_train.csv', df_X_train)
write_csv('y_train.csv', df_y_train)
write_csv('X_test.csv', df_X_test)
#uncomment the following when ready
#X_train = np.genfromtxt(sys.argv[3], delimiter = ",")
#y_train = np.genfromtxt(sys.argv[4])
#X_test = np.genfromtxt(sys.argv[5], delimiter = ",")
#### Part 1
lambda_input = 2
wRR, cov_matrix, deg_f = RidgeRegression(df_X_train,df_y_train,lambda_input)
# write the output csv file with the wRR values
np.savetxt("wRR_" + str(lambda_input) + ".csv", wRR, fmt='%1.2f', delimiter="\n")
#### Part 2
sigma2_input = 3
X_indexes = activeLearning(df_X_train, df_y_train, df_X_test, lambda_input, sigma2_input)
# write the output csv file
np.savetxt("active_" + str(lambda_input) + "_" + str(int(sigma2_input)) + ".csv", X_indexes, fmt='%.d', delimiter="\n")
if __name__ == '__main__':
main()
|
53151036235900e092ebba543a029f333ef8228f | monilezama/inteligencia_artificial | /lezamaMonicaT3.py | 5,708 | 3.609375 | 4 |
# Este archivo contiene un programa con varias funciones incompletas, que el
# usuario tiene que terminar.
# Las configuraciones del tablero son una lista de listas
# pe meta = [[1,2,3],[8,0,4],[7,6,5]] donde 0 es el blanco
# Ab es una lista de tuple de la forma (node,padre,f(n),g(n))
# g(n) es la longitud del camino al nodo, f(n) = g(n) + h(n)
# donde h puede ser una de 3 funciones heuristicas h1,h2,h3 (nota: h2,h3 falta terminar)
# Ce es un diccionario que contiene el nodo como una tuple de tuples para ser la llave
# y un valor una lista de [padre, f(n), g(n)]
# falta completar h2 (tejas fuera de lugar), h3 (distancia de Manhattan)
# suces, la funciรณn que genera los sucesores de un nodo
# moverD, moverA, moverAb
# El codigo es basico y falta pe incluir un interfaz del usuario
# para copiando importamos copy y usamos deepcopy
import copy
# los sucesores estan tomados en el orden I, D, A, Ab
def suces(estado):
pos = [(i,j) for i in range(3) for j in range(3) if estado[i][j] == 0]
fila = pos[0][0]
col = pos[0][1]
sucesores = []
if fila == 0 and col == 0:
sucesores.append(moverD(estado, fila, col))
sucesores.append(moverAb(estado, fila, col))
elif fila == 0 and col == 2:
sucesores.append(moverIz(estado,fila,col))
sucesores.append(moverAb(estado,fila,col))
elif fila == 0 and col ==1:
sucesores.append(moverIz(estado,fila,col))
sucesores.append(moverD(estado, fila, col))
sucesores.append(moverAb(estado, fila, col))
elif fila == 1 and col == 0:
sucesores.append(moverA(estado,fila,col))
sucesores.append(moverD(estado, fila, col))
sucesores.append(moverAb(estado,fila,col))
elif fila==1 and col==1:
sucesores.append(moverIz(estado,fila,col))
sucesores.append(moverD(estado, fila, col))
sucesores.append(moverA(estado,fila,col))
sucesores.append(moverAb(estado,fila,col))
elif fila==1 and col==2:
sucesores.append(moverIz(estado,fila,col))
sucesores.append(moverA(estado,fila,col))
sucesores.append(moverAb(estado,fila,col))
elif fila==2 and col==0:
sucesores.append(moverD(estado, fila, col))
sucesores.append(moverA(estado,fila,col))
elif fila ==2 and col==1:
sucesores.append(moverIz(estado,fila,col))
sucesores.append(moverD(estado, fila, col))
sucesores.append(moverA(estado,fila,col))
elif fila==2 and col==2:
sucesores.append(moverIz(estado,fila,col))
sucesores.append(moverA(estado,fila,col))
return sucesores
def moverIz(est,fila, col):
temp = copy.deepcopy(est)
temp[fila][col], temp[fila][col-1] = temp[fila][col-1], temp[fila][col]
return temp
def moverD(est,fila, col):
temp = copy.deepcopy(est)
temp[fila][col], temp[fila][col+1] = temp[fila][col+1], temp[fila][col]
return temp
def moverA(est,fila, col):
temp = copy.deepcopy(est)
temp[fila][col], temp[fila-1][col] = temp[fila-1][col], temp[fila][col]
return temp
def moverAb(est,fila,col):
temp = copy.deepcopy(est)
temp[fila][col], temp[fila+1][col] = temp[fila+1][col], temp[fila][col]
return temp
# devuelve 0 a todos los estados (reduce a BPA o costo uniforme)
def h1(est):
return 0
# fuera de lugar
def h2(est):
cont=0
for i in range(len(meta)):
for j in range(len(meta)):
if not meta[i][j]==est[i][j]:
cont=cont+1
return cont
# manhattan
def h3(nodo):
cont=0
for i in range(len(meta)):
for j in range(len(meta)):
for x in range(len(nodo)):
for y in range(len(nodo)):
if meta[i][j]==nodo[x][y]:
cont=abs(i-x)+abs(j-y)+cont
return cont
def g(est,cam):
return cam+1
def f(est,cam):
return cam + h(est)
meta = [[1,2,3],[8,0,4],[7,6,5]]
print "dame el tablero inicial"
print "primer renglon"
a=input("numero: ")
b=input("numero: ")
c=input("numero: ")
print "segundo renglon"
d=input("numero: ")
e=input("numero: ")
f=input("numero: ")
print "tercer renglon"
g=input("numero: ")
h=input("numero: ")
i=input("numero: ")
inicio = [[a,b,c],[d,e,f],[g,h,i]]
print "iniciaremos desde ", inicio
print "Eliga una heuristica"
print "1: Zero heuristica"
print "2:Tejas fuera de lugar"
print "3: Distancia Manhattan"
heur=input()
Ce = {}
if heur == 1:
h = h1
elif heur == 2:
h = h2
else:
h = h3
Ab = [(inicio, None, h(inicio), 0)]
Estado = False
while Ab and not Estado:
nodo = Ab.pop(0)
a = tuple([tuple(i) for i in nodo[0]])
if nodo[1] == None:
b = None
else:
b = tuple([tuple(i) for i in nodo[1]])
Ce[a] = [b, nodo[2], nodo[3]]
if nodo[0] == meta:
print 'encontramos un camino'
print 'longitud del camino %d' % nodo[3]
print 'numero de nodos %d' % (len(Ab)+len(Ce))
Estado = True
else:
hijos = suces(nodo[0])
for hijo in hijos:
thijo = tuple([tuple(i) for i in hijo])
abtiene = False
cetiene = False
padre = nodo[0]
g = nodo[3] + 1
f = g + h(hijo)
for m in Ab:
if m[0] == hijo:
abtiene = True
if f > m[2]:
continue
if Ce.has_key(thijo):
cetiene = True
if f > Ce[thijo][2]:
continue
if abtiene:
Ab = [m for m in Ab if m[0] != hijo]
if cetiene:
del Ce[thijo]
Ab.append([hijo,padre,f,g])
Ab.sort(key=lambda tup: tup[2])
if not Estado:
print 'No hay solucion'
|
d459bade9a96ebe9963e0d240e2724506b9f7665 | TitoSilver/codigoFacultad | /diccionario/practica.py | 6,558 | 3.671875 | 4 | from algo1 import *
from mydictionary import *
from myarray import *
from linkedlist import *
#=========================================#
#ejercicio 4
def igualString(text1,text2):
#funciรณn que verifica si dos strings son iguales
#creamos un dic con los elementos del text2
if len(text1)==len(text2):
dict_text2=Array(5,Dictionary() )
for char in text2:
dictInsert(dict_text2,char,char)
for char in dict_text2:
if char:
currentNode= char.head
while currentNode:
print("({0}:{1})".format(currentNode.value.key,currentNode.value.value))
currentNode= currentNode.nextNode
print(",")
else:
print("None")
print(",")
print("")
for char in text1:
if char!= dictSearch(dict_text2, char):
return False
return True
else:
return False
#=========================================#
#Ejercicio 5
#funciรณn que verifica si existen elementos repetidos
def unicElements(A):
dictElements= Array(5, Dictionary())
for element in A:
if dictSearch(dictElements,element):
return False
else:
dictInsert(dictElements,element,element)
return True
#=========================================#
#Ejercicio 6
#cรณdigo postal Argentino
def hash_ISO3166(key):
"""
Sistema ISO 3166-2:AR
A cada provincia le corresponde el codigo AR-X
key= key.upper()
coso=
{
"SALTA":A,
"PROVINCIA DE BUENOS AIRES":B,
"CIUDAD AUTONOMA DE BUENOS AIRES":C,
"SAN LUIS":D,
"ENTRE RIOS":E,
"LA RIOJA":F,
"SANTIAGO DEL ESTERO":G,
"CHACO":H,
"SAN JUAN":J,
"CATAMARCA":K,
"LA PAMPA":L,
"MENDOZA":M,
"MISIONES":N,
"FORMOSA":P,
"NEUQUEN":Q,
"RIO NEGRO":R,
"SANTA FE":S,
"TUCUMAN":T,
"CHUBUT":U,
"TIERRA DEL FUEGO":V,
"CORRIENTES":W,
"CORDOBA":X,
"JUJUY":Y,
"SANTA CRUZ":Z
}
return coso[key]
"""
return "M"
def codPostal(direccion):
ciudad=""
direct=""
coord=""
for idx in range(0,len(direccion)):
if direccion[idx]== ",":
key= direccion[idx+1:]
ciudad= hash_ISO3166(key)
break
try:
int(direccion[idx])
direct= direct + direccion[idx]
except ValueError:
coord= coord + direccion[idx]
print("direccion: ",direccion)
print("ciudad: {0}, direct: {1}, cord: {2}".format(ciudad,direct,coord))
return ciudad+direct+"XXX"
#=========================================#
#Ejercicio 7
#Compresion de un String
def comprexString(string):
dictComprex=Array(len(string),Dictionary())
dictInsert(dictComprex,string[0],1)
prevkey=string[0]
return_comprex_string= ""
for idx in range(1,len(string)):
if string[idx]==prevkey:
dictUpdate(dictComprex,prevkey,dictSearch(dictComprex,prevkey) + 1)
else:
#Al cambiar de valor la key inserta el valor de las veces que se repitio el caracter
return_comprex_string= return_comprex_string + prevkey + str(dictSearch(dictComprex,prevkey))
prevkey= string[idx]
dictInsert(dictComprex,prevkey,1)
#al terminar de recorrer el string inserta lo que quedo en ultimo elemento
return_comprex_string= return_comprex_string + prevkey + str(dictSearch(dictComprex,prevkey))
return return_comprex_string
#=========================================#
#Ejercicio 9
#Ocurrencia en Strings
def ocurrenceSearch(T1,T2,consecutiveIndex,firstCharEqual):
#siendo T1: Diccionario con la palabra mayor
#siendo T2: Diccionario con la palabra a corroborar
#siendo consecutiveIndex: las veces que se han acertado caracteres
#siendo firstCharEqual: El indice del primer caracter en tener coinsidencia
currentNode= T1[hash_Key(dictSearch(T2,consecutiveIndex), len(T1))]
try:
currentNode=currentNode.head
while currentNode:
if currentNode.value.key== T2[consecutiveIndex].head.value.key and currentNode.value.value==(firstCharEqual+consecutiveIndex):
return True
currentNode=currentNode.nextNode
return False
except AttributeError:
return False
def nextCharEqual(T1,T2,consecutiveIndex,firstCharEqual):
currentNode= T1[hash_Key(dictSearch(T2,consecutiveIndex), len(T1))]
try:
currentNode=currentNode.head
while currentNode:
test=ocurrenceSearch(T1,T2,consecutiveIndex,firstCharEqual)
if consecutiveIndex==len(T2-1) and test:
return True
if test:
return nextCharEqual(T1,T2,consecutiveIndex+1,firstCharEqual)
currentNode.nextNode
return False
except AttributeError:
return False
def funcFirstCharEqual(T1,T2):
firstChar= T2[0].head.value.value
currentFirstChar= T1[hash_Key(dictSearch(T2,0),len(T1))]
try:
currentFirstChar=currentFirstChar.head
while currentFirstChar:
if currentFirstChar.value.key== T2[0].head.value.value:
testFirstChar= nextCharEqual(T1,T2,0,currentFirstChar.value.value)
if testFirstChar:
return print("T2 Existe en T1")
if currentFirstChar.nextNode:
currentFirstChar= currentFirstChar.nextNode
else:
return print("T2 no existe en T1")
except AttributeError:
return ("T2 no existe en T1")
def ocurrenceString(word1,word2):
#insertamos en un diccionario word1 (palabra que contiene )
dictContainerOcurrence=Array(len(word1),Dictionary())
for idx in range(0,len(word1)):
dictInsert(dictContainerOcurrence,idx,word1[idx])
#insertamos en un diccionario word2 (palabra a corroborar)
dictOcurrence=Array(len(word2),Dictionary())
for idx in range(0,len(word1)):
dictInsert(dictOcurrence,word1[idx],idx)
funcFirstCharEqual(dictContainerOcurrence,dictOcurrence)
return |
8eb212398880ce375cf3541eac5fcd73c1ab95fe | Srbigotes33y/Programacion | /Python/Aprendizaje/Condiociones anidadas/Taller Condiciones2/Ejercicio_5.py | 1,767 | 4.125 | 4 | # Programa que solicita 3 nรบmeros,los muestra en pantalla de mayor a menor en lineas distintas.
# En caso de haber numeros iguales, se pintan en la misma linea.
# Solicitud de datos
n1=int(input("Ingrese tres nรบmeros.\nNรบmero #1: "))
n2=int(input("Nรบmero #2: "))
n3=int(input("Nรบmero #3: "))
# En caso de que no se presenten nรบmeros iguales
if n1>n2 and n2>n3:
print("\nEl orden de los nรบmeros es:\n",n1,"\n",n2,"\n",n3,"\n")
elif n1>n3 and n3>n2:
print("\nEl orden de los nรบmeros es:\n",n1,"\n",n3,"\n",n2,"\n")
elif n2>n3 and n3>n1:
print("\nEl orden de los nรบmeros es:\n",n2,"\n",n3,"\n",n1,"\n")
elif n2>n1 and n1>n3:
print("\nEl orden de los nรบmeros es:\n",n2,"\n",n1,"\n",n3,"\n")
elif n3>n2 and n2>n1:
print("\nEl orden de los nรบmeros es:\n",n3,"\n",n2,"\n",n1,"\n")
elif n3>n1 and n1>n2:
print("\nEl orden de los nรบmeros es:\n",n3,"\n",n1,"\n",n2,"\n")
# En caso de que se pressenten nรบmeros iguales
elif n1==n2 and n3<n1:
print("\nEl orden de los nรบmeros es:\n",n1,"=",n2,"\n",n3,"\n")
elif n1==n2 and n3>n1:
print("\nEl orden de los nรบmeros es:\n",n3,"\n",n1,"=",n2,"\n")
elif n1==n3 and n2<n1:
print("\nEl orden de los nรบmeros es:\n",n3,"=",n1,"\n",n2,"\n")
elif n1==n3 and n2>n1:
print("\nEl orden de los nรบmeros es:\n",n2,"\n",n1,"=",n3,"\n")
elif n2==n3 and n1<n2:
print("\nEl orden de los nรบmeros es:\n",n2,"=",n3,"\n",n1,"\n")
elif n1==n2 and n1>n2:
print("\nEl orden de los nรบmeros es:\n",n1,"\n",n2,"=",n3,"\n")
# En caso de que los 3 nรบmeros sean iguales
elif n1==n2 and n2==n3:
print("\nLos tres nรบmeros son iguales\n")
# Crรฉditos
print("====================================")
print("Programa hecho por Alejandro Giraldo")
print("====================================\n")
|
b3f93af0e701d69fe601fa45a19863f742fa0e49 | Srbigotes33y/Programacion | /Python/Traductor binario/main.py | 3,260 | 4.0625 | 4 | # Traductor que convierte decimales y caracteres a binario y visceversa.
# Importaciรณn de la libreria de conversores
from conversor_binario import *
# Solicitud de datos decimal a binario
def solicitud_decimal_binario():
bandera = True
while bandera:
decimal = input("\nIngrese el nรบmero decimal (X para salir): ")
if decimal.upper() == "X":
print("___________\nSaliendo...\n\n")
bandera = False
else:
print(conversor_decimal_binario(decimal))
# Solicitud de datos binario decimal
def solicitud_binario_decimal():
bandera = True
while bandera:
error = 0
binario = input("\nIngrese el nรบmero binario (X para salir): ")
for a in binario:
if a >= "2" and a <= "9":
error = 1
if error == 1:
print("Solo se permiten '0' y '1'")
error = 0
elif binario.upper() == "X":
print("___________\nSaliendo...\n\n")
bandera = False
else:
print(conversor_binario_decimal(binario))
# Solicitud de caracteres binario
def solicitud_caracter_binario():
bandera = True
while bandera:
caracter = input("\nIngrese el/los caracter(es) (salir123 para salir): ")
if caracter == "salir123":
print("___________\nSaliendo...\n\n")
bandera = False
else:
print(conversor_caracter_binario(caracter))
# Solicitud de binario caracteres
def solicitud_binario_caracter():
bandera = True
while bandera:
error = 0
bin_caracter = input("\nIngrese la cadena binaria: (X para salir): ")
bin_caracter = bin_caracter.replace(" ", "")
for j in bin_caracter:
if j >= "2" and j <= "9":
error = 1
if error == 1:
print("Solo se permiten '0' y '1'")
error = 0
elif bin_caracter.upper() == "X":
print("___________\nSaliendo...\n\n")
bandera = False
else:
segmentos = segmentador_binario(bin_caracter.zfill(8))
partes_decimales = conversor_decimal_caracter_lista(segmentos)
caracteres = conversor_decimales_caracter(partes_decimales)
print(f"\n{caracteres}\n")
# "Menรบ principal"
def main():
bandera = True
while bandera:
print("__________________________________________________________________")
entrada = input("Seleccione el nรบmero correspondiente de la conversiรณn a realizar:\n1. De decimal a binario.\n2. De binario a decimal.\n3. De caracter a binario.\n4. De binario a caracter.\n5. Salir.\nOpciรณn: ")
print("__________________________________________________________________")
if entrada == "1":
solicitud_decimal_binario()
elif entrada == "2":
solicitud_binario_decimal()
elif entrada == "3":
solicitud_caracter_binario()
elif entrada == "4":
solicitud_binario_caracter()
elif entrada == "5":
bandera = False
else:
print("\nIngrese una opciรณn correcta.\n")
if __name__ == "__main__":
main()
# Llamada de la funciรณn principal
|
25b2d05140a1397680d93d95c6a305f6c39f5602 | Srbigotes33y/Programacion | /Python/Aprendizaje/Condiociones anidadas/Taller Condiciones2/Ejercicio_4.py | 1,043 | 4.15625 | 4 | # Programa que pide 3 nรบmeros y los muestra en pantalla de menor a mayor
# Solicitud de datos
n1=int(input("Ingrese tres nรบmeros.\nNรบmero #1: "))
n2=int(input("Nรบmero #2: "))
n3=int(input("Nรบmero #3: "))
# Determinacion y exposiciรณn de los resultados
if n1>n2 and n2>n3:
print("\nEl orden de los nรบmeros es:\n",n3,"\n",n2,"\n",n1,"\n")
elif n1>n3 and n3>n2:
print("\nEl orden de los nรบmeros es:\n",n2,"\n",n3,"\n",n1,"\n")
elif n2>n3 and n3>n1:
print("\nEl orden de los nรบmeros es:\n",n1,"\n",n3,"\n",n2,"\n")
elif n2>n1 and n1>n3:
print("\nEl orden de los nรบmeros es:\n",n3,"\n",n1,"\n",n2,"\n")
elif n3>n2 and n2>n1:
print("\nEl orden de los nรบmeros es:\n",n1,"\n",n2,"\n",n3,"\n")
elif n3>n1 and n1>n2:
print("\nEl orden de los nรบmeros es:\n",n2,"\n",n1,"\n",n3,"\n")
elif n1==n2 or n1==n3 or n2==n3:
print("\nDos o mรกs nรบmeros son iguales","\n")
# Crรฉditos
print("====================================")
print("Programa hecho por Alejandro Giraldo")
print("====================================\n")
|
7d3db72a696aaa2ce106381c13f94b983447ae41 | Srbigotes33y/Programacion | /Python/Aprendizaje/Ciclo For/Taller for/Ejercicio_1.py | 1,210 | 3.984375 | 4 | # Programa que lee los lados de n triangulos e informa el tipo de triรกngulo y la cantidad de tringulos de cada tipo
veces=int(input("ยฟCuรกntos triรกngulos va a ingresar?\nTriรกngulos: "))
equilatero=0
isoceles=0
escaleno=0
print("Ingrese el valor de cada lado del triรกngulo: ")
for i in range(1,veces+1):
lado1=int(input("Lado 1: "))
lado2=int(input("Lado 2: "))
lado3=int(input("Lado 3: "))
if lado1==lado2 and lado2==lado3:
print(f"El triรกngulo #{i} es un triรกngulo equilรกtero\n")
equilatero=equilatero+1
elif lado1==lado2 or lado1==lado3 or lado2==lado3:
print(f"El triรกngulo #{i} es un triรกngulo isรณceles\n")
isoceles=isoceles+1
else:
print(f"El triรกngulo #{i} es un triรกngulo escaleno\n")
escaleno=escaleno+1
if equilatero>0:
print(f"\nLa cantidad de triรกngulos equilateros son: {equilatero}")
if isoceles>0:
print(f"\nLa cantidad de triรกngulos isoceles son: {isoceles}")
if escaleno>0:
print(f"\nLa cantidad de triรกngulos escaleno son: {escaleno}")
# Crรฉditos
print("\n====================================")
print("Programa hecho por Alejandro Giraldo")
print("====================================\n")
|
94ec7029af42fab2fc4ab0082f21a99505977bd0 | Srbigotes33y/Programacion | /Testing y Debugging/POO/3_atrubitos_metodos2.py | 750 | 3.703125 | 4 | # Se define la clase Auto
class Auto:
rojo = False
# Mรฉtodo __init__ o constructor, instancia el objeto al momento de ser llamada la clase.
def __init__(self, puertas=None, color=None):
self.puertas = puertas
self.color = color
if puertas != None and color != None:
print(f"Se creรณ un auto con {puertas} puertas y de color {color}.")
else:
print("Se creรณ un auto sin especificar su nรบmero de puertas ni su color")
def Fabricar(self):
self.rojo = True
def confirmar_fabricacion(self):
if (self.rojo):
print("El auto es rojo.")
else:
print("EL auto no es rojo.")
# Se crea el objeto
a = Auto()
a2 = Auto(4, "Rojo") |
3380b8cb3334eb26b54958785764f0220bf0e9a6 | Srbigotes33y/Programacion | /Python/Aprendizaje/Ciclo For/Taller for/Ejercicio_5.py | 615 | 4.09375 | 4 | # Progrma que calcula el factorial de un nรบmero
factorial=1
numero=int(input("Ingrese el nรบmero a calcular el factorial: "))
if numero<0:
print("El nรบmero no puede ser negativo")
elif numero>50000:
print("El nรบmero es demasiado grande")
else:
for i in range(1,numero+1):
factorial=factorial*numero
numero=numero-1
cifras=len(str(factorial))
print(f"El factorial de {i} es: {factorial}")
print(f"El nรบmero tiene {cifras} cifras")
# Crรฉditos
print("\n====================================")
print("Programa hecho por Alejandro Giraldo")
print("====================================\n")
|
e6e5d947ff4072402a040cdb5efb6f19e32b3ad8 | Srbigotes33y/Programacion | /Python/Aprendizaje/Pruebas/Critografia.py | 624 | 3.671875 | 4 | #Critografia E=3, A=4, O=0, B=8
#Sapo=54p0 ; ALEJO= 413J0
palabra=input("Ingrese una palabra o frase: ").upper()
i=0
nueva=""
while(i<len(palabra)):
if(palabra[i]=="a"):
nueva=nueva+"4"
elif (palabra[i]=="e"):
nueva=nueva+"3"
elif (palabra[i]=="l"):
nueva=nueva+"1"
elif (palabra[i]=="s"):
nueva=nueva+"5"
elif (palabra[i]=="o"):
nueva=nueva+"0"
elif (palabra[i]=="t"):
nueva=nueva+"7"
elif (palabra[i]=="g"):
nueva=nueva+"6"
elif (palabra[i]=="b"):
nueva=nueva+"8"
else:
nueva=nueva+palabra[i]
i+=1
print(nueva) |
f423d11aa0d16c8959e8899f15e1761a4fe6a16a | zhtiansweet/DataStructure | /StackByQueue.py | 1,428 | 3.6875 | 4 | __author__ = 'tianzhang'
# Implement a stack with two queues
import Queue
class stack:
def __init__(self):
self.queue1 = Queue.Queue()
self.queue2 = Queue.Queue()
def push(self, x):
if self.queue1.empty():
self.queue2.put(x, False)
else:
self.queue1.put(x, False)
def pop(self):
if self.queue1.empty():
while self.queue2.qsize() > 1:
self.queue1.put(self.queue2.get(False))
return self.queue2.get(False)
else:
while self.queue1.qsize() > 1:
self.queue2.put(self.queue1.get(False))
return self.queue1.get(False)
'''
def output(self):
if self.queue1.empty():
temp = [self.queue2[i] for i in range(self.queue2.qsize())]
else:
temp = [self.queue1[i] for i in range(self.queue1.qsize())]
print temp
'''
if __name__ == '__main__':
events = [('pu', 0), ('pu', 1), ('po', -1), ('pu', 2), ('po', -1), ('po', -1), ('pu', 3), ('pu', 4), ('po', -1), ('po', -1), ('po', -1), ('pu', 5)]
test = stack()
for event in events:
try:
if event[0] == 'pu':
test.push(event[1])
print 'Push ' + str(event[1])
else:
print 'Pop ' + str(test.pop())
except Queue.Empty as e:
print 'Pop an empty stack!'
continue |
7f04fcd227b6abbc473ac21f48241b9d0e88296f | jarulsamy/boxSim | /src/sim.py | 11,428 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Simple simulator for the shortest-path-to-target problem.
+------------------------------------------------------------------------------+
| |
| โก ------------------------------------- |
| ^(player) | |
| | |
| โ |
| ^(target) |
| |
+------------------------------------------------------------------------------+
"""
import random
import time
from collections import defaultdict
from typing import Callable, Optional, Union
import cv2
import numpy as np
def empty_path() -> dict[str, int]:
"""Get an empty path."""
return {"UP": 0, "DOWN": 0, "LEFT": 0, "RIGHT": 0}
class Pt:
"""Represent a point in 2D space."""
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __iter__(self):
"""Get the point as an iterable."""
pt = (self.x, self.y)
for i in pt:
yield i
def __eq__(self, rhs):
"""Check if two points 'point' to the same point."""
return self.x == rhs.x and self.y == rhs.y
def __add__(self, rhs: Union[float]):
"""Add two points together."""
if isinstance(rhs, Pt):
return Pt(self.x + rhs.x, self.y + rhs.y)
else:
return Pt(self.x + rhs, self.y + rhs)
def __sub__(self, rhs):
"""Subtract two points."""
if isinstance(rhs, Pt):
return Pt(self.x - rhs.x, self.y - rhs.y)
else:
return Pt(self.x - rhs, self.y - rhs)
def __repr__(self):
"""Debug output."""
return f"Pt(x={self.x}, y={self.y})"
@property
def np(self):
"""Get Pt as numpy array."""
return np.array([self.x, self.y])
class Simulator:
"""2D Simulator for shortest-path-to-target problem."""
PLAYER_DIM = 16
MOVE_INC = PLAYER_DIM
BACKGROUND_COLOR = (255, 255, 255)
PLAYER_COLOR = (255, 0, 0)
GOAL_COLOR = (0, 0, 255)
KEYMAP = {
"UP": ("w", "k"),
"DOWN": ("s", "j"),
"LEFT": ("a", "h"),
"RIGHT": ("d", "l"),
"QUIT": (chr(27), "q"),
}
_goal = None
def __init__(
self,
height: int,
width: int,
win_name: Optional[str] = "Simulator",
display: Optional[bool] = True,
player_start_pos: Optional[Pt] = None,
action_callback: Optional[Callable] = None,
*callback_args,
):
self._height = height
self._width = width
self._display = display
self._player_start_pos = None
self._win_name = win_name
self.FUNCMAP = {
"UP": self.player_up,
"DOWN": self.player_down,
"LEFT": self.player_left,
"RIGHT": self.player_right,
}
self._routes = defaultdict(empty_path)
self.reset()
if action_callback is None:
self._user_game_loop()
else:
self._action_callback = action_callback
self._action_callback_args = callback_args
def reset(self):
"""Reset all actions taken by the player."""
self._steps = 0
self._empty_canvas()
if self._player_start_pos is None:
x = random.randint(0, (self._width // self.PLAYER_DIM) - 1)
y = random.randint(0, (self._height // self.PLAYER_DIM) - 1)
x *= self.PLAYER_DIM
y *= self.PLAYER_DIM
self._player = Pt(x, y)
else:
self._player = self._player_start_pos
self._goal_generate()
self._current_route_key = (tuple(self._player), tuple(self._goal))
while self._current_route_key in self._routes.keys():
self._goal_generate()
self._current_route_key = (tuple(self._player), tuple(self._goal))
self._routes[self._current_route_key]
self._update()
def _empty_canvas(self):
self.frame = np.ones((self._height, self._width, 3), np.uint8)
self.frame[self.frame.all(axis=2)] = self.BACKGROUND_COLOR
def _goal_generate(self):
self._goal_erase()
self._goal = self._player
max_x = (self._width // self.PLAYER_DIM) - 1
max_y = (self._height // self.PLAYER_DIM) - 1
while self._goal == self._player:
self._goal = Pt(
random.randint(1, max_x) * self.PLAYER_DIM,
random.randint(1, max_y) * self.PLAYER_DIM,
)
self._goal_draw()
def _goal_draw(self, color=GOAL_COLOR):
offset = self.PLAYER_DIM // 2
top_left = self._goal - offset
bottom_right = self._goal + offset
cv2.rectangle(
self.frame,
tuple(top_left),
tuple(bottom_right),
color,
-1,
)
def _goal_erase(self):
if self._goal is not None:
self._goal_draw(color=self.BACKGROUND_COLOR)
def _player_draw(self, color=PLAYER_COLOR):
offset = self.PLAYER_DIM // 2
top_left = Pt(self._player.x - offset, self._player.y - offset)
bottom_right = Pt(self._player.x + offset, self._player.y + offset)
cv2.rectangle(
self.frame,
tuple(top_left),
tuple(bottom_right),
color,
-1,
)
def _player_erase(self):
self._player_draw(color=self.BACKGROUND_COLOR)
def _update(self):
if self._display:
self._player_draw()
cv2.imshow(self._win_name, self.frame)
cv2.namedWindow(self._win_name)
@property
def player_pos(self) -> Pt:
"""Get the current position of the player."""
return self._player
@property
def goal_pos(self) -> Pt:
"""Get the current position of the goal."""
return self._goal
@property
def player_goal_distance(self) -> float:
"""Get the distance between the player and the goal."""
route = self.best_route
return sum(route.values())
def best_route(self, player: Optional[Pt] = None, goal: Optional[Pt] = None):
"""Get the best route from the player to the goal."""
best = empty_path()
if player is None and goal is None:
diff = self._goal - self._player
else:
diff = goal - player
horz = diff.x // self.PLAYER_DIM
vert = diff.y // self.PLAYER_DIM
if vert < 0:
best["UP"] = abs(vert)
elif vert > 0:
best["DOWN"] = vert
if horz > 0:
best["RIGHT"] = horz
elif horz < 0:
best["LEFT"] = abs(horz)
return best
@property
def routes(self) -> dict:
"""Get all the routes."""
return dict(self._routes)
@property
def best_routes_matrix(self) -> np.array:
"""Get the best route as a numpy array."""
x = np.empty((0, 4))
y = np.empty((0, 4))
for k, v in self.routes.items():
x_row = np.zeros((1, 4))
y_row = np.zeros((1, 4))
# Player start position
player = Pt(k[0][0], k[0][1])
x_row[0, 0] = player.x
x_row[0, 1] = player.y
# Goal start position
goal = Pt(k[1][0], k[1][1])
x_row[0, 2] = goal.x
x_row[0, 3] = goal.y
x = np.vstack((x, x_row))
# Outputs
best_route = self.best_route(player, goal)
y_row[0, 0] = best_route["UP"]
y_row[0, 1] = best_route["DOWN"]
y_row[0, 2] = best_route["LEFT"]
y_row[0, 3] = best_route["RIGHT"]
y = np.vstack((y, y_row))
return x, y
def player_up(self) -> None:
"""Move the player up one cell."""
self._routes[self._current_route_key]["UP"] += 1
new_pos = self._player.y - self.MOVE_INC
if new_pos + self.PLAYER_DIM <= self._height and new_pos - self.PLAYER_DIM >= 0:
self._player.y = new_pos
def player_down(self) -> None:
"""Move the player down one cell."""
self._routes[self._current_route_key]["DOWN"] += 1
new_pos = self._player.y + self.MOVE_INC
if new_pos + self.PLAYER_DIM <= self._height and new_pos - self.PLAYER_DIM >= 0:
self._player.y = new_pos
def player_left(self) -> None:
"""Move the player left one cell."""
self._routes[self._current_route_key]["LEFT"] += 1
new_pos = self._player.x - self.MOVE_INC
if new_pos + self.PLAYER_DIM <= self._width and new_pos - self.PLAYER_DIM >= 0:
self._player.x = new_pos
def player_right(self) -> None:
"""Move the player right one cell."""
self._routes[self._current_route_key]["RIGHT"] += 1
new_pos = self._player.x + self.MOVE_INC
if new_pos + self.PLAYER_DIM <= self._height and new_pos - self.PLAYER_DIM >= 0:
self._player.x = new_pos
def _handle_key_press(self, key):
self._player_erase()
key = chr(key)
if key in self.KEYMAP["QUIT"]:
return False
elif key in self.KEYMAP["UP"]:
self.FUNCMAP["UP"]()
elif key in self.KEYMAP["DOWN"]:
self.FUNCMAP["DOWN"]()
elif key in self.KEYMAP["LEFT"]:
self.FUNCMAP["LEFT"]()
elif key in self.KEYMAP["RIGHT"]:
self.FUNCMAP["RIGHT"]()
self._update()
return True
def _user_game_loop(self):
self._update()
run = True
while run:
# print(f"Best path: {self.best_route}")
self.reset()
while self._player != self._goal:
self._update()
if not self._handle_key_press(cv2.waitKey(0)):
run = False
break
print(f"Steps taken: {self._routes[self._current_route_key]}")
self._goal_generate()
self._update()
def callback_game_loop(self) -> None:
"""Initiate a game loop by using the action callback to get player movements."""
self._goal_generate()
self._update()
self.reset()
while self._player != self._goal:
self._update()
action = self._action_callback(
self._player.np,
self._goal.np,
*self._action_callback_args,
)
if action == "QUIT":
break
self._player_erase()
self.FUNCMAP[action]()
self._update()
if self._display:
time.sleep(0.1)
try:
if chr(cv2.waitKey(5)) in self.KEYMAP["QUIT"]:
break
except ValueError:
pass
if self._display:
print(f"Steps taken: {self._routes[self._current_route_key]}")
if self._display:
cv2.waitKey(0)
if __name__ == "__main__":
s = Simulator(512, 512)
|
aabdf3585e0921c82e2753eabc623be348f63000 | aleksbel/python-project-lvl1 | /brain_games/games/prime.py | 486 | 3.9375 | 4 | from random import randrange
GAME_TOPIC = 'Answer "yes" if given number is prime. Otherwise answer "no".'
def is_prime(n):
d = 3
while d * d <= n and n % d != 0:
d += 2
return d * d > n
def new_round():
# Odd numbers only
x = randrange(1, 1000, 2)
# Correct answer
if is_prime(x):
correct_answer = 'yes'
else:
correct_answer = 'no'
# We formulate a question
expression = str(x)
return expression, correct_answer
|
c92ac1ecaf837ff1e754475007b37ff58e30ab28 | shilpageo/pythonproject | /functions/factorial.py | 356 | 3.921875 | 4 | #method1
def fact():
num=int(input("enter number"))
fact=1
for i in range(1,num+1):
fact*=i
print(fact)
fact()
#method2
def fact(n1):
fact=1
for i in range(1,n1+1):
fact*=i
print(fact)
fact(5)
#method3
def fact(num1):
fact=1
for i in range(1,num1+1):
fact*=i
return fact
d=fact(5)
print(d)
|
25732642d700e35e08b653d3cb7dbab3adb4fc6e | shilpageo/pythonproject | /functions/demo1.py | 343 | 3.953125 | 4 | #def functionname(arg1,arg2):
#fn statemnt
#fncall()
#fn without arg and no return type
#fn with arg and no return type
#fn with arg and return type
#1st method(without arg and no return type)
#.............
def add():
num1=int(input("enter a number1"))
num2=int(input("enter a number2"))
sum=num1+num2
print(sum)
add() |
962aaa4964ae4989cce63115c3ccf6397161a36e | shilpageo/pythonproject | /collections/demo6.py | 96 | 3.59375 | 4 | #insert 1 to 100 elements into a list
lst=[]
for i in range(101):
lst.append(i)
print(lst)
|
e32224443d385bc3aa0b5caa0291a1537e44ff3f | shilpageo/pythonproject | /collections/word count.py | 214 | 3.671875 | 4 | #split line of data can be split into word by word
line="hai hello hai hello"
words=line.split(" ")
dict={}
count=0
for i in words:
if i not in dict:
dict[i]=1
elif i in dict:
dict[i]+=1
print(dict) |
fa492076ecbfed6856da7e20a3bf7a06464dbdb3 | shilpageo/pythonproject | /functional programming/lambda fn.py | 844 | 4.0625 | 4 | #lambda keyword is used
#ad=lambda num1,num2:num1+num2
#print(ad(10,20))
#function
#---------
#def sub(num1,num2):
# return num1-num2
#lambda function
#----------------
#sub=lambda num1,num2:num1-num2
#print(sub(20,13))
#mul=lambda num1,num2:num1*num2
#print(mul(10,20))
#div=lambda num1,num2:num1/num2
#print(div(10,20))
lst1=[7,8,9,4,3,1]
#if num>5 num+1
#else num=1
#[8,9,10,3,2,0]-output
#lst=[10,20,21,22,23]
#lst2=[20,21,10,22,23]
#check for given two list are same or not
#map() {used in list}
#used to filter data without any specific condition
#filter {used in list}
#used to filter data using specific conition
#reduce
#map example
lst=[2,3,4,5,6,7]
squares=list(map(lambda num:num**2,lst))
print(squares)
names=["ajay","aravind","arun"]
upp=list(map(lambda name:name.upper(),names))
print(upp)
|
10145e2e0f1a58ea60288828d7c09f87399ca253 | ngocthuan94/Python-Thuan-2 | /myFirstPython/first.py | 118 | 3.828125 | 4 | print('hello from a file')
print( 'My name is Thuan. Have a nice day!')
x= 20
while x > 3:
print (x)
x -= 3
|
e9aa4621abbe5b8b60fa7bc02b3a54ba2f42531a | sharmar0790/python-samples | /misc/findUpperLowerCaseLetter.py | 241 | 4.25 | 4 | #find the number of upper and lower case characters
str = "Hello World!!"
l = 0
u=0
for i in str:
if i.islower():
l+=1
elif i.isupper():
u+=1
else:
print("ignore")
print("Lower = %d, upper = %d" %(l,u)) |
94f1c45ba972a5e598b11d8db7068135ccdcc79b | sharmar0790/python-samples | /graphing/barGraphPlotting.py | 654 | 3.546875 | 4 | import matplotlib.pyplot as p
import csv,numpy as np
list_hurricanes = list()
list_year = list()
with open("../data/Hurricanes.csv", mode="r") as h:
reader = csv.DictReader(h)
for row in reader:
print(row)
list_hurricanes.append(row.get("Hurricanes"))
list_year.append(row.get("Year"))
print("list_hurricanes == \n",list_hurricanes)
print("list_year == \n",list_year)
x_axis = np.asarray(list_year,dtype=int)
y_axis = np.asarray(list_hurricanes,dtype=int)
p.bar(x_axis,y_axis, alpha=0.8,align='center')
print(type(p))
p.title("Hurricanes Summary")
p.grid(True)
p.xlabel("Year")
p.ylabel("Number Of HurriCanes")
p.show()
|
4b6bf4b0865f101b5545c7cb1033c5738c33dc3b | sharmar0790/python-samples | /misc/factors.py | 267 | 4.28125 | 4 |
nbr = int(input("Enter the number to find the factors : "))
for i in range(1, nbr+ 1 ):
if (nbr % i == 0):
if i % 2 == 0:
print("Factor is :", i , " and it is : Even")
else:
print("Factor is :", i , " and it is : Odd")
|
916ae65531ca61db7f61c5c0b30f8f7c0f5ca99c | MorphisHe/NumericalAnalysis | /linear_algebra/linear_system/gauss_elimination.py | 1,776 | 3.640625 | 4 | '''
Author: Jiang He
SBU ID: 111103814
'''
import time
import numpy as np
'''
A is a matrix (square)
B is a col vector
'''
def forward_elimination(A, b):
'''
N = len(A)
for j in range(N-1):
for i in range(j+1, N):
mij = A[i][j] / A[j][j]
for k in range(j, N):
A[i][k] -= (mij*A[j][k])
b[i] -= (mij*b[j])
return A, b
'''
Ab = np.hstack([A, b])
n = len(A)
for i in range(n):
a = Ab[i]
for j in range(i + 1, n):
b = Ab[j]
m = a[i] / b[i]
Ab[j] = a - m * b
return Ab[:,:-1], Ab[:,-1:]
def backward_elimination(A, b):
Ab = np.hstack([A, b])
n = len(A)
for i in range(n - 1, -1, -1):
Ab[i] = Ab[i] / Ab[i, i]
a = Ab[i]
for j in range(i - 1, -1, -1):
b = Ab[j]
m = a[i] / b[i]
Ab[j] = a - m * b
return Ab[:,:-1], Ab[:,-1:]
#A = np.random.randint(0, 10, 9).reshape(3, 3)
A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]], np.float32)
b = np.array([8, -11, -3], np.float32).reshape(3, 1)
print("Input A:\n", A, "\n")
print("Input b:\n", b, "\n")
print("\n\n")
s = time.time()
forward_output_A, forward_output_b = forward_elimination(A, b)
e = time.time()
print("Forward result A:\n", forward_output_A, "\n")
print("Forward result b:\n", forward_output_b, "\n")
print("Total Time Used:", round(e-s, 2), "Seconds")
print("\n\n")
s = time.time()
backward_output_A, backward_output_b = backward_elimination(forward_output_A, forward_output_b)
e = time.time()
print("Backward result A:\n", backward_output_A, "\n")
print("Backward result b:\n", backward_output_b, "\n")
print("Total Time Used:", round(e-s, 2), "Seconds")
print("\n\n")
|
4de948a13a9c7415536a74070b4f4792108e7e40 | createwv/exploring_python | /language/variables/functions_main.py | 107 | 3.53125 | 4 | def add_numbers(first_num, second_num):
sum = first_num + second_num
return sum
print(add_numbers(1,2))
|
560998d4f73fc42ba65c869a1ba50160f59600dc | Vinicius-Tessaro/Python | /solar_yesol.py | 1,454 | 3.609375 | 4 | con_t = float (input ('Digite o valor do consumo total(em KWh): '))
qnt_f = int (input ('Digite a quantidade de fases do motor: '))
con_r = float
if qnt_f == 1:
con_r = con_t-30
elif qnt_f == 2:
con_r = con_t-50
else:
con_r = con_t-100
con_rd = float (con_r/30)
hrs_sp = float (input ('digite Horas sol pico: '))
pps = con_rd/hrs_sp
wpp = float (input('Insira WPpainel: '))
np = float (pps/wpp)
temp_a = float (input('Digite a temperatura ambiente(em:ยฐC) '))
temp_sm = float (temp_a+30)
c_temp = float (input('Digite o valor do coeficiente de temperatura: '))
pmm = float (con_t*(1+c_temp/100)*(temp_sm-temp_a))
print ('\n\nConsumo do cliente:\n Consumo total: {}KWh\n Tipo de ligaรงรฃo: {} fases\n **Consumo Real: {}KWp**\n **Consumo Real diรกrio:{}KWp**\n\n'.format(con_t,qnt_f,con_r,con_rd))
print ('Potรชncia do sistema:\n Horas Sol pico: {}h/d\n **Potรชncia de pico do sistema: {}KWp**\n\n'.format(hrs_sp,pps))
print ('Dados dos paineis:\n WPpainel: {}KWp\n **Nรบmero de painรฉis: {} painรฉis**\n\n'.format(wpp,np))
print ('Temperatura nos mรณdulos:\n Temperatura Ambiente: {}ยฐC)\n **Temperatura na superfรญcie do mรณdulo {}ยฐC**\n\n'.format(temp_a,temp_sm))
print ('Potรชncia-Pico nos mรณdulos: \n Coeficiente de temperatura: {}\n **Potรชncia mรกxima nos mรณdulos: {}KWp**\n\n'.format(c_temp,pmm))
print ('@Nota: Os valores que possuem **...** indicam que foi gerado pelo programa@\nDeveloped by V1nicius Tessaro\nFor Gustavo Shawn')
input()
|
6772ec2535d0416e96d0d0a82cdc3359ba8c1341 | 603627156/python | /day-01/03-็ปไน -ๆฑๆๅคงๅผ.py | 458 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time :
# @Author : tangbo
# @Site :
# @File :
# @Software:
#ๆฑ่ฟไธชlist็ๆๅคง็ไธคไธชๅผ
list = [1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,65555,45,33,45,5000]
#ๆนๆณไธใ
list.sort()
print(list[-2:])
#ๆนๆณไบใ
max = 0
max1 = 0
#max_list = []
for i in list:
if max<i:
max=i
for x in list:
if max1<x and x<max:
max1=x
print(max,max1)
|
4cbdbc1b64a1500d6c1f02ee3f665a0721f6f6e8 | jblazzy/Weather | /Weather.py | 2,346 | 4.03125 | 4 | """
-- Weather.py
-- Josh Blaz
-- Denison University -- 2019
-- [email protected]
"""
import requests
import datetime
import calendar
def UnixConverter(timestamp):
"""
Converts Unix Timestamps to readable time.
See https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-python for Unix-to-time Conversion formatting.
"""
return(datetime.datetime.fromtimestamp(int(timestamp)).strftime('%a, %B %dth %I%p'))
def KelvinToFahrenheit(temp):
"""
Converts temperature value from Kelvin to Fahrenheit.
"""
return((9/5) * (temp - 273) + 32)
def main():
ZIP = input("Please enter a ZIP Code: \n")
"""
unsure if ZIP needs to be a string or int yet
for now will leave as string
"""
# URL for basic weather info API
URL1 = "http://api.openweathermap.org/data/2.5/weather?appid=eb8707e702d345d487b0f91037928f2d&zip={}".format(ZIP)
json1 = requests.get(URL1).json()
weather = json1['weather']
# URL for forecast API
URL2 = "http://api.openweathermap.org/data/2.5/forecast?appid=eb8707e702d345d487b0f91037928f2d&zip={}".format(ZIP)
json2 = requests.get(URL2).json()
tempstr1 = str(KelvinToFahrenheit(json1['main']['temp']))
# Basic weather info of given ZIP
print("Current Weather Status")
print("City: " + json1['name'])
print("Temperature: " + tempstr1[0:4] + " ยฐF")
print("Current Weather: " + weather[0]['main'])
print("Description: " + weather[0]['description'])
# Prompt user for forecast
Forecast = input("Would you like to see the forecast? (Yes/No) \n")
if (Forecast == "Yes"):
print("Forecast:")
for i in range(1, len(json2['list'])): #iterate through list forcast times (every 3 hours)
print(UnixConverter(json2['list'][i]['dt'])) #convert timestamps to readable time
tempstr2 = str(KelvinToFahrenheit(json2['list'][i]['main']['temp'])) #convert to ยฐF and cast as string
print(" Temperature: " + tempstr2[0:4] + " ยฐF")
print(" " + "Current Weather: " + json2['list'][i]['weather'][0]['main'])
print(" " + "Description: " + json2['list'][i]['weather'][0]['description'])
print(" " + "Humidity: " + str(json2['list'][i]['main']['humidity']) + "%\n")
else:
return
if __name__ == "__main__":
main()
|
8ca83b341856182afc219534f0f80040a639eb7a | mareis/inf1-2021 | /Thonny/oppgaver3_1.py | 338 | 3.921875 | 4 | tall1 = float(input("Skriv in et tall: "))
talle = float(input("Skriv in et tall til: "))
if tall1 > tall2:
print(f'{tall1} er stรธrre enn {tall2}.')
#print(tall1, "er stรธrre enn", tall2)
elif tall2 > tall1:
print(f'{tall2} er stรธrre enn {tall1}.')
elif tall1 == tall2:
print(f'{tall1} er lik {tall2}.')
|
0fffed88c100ea269eb0c1da41846323a0003698 | mareis/inf1-2021 | /Thonny/input_og_sqrt.py | 156 | 3.734375 | 4 | from math import sqrt
n = input("Skriv iunn det du รธnsker รฅ ta kvadratroten till: ")
n = int(n)
kvadratrot = sqrt(n)
print("kvadratroten er", kvadratrot) |
a182d55b5efe26137379a07556a8a04e001878fc | MehmetCanBOZ/AI_minimaxalgoritm_tictoctoe_game | /tictactoe.py | 3,532 | 3.890625 | 4 | """
Tic Tac Toe Player
"""
import math
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
count=0
for i in board:
for j in i:
if j:
count += 1
if count % 2 != 0:
return O
return X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
actionss = set()
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == EMPTY:
actionss.add((i, j))
return actionss
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
import copy
if action not in actions(board):
raise ValueError
new_board = copy.deepcopy(board)
new_board[action[0]][action[1]] = player(new_board)
return new_board
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
winner_board = [[(0, 0), (0, 1), (0, 2)],
[(1, 0), (1, 1), (1, 2)],
[(2, 0), (2, 1), (2, 2)],
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 0), (1, 1), (2, 2)],
[(0, 2), (1, 1), (2, 0)]]
for combination in winner_board:
count_x = 0
count_o = 0
for i, j in combination:
if board[i][j] == X:
count_x += 1
if board[i][j] == O:
count_o += 1
if count_x == 3:
return X
if count_o == 3:
return O
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board)==X or winner(board)==O:
return True
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == EMPTY:
return False
return True
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board)==X:
return 1
elif winner(board)==O:
return -1
else:
return 0
def minimax(board):
ply = player(board)
# If empty board is provided as input, return corner.
if board == [[EMPTY] * 3] * 3:
return (0, 0)
if ply == X:
v = float("-inf")
selected_action = None
for action in actions(board):
minValueResult = minValue(result(board, action))
if minValueResult > v:
v = minValueResult
selected_action = action
elif ply == O:
v = float("inf")
selected_action = None
for action in actions(board):
maxValueResult = maxValue(result(board, action))
if maxValueResult < v:
v = maxValueResult
selected_action = action
return selected_action
def maxValue(board):
v = float("-inf")
if terminal(board):
return utility(board)
for action in actions(board):
v = max(v, minValue(result(board, action)))
return v
def minValue(board):
v = float("inf")
if terminal(board):
return utility(board)
for action in actions(board):
v = min(v, maxValue(result(board, action)))
return v
|
5f364e19483cf86257903c17167941a190da1bd8 | traders-see/pytohn1 | /program/if for .py | 1,819 | 3.625 | 4 | # if็ๆๆ๏ผๅฆๆ๏ผ็ๆๆ๏ผ ไป็่พๅบๅฟ
้กปๆฏๅธๅฐๅผ๏ผ
'''
if ๆกไปถAๆปก่ถณๅธๅฐๅผ
elif ๆกไปถBๆปก่ถณๅธๅฐๅผ
elif ๆกไปถCๆปก่ถณๅธๅฐๅผ
else ไปฅไธๆๆๆกไปถ้ฝไธๆปก่ถณ็ๆถๅๆง่ก
'''
# symbol = 'btcusd'
# if symbol.endswith('usd'): # aๆกไปถ
# print(symbol, '็พๅ
่ฎกไปท')
# elif symbol.endswith('btc'): # bๆกไปถ
# print(symbol, 'ๆฏ็นๅธ่ฎกไปท')
# elif symbol.endswith('eth'): # cๆกไปถ
# print(symbol, 'ไปฅๅคชๅ่ฎกไปท')
# else: # ้ฝไธๆปก่ถณ
# print(symbol, '้ฝไธๆปก่ถณ')
#ๆปก่ถณไธญ้ดไปปไฝไธไธชๆกไปถๅ ไธ้ขๆกไปถๆปก่ถณ็ๆถๅไนไธๆง่กไบใ
'''
for ๅพช็ฏ่ฏญๅฅ ๅฐฑๆฏ้ๅคไบๆ
๏ผ ไธ็จๅคๅถๅฅฝๅ ๆฌก
'''
# list_var = ['btc', 'usd' , 'eth']
# print(list_var[0])
# print(list_var[1])
# print(list_var[2])
# #for
# for i in list_var:
# print(i)
# print('ๆๅฐไบ')
# for i in range(1, 10):
# print('ๆๅฐ')
#
# sum_num = 0
# for i in [1,2,3,4,5,6,7,8,9,10]: # range(10+1)ไธๆ ท็
# sum_num +=i
# print(i, sum_num)
# # ๆกไพ
# symbol_list = ['btcusd', 'xrpbtc', 'xrpusd', 'ethusd','xrpeth']
# for symbol in symbol_list:
# if symbol.endswith('usd'):
# print(symbol, '็พๅ
่ฎกไปท')
# continue # ๆ่ฟไธชๅฐฑๆฏๆพไบ่ฟไธชๆกไปถไธ้ขไธๆง่ก๏ผๅจๅๅปไธ่ฝฎ่ฏญๅฅๅพช็ฏ
# if symbol.endswith('btc'):
# print(symbol, 'btc่ฎกไปท')
# continue
# if symbol.endswith('eth'):
# print(symbol, 'ไปฅๅคชๅ่ฎกไปท')
# continue
# print(symbol, 'ไธ็ฅ้ไปฅไปไนไปทๆ ผ')
# while ๆกไปถ ๆญปๅพช็ฏ ๅชๆๅฝๆกไปถไธๆปก่ถณ็ๆถๅๆไผ้ๅบ
num = 1
max_num = 10
sum_num = 0
while True:
sum_num += num
num += 1
print(sum_num, num)
if num == max_num+1:
break # IF่ฟๆกๆปก่ถณ็ๆถๅ่ทณๅบๆๆๅพช็ฏ่ฏญๅฅ |
3f4868748b96cde0ad69c6724fbc780f11489d27 | CapsLockAF/python--tqa-hw-tasks | /p1/task4-pythoncore-CapsLockAF/src/squares_sum.py | 155 | 3.578125 | 4 | def squares_sum(n):
# Type your code
count = 1
res = 0
while count <= n:
res += count**2
count += 1
return res
|
b9bff2a8e344dabb03de95bfd95e9f2ac59f1cc5 | WillLuong97/MultiThreading-Module | /openWeatherAPI.py | 4,137 | 3.75 | 4 | '''
OpenWeatherMap API, https://openweathermap.org/api
by city name --> api.openweathermap.org/data/2.5/weather?q={city name},{country code}
JSON parameters https://openweathermap.org/current#current_JSON
weather.description Weather condition within the group
main.temp Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit
wind.speed Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour
'''
import requests # http requests library, e.g. requests.get(API_Call).json()
# Initialize variables, console loop
def main():
# Console loop
print('\nWelcome to the Web Services API Demonstrator\n')
# input('Please press ENTER to continue!\n')
testCases = {1: 'Current Weather, city = Houston',
2: 'Current Weather, enter city name',
3: 'Current Weather, invalid key',
4: 'Current Weather, invalid city',
5: 'Future: current weather, enter zip code',
6: 'Future',
7: 'Future',
99: 'Exit this menu'}
userInput(testCases)
input('\n\nSay Bye-bye'.upper())
# Map user console input to a test case
# userChoices is a dictionary, key points to test case
# Includes user input exception handling
# Loop until user input is '99'
def userInput(userChoices):
while True:
print(' your choices'.upper(), '\t\t\tTest Case\n'.upper(), '-' * 55)
for key, value in userChoices.items():
print('\t', key, ' \t\t\t\t', value)
try:
choice = int(input("\nPlease enter the numeric choice for a Test Case \n\t --> ".upper()))
except:
print("\nSomething went wrong, please enter a numeric value!!!\n")
continue
if choice == 99:
break
menuExcept(choice)
# Map user menu selection (parameter) to module (function call)
def menuExcept(choice):
city = "Houston" #default city
API_key = '5bd2695ec45f88d4c14d7b43fd06a230' # Mulholland's key
invalidAPI_key = 'fd38d62aa4fe1a03d86eee91fcd69f6e' # used by You Tube video, not active 9/2018
units = '&units=imperial' # API default is Kelvin and meters/sec
invalidCity = city + '88' + 'abc'
if choice == 1:
JSON_Response = currentWeatherByCity(API_key, units, 'Houston')
currentWeatherFields(JSON_Response)
elif choice == 2:
city = input('\tPlease enter a city name --> ')
JSON_Response = currentWeatherByCity(API_key, units, city)
currentWeatherFields(JSON_Response)
elif choice == 3:
JSON_Response = currentWeatherByCity(invalidAPI_key, units, 'chicago')
elif choice == 4:
JSON_Response = currentWeatherByCity(API_key, units, invalidCity)
elif choice == 5:
print('test case construction underway, come back soon!')
elif choice == 6:
print('test case construction underway, come back soon!')
elif choice == 7:
print('test case construction underway, come back soon!')
else:
print('Whatchu talking about Willis? Please try a valid choice!')
input('*************** Press Enter to continue ******************\n\n'.upper())
# build the openweathermap REST Request
def currentWeatherByCity(key, units, city):
city = '&q=' + city
API_Call = 'http://api.openweathermap.org/data/2.5/weather?appid=' + key + city + units
print('\tThe api http string --> ' + API_Call)
input('\t*** hit ENTER to execute the API GET request ***\n')
jsonResponse = requests.get(API_Call).json()
print(jsonResponse)
return jsonResponse
# display selected values from the openweathermap REST response
def currentWeatherFields(response):
input('\n\t*** hit ENTER to check out selected JSON values ***\n')
print("\t Entire attribute of weather --> ", response['weather'])
print('\tdescription --> ', response['weather'][0]['main'])
print('\twind speed, mph --> ', response['wind']['speed'])
print('\ttemperature, F --> ', response['main']['temp'])
main() |
66c870b15db3040c1030deb637c4e5b8998897ff | bukovskiy/Coursera-Data-Structures-and-Algorithms-Specialization | /algorithmic_toolbox/week2/fibonacci.py | 400 | 3.921875 | 4 | # Uses python3
def fibNonRecursive(n):
counter = 1
array=[0,1]
while counter < n:
number = array[counter]+array[counter-1]
# print(number)
counter = counter+1
array.append(number)
return array[-1]
def main():
c = {0:0,1:1,2:1}
n = int(input())
print(fibNonRecursive(n,c))
if __name__ == "__main__":
main()
|
8fc1a31146fa1377e33283d271c58144c5492a41 | Muha-tsokotukha/PyGame | /TSIS-6/11.py | 170 | 3.765625 | 4 | def perf(a):
summ = 1
x = 2
while x <= a:
if a % x == 0:
summ += x
x += 1
return summ/2 == a
x = int(input())
print(perf(x))
|
9f4e38cd4a6a1e6f2ec380f64571e72634ddb1a2 | Muha-tsokotukha/PyGame | /week3-4/classing2.py | 410 | 3.671875 | 4 | class transport():
def __init__( self, brand, model ):
self.brand = brand
self.model = model
def brnd(self):
print(self.brand)
class cars(transport):
def __init__(self, brand,model,price):
super().__init__(brand,model)
self.price = price
def prs(self):
print(self.price*2)
car = cars("Toyota", "Camry", int(input()))
car.prs()
car.brnd()
|
2ab5b0f7a4a6071ab828ed713a990ed4b0e8c51f | Muha-tsokotukha/PyGame | /week10_Tsis7/2_3.py | 803 | 3.6875 | 4 | import pygame
pygame.init()
screen = pygame.display.set_mode((480,360))
x = 50
y = 100
done = False
step = 5
while not done:
for events in pygame.event.get():
if events.type == pygame.QUIT:
done = True
press = pygame.key.get_pressed()
if press[pygame.K_UP]: y -= step
if press[pygame.K_DOWN]: y += step
if press[pygame.K_LEFT]: x -= step
if press[pygame.K_RIGHT]: x += step
if press[pygame.K_SPACE]:
x = 240
y = 180
if x >= 480:
x -= 100
if x <= 0:
x += 100
if y >= 360:
y -= 100
if y <= 0:
y += 100
screen.fill((0,0,0))
pygame.draw.circle(screen, (140,140,255), (x,y), 40 )
pygame.display.flip()
pygame.time.Clock().tick(60) |
8ea6c2251009090a4b37666cc05741637705ae66 | madinamantay/webdev2019 | /week10/Informatics/3/for/K.py | 76 | 3.53125 | 4 | a = int(input())
s=0
for i in range(a):
s += int(input())
print(s)
|
3cb4b68000a36fb919a7766351baf05f84c1a6a3 | sumi89/Numpy_based_CNN | /cnn_numpy_utils.py | 2,708 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 16 18:09:03 2017
@author: Anthony
"""
import cnn_numpy as layer
def cnn_relu_forward(x, w, b, cnn_param):
"""
A convenience layer that performs a convolution followed by a ReLU.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
Returns a tuple of:
- out: Output from the ReLU
- cache: Object to give to the backward pass
"""
a, conv_cache = layer.cnn_backward_pass(x, w, b, cnn_param[0], cnn_param[1])
out, relu_cache = layer.relu_forward(a)
cache = (conv_cache, relu_cache)
return out, cache
def cnn_relu_backward(dout, cache):
"""
Backward pass for the conv-relu convenience layer.
"""
cnn_cache, relu_cache = cache
da = layer.relu_backward(dout, relu_cache)
dx, dw, db = layer.cnn_backward_pass(da, cnn_cache)
return dx, dw, db
def cnn_relu_pool_forward(x, w, b, stride, padding, pool_param):
"""
Convenience layer that performs a convolution, a ReLU, and a pool.
Inputs:
- x: Input to the convolutional layer
- w, b, conv_param: Weights and parameters for the convolutional layer
- pool_param: Parameters for the pooling layer
Returns a tuple of:
- out: Output from the pooling layer
- cache: Object to give to the backward pass
"""
a, cnn_cache = layer.cnn_forward_pass(x, w, b, stride, padding)
s, relu_cache = layer.relu_forward(a)
out, pool_cache = layer.max_pooling_forward_pass(s, pool_param)
cache = (cnn_cache, relu_cache, pool_cache)
return out, cache
def cnn_relu_pool_backward(dout, cache):
"""
Backward pass for the conv-relu-pool convenience layer
"""
cnn_cache, relu_cache, pool_cache = cache
ds = layer.max_pooling_backward_pass(dout, pool_cache)
da = layer.relu_backward(ds, relu_cache)
dx, dw, db = layer.cnn_backward_pass(da, cnn_cache)
return dx, dw, db
def fully_connected_relu_forward(x, w, b):
"""
Convenience layer that perorms an affine transform followed by a ReLU
Inputs:
- x: Input to the affine layer
- w, b: Weights for the affine layer
Returns a tuple of:
- out: Output from the ReLU
- cache: Object to give to the backward pass
"""
a, fc_cache = layer.fully_connected_forward(x, w, b)
out, relu_cache = layer.relu_forward(a)
cache = (fc_cache, relu_cache)
return out, cache
def fully_connected_relu_backward(dout, cache):
"""
Backward pass for the affine-relu convenience layer
"""
fc_cache, relu_cache = cache
da = layer.relu_backward(dout, relu_cache)
dx, dw, db = layer.fully_connected_backward(da, fc_cache)
return dx, dw, db |
3ec1466ffce05f83b108a81a83c5aeef1f999a05 | ethan-douglass/SHSPythonWork | /Chapter 2/Exersises/(2-10) Adding_Comments.py | 296 | 3.671875 | 4 | # Adds a Name to a quote
famous_person = "Albert Einstein"
message = f'{famous_person} once said,"A person who never made a mistake never tried anything new."'
print(message)
#Asks Eric if he wants to learn python
message = "\nHello Eric, would you like to learn some Python today?"
print(message)
|
9b4ca5602cbf2ce9bb25e5d5ce8faa29d7d3e7c2 | wiktoriamroczko/pp1 | /04-Subroutines/z31.py | 107 | 3.859375 | 4 | def reverse(tab):
return tab[::-1]
tab = [2, 5, 4, 1, 8, 7, 4, 0, 9]
print (tab)
print (reverse(tab)) |
3b50eb1cf1d948aeff1a9e9b41cde7f7efaa8b90 | wiktoriamroczko/pp1 | /06-ClassesAndObjects/z7.8.9.py | 683 | 3.703125 | 4 | class University():
# konstruktor obiektu (metoda __init__)
def __init__(self):
# cechy obiektu (pola)
self.name = 'UEK'
self.fullname = 'Uniwersytet Ekonomiczny w Karkowie'
# zachowania obiektu (metody)
def print_name(self):
print(self.name)
def set_name(self, new_name):
self.name = new_name
def print_fullname(self):
print(self.fullname)
def set_fullname(self, new_fullname):
self.fullname = new_fullname
n = University()
n.print_name()
n.print_fullname()
n2 = University()
n2.set_name('AGH')
n2.print_name()
n2.set_fullname('Akademia Gรณrniczo Hutnicza')
n2.print_fullname() |
02b28b1caa84961387b5bbdce17aa7dd531afb48 | wiktoriamroczko/pp1 | /10-SoftwareTesting/programs/zadanie6pkt.py | 1,008 | 3.765625 | 4 | class Macierz():
def __init__(self,m,n):
self.m = m
self.n = n
def stworzMacierz(self):
self.macierz = [[0 for a in range(self.m)]for b in range(self.n)]
return self.macierz
def rand(self):
import random
for i in self.macierz:
for j in range(len(i)):
i[j]=random.randint(0,9)
def __add__(self,other):
if self.m == other.m and self.n == other.n:
for i in range(len(self.macierz)):
for j in range(len(self.macierz[0])):
self.macierz[i][j] += other.macierz[i][j]
return [i for i in self.macierz]
else:
return []
def print(self):
for i in self.macierz:
print(i)
macierz = Macierz(3,4)
macierz.stworzMacierz()
Macierz.rand(macierz)
Macierz.print(macierz)
macierz2 = Macierz(3,4)
macierz2.stworzMacierz()
Macierz.rand(macierz2)
Macierz.print(macierz2)
print(macierz+macierz2) |
a0f15910ea6d931d057bc6e61e57b84c28f15622 | wiktoriamroczko/pp1 | /07-ObjectOrientedProgramming/z14.py | 814 | 3.984375 | 4 | class Phone():
def __init__(self, phone_number, brand, operating_system):
self.phone_number = phone_number
self.brand = brand
self.operating_system = operating_system
self.is_on = False
def turn_on(self):
self.is_on = True
def turn_off(self):
self.is_on = False
def __str__(self):
if self.is_on == False:
return f'''Phone number: {self.phone_number}
Brand: {self.brand}
Operating system: {self.operating_system}
Phone is off'''
else:
return f'''Phone number: {self.phone_number}
Brand: {self.brand}
Operating system: {self.operating_system}
Phone is on'''
p1 = Phone(987876765, 'Sony', 'Android')
p1.turn_on()
p2 = Phone(876098432, 'iPhone', 'iOS')
print(p1)
print(p2) |
88cd3bb80fcae3d0b2630154be9887310cbe9ea9 | wiktoriamroczko/pp1 | /02-ControlStructures/zadanie49.py | 471 | 3.921875 | 4 | print ('| PN | WT | SR | CZ | PT | SB | ND |')
nrDniaTygodnia =3
print ('| '*nrDniaTygodnia, end='')
for i in range(1, 31):
if i < 10:
print ('|', i, end=' ')
elif i >=10:
print ('|', i, end=' ')
if i == 7-nrDniaTygodnia:
print ('|')
if i == 14-nrDniaTygodnia:
print ('|')
if i == 21-nrDniaTygodnia:
print ('|')
if i == 28-nrDniaTygodnia:
print ('|')
if i==30:
print ('|')
|
4a374436c0bf4099eb09579a49d15befe5b27c50 | wiktoriamroczko/pp1 | /07-ObjectOrientedProgramming/z16.py | 710 | 3.75 | 4 | class Student():
def __init__(self, name, surname, album):
self.name = name
self.surname = surname
self.album = album
def __str__(self):
return f'{self.name} {self.surname} {self.album}'
def __eq__(self,other):
return self.album == other.album
def __it__(self,other):
return self.album < other.album
s1= Student('Anna','Tomaszewska',141820)
s2= Student('Wojciech','Zbych',201003)
s3= Student('Maja','Kowalska',153202)
s4= Student('Marek','Migiel',138600)
lista = [s1,s2,s3,s4]
for i in lista:
print(i)
print()
s = sorted(lista, key = lambda Student: Student.album)
for i in s:
print(i) |
fd8b41ce2736ce7e7818be2855f5b4bd01b64db1 | wiktoriamroczko/pp1 | /02-ControlStructures/1.py | 357 | 3.78125 | 4 | x = int(input('wprowadลบ liczbฤ: '))
if x % 2 == 0 and x >= 0:
print (f'{x} jest liczbฤ
parzystฤ
i dodatniฤ
')
elif x % 2 == 0 and x < 0:
print (f'{x} jest liczbฤ
parzystฤ
i ujemnฤ
')
elif x % 2 != 0 and x >= 0:
print (f'{x} jest liczbฤ
nieparzystฤ
i dodatniฤ
')
else :
print (f'{x} jest liczbฤ
nieparzystฤ
i ujemnฤ
')
|
628b0675e9e0ce68c1b7f212ac66fc26c1f6b1e8 | wiktoriamroczko/pp1 | /01-TypesAndVariables/BMI.py | 287 | 3.9375 | 4 | height = int(input("Podaj wzrost w cm:"))
x = height/100
weight = int(input(("Podaj wagฤ w kg:")))
bmi = weight/x**2
print (f"wskaลบnik BMI: {bmi}")
if bmi >= 18.5 and bmi <= 24.99:
print ("waga prawidลowa")
elif bmi< 18.5:
print ("niedowaga")
else:
print ("nadwaga")
|
fa2a9583c449a012a6ed19295f87e00d94b79bc1 | wiktoriamroczko/pp1 | /02-ControlStructures/zadanie39.py | 92 | 3.546875 | 4 | a = 0
b = 1
c = 0
for i in range(51):
print(a, end=' ')
c = a+b
a = b
b = c |
4f5fa5eb22637e05980a2e6c97f7f19e691540ac | Svengeelhoed/nogmaals | /duizelig/duizelig5.py | 228 | 3.609375 | 4 | banaan = input("vindt u ook bananen lekker?")
poging = 1
print(poging)
while banaan != "quit":
banaan = input("vindt u ook bananen lekker?")
poging = poging + 1
print(poging)
if banaan == "quit":
quit()
|
8c18d8b92868feb42bc1570ee7d5dd5f9fc3d757 | RomyNRug/pythonProject2 | /Week 4/Week 4.py | 1,186 | 3.9375 | 4 | import turtle
def draw_multicolor_square(animal, size):
for color in ["red", "purple", "hotpink", "blue"]:
animal.color(color)
animal.forward(size)
animal.left(90)
def draw_rectangle(animal, width, height):
for _ in range(2):
animal.forward(width)
animal.left(90)
animal.forward(height)
animal.left(90)
window = turtle.Screen() # Set up the window and its attributes
window.bgcolor("lightgreen")
tess = turtle.Turtle() # Create tess and set some attributes
tess.pensize(3)
size = 20 # Size of the smallest square
for _ in range(15):
draw_multicolor_square(tess, size)
size += 10 # Increase the size for next time
tess.forward(10) # Move tess along a little
tess.right(18)
def draw_square(animal, size):
for _ in range(4):
animal.forward(size)
animal.left(90)
window = turtle.Screen()
tess = turtle.Turtle()
draw_square(tess, 50)
window.mainloop()
def final_amount(p, r, n, t):
a = p * (1 + r/n) ** (n*t)
return a
toInvest = float(input("How much do you want to invest?"))
fnl = final_amount(toInvest, 0.08, 12, 5)
print("At the end of the period you'll have", fnl)
|
cbc542bd2d87fe3291b7b58cfac7ad584ca0037c | RomyNRug/pythonProject2 | /Week 5/Exercises5.4.6.py | 987 | 3.84375 | 4 | #1
def count_letters(text):
letter_counts = {}
for letter in text.lower():
if letter.isalpha():
if letter not in letter_counts:
letter_counts[letter] = 1
else:
letter_counts[letter] += 1
return letter_counts
def print_letter_counts(letter_counts):
for letter in sorted(letter_counts):
print(letter, letter_counts[letter])
input_text = "ThiS is String with Upper and lower case Letters"
print_letter_counts(count_letters(input_text))
#2
def add_fruit(inventory, fruit, quantity=0):
if fruit not in inventory:
inventory[fruit] = quantity
else:
inventory[fruit] += quantity
new_inventory = {}
add_fruit(new_inventory, "strawberries", 10)
print(new_inventory)
add_fruit(new_inventory, "strawberries", 25)
print(new_inventory)
#3
#????
#4
for words in (alice.txt):
if len(longwords)>len(words):
longwords=words
print("the longest word is ",longwords, ".") |
a2f83dfcfdc486d479192c74fffe1b9ca6c7b82c | scmartin/python_utilities | /GAOptimizer/population.py | 8,594 | 3.5625 | 4 | # ToDo:
# - redesign evolution algorithm to create a new population
# without replacing any of the old population. Then, take
# top 50% of parent and child populations
# - add threading for creating child population
# - add convergence criteria
#
import numpy as np
from abc import ABC, abstractmethod
import xml.etree.ElementTree as et
import copy
class population:
"""defines a population with n_members individuals. The fitness function is set at the population level so that all individuals
share the same fitness function. The fitness function is to be minimized, so the most fit individual will have the lowest fitness
value. """
def __init__(self, bounds, ffxml, fitnessFunction):
self._generation = 0
# individuals are generated with the _member initializer
self._initialff = ffxml
self._fitnessFunc = fitnessFunction
self._bounds = bounds
@classmethod
def new_population(cls, n_members: int, bounds, ffxml, fitnessFunction):
instant = cls(bounds, ffxml, fitnessFunction)
instant._nMembers = n_members
instant._generation = 0
# individuals are generated with the _member initializer
instant._members = [_member.make_member(bounds, ffxml, False) for i in range(n_members)]
for i in instant._members:
i.fitness = instant._fitnessFunc(i.params)
# members are sorted so that the least fit member is easily accessed
instant._members.sort(key=lambda member: member.fitness)
return instant
@classmethod
def read_population(cls, bounds, base_xml, ffxml, fitnessFunction):
instant = cls(bounds, base_xml, fitnessFunction)
# individuals are generated with the _member initializer
instant._members = [_member.make_member(bounds, i, True) for i in ffxml]
instant._nMembers = len(instant._members)
for i in instant._members:
i.fitness = instant._fitnessFunc(i.params)
# members are sorted so that the least fit member is easily accessed
instant._members.sort(key=lambda member: member.fitness)
return instant
@property
def bounds(self):
return self._bounds
@property
def initialff(self):
return self._initialff
@property
def generation(self):
return self._generation
@property
def nMembers(self):
return self._nMembers
@property
def members(self):
return self._members
def mutate_member(self, idx):
"""Choose a member and mutate it."""
self._members[idx].mutate(self._bounds,1.0)
self._members[idx]._fitness = self._fitnessFunc(self._members[idx].params)
self._members.sort(key=lambda member: member.fitness)
def mate(self):
"""Choose two individuals from the population and create a child. If the child is fitter than the
least fit current individual in the population, replace the individual with the child"""
parents = np.random.randint(self._nMembers, size=2)
child = _member.make_member(self.bounds, self.initialff, True)
root = self.bounds.getroot()
for section in root:
s_tag = section.tag
for interaction in section:
i_tag = interaction.tag
i_attrib = f'[@order="{interaction.get("order")}"]'
for group in interaction:
parent = self.members[parents[np.random.randint(2)]].params
where = f'./{s_tag}/{i_tag}{i_attrib}/{group.tag}[@order="{group.get("order")}"]'
param = parent.find(where).text
child.params.find(where).text = param
#Mutate the child to widen parameters outside the parents
if np.random.random_sample() < 0.6:
child.mutate(self._bounds, 1.0)
child._fitness = self._fitnessFunc(child.params)
return child
# if (child.__lt__(self._members[-1])):
# self._members[-1] = child
# self._members.sort(key=lambda member: member.fitness)
def evolve(self):
"""Move the population forward a generation by creating population.nMembers new potential children.
Whether children survive is determined by the population.mate() function."""
children = []
for whichmember in range(self.nMembers):
children.append(self.mate())
children.sort(key=lambda member: member.fitness)
self._members = self._members[:self.nMembers//2] + children[:(self.nMembers+1)//2]
self._members.sort(key=lambda member: member.fitness)
self._generation += 1
class _member(ABC):
"""Define an individual. Each individual has a parameter vector and a fitness."""
def __init__(self):
self._fitness = 0.
def make_member(bounds,ffxml,restart):
creator = choose_type(bounds)
return(creator(bounds,ffxml,restart))
def __gt__(self, othermember):
"""Define greater-than comparison function."""
return self.fitness > othermember.fitness
def __lt__(self, othermember):
"""Define less-than comparison function."""
return self.fitness < othermember.fitness
@property
def fitness(self):
return self._fitness
@fitness.setter
def fitness(self, value):
self._fitness = value
@abstractmethod
def mutate(self):
pass
# class param_list_member(_member):
# """Parameters are given as a simple list or numpy array"""
#
# def __init__(self, bounds):
# super().__init__()
# self._params = []
# for i in range(len(bounds)):
# self._params.append(bounds[0] + np.random.random()
# *(bounds[1] - bounds[0]))
#
# def mutate(self, bounds, scale):
# """Mutate a member by choosing a single parameter and modifying it. If the new
# parameter value falls outside the bounds, randomly assign a value within the bounds."""
# idx = np.random.randint(len(self.params))
# bounds = bounds[idx]
# self.params[idx] = self.params[idx] + (np.random.random() - 0.5)*(bounds[1] - bounds[0])*scale
# if (self.params[idx] < min(bounds) or self.params[idx] > max(bounds)):
# self.params[idx] = np.random.random()*(bounds[1] - bounds[0]) + bounds[0]
class reaxFF_member(_member):
"""Parameters are defined by a nested dictionary and xml representation of
the forcefield file"""
def __init__(self, bounds, ffxml, restart):
super().__init__()
self._chromosome = []
self.params = copy.deepcopy(ffxml)
root = bounds.getroot()
for section in root:
s_tag = section.tag
for interaction in section:
i_tag = interaction.tag
i_attrib = f'[@order="{interaction.get("order")}"]'
for group in interaction:
where = f'./{s_tag}/{i_tag}{i_attrib}/{group.tag}[@order="{group.get("order")}"]'
self._chromosome.append(where)
if not restart:
lower = float(group.get("lower"))
upper = float(group.get("upper"))
param = lower + np.random.random()*(upper - lower)
self.params.find(where).text = str(param)
@property
def chromosome(self):
return self._chromosome
def mutate(self, bounds, scale):
"""Mutate a member by choosing a single parameter and modifying it. If the new
parameter value falls outside the bounds, randomly assign a value within the bounds."""
gene = self.chromosome[np.random.randint(len(self.chromosome))]
root = bounds.getroot()
lower = float(root.find(gene).get('lower'))
upper = float(root.find(gene).get('upper'))
mutation = (np.random.random()-0.5)*(upper - lower)*scale
param = float(self.params.find(gene).text)
newparam = param + mutation
if newparam < lower or newparam > upper:
newparam = lower + np.random.random()*(upper - lower)
self.params.find(gene).text = str(newparam)
def choose_type(bounds):
if type(bounds) == list:
return param_list_member
elif type(bounds) == et.ElementTree:
return reaxFF_member
else:
raise ValueError(f'Bounds are of type {type(bounds)}, which is not of a valid type')
|
3b084397643d6a5276f75f7b4abe42e7b487ccd3 | trup922/ExtractCompetitorKeywords | /venv/Include/FindKeywords.py | 4,289 | 3.5625 | 4 | import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import re
import heapq
import difflib
#helper function for removing all occurences of an item from a list, will come in hand when we will filter out certain words from a string
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
#helper function for extracting second element of tuple
def take_second(elem):
return elem[1]
#function for computing 10 most common words in text
def findTenFreqWords(text):
text = text.split()#convert string to list
blackList = ['ืฉื','ืขื','ืขื','ืืช']#Subjective part of code, words to filter out should differ between projects
for word in blackList:
text = remove_values_from_list(text,word)
textDict = dict.fromkeys(text)#convert list to dictionary (and keep only 1 occurrence of each word)
for word in textDict:
textDict[word] = text.count(word)#create pairs of '(word, word occurence)' in dictionary
WordList = [(k,v) for k,v in textDict.items()]#create tuples from dictionary
sortedList = sorted(WordList,key= take_second)#create sorted list from tuples
return (sortedList[-10:])#return 10 last items of sorted list i.e. 10 most common words in string)
#extract the keywords based on the Title, H1 and meta description of the page
def returnKeywords(link):
#----------make request---------
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}
response = requests.get(link, headers=headers)
html = response.content
bsElement = BeautifulSoup(html, "html.parser")
with open('{}.html'.format(str(link)[8:1]), 'wb') as file:
file.write(bsElement.prettify('utf-8'))
#-----------extract SEO-relevant information from tags on page-------------
title = bsElement.title
if title == None:
title = 'none'
else:
title = title.text
h1 = bsElement.h1
if h1 == None:
h1 = 'none'
else:
h1 = h1.text
H2s = bsElement.find_all("h2")
H2sTexts = []
if H2s != None:
for h in H2s:
H2sTexts.append(h.text)
H3s = bsElement.find_all("h3")
H3sTexts = []
if H3s != None:
for h in H3s:
H3sTexts.append(h.text)
metaDes = bsElement.find('meta', {'name': 'description', })
if metaDes == None:
metaDes = 'none'
else:
metaDes = metaDes.get('content')
metaKeyWords = bsElement.find('meta', {'name': 'keywords', })
if metaKeyWords == None:
metaKeyWords = 'none'
else:
metaKeyWords = metaKeyWords.get('content')
All_texts = bsElement.find_all("p")
texts = " "
for p in All_texts:
texts = texts + (str(p.text))
texts = texts.strip("\n")
imgs = bsElement.find_all("img")
imgList = []
for img in imgs:
if 'alt' in img.attrs: # make sure we scan only images that have an alt attribute
if img['alt'] != "": # scan only images that alt attribute for them isn't empty (avoid an index out of bounds error)
if img['alt'][0] != '{': # check that alt text is indeed text and not a parameter like "{{product.name}}"
imgList.append(str(img['alt']))
imgList = list(dict.fromkeys(imgList))
TitleList = title.split()
DescriptionList = metaDes.split()
H1List = h1.split()
MetaKeywordsList = metaKeyWords.split()
textsList = texts.split()
print('The words constructing the title are: '+TitleList)
#print(H1List)
#print(DescriptionList)
#print(MetaKeywordsList)
print(texts)
TenWords = findTenFreqWords(texts)
H1Dict = dict.fromkeys(H1List)
ListOfSEOElements = (title, h1, H2sTexts,H3sTexts, metaDes, metaKeyWords,imgList,TenWords)
#---------compute the words most likely to be the keywords---------------
for key in TitleList:
H1Dict[key] = difflib.get_close_matches(key, TitleList)+difflib.get_close_matches(key, DescriptionList)+difflib.get_close_matches(key, textsList)+difflib.get_close_matches(key, imgList)+difflib.get_close_matches(key, texts)
print([(k, H1Dict[k]) for k in H1Dict])
return ListOfSEOElements
|
e4abf277d6f7e139a1a8c52d0101707400a92396 | Marcbaer/02.01.Deploying_Forecasting_Model_using_AzureML_SDK | /Train_LSTM.py | 735 | 3.515625 | 4 | import matplotlib.pyplot as plt
from LSTM_LV import Lotka_Volterra
#Define model and training parameters
n_features=2
n_steps=12
hidden_lstm=6
Dense_output=2
epochs=250
#Lotka Volterra data parameters
shift=1
sequence_length=12
sample_size=2000
#Build, train and evaluate the model
LV=Lotka_Volterra(shift,sequence_length,sample_size,hidden_lstm,Dense_output,n_steps,n_features,epochs)
model,history,score=LV.build_train_lstm()
print(f'Test loss: {score}')
# Visualize training history
plt.plot(history.history['val_loss'],label='Validation Loss')
plt.plot(history.history['loss'],label='Training Loss')
plt.title('Validation loss history')
plt.ylabel('Loss value')
plt.xlabel('No. epoch')
plt.legend(loc=1)
plt.show() |
8d1ae76c20631b26a86436a0a4a02a0fdb73699a | nedchewnabrJCU/Sandbox | /Finished Practicals/prac_02/randoms.py | 917 | 4.09375 | 4 | import random
print(random.randint(5, 20)) # line 1
print(random.randrange(3, 10, 2)) # line 2
print(random.uniform(2.5, 5.5)) # line 3
# What did you see on line 1?
# The number seen was "5".
# What was the smallest number you could have seen, what was the largest?
# Smallest number is "5", largest number is "20".
# What did you see on line 2?
# The number seen was "5".
# What was the smallest number you could have seen, what was the largest?
# Smallest number is "3", largest number is "9".
# Could line 2 have produced a 4?
# No
# What did you see on line 3?
# The number seen was "4.285261416399966"
# What was the smallest number you could have seen, what was the largest?
# Smallest number is "2.500000000000000", largest number is "5.500000000000000".
# Write code, not a comment, to produce a random number between 1 and 100 inclusive.
print(random.randint(1, 100))
|
0fec5b9ccde19b79c8751870433d1c3fad64c483 | gauravthadani/ml-learning | /python/demo_dtc.py | 800 | 3.953125 | 4 | #Introduction - Learn Python for Data Science #1
#youtube link = https://www.youtube.com/watch?v=T5pRlIbr6gg&t=3s
from sklearn import tree
import graphviz
#[height, weight, shoe size]
X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37],
[166, 65, 40], [190, 90, 47], [175, 64, 39], [177, 70, 40], [159, 55, 37],
[171, 75, 42], [181, 85, 43]]
Y = ['male', 'female', 'female', 'female',
'male', 'male', 'male', 'female','male',
'female','male' ]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X,Y)
dot_data = tree.export_graphviz(clf, out_file=None)
graph = graphviz.Source(dot_data)
graph.render("gender_classifier")
prediction = clf.predict([[190,70,43]])
prediction_proba = clf.predict_proba([[190,70,43]])
# print clf
print prediction
print prediction_proba |
18bd45cd6fa90bd71e719888237f80fc44908984 | leonh/pyelements | /examples/a7_generators.py | 801 | 3.875 | 4 | from examples.a1_code_blocks import line
# generators use yield something
def integers():
for i in range(1, 9):
yield i
integers()
print(line(), integers())
# Generator objects execute when next() is called
print(line(), next(integers()))
chain = integers()
print(line(), list(chain))
def squared(seq):
for i in seq:
yield i * i
def negated(seq):
for i in seq:
yield -i
chain = negated(squared(integers()))
print(line(), list(chain))
# generator expressions
integers = range(8)
squared = (i * i for i in integers)
negated = (-i for i in squared)
print(line(), list(negated))
s1 = sum((x * 2 for x in range(10)))
print(line(), s1)
# if it is a single call to a function you can drop the outer "()"
s2 = sum(x * 2 for x in range(10))
print(line(), s2)
|
b0c33c8848844a6a025ee5c145f1ef1373ba3c30 | x223/cs11-student-work-Aileen-Lopez | /practice_makes_perferct.py | 160 | 4.125 | 4 | number = input("give me a number")
def is_even(input):
if x % 2 == 8:
print True
else:
print False
#can't get it to say true or false
|
ece16e9a25e880eaa3381b787b12cecf86625886 | x223/cs11-student-work-Aileen-Lopez | /March21DoNow.py | 462 | 4.46875 | 4 | import random
random.randint(0, 8)
random.randint(0, 8)
print(random.randint(0, 3))
print(random.randint(0, 3))
print(random.randint(0, 3))
# What Randint does is it accepts two numbers, a lowest and a highest number.
# The values of 0 and 3 gives us the number 0, 3, and 0.
# I Changed the numbers to (0,8) and the results where 1 0 1.
# The difference between Randint and print is that print will continue giving a 3, while Randint stays the same of changes.
|
5db2ce733c009c2807c8179ef38c2dae82c46036 | x223/cs11-student-work-Aileen-Lopez | /find_odds.py | 157 | 3.65625 | 4 | list = [3,4,7,13,54,32,653,256,1,41,65,83,92,31]
def find_odds(input):
for whatever in input:
if whatever % 2 == 1:
print "whatever"
|
e12e1a8823861cee15aee0f931bcc4f117d3e514 | KNootanKumar/prototype-for-Notifying-user-of-a-database-through-mail | /youtube_video_list.py | 778 | 3.8125 | 4 | import sqlite3
#print("hello")
conn =sqlite3.connect("Youtube_videos.db")
cur=conn.cursor()
#print("hiii babes")
cur.execute("CREATE TABLE IF NOT EXISTS youtube_videos(id INTEGER,tittle text , url text)")
#print("hello baby")
cur.execute("INSERT INTO youtube_videos VALUES(12,'Video_12','https://www.youtube.com/watch?v=Ae7yiE6Sx38')")
#cur.execute("INSERT INTO youtube_videos VALUES(2,'Video_2','https:////www.youtube.com//watch?v=0Zp0dvT3nCQ')")
#cur.execute("INSERT INTO youtube_videos VALUES(3,'Video_3','https://www.youtube.com/watch?v=sayK41hPXyM')")
#cur.execute("INSERT INTO youtube_videos VALUES(4,'Video_4','https://www.youtube.com/watch?v=KyOPKQZUaJA')")
cur.execute("SELECT *FROM youtube_videos")
conn.commit()
db=cur.fetchall()
print(db)
conn.commit()
conn.close()
|
016c7e2da4516be168d3f51b34888d12e0be1c5d | adrian-calugaru/fullonpython | /sets.py | 977 | 4.4375 | 4 | """
Details:
Whats your favorite song?
Think of all the attributes that you could use to describe that song. That is: all of it's details or "meta-data". These are attributes like "Artist", "Year Released", "Genre", "Duration", etc. Think of as many different characteristics as you can.
In your text editor, create an empty file and name it main.py
Now, within that file, list all of the attributes of the song, one after another, by creating variables for each attribute, and giving each variable a value. Here's an example:
Genre = "Jazz"
Give each variable its own line. Then, after you have listed the variables, print each one of them out.
For example:
Artist = "Dave Brubeck"
Genre = "Jazz"
DurationInSeconds = 328
print(Artist)
print(Genre)
print(DurationInSeconds)
Your actual assignment should be significantly longer than the example above. Think of as many characteristics of the song as you can. Try to use Strings, Integers and Decimals (floats)!
"""
|
40ec1ba7e942414a776398fba3730f76d3471fb7 | star83424/python-practice | /python-practice/sorting.py | 5,137 | 3.984375 | 4 | def swap(nums, i, j):
tmp = nums[i]
nums[i] = nums[j]
nums[j] = tmp
class SortUtils:
@staticmethod
def bubble_sort(nums):
print(f'start sorting {nums}')
for i in range(len(nums) - 1):
for j in range(len(nums) - 1):
if nums[j] > nums[j+1]:
swap(nums, j, j+1)
return nums
@staticmethod
def selection_sort(nums):
print(f'start sorting {nums}')
for i in range(len(nums)):
min_index = i
for j in range(i + 1, len(nums)):
if nums[j] < nums[min_index]:
min_index = j
swap(nums, i, min_index)
return nums
@staticmethod
def insertion_sort(nums):
print(f'start sorting {nums}')
ans = [nums[0]]
for i in range(1, len(nums)):
for j in range(len(ans)):
if nums[i] < ans[j]:
ans.insert(j, nums[i])
break
if j == len(ans)-1:
ans.append(nums[i])
return ans
@staticmethod
def quick_sort(nums):
print(f'start sorting {nums}')
left, right, pivot = 0, len(nums)-2, len(nums)-1
while True:
while left < pivot and nums[left] <= nums[pivot]:
left += 1
while right > left and nums[right] >= nums[pivot]:
right -= 1
# print(nums)
if left < right:
# print(f'swap {left}(val:{nums[left]}) with {right}(val:{nums[right]})')
swap(nums, left, right)
else:
swap(nums, pivot, left)
# print(f"swap pivot {pivot} at {left}: {nums}")
if left > 0:
nums[0: left] = SortUtils.quick_sort(nums[0: left])
if left < len(nums)-2:
nums[left+1:] = SortUtils.quick_sort(nums[left+1:])
return nums
return nums
@staticmethod
def merge_sort(nums):
print(f'start sorting {nums}')
length = len(nums)
if length < 2:
return nums
left = SortUtils.merge_sort(nums[0: int(length/2)])
right = SortUtils.merge_sort(nums[int(length/2):])
ans, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
ans.append(left[i])
i += 1
else:
ans.append(right[j])
j += 1
if i < len(left):
ans.extend(left[i:])
if j < len(right):
ans.extend(right[j:])
return ans
@classmethod
def heap_sort(cls, nums):
print(f'start sorting {nums}')
# build the heap : n^n
cls.__build_heap(nums)
print(f'__build_heap: {nums}')
# pop out the first one & heapify down to maintain the heap
for i in range(len(nums)-1, -1, -1):
cls.__pop(nums, i)
cls.__heapify(nums, 0, i)
return nums
@classmethod
def __build_heap(cls, nums):
# Heapify all none leaves nodes from bottom to top
for i in range(int(len(nums)/2), -1, -1):
cls.__heapify(nums, i, len(nums))
@staticmethod
def __heapify(nums, i, length):
max_index = i
left = i*2 + 1
if left < length and nums[left] > nums[max_index]:
# left child might be the max
max_index = left
right = (i+1) * 2
if right < length and nums[right] > nums[max_index]:
# right child is the max
max_index = right
# Need swap
if max_index != i:
nums[i], nums[max_index] = nums[max_index], nums[i]
# keep on heapify-ing down
SortUtils.__heapify(nums, max_index, length)
@staticmethod
def __pop(nums, i):
print(f'pop{nums[0]}')
# fake pop: swap the popped one with the last one
nums[i], nums[0] = nums[0], nums[i]
class Node:
def __init__(self, val, left=None, right=None):
self.left = left
self.right = right
self.val = val
"""
0
1 2
3 4 5 6
[3, 1, 5, 3, 4, 2, 1, 6, 7, 8, 4, 10, 12, 8, 9, 0, 11]
12
11 10
7 8 5 9
6 1 4 4 3 2 8 1
0 3
[0, 1, 1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12]
"""
class Sorting:
@staticmethod
def main(case):
# 2021/05/09
# print(SortUtils.bubble_sort(case1[:]))
# print("----")
# print(SortUtils.selection_sort(case1[:]))
# print("----")
# print(SortUtils.insertion_sort(case1[:]))
# print("----")
# print(SortUtils.quick_sort(case1[:]))
# print("----")
# print(SortUtils.merge_sort(case1[:]))
# ----------------------------------------------------------
# 2021/05/10
for i in range(20 - 1, -1, -1):
print(i)
print("----")
print(SortUtils.heap_sort(case[:]))
|
9987ab52003b44485eca176c04f343d30a0e937a | star83424/python-practice | /python-practice/binary_search_tree.py | 1,984 | 3.921875 | 4 | from sorting import SortUtils
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def print(self):
print(f'val: {self.val}, left: "{self.left}, right: {self.right}')
def build_binary_search_tree(nums):
root = None
for i in nums:
root = build_tree_node(root, i)
return root
def build_tree_node(root, i):
if root is None:
return Node(i)
if i >= root.val:
if root.right is None:
root.right = Node(i)
else:
root.right = build_tree_node(root.right, i)
else:
if root.left is None:
root.left = Node(i)
else:
root.left = build_tree_node(root.left, i)
return root
def traversal(root):
if root is None:
return
traversal(root.left)
root.print()
traversal(root.right)
#
# def self_then_children(root):
# if root is None:
# return
# root.print()
# self_then_children(root.left)
# self_then_children(root.right)
def binary_search_in_sorted_list(nums, target, i = None, j = None):
if i is None:
i = 0
if j is None:
j = len(nums)
if i == j:
print(f"Cannot find {target}!")
return
center = int((i+j) / 2)
if target == nums[center]:
print(f"{target} found!")
elif target > nums[center]:
binary_search_in_sorted_list(nums, target, center+1, j)
else:
binary_search_in_sorted_list(nums, target, i, center)
"""
0
1 2
3 4 5 6
left: i*2 +1
right (i+1)*2
"""
class BST:
@staticmethod
def main(case1):
root = build_binary_search_tree(case1)
traversal(root)
# Binary search
test = [8, 2, 4, 1, 3]
print(test)
SortUtils.heap_sort(test)
print(test)
binary_search_in_sorted_list(test, 5)
|
6dba0696232cf84d9d0f5625f8e58972f892d179 | Robo4al/robot | /step.py | 1,606 | 3.546875 | 4 | import time
from machine import Pin
'''
[StepMotor]
Por padrรฃo, ao criar um objeto do tipo StepMotor os pinos utilizados do Roberval serรฃo:
- PIN1 = 18
- PIN2 = 19
- PIN3 = 22
- PIN4 = 23
* Fases do motor:
a) phase IN4 = [0,0,0,1]
b) phase IN4 and IN3 = [0,0,1,1]
c) phase IN3 = [0,0,1,0]
d) phase IN3 and IN2 = [0,1,1,0]
e) phase IN2 = [0,1,0,0]
f) phase IN2 and IN1 = [1,1,0,0]
g) phase IN1 = [1,0,0,0]
h) phase IN1 and IN4 = [1,0,0,1]
* step()
- Movimento = direita | velocidade = 5ms | passos = 1
stepMotor.step(False)
- Movimento = direita | velocidade = 10ms | passos = 1
stepMotor.step(False, 10)
- Movimento = esquerda | velocidade = 10ms | passos = 100
stepMotor.step(True, 10, 100)
- Movimento = direita | velocidade = 5ms | passos = 100
stepMotor.step(False, stepCount=100)
- Movimento = esquerda | velocidade = 10ms | passos = 1
stepMotor.step(True, sleepMs=100)
'''
class StepMotor:
def __init__(self, PIN1=18, PIN2=19, PIN3=22, PIN4=23):
self.in1 = Pin(PIN1, Pin.OUT)
self.in2 = Pin(PIN2, Pin.OUT)
self.in3 = Pin(PIN3, Pin.OUT)
self.in4 = Pin(PIN4, Pin.OUT)
def step(self, left, sleepMs=5, stepCount=1):
values = [[0,0,0,1], [0,0,1,1], [0,0,1,0], [0,1,1,0], [0,1,0,0], [1,1,0,0], [1,0,0,0], [0,0,1,1]]
if left:
values.reverse()
for count in range(stepCount):
for value in values:
self.in1.value(value[0])
self.in2.value(value[1])
self.in3.value(value[2])
self.in4.value(value[3])
time.sleep_ms(sleepMs)
if __name__ == "__main__":
motor = StepMotor()
motor.step(False, stepCount=4096) |
6657511dc98487fd3160d8fbe9bfee4975f5cb6d | mkatzef/difference-checker | /DifferenceChecker.py | 7,078 | 3.8125 | 4 | """ Number base, and to/from ASCII converter GUI. Now supporting Fractions
Author: Marc Katzef
Date: 20/4/2016
"""
from tkinter import *
#from tkinter.ttk import *
class Maingui:
"""Builds the gui in a given window or frame"""
def __init__(self, window):
"""Places all of the GUI elements in the given window/frame, and
initializes the variables that are needed for this GUI to do anything"""
self.window = window
self.top_rely = 0
self.next_rely = 0.15
top_height = 40
self.w2 = StringVar()
self.w2.set('20')
self.h2 = StringVar()
self.h2.set('14')
self.top_bar = Frame(window)
self.top_bar.place(x=0, y=0, relwidth=1, height=top_height)
self.entry1_label = Label(self.top_bar, text='Text A', font=('Arial', 12), anchor='center')
self.entry1_label.place(relx=0.1, y=0, height=top_height, relwidth=0.3)
self.entries = Frame(window)
self.string1_entry = Text(self.entries)
self.string1_entry.place(relx=0, y=0, relwidth=0.5, relheight=1)
self.entry2_label = Label(self.top_bar, text='Text B', font=('Arial', 12), anchor='center')
self.entry2_label.place(relx=0.6, y=0, height=top_height, relwidth=0.3)
self.string2_entry = Text(self.entries)
self.string2_entry.place(relx=0.5, y=0, relwidth=0.5, relheight=1)
self.entries.place(relx=0, y=top_height, relwidth=1, relheight=1, height=-(top_height))
self.button1 = Button(self.top_bar, command=self.check, font=('Arial', 10, 'bold'))
self.button1.place(relx=0.5, y=top_height/2, relwidth=0.2, anchor='center')
self.displaying_results = False
self.change_button('light gray', 'Check')
def insert_result(self, result, summary, ratio, red_map=-1):
self.result = Text(self.entries)
self.result.place(relx=0, relwidth=1, relheight=1)#
self.button1['command'] = self.remove_results
self.result.delete('1.0', END)
self.result.tag_configure("red", background="#ffC0C0")
self.result.tag_configure("grey", background="#E0E0E0")
grey_white = 0
if red_map == -1:
self.result.insert(END, result)
else:
counter = 0
for line in result:
self.result.insert(END, line + '\n')
is_red = red_map[counter]
grey_white = 1 - grey_white
if is_red:
self.result.tag_add("red", '%d.0' % (counter + 1), 'end-1c')
elif grey_white:
self.result.tag_add("grey", '%d.0' % (counter + 1), 'end-1c')
counter += 1
self.entry1_label['text'] = ''
self.entry2_label['text'] = ''
#red_component = int((1-ratio) * 255)
#green_component = int((2 ** ratio - 1) * 255)
#colour = "#%02x%02x00" % (red_component, green_component)
if summary == 'Identical':
self.change_button("light green", "100%")
else:
self.change_button("#FFC0C0", "%.0f%%" % (100 * ratio))
self.displaying_results = True
def change_button(self, colour, text):
self.button1['background'] = colour
self.button1['text'] = text
def remove_results(self):
self.result.destroy()
self.change_button('light gray', 'Check')
self.button1['text'] = 'Check'
self.button1['command'] = self.check
self.entry1_label['text'] = 'Text A'
self.entry2_label['text'] = 'Text B'
self.displaying_results = False
def check(self, *args):
"""Collects the appropriate information from the user input, then
retrieves the appropriate output, and places it in the appropriate text
field, appropriately"""
file_a = input_string = self.string1_entry.get('1.0', 'end-1c')
file_b = input_string = self.string2_entry.get('1.0', 'end-1c')
list_a = [line.strip() for line in file_a.splitlines()]
list_b = [line.strip() for line in file_b.splitlines()]
size_a = len(list_a)
size_b = len(list_b)
oh_oh = 'Empty:'
problem = 0
if size_a == 0:
oh_oh += ' Text A'
problem += 1
if size_b == 0:
oh_oh += ' Text B'
problem += 1
if problem == 1:
self.insert_result(oh_oh, 'Problem', 0)
return
elif problem == 2: #Both empty
self.insert_result(oh_oh, 'Identical', 1)
return
result = []
identical = True
red_map = []
correct_counter = 0
space = max([len(line) for line in list_a])
common_template = '%d:\t%' + str(space) + 's |=| %''s'
difference_template = '%d:\t%' + str(space) + 's |X| %''s'
#common_template = '%s |= %d =| %s\n'
#difference_template = '%s |X %d X| %s\n'
for index in range(min(size_a, size_b)):
line_a = list_a.pop(0)
line_b = list_b.pop(0)
if line_a == line_b:
correct_counter += 1
result.append(common_template % (index+1, line_a, line_a))
#result += common_template % (line_a, index+1, line_a)
red_map.append(False)
else:
identical = False
new_part = difference_template % (index+1, line_a, line_b)
result.append(new_part)
red_map.append(True)
#result += difference_template % (line_a, index+1, line_b)
if len(list_a) > 0:
identical = False
for line in list_a:
index += 1
new_part = difference_template % (index+1, line, '')
result.append(new_part)
red_map.append(True)
#result += difference_template % (line, index+1, '')
elif len(list_b) > 0:
identical = False
for line in list_b:
index += 1
new_part = difference_template % (index+1, '', line)
result.append(new_part)
red_map.append(True)
#result += difference_template % ('', index+1, line)
correct_ratio = correct_counter / max(size_a, size_b)
if identical:
summary = 'Identical'
else:
summary = 'Different'
self.insert_result(result, summary, correct_ratio, red_map)
def main():
"""Sets everything in motion"""
window = Tk()
window.title('Difference Checker')
window.minsize(220, 200)
Maingui(window)
window.mainloop()
if __name__ == '__main__':
main()
|
f1dd49c9897bd996a589f1421a058fed769e444d | AnttiVainikka/ot-harjoitustyo | /game/src/UI/move.py | 1,056 | 3.546875 | 4 | # pylint: disable=no-member
import pygame
pygame.init()
from Classes.character import Character
def move(character):
"""Registers if the player presses or releases the arrow keys and configures the main character based on it."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
character.move_left()
if event.key == pygame.K_RIGHT:
character.move_right()
if event.key == pygame.K_UP:
character.move_up()
if event.key == pygame.K_DOWN:
character.move_down()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
character.stop_left()
if event.key == pygame.K_RIGHT:
character.stop_right()
if event.key == pygame.K_UP:
character.stop_up()
if event.key == pygame.K_DOWN:
character.stop_down()
|
95b5e8ce6cfb6939b7c7eb12614f655792453046 | kaen98/python_demo | /ChapterFive/5-3.py | 203 | 3.640625 | 4 | alien_color = ['green', 'yellow', 'red']
alien_one = 'green'
if alien_one in alien_color:
print('alien color is green, +5 points')
alien_two = 'white'
if alien_two in alien_color:
print('+5 points') |
1c3ab432c612e27d412d644ff7386660a18a209a | Evohmike/Password-Locker | /Display.py | 8,410 | 4.125 | 4 | #!/usr/bin/env python3.6
from creds import Credentials
from user import User
def create_account(username,password):
'''
This function creates new account
'''
new_user = User(username,password)
return new_user
def save_new_user(user):
'''
This function saves a user
'''
User.save_user(user)
def login_account(login):
return User.user_login(login)
def create_credentials(account,username,email,password):
'''
This creates new credentials
'''
new_credentials = Credentials(account,username,email,password)
return new_credentials
def save_user_credentials(credentials):
'''
This function saves credentials
'''
credentials.save_credentials()
def delete_credentials(credentials):
'''
This deletes credentials
'''
credentials.delete_credentials()
def find_credentials(name):
'''
this finds the credentials using account name and returns details
'''
return Credentials.find_by_account_name(name)
def copy_username(name):
return Credentials.copy_username(name)
def check_credentials_exist(name):
'''
This function to check if a credentials exists
'''
return Credentials.credentials_exist(name)
def display_credentials():
'''
Function that returns all the saved credentials
'''
return Credentials.display_credentials()
def generate_password(password_length):
return Credentials.generate_password(password_length)
def main():
print("HELLO! WELCOME TO PASSWORD LOCKER!!")
while True:
print('''
ca - create account
log - login
esc - Escape''')
short_code = input().lower()
if short_code == "ca":
print("Create Acount")
print("First, Create a username:")
print("_" * 20)
username = input()
password= input("Choose a password of your choice: ")
print("_" * 20)
save_new_user(create_account(username, password))
print(f"""Your user details - Username : {username} Password : {password}""")
print("")
print(f"Hello {username} Choose the options below")
print("")
while True:
print("Use these short codes: cc - create new credentials, dc - display credentials, fc - find a credentials, wq - exit credentials list")
short_code = input().lower()
if short_code == 'cc':
print("New credentials")
print("-"*40)
print('')
print("Account name ...")
a_name = input()
print('')
print("User name ...")
u_name = input()
print('')
print("Email address ...")
email = input()
print('')
print("Account password")
acc_password = input()
print('')
save_user_credentials(create_credentials(a_name, u_name, email, acc_password))
print('')
print(f"New credential account : {a_name}, User name : {u_name}")
print('')
elif short_code == 'dc':
if display_credentials():
print("This is a list of all the credentials")
print('')
for Credentials in display_credentials():
print(f"Account : {Credentials.account_name}, User name : {Credentials.user_name} E-mail address : {Credentials.email} Password : {Credentials.password}")
print('')
else:
print('')
print("I'm sorry, you seem not to have saved any credentials")
print('')
elif short_code == 'fc':
print("Enter the Account you want")
search_name = input()
if check_credentials_exist(search_name):
search_name = find_credentials(search_name)
print('')
print(f"{search_name.user_name} {search_name.email}")
print('-'*20)
print('')
print(f"Account ... {search_name.account_name}")
print(f"Password ... {search_name.password}")
print('')
else:
print('')
print("Credentials do not exist")
print('')
elif short_code == "wq":
print('')
print("Goodbye ...")
break
else:
print("Please input a valid code")
elif short_code == "log":
print("Log in")
print("Enter User Name")
uname = input()
print("Enter password")
password = input()
print("_" * 20)
print(f"Hello {uname} Kindly choose the options below")
print("")
while True:
print("Use these short codes: cc - create new credentials, dc - display credentials, wq - exit credentials list")
short_code = input().lower()
if short_code == 'cc':
print("New credentials")
print("-"*10)
print('')
print("Account name ...")
a_name = input()
print('')
print("User name ...")
u_name = input()
print(f"Hello {uname} Kindly choose the options below")
print("")
while True:
print("Use these short codes: cc - create new credentials, dc - display credentials, wq - exit credentials list")
short_code = input().lower()
if short_code == 'cc':
print("New credentials")
print("-"*10)
print('')
print("Account name ...")
a_name = input()
print('')
print("User name ...")
u_name = input()
print('')
print("Email address ...")
email = input()
print('')
print("Account password")
acc_password = input()
save_user_credentials(create_credentials(a_name, u_name, email, acc_password))
print('')
print(f"New credential account : {a_name}, User name : {u_name}")
print('')
elif short_code == 'dc':
if display_credentials():
print("This is a list of all the credentials")
print('')
for Credentials in display_credentials():
print(f"Account : {Credentials.account_name}, User name : {Credentials.user_name} E-mail address : {Credentials.email} Password : {Credentials.password}")
print('')
else:
print('')
print("I'm sorry, you seem not to have saved any credentials")
print('')
elif short_code == "wq":
print('')
print("Goodbye ...")
break
else:
print("Please input a valid code")
elif short_code == "esc":
print('')
print("Exiting")
break
else:
print("The short code does not seem to exist,please try again")
if __name__ == '__main__':
main() |
c0fcc2f027faf50b1e329d5f5e4ef07f6228eff3 | mercado-joshua/Tkinter__Program_Password-Generator | /main.py | 3,720 | 3.546875 | 4 | #===========================
# Imports
#===========================
import tkinter as tk
from tkinter import ttk, colorchooser as cc, Menu, Spinbox as sb, scrolledtext as st, messagebox as mb, filedialog as fd
import string
import random
class Password:
"""Creates Password."""
def __init__(self, adjectives, nouns):
self._adjectives = adjectives
self._nouns = nouns
self._adjective = random.choice(self._adjectives)
self._noun = random.choice(self._nouns)
self._number = random.randrange(0, 100)
self._special_char = random.choice(string.punctuation)
# ------------------------------------------
def generate(self):
password = f'{self._adjective}{self._noun}{str(self._number)}{self._special_char}'
return password
#===========================
# Main App
#===========================
class App(tk.Tk):
"""Main Application."""
#------------------------------------------
# Initializer
#------------------------------------------
def __init__(self):
super().__init__()
self._init_config()
self._init_vars()
self._init_widgets()
#-------------------------------------------
# Window Settings
#-------------------------------------------
def _init_config(self):
self.resizable(False, False)
self.title('Password Generator Version 1.0')
self.iconbitmap('python.ico')
self.style = ttk.Style(self)
self.style.theme_use('clam')
#------------------------------------------
# Instance Variables
#------------------------------------------
def _init_vars(self):
self._adjectives = [
'sleepy', 'slow', 'smelly', 'wet', 'fat',
'red', 'orange', 'yellow', 'green', 'blue',
'purple', 'fluffy', 'white', 'proud', 'brave'
]
self._nouns = [
'apple', 'dinosaur', 'ball', 'toaster', 'goat',
'dragon', 'hammer', 'duck', 'panda', 'cobra'
]
#-------------------------------------------
# Widgets / Components
#-------------------------------------------
def _init_widgets(self):
frame = self._create_frame(self,
side=tk.TOP, fill=tk.BOTH, expand=True)
fieldset = self._create_fieldset(frame, 'Create Password',
side=tk.TOP, fill=tk.BOTH, expand=True, padx=10, pady=10)
self.password = tk.StringVar()
self._create_entry(fieldset, '', self.password, 'Helvetica 20 bold',
fill=tk.X, padx=10, pady=10, ipady=10)
self._create_button(fieldset, 'Generate', self._create_password,
pady=(0, 10))
# INSTANCE ---------------------------------
def _create_frame(self, parent, **kwargs):
frame = ttk.Frame(parent)
frame.pack(**kwargs)
return frame
def _create_fieldset(self, parent, title, **kwargs):
fieldset = ttk.LabelFrame(parent, text=title)
fieldset.pack(**kwargs)
return fieldset
def _create_button(self, parent, title, method, **kwargs):
button = ttk.Button(parent, text=title, command=lambda: method())
button.pack(**kwargs)
return button
def _create_entry(self, parent, title, var_, font, **kwargs):
entry = ttk.Entry(parent, text=title, textvariable=var_, font=font)
entry.pack(**kwargs)
return entry
def _create_password(self):
password = Password(self._adjectives, self._nouns)
self.password.set(password.generate())
#===========================
# Start GUI
#===========================
def main():
app = App()
app.mainloop()
if __name__ == '__main__':
main() |
8e2115c1623bfb4c296b2c4ec8a88ce21dd41e93 | nalin2002/Cryptography-Encryptions | /upload_file_to_googledrive.py | 1,232 | 3.5 | 4 |
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os
def Upload_File_GD(filename):
gauth=GoogleAuth()
gauth.LocalWebserverAuth()
drive=GoogleDrive(gauth)
local_file_path=" " # The path of the file in the system
for file in os.listdir(local_file_path):
if (file==' '): #Mention the file name to be uploaded
f= drive.CreateFile({'title':file})
f.SetContentString(os.path.join(local_file_path,file))
f.Upload()
f=None
str= filename+' Successfully Uploaded to Google Drive'
print(str)
# gauth = GoogleAuth()
# gauth.LocalWebserverAuth()
# drive = GoogleDrive(gauth)
#
# #used for creating a new file and then upload into my drive
# file1=drive.CreateFile({'title':'Hello.pdf'})
# file1.SetContentString('Success')
# file1.Upload()
#
# #for sending a local file to google drive
# #path=r"C:\Users\aprab\PycharmProjects\Python_Projects"
# path=r"D:\downloads"
# for x in os.listdir(path):
# if(x=='download.txt'):
# f=drive.CreateFile({'title':x})
# f.SetContentString(os.path.join(path,x))
# f.Upload()
# f=None
|
4da4b5e0a87f9220caa5fb470cac464fe17975cb | aniketpatil03/Hangman-Game | /main.py | 1,650 | 4.125 | 4 | import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
Death|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
# Variable that is going to keep a track of lives
lives = 6
# Generating random word from list
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print("psst, the chosen random word", chosen_word)
# Generating as many blanks as the word
display = []
for _ in range(len(chosen_word)):
display += "_"
print(display)
game_over = False
while not game_over: # Condition for while loop to keep going
# Taking input guess from user
guess = input("Enter your guess: ").lower()
# Replacing the blank value with guessed letter
for position in range(len(chosen_word)):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(display)
if guess not in chosen_word:
lives = lives - 1
if lives == 0:
print("The end, you lose")
game_over = True
if "_" not in display:
game_over = True # Condition which is required to end while loop or goes infinite
print("Game Over, you won")
# prints stages as per lives left from ASCII Art and art is arranged acc to it
print(stages[lives])
|
6f308a43412f0cdeca2b3764cf5c2b84be15f98e | apostonaut/6.00.1x | /problem_sets/probset2/pay_off_fully.py | 732 | 3.71875 | 4 | def pay_off_fully(balance, annualInterestRate):
"""
Calculates the minimum monthly payment required in order to pay off the balance of a credit card
within one year
:param balance: Outstanding balance on credit card
:type balance: float
:param annualInterestRate: annual interest rate as a decimal
:type annualInterestRate: float
:param monthlyPaymentRate: minimum monthly payment rate as a decimal
:type monthlyPaymentRate: float
:return: monthly payment required to pay off balance within one year, as a multiple of $10
:rtype: int
>>> pay_off_fully(3329, 0.2)
310
"""
#variable assignment
currentBalance = balance
monthlyInterestRate = annualInterestRate/12
|
20694cf0fb96be02c7eb330b5eb4e020d1e162ec | zouzhuo939/python | /ๅๆณกๆๅบ.py | 194 | 3.828125 | 4 | # array = [4,5,6,4,6,3,9]
# for i in range(len(array)):
# for j in range(i+1):
# if array[i]<array[j]:
# array[i],array[j]=array[j],array[j]
# print(array)
|
5ef84c9d17063edd0bc3f5351c291cf46b1cf2c0 | qinghao1/cmpe561 | /FST.py | 1,004 | 3.609375 | 4 | class State:
#Transition list is a list of tuples of (input, output, next_state)
def __init__(self, state_num):
self.state_num = state_num
#self.transition is a hashmap of input -> (output, next_state)
self.transition = {}
def add_transition(self, _input, _output, next_state):
self.transition[input] = (_output, next_state)
class FST:
def __init__(self):
self.states = {}
def add_arc(self, state1, state2, _input, _output):
if not state1 in self.states:
self.states[state1] = State(state1)
if not state2 in self.states:
self.states[state2] = State(state2)
self.states[state1].add_transition(_input, _output, state2)
def feed(self, string):
current_state = self.states[0] #Start state TODO
for char in string:
print(current_state.transition('c'))
output_tuple = current_state.transition[char]
print(output_tuple(0))
current_state = states[output_tuple[1]]
f = FST()
f.add_arc(0, 1, 'c', 'c')
f.add_arc(1, 2, 'a', 'u')
f.add_arc(2, 3, 't', 't')
f.feed("cat") |
4e292f2cd12f9adeb7df2ddc5bdd927b706beef1 | DStar1/word_guessing_game | /srcs/print_graphics.py | 3,497 | 3.59375 | 4 | import os
from termcolor import colored, cprint
class Graphics:
def __init__(self):
self.body_parts = [ colored("O", "magenta", attrs=["bold"]),
colored("|", "green", attrs=["bold"]),
colored("-", "red", attrs=["bold"]),
colored("-", "red", attrs=["bold"]),
colored("/", "blue", attrs=["bold"]),
colored("\\", "blue", attrs=["bold"])]
self.parts = [ colored("/", "cyan", attrs=["bold"]),
colored("___", "cyan", attrs=["bold"]),
colored("\\", "cyan", attrs=["bold"]),
colored("|", "cyan", attrs=["bold"])]
def draw_person(self, num_wrong_guesses):
for i in range(num_wrong_guesses):
print(self.body[i])
class Print(Graphics):
def __init__(self):
super().__init__()
self.help_message = "\nTo play enter the level 1-10, then a valid letter or '-' for the computer to make a guess for you.\
\nWhen prompted to play again, enter y/n to play again\nType -exit anywhere to exit\n"
self.bye_message = "\nEnding game, bye! Hope to see you again soon!\n"
self.letter_input = "Enter a letter or word to guess, enter '-' for computer to guess: "
self.play_again = "Would you like to play again? y/n: "
self.level_input = "\nEnter level int 1-10: "
self.secret = None
self.print_parts = None
# Clears the screen for UI
def clear_screen(self):
os.system('cls' if os.name == 'nt' else 'clear')
def update_print_variables(self, secret, level=None):
self.secret = secret
self.print_parts = [self.body_parts[idx] if idx < len(secret.wrong_guesses) else " " for idx in range(len(self.body_parts))]
if level:
self.level = level
def new_game_header(self):
cprint("NEW GAME OF HANGMAN\n", "blue")
def print_progress_info(self):
self.clear_screen()
self.new_game_header()
if not self.secret:
print(f" {self.parts[1]} ")
print(f" {self.parts[0]} {self.parts[2]}")
print(f" {self.parts[3]}")
print(f" {self.parts[3]}")
print(f" {self.parts[3]}")
print(f" {self.parts[1]}")
else:
print(f" {self.parts[1]} ")
print(f" {self.parts[0]} {self.parts[2]}", end="")
print(" Word length is:", len(self.secret.word))
print(f" {self.print_parts[0]} {self.parts[3]}", end='')
print(" Level is:", self.level)
print(f" {self.print_parts[2]}{self.print_parts[1]}{self.print_parts[3]} {self.parts[3]}", end='')
print(" Total guesses:", len(self.secret.guesses))
print(f" {self.print_parts[4]} {self.print_parts[5]} {self.parts[3]}", end='')
cprint(f" Wrong guesses: {', '.join(self.secret.wrong_guesses)}", "red")
print(f" {self.parts[3]}", end='')
print(" Remaining guesses:", 6 - len(self.secret.wrong_guesses))
print(f" {self.parts[1]}", end='')
print(" ", self.secret.word_to_show)
print()
def correct(self, correct, guesser):
self.print_progress_info()
if correct:
cprint(f"\'{guesser.input}\' is correct! :)", "green")
else:
cprint(f"\'{guesser.input}\' is not correct! :(", "red")
def invalid_input(self, start= False):
self.print_progress_info()
cprint("Invalid input, -help for usage", "red")
def win_loose(self, win):
self.print_progress_info()
if win:
cprint("\nYOU WIN!!!!!\n", "green")
else:
cprint("\nYou LOST after 6 wrong guesses :(\n", "red")
print(f"The word was {self.secret.word}\n")
def help(self):
self.print_progress_info()
print(self.help_message)
def exit(self):
self.print_progress_info()
print(self.bye_message)
|
149ad2636c553b6dd7717586d306a9a343260295 | FredericoTakayama/TicTacToe-Project | /projeto1.py | 5,668 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#tic tac toe - project1 study python
import os
SQUARE_SPACE_V=5
SQUARE_SPACE_H=9
TABLE_SPACE=29
def draw_x(pos_x,pos_y,table_matrix):
# matrix_x=[[0]*SQUARE_SPACE_H]*SQUARE_SPACE_V
# x=''
# for i in len(matrix_x):
# if i < (SQUARE_SPACE_H/2):
# x+='\\'
# elif i > (SQUARE_SPACE_H/2):
# x+='/'
# else:
# x+='X'
x=[]
x += [r' \ / ']
x += [r' \ / ']
x += [r' X ']
x += [r' / \ ']
x += [r' / \ ']
for i in range(0,SQUARE_SPACE_V):
for j in range(0,SQUARE_SPACE_H):
table_matrix[(pos_x*SQUARE_SPACE_V)+(1*pos_x)+i][(pos_y*SQUARE_SPACE_H)+(1*pos_y)+j]=x[i][j]
def draw_o(pos_x,pos_y,table_matrix):
o=[]
o += [r' --- ']
o += [r' / \ ']
o += [r'| |']
o += [r' \ / ']
o += [r' --- ']
for i in range(0,SQUARE_SPACE_V):
for j in range(0,SQUARE_SPACE_H):
table_matrix[(pos_x*SQUARE_SPACE_V)+(1*pos_x)+i][(pos_y*SQUARE_SPACE_H)+(1*pos_y)+j]=o[i][j]
def draw_vertical_lines(table_matrix):
for i in range(0,2):
for j in range(0,SQUARE_SPACE_V*3+2):
table_matrix[j][(SQUARE_SPACE_H)*(i+1)+(1*i)] = '|'
def draw_horizontal_lines(table_matrix):
for i in range(0,2):
for j in range(0,TABLE_SPACE):
table_matrix[((SQUARE_SPACE_V)*(i+1)+(1*i))][j] = '-'
def draw_number_positions(table_matrix):
count=1
for i in range(0,3): # row
for j in range(0,3): # column
table_matrix[SQUARE_SPACE_V*i+i][SQUARE_SPACE_H*j+j] = str(count)
count+=1
def draw_table(game_table):
# nao serve! ele copia como referencia e depois nao permite mexer um elemento sem mexer
# table_matrix = [['0']*TABLE_SPACE]*(SQUARE_SPACE_V*3+2)
table_matrix = [[' ' for j in range(0,TABLE_SPACE)] for i in range(0, SQUARE_SPACE_V*3+2)]
# print(len(table_matrix)) # rows
# print(len(table_matrix[0])) # columns
# matrix[5*3+2)][30]
draw_vertical_lines(table_matrix)
draw_horizontal_lines(table_matrix)
for i in range(0,3):
for j in range(0,3):
if game_table[i*3+j] == 1:
draw_x(i,j,table_matrix)
elif game_table[i*3+j] == 2:
draw_o(i,j,table_matrix)
# add number positions
draw_number_positions(table_matrix)
drew_table = ''
for row in table_matrix:
for column in row:
drew_table += column
drew_table += '\n'
return drew_table
def gretting_display():
print('_____________________________________')
print('___________ tic tac toe _____________')
print('_____________________________________')
print('')
game_table=[0]*9
# game_table=[[0]*3]*3
def check_position(position):
try:
return game_table[(int(position)-1)] == 0
except:
return False
def check_end_game(game_table):
'''check if there is a winner or its a tie'''
for i in range(0,3):
# check rows:
if(game_table[i] == game_table[i+1] == game_table[i+2] and game_table[i] != 0):
return game_table[i] # player wins
# check columns:
elif(game_table[i] == game_table[3+i] == game_table[6+i] and game_table[i] != 0):
return game_table[i] # player wins
if(game_table[0] == game_table[4] == game_table[8] and game_table[4] != 0) or\
(game_table[2] == game_table[4] == game_table[6] and game_table[4] != 0):
return game_table[4] # player wins
for i in range(0,9):
if(game_table[i] == 0):
return 0 # didn't finished
return -1 # tie
if __name__ == "__main__":
# pega o tamanho do terminal
# rows, columns = os.popen('stty size', 'r').read().split()
# print(rows,columns)
# FACTOR=0.7
# TABLE_SPACE = int(int(rows)*FACTOR*2.3)
# SQUARE_SPACE_V=int((int(rows)*FACTOR)/3.0)
# SQUARE_SPACE_H=int((int(rows)*FACTOR)/1.3)
player = 0
# print(game_table) # debug
gretting_display()
print(draw_table(game_table))
while(True):
text = 'Player %s, please choose a position:' % str(player+1)
position = input(text)
os.system('clear')
# printar o tabuleiro com lugares disponรญveis
try:
if int(position) > 0 and int(position) <= 9 and check_position(position):
# valid position
game_table[int(position)-1] = player+1
#exchange between players
player = (player+1)%2
# print(game_table) # debug
gretting_display()
print(draw_table(game_table))
else:
gretting_display()
print(draw_table(game_table))
print('Invalid position. Please try again.')
except:
gretting_display()
print(draw_table(game_table))
print('Invalid position. Please try again.')
# check if game finished:
res = check_end_game(game_table)
if res == 0:
continue
else:
if res == -1:
print('Game end: Tie!')
else:
print('Game end: Player %s wins!' % res)
if input('Play again? (y/n): ') == 'y':
# reset games
game_table=[0]*9
gretting_display()
print(draw_table(game_table))
player=0
else:
break
|
b696c672826c50de8f03c45055ca4553031c7f02 | JNFernandes/Python-Scripts | /Tic Tac Toe/player_choice.py | 375 | 4 | 4 | def player_choice(board):
position = int(input('Choose a position from 1 to 9 (ONLY INTEGERS): '))
while position not in range(1,10) or not check_space(board,position):
print('Either you selected an already filled position or the number is out of range! Try again')
position = int(input('Choose a position from 1 to 9: '))
return position |
b5ab8666d6d080ea2022313f0e484f60fb94a229 | JNFernandes/Python-Scripts | /Morse_Code/main.py | 340 | 3.953125 | 4 | from decode_encode import encoding,decoding
from logo import logo
print(logo)
message = input("Type message to encode: ").upper()
decoding_msg = input("Do you want to decode? Type 'y' for yes or 'n' for no: ").lower()
if decoding_msg == 'n':
encoding(message)
else:
decoding(message,encoding(message))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.