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 |
|---|---|---|---|---|---|---|
fda220a40796a2b8dd83b752bc0cf350830b95ea | ishaniMadhuwanthi/Semester-6 | /CO544-Machine Learning and Data Mining/Lab2-Numpy and Pandas/randomWalk.py | 303 | 3.8125 | 4 | #implement basic version of random walk.
import random
import matplotlib.pyplot as plt
xrange = range
position =0
walk = [position]
steps = 500
for i in xrange(steps):
step = 1 if random.randint(0,1) else -1
position += step
walk.append(position)
plt.plot(walk)
plt.show() |
d9b0a9947e1704fda375f2fddda419d3604cd7f9 | iamhemantgauhai/Digital-Hotel-Menu | /digital-menu-code.py | 6,664 | 3.984375 | 4 | print('''
Welcome to Gauhai's Hotel
गौहाई के होटल में आपका स्वागत है''')
a=True
while a==True:
user=int(input('''
1:Breakfast 2:Lunch 3:Snack 4:Dinner
Order Number Please: '''))
if user==1:
user1=int(input('''
1:Tea 2:Dal ka Paratha 3:Namkeen Seviyaan 4:Aloo Paratha 5:Bread Pakora
Order Number Please: '''))
if user1==1:
print('''
10rs''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==2:
print('''
20rs half plate, 40rs full plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==3:
print('''
30rs half plate, 5ors full plate''')
back=input('''Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==4:
print('''40rs half plate, 70rs full plate''')
back=input('''Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==5:
print('''20rs half plate, 40rs full plate''')
back=input('''Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
else:
print('''invalid input''')
back=input('''Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
back=input('''Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user==2:
print('''
1:Chole bhature 2:Kadhi Rice 3:Biryani 4:Rajma Rice 5:Dal Makhani''')
user1=int(input('''
Order Number Please: '''))
if user1==1:
print('''
50rs per plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==2:
print('''
half plate 40rs, full plate 70rs''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==3:
print('''
80rs per plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==4:
print('''
half plate 50rs, full plate 80rs''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==5:
print('''
60rs per plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
else:
print('''
invalid input''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user==3:
print('''
1:Dal Ki Kachori 2:Bonda 3:Dahi vada 4:Halva 5:Momo''')
user1=int(input('''
Order Number Please: '''))
if user1==1:
print('''
25rs per plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==2:
print('''
99rs medium size''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==3:
print('''
20rs per cup''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==4:
print('''
half plate 30rs, full plate 50rs''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==5:
print('''
30rs''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
else:
print('''
invalid input''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user==4:
print('''
1:Butter Chicken Roti 2:Chicken Korma Roti 3:Fish Roti 4: Tandoori Chops Roti 5:Egg Roti''')
user1=int(input('''
Order Number Please: '''))
if user1==1:
print('''
4 eggs 4 roti 100rs plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==2:
print('''
half plate chicken 4 roti 150rs plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==3:
print('''
half plate mutton 4 roti 200rs plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==4:
print('''
half plate chicken corma 4 roti 200rs plate''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
elif user1==5:
print('''
half plate 80rs full plate 150rs''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
else:
print('''
invalid input''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False
else:
print('''
invalid input''')
back=input('''
Any more order? (yes/no) : ''')
if back!='''yes''':
a=False |
2e23437ffd15f9ca5ec0383f172fba7fcb4f48af | AmirZimhony/University-Projects | /Assignment 4/create_db.py | 3,084 | 3.984375 | 4 | import sqlite3
import os
import sys
def main():
database_name = "schedule.db"
is_database_exists = os.path.isfile(database_name)
if not is_database_exists: # if database does not exists - we're going to create it.
connection_to_database = sqlite3.connect(database_name)
with connection_to_database: # this promises to close the connection when we're done with it
cursor = connection_to_database.cursor() # this enables us to go through the database.
cursor.execute("""CREATE TABLE courses
(id INTEGER PRIMARY KEY,
course_name TEXT NOT NULL,
student TEXT NOT NULL,
number_of_students INTEGER NOT NULL,
class_id INTEGER REFERENCES classrooms(id),
course_length INTEGER NOT NULL)""")
cursor.execute("""CREATE TABLE students
(grade TEXT PRIMARY KEY,
count INTEGER NOT NULL)""")
cursor.execute("""CREATE TABLE classrooms
(id INTEGER PRIMARY KEY,
location TEXT NOT NULL,
current_course_id INTEGER NOT NULL,
current_course_time_left INTEGER NOT NULL)""")
with open(sys.argv[1]) as f:
file = f.read()
input = file.split('\n')
for line in input:
list = line.split(', ')
if list[0] == "C": # course
cursor.execute("""INSERT INTO courses
(id, course_name, student, number_of_students, class_id, course_length)
VALUES(?,?,?,?,?,?)""", (list[1], list[2], list[3], list[4], list[5], list[6]))
elif list[0] == "S": # student
cursor.execute("""INSERT INTO students
(grade, count)
VALUES(?,?)""", (list[1], list[2]))
elif list[0] == "R": # classroom
cursor.execute("""INSERT INTO classrooms
(id, location, current_course_id, current_course_time_left)
VALUES(?,?,?,?)""", (list[1], list[2], 0, 0))
# we will now print the database:
print("courses")
cursor.execute("SELECT * FROM courses")
courses = cursor.fetchall()
for course in courses:
print(course)
print("classrooms")
cursor.execute("SELECT * FROM classrooms")
classrooms = cursor.fetchall()
for classroom in classrooms:
print(classroom)
print("students")
cursor.execute("SELECT * FROM students")
students = cursor.fetchall()
for student in students:
print(student)
connection_to_database.commit()
if __name__ == '__main__':
main()
|
97428ffc166ec44c733e2bda85f6421c922540d7 | boris-vasilev/kalah | /kalah/kalahboard.py | 6,177 | 4.15625 | 4 | class KalahBoard:
"""
A implementation of the game Kalah
Example layout for a 6 bin board:
<--- North
------------------------
12 11 10 9 8 7
13 6
0 1 2 3 4 5
------------------------
South --->
"""
bins = 0
seeds = 0
board = []
player = 0
def __init__(self, bins, seeds):
self.bins = bins
self.seeds = seeds
self.board = [seeds]*(bins*2+2)
self.board[bins] = 0
self.board[2*bins + 1] = 0
if not self._check_board_consistency(self.board):
raise ValueError('The board created is not consistent, some error must have happened')
self._player_houses = { 0: self.bins*(1),
1: self.bins*(2) + 1}
def copy(self):
board = KalahBoard(self.bins, self.seeds)
board.set_board(list(self.board))
board.set_current_player(self.player)
if not board._check_board_consistency(board.board):
raise ValueError('The board that was copied is not consistent, some error must have happened')
return board
def reset(self):
self.board = [self.seeds]*(self.bins*2+2)
self.board[self.bins] = 0
self.board[2*self.bins + 1] = 0
self.player = 0
def pretty_print(self):
print(self.get_board())
def move(self, b):
if b not in self.allowed_moves():
return False
old_board = list(self.board)
seeds_to_distribute = self.board[b]
self.board[b] = 0
other_player = 1 if self.current_player() == 0 else 0
current_bin = b
while seeds_to_distribute > 0:
current_bin = current_bin+1
if current_bin >= len(self.board):
current_bin -= len(self.board)
if current_bin == self._get_house(other_player):
continue
self.board[current_bin] += 1
seeds_to_distribute -= 1
# Seed in empty bin -> take seeds on the opponents side
if ( current_bin != self.get_house_id(self.current_player()) and
self.board[current_bin] == 1 and
current_bin >= self._get_first_bin(self.current_player()) and
current_bin < self._get_last_bin(self.current_player()) ):
opposite_bin = current_bin + self.bins+1
if opposite_bin >= len(self.board):
opposite_bin -= len(self.board)
if self.board[opposite_bin] > 0:
self.board[self._get_house(self.current_player())] += self.board[opposite_bin] + self.board[current_bin]
self.board[opposite_bin] = 0
self.board[current_bin] = 0
# All seeds empty, opponent takes all his seeds
if self._all_empty_bins(self.current_player()):
for b in range(self.bins):
self.board[self._get_house(other_player)] += self.board[other_player*self.bins + other_player + b]
self.board[other_player*self.bins + other_player + b] = 0
if current_bin != self.get_house_id(self.current_player()):
self.player = 1 if self.current_player() == 0 else 0
if not self._check_board_consistency(self.board):
raise ValueError('The board is not consistent, some error must have happened. Old Board: ' + str(old_board) + ", move = " + str(b) +", new Board: " + str(self.get_board()))
return True
def _get_first_bin(self, player):
return player*self.bins + player
def _get_last_bin(self, player):
return self._get_first_bin(player) + self.bins - 1
def _all_empty_bins(self, player):
player_board = self._get_player_board(player)
for seed in player_board[:-1]:
if seed > 0:
return False
return True
def _check_board_consistency(self, board):
expected_seeds = 2*self.seeds*self.bins
actual_seeds = 0
for s in board:
actual_seeds += s
return actual_seeds == expected_seeds
def _get_house(self, player):
return self._player_houses[player]
def get_board(self):
return list(self.board)
def current_player(self):
return self.player
def _get_player_board(self, player):
return self.get_board()[player*self.bins + player : player*self.bins + player + self.bins + 1]
def game_over(self):
player_board_one = self._get_player_board(0)
player_board_two = self._get_player_board(1)
player_one_empty = True
for seed in player_board_one[:-1]:
if seed > 0:
player_one_empty = False
player_two_empty = True
for seed in player_board_two[:-1]:
if seed > 0:
player_two_empty = False
return player_one_empty or player_two_empty
def score(self):
return [self.board[self.bins], self.board[2*self.bins + 1]]
def allowed_moves(self):
allowed_moves = []
player_board = self._get_player_board(self.current_player())
for b in range(len(player_board)-1):
if player_board[b] > 0:
allowed_moves.append(b + self.current_player()*self.bins + self.current_player())
return allowed_moves
def set_board(self, board):
if len(board) != self.bins*2 + 2:
raise ValueError('Passed board size does not match number of bins = ' + str(self.bins) + ' used to create the board')
if not self._check_board_consistency(board):
raise ValueError('The board is not consistent, cannot use it')
self.board = list(board)
def set_current_player(self, player):
if player >= 0 and player < 2:
self.player = player
else:
raise ValueError('Passed player number is not 0 or 1')
def current_player_score(self):
return self.score()[self.current_player()]
def get_house_id(self, player):
return self._get_house(player)
|
4aa122bf3782a63b4d7680c9f24bd5f70ef0a7c2 | MirjahonMirsaidov/interviewPrep | /merge_sort_linked_list.py | 1,754 | 4.09375 | 4 | import random
from linked_list import LinkedList
def merge_sort(linked_list):
if linked_list.size() == 1 or linked_list.head is None:
return linked_list
left_half, right_half = split(linked_list)
left = merge_sort(left_half)
right = merge_sort(right_half)
return merge(left, right)
def split(linked_list):
if linked_list is None or linked_list.head is None:
left, right = linked_list, None
else:
mid = linked_list.size()//2
mid_node = linked_list.node_at_index(mid - 1)
left = linked_list
right = LinkedList()
right.head = mid_node.next_node
mid_node.next_node = None
return left, right
def merge(left, right):
new_linked_list = LinkedList()
new_linked_list.add(0)
current = new_linked_list.head
left_head = left.head
right_head = right.head
while left_head or right_head:
if left_head is None:
current.next_node = right_head
right_head = right_head.next_node
elif right_head is None:
current.next_node = left_head
left_head = left_head.next_node
else:
left_data = left_head.data
right_data = right_head.data
if left_data < right_data:
current.next_node = left_head
left_head = left_head.next_node
else:
current.next_node = right_head
right_head = right_head.next_node
current = current.next_node
new_linked_list.head = new_linked_list.head.next_node
return new_linked_list
linked_list = LinkedList()
for i in range(11):
linked_list.add(random.randint(1, 100))
print(linked_list)
print(merge_sort(linked_list))
|
dc81b34ba79a23123018f6a0b2c026c47d49e4f4 | makarandmadhavi/intermediate-python-course | /dice_roller.py | 848 | 3.796875 | 4 | import random
def main():
dice_sum = 0
pname = [0,0]
pscore = [0,0]
pname[0] = input('Player 1 what is your name? ')
pname[1] = input('Player 2 what should we call you? ')
dicerolls = int(input('How many dice would you like to roll? '))
dice_size = int(input('How many sides are the dice? '))
for j in range(0,2):
for i in range(0,dicerolls):
roll= random.randint(1,dice_size)
pscore[j] += roll
if roll == 1:
print(f'{pname[j]} rolled a {roll}! Critical Fail')
elif roll == dice_size:
print(f'{pname[j]} rolled a {roll}! Critical Success!')
else:
print(f'{pname[j]} rolled a {roll}')
print(f'{pname[j]} have rolled a total of {dice_sum}')
if(pscore[0]>pscore[1]):
print(f'{pname[0]} Wins!')
else:
print(f'{pname[1]} Wins!')
if __name__== "__main__":
main() |
fdc8270e35fde55df9e9daf93194db8f51ee6b07 | JonathanQu/Testing2 | /2015-2016 Spring Term Homework/list-1.py | 2,048 | 4.03125 | 4 | import random
def merge (firstList, secondList):
OutputList = []
SmallerList = []
smallestListSize = 0
#determine what list is bigger and smaller
if len(firstList) > len(secondList):
OutputList=firstList
SmallerList=secondList
smallestListSize = len(secondList)
elif len(secondList) >= len(firstList):
OutputList=secondList
smallestListSize = len(firstList)
SmallerList=firstList
#determine the first comparison outside of the while loop to prevent an out of index range error
if OutputList[0] >= SmallerList[0]:
OutputList.insert(0,SmallerList[0])
else:
OutputList.insert(1,SmallerList[0])
firstCounter = 1
secondCounter = 0
EndThis = 0
#the while loop excluding comparing the last number of the longer string because there is no number that exists after the last
while firstCounter < (len(OutputList) - 1):
while secondCounter < len(SmallerList) and EndThis == 0:
if SmallerList[secondCounter] < OutputList[firstCounter] and SmallerList[secondCounter] >= OutputList[firstCounter - 1]:
OutputList.insert(firstCounter,SmallerList[secondCounter])
EndThis = 1
else:
secondCounter += 1
secondCounter = 0
EndThis = 0
firstCounter += 2
if OutputList[(len(OutputList)-1)] >= SmallerList[smallestListSize-1]:
OutputList.insert((len(OutputList)-1),SmallerList[smallestListSize-1])
else:
OutputList.append(SmallerList[smallestListSize-1])
return OutputList
g1 = [0, 2, 4, 6, 8]
g2 = [1, 3, 5, 7]
print merge(g1, g2)
def randomList(n):
listCon = []
counter = 0
while counter < n:
listCon.append(random.randrange(-10,11))
counter += 1
return listCon
print randomList(5)
def doublify(aList):
counter = 0
while counter < len(aList):
aList[counter] = aList[counter] * 2
counter += 1
return aList
print doublify( [3, 5, -20, 45] )
def barGraph(aList):
counter = 0
while counter < len(aList):
print str(counter) + ":" + ("=" * aList[counter])
counter += 1
x = [3,4,1,0,5]
barGraph(x)
|
b08dd793de1d6f63d90d5c42b740fc8f57ded57e | rafiud1305/Rafi-ud-Darojat_I0320079_Aditya-Mahendra_Tugas-3 | /I0320079_Exercise 3.6.py | 174 | 4.09375 | 4 | dict = {'Name':'Zara','Age': 7,'Class':'First'}
dict['Age'] = 8;
dict['School'] = "DPS School"
print("dict['Age']:", dict['Age'])
print("dict['School']:", dict['School']) |
27ebcf2e51a5a9184d718ad14097aba5fb714d94 | tanawitpat/python-playground | /zhiwehu_programming_exercise/exercise/Q006.py | 1,421 | 4.28125 | 4 | import unittest
'''
Question 6
Level 2
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
'''
def logic(input_string):
c = 50
h = 30
input_list = input_string.split(",")
output_list = []
output_string = ""
for d in input_list:
output_list.append(str(int((2*c*int(d)/h)**0.5)))
for i in range(len(output_list)):
if i == 0:
output_string = output_string+output_list[i]
else:
output_string = output_string+","+output_list[i]
return output_string
class TestLogic(unittest.TestCase):
def test_logic(self):
self.assertEqual(
logic("100,150,180"),
"18,22,24",
"Should be `18,22,24`")
if __name__ == '__main__':
unittest.main() |
ca33cf3f9132ec9aa4d3e4b77a995fabdd67971c | ivafer00/MiniCrypto | /classic/Vigenere.py | 1,300 | 3.578125 | 4 | class Vigenere():
def __init__(self):
self.plaintext = ""
self.ciphertext = ""
self.key = []
def set_plaintext(self, message):
self.plaintext = message
def set_ciphertext(self, cipher):
self.ciphertext = cipher
def set_key(self, k):
self.key = []
for i in range(len(k)):
self.key.append(int(k[i]))
def cipher(self):
self.ciphertext = ""
for i in range(len(self.plaintext)):
if self.plaintext[i].isalpha():
code_ascii = 97
if self.plaintext[i].isupper():
code_ascii = 65
self.ciphertext += chr(((ord(self.plaintext[i]) % code_ascii + self.key[i % len(self.key)]) % 26) + code_ascii)
else:
self.ciphertext += self.plaintext[i]
def decipher(self):
self.plaintext = ""
for i in range(len(self.ciphertext)):
if self.ciphertext[i].isalpha():
code_ascii = 97
if self.ciphertext[i].isupper():
code_ascii = 65
self.plaintext += chr(((ord(self.ciphertext[i]) % code_ascii - self.key[i % len(self.key)]) % 26) + code_ascii)
else:
self.plaintext += self.ciphertext[i] |
9fa5ecf1948273aa4e80924f56b63343a63e37cb | raquelmachado4993/omundodanarrativagit | /python/funcoes_busca_intermediario.py | 2,370 | 3.828125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
import funcoes as fun
def verifica_escola(texto):
result=""
contador=0
substring1 = "escola"
if substring1 in texto:
result+=substring1+" "
contador+=1
return result,contador
def encontra_esportes(texto):
result=""
contador=0
pesquisar_esportes = ['futebol', 'volei', 'tênis de mesa', 'natação', 'futsal', 'capoeira', 'skate', 'skatismo', 'surf', 'vôlei de praia', 'badminton', 'frescobol', 'judô', 'atletismo', 'críquete', 'basquete', 'hockey na grama', 'hockey no gelo', 'beisebol', 'fórmula 1', 'Rugby', 'futebol americano', 'golfe', 'handebol', 'queimado', 'hipismo', 'ginástica olímpica', 'Triatlo', 'maratona', 'canoagem', 'peteca', 'jiu-jitsu', 'esgrima', 'vale-tudo', 'karatê', 'corrida', 'ciclismo', 'boxe', 'MMA', 'Taekwondo']
# print(len(pesquisar_esportes))
for i in pesquisar_esportes:
if i in texto:
result+=i+" "
contador+=1
return result,contador
def busca_batalha_luta_guerra(texto):
result=""
contador=0
palavras_crivo_intermediario = ['lut','guerr','batalha']
# palavras_crivo_intermediario = ''.join(palavras_crivo_intermediario_inicio)
# palavras_crivo_intermediario = palavras_crivo_intermediario_inicio.split()
# palavras_crivo_intermediario_encontradas = []
for i in palavras_crivo_intermediario:
if i in texto:
result+=i+" "
contador+=1
return result,contador
def busca_amizade(texto):
result=""
contador=0
palavras_crivo_amizade = ['amig', 'amiz', 'migux','amigos','amigas']
for i in palavras_crivo_amizade:
if i in texto:
result+=i+" "
contador+=1
return result,contador
def busca_jogo(texto):
result=""
contador=0
substring = "jog"
if substring in texto:
result+=substring+" "
contador+=1
return result,contador
def proc_inter(texto):
result=""
contador=0
r,c =encontra_esportes(texto)
result+=r
contador+=c
r,c =busca_batalha_luta_guerra(texto)
result+=r
contador+=c
r,c =busca_amizade(texto)
result+=r
contador+=c
r,c =busca_jogo(texto)
result+=r
contador+=c
return result,contador |
3e63333e7ddfc297059762314bc608723cb3b246 | raquelmachado4993/omundodanarrativagit | /python/RASCUNHOS/teste_regex_findall.py | 162 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import re
sentence = "Eu amava amar você"
word = "ama"
for match in re.finditer(word, sentence):
print (match.start(), match.end())
|
4cbc0f8a14c5b9ec8ae6d9c4dc5b4741ad43700c | raquelmachado4993/omundodanarrativagit | /python/dao/mysql_connect.py | 1,636 | 3.609375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import mysql
from mysql.connector import Error
def connect():
""" Connect to MySQL database """
try:
conn = mysql.connector.connect(host="", # your host, usually localhost
user="", # your username
passwd="", # your password
db="") # name of the data base
# conn = mysql.connector.connect(host="raqueleluis.ddns.net", # your host, usually localhost
# user="jogonarrativa", # your username
# passwd="k9kbg1tmMAeK", # your password
# db="omundo88_jogonarrativa") # name of the data base
#print("estou aqui vivo")
return conn
except Error as e:
print(e)
def buscar(sql):
cnx = connect()
cur = cnx.cursor()
cur.execute(sql)
myresult = cur.fetchall()
cnx.close()
return myresult
## def busca2(sql):
## cnx = connect()
## cur = cnx.cursor(dictionary=True)
## return cur.execute(sql)
## cnx.close()
## return cur
def alterar(sql):
# cnx = connect()
# cur = cnx.cursor()
# cur.execute(sql)
# cur.execute(sql)
# myresult = cnx.commit()
# return myresult
return("ainda nao implementado")
def inserir(sql):
try:
cnx = connect()
cur = cnx.cursor()
cur.execute(sql)
cnx.commit()
cnx.close()
except Error as error:
print(error)
print(sql)
finally:
cur.close()
cnx.close()
def escapa(sql):
return mysql.escape_string(sql) |
1503bb3b33f20f77499db340de8b33523043ea56 | digitalMirko/PythonReview | /python_review08_functions.py | 1,175 | 3.78125 | 4 | # Python Programming Review
# file name: python_review08_functions.py
# JetBrains PyCharm 4.5.4 under Python 3.5.0
import random # random number generator
import sys # sys module
import os # operating system
# functions allow us to both re-use and write more readable code
# define a function that adds numbers
# define a function, function name (parameters it receives)
def addNumber(fNum, lNum):
sumNum = fNum + lNum
return sumNum # return something to the caller of this function
# make sure you define your functions before you call them
# calling function below
print(addNumber(1, 4)) # outputs: 5
# also assign it to a String
string = addNumber(1, 4) # works the same way when called
# note even though sumNum is created inside the variable up above
# it is not available outside it, it doesnt exist outside
# unresolved reference error thrown, its not defined, out of scope
# print(sumNum)
# get input from the user
print('What is your name') # outputs: What is your name
# get input from user using sys.stdin.readline()
name = sys.stdin.readline()
# prints out Hello with persons name entered
print('Hello ', name) # outputs Hello Mirko
|
4a30e4eb36ebcc74d1f0bc0f7a6249ed5b8a0951 | digitalMirko/PythonReview | /python_review14_inheritance.py | 3,567 | 4.21875 | 4 | # Python Programming Review
# file name: python_review14_inheritance.py
# JetBrains PyCharm 4.5.4 under Python 3.5.0
import random # random number generator
import sys # sys module
import os # operating system
class Animal:
__name = ""
__height = 0
__weight = 0
__sound = 0
def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound
def set_name(self, name):
self.__name = name
def set_height(self, height):
self.height = height
def set_weight(self, weight):
self.__weight = weight
def set_sound(self, sound):
self.__sound = sound
def get_name(self):
return self.__name
def get_height(self):
return self.__height
def get_weight(self):
return self.__weight
def get_sound(self):
return self.__sound
def get_type(self):
print("Animal") #outputs: Animal
def toString(self):
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)
cat = Animal('Whiskers', 33, 10, 'Meow')
print(cat.toString())
# outputs: Whiskers is 33 cm tall and 10 kilograms and says Meow
# Inheritance: all it means is when you inherit from another class that your
# automatically going to get all the variables, methods or functions that
# are created in the class you are inheriting from.
# Class called Dog, inherit from the Animal class
class Dog(Animal):
# automatically get every variable and function already in the Animal class
# give it a name like owner
__owner = "" # every dog but not Animal gonna have an owner
# then over right the constructor for the Animal class
# i want to do something more specific here since its a dog
# still require them to enter a: name, height, weight, sound
# but now i also require them to enter an owner name
def __init__(self, name, height, weight, sound, owner):
# set the owner, make it equal to the owner value they passed in
self.__owner = owner
# if we want the name, height, weight, sound to be handled by
# the Animal super classes constructor on top
# super, its a super class, then Dog, self, init then pass in
# the name, height, weight, sound
super(Dog, self).__init__(name, height, weight, sound)
# Allow them to set the owner, owner passed here
def set_owner(self, owner):
# self owner, owner value passed in
self.__owner = owner
# Do the same thing to get the owner
def get_owner(self, owner):
return self.__owner
# define get type
def get_type(self):
# print we are using a Dog object
print("Dog")
# override functions on our super class, change the toSting, add the __owner
def toString(self):
return "{} is {} cm tall and {} kilograms and says {} His owner is {}".format(self.__name,
self.__height,
self.__weight,
self.__sound,
self.__owner) |
3314f67d5a12e55b836587554f792d7f5653cf1b | easternHong/pythonStudy | /Lesson3/Func.py | 332 | 3.953125 | 4 | # 偏函数的使用
def func():
print(int('2222'))
print(int('2222', base=8))
print(int2('533', 8))
print(int_custom('533'))
def int2(x, base=2):
return int(x, base)
def int_custom(x):
kw = {'base': 8}
return int(x, **kw)
if __name__ == '__main__':
print('''偏函数的使用''')
func()
|
cb3fb384955f9767077db0d80a5b1374c82c1674 | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1001/Input05.py | 304 | 4.1875 | 4 | # 문자열은 인덱스 번호가 부여됨
strTemp = input("아무 문자열이나 입력하세요: ")
print("strTemp : ", strTemp)
print("strTemp : {}".format(strTemp))
print("strTemp[0] : {}".format(strTemp[0]))
print("strTemp[1] : {}".format(strTemp[1]))
print("strTemp[2] : {}".format(strTemp[2])) |
dd7a778882684ed3a30f3ae0df1465977d46d51d | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1015/FUNCTION11.py | 219 | 3.640625 | 4 | def func3(num):
# 매개변수로 선언된 것도 지역변수
print(f"func3() num: {num}")
def func4(n1, n2, n3):
print(f"func4() n1, n2, n3 -> {n1}, {n2}, {n3}")
num = 0
func3(num)
print("num : ", num) |
3ab7e81a15e1efa8bd293f6ba35cc5bd8e6a7e23 | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1011/WINDOW06.py | 241 | 3.671875 | 4 | from tkinter import *
from tkinter import messagebox
def clickLeft(event):
messagebox.showinfo("마우스", "마우스 왼쪽 버튼 클릭됨.")
window = Tk()
button = Button()
window.bind("<Button-1>", clickLeft)
window.mainloop() |
53fa58a6f7b911378a298d8e96e81dec0423f927 | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1011/LIST06.py | 384 | 3.78125 | 4 | heros = ["스파이더맨", "헐크", "캡틴마블", "아이언맨", "앤트맨", "토르", "배트맨"]
srhName = input("찾을 영웅 이름: ")
for i in heros:
if i == srhName:
print("찾음")
break
else:
print("없음")
delName = input("삭제할 이름: ")
for i in heros:
if heros.index(delName):
heros.remove(delName)
print(heros) |
d333885fa35681071ef0c8c01efd9163b7244fdf | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1008/STRING05.py | 230 | 3.703125 | 4 | # 문자열 반대로 출력
inStr = ""
outStr = ""
count = 0
inStr = input("문자열을 입력하시오: ")
count = len(inStr)
for i in range(0, count):
outStr += inStr[count - (i + 1)]
print(outStr)
# print(inStr[::-1]) |
a9c300955bbfb4d7187b8018d0319a4912c76454 | BurnFaithful/KW | /Programming_Practice/Python/MachineLearning/Keras/keras13_lstm5_ensemble.py | 3,182 | 3.5625 | 4 | # LSTM(Long Short Term Memory) : 연속적인 data. 시(Time)계열.
import numpy as np
from keras.models import Sequential, Model
from keras.layers import Dense, LSTM, Input
#1. 데이터
x = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7],
[6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12],
[20, 30, 40], [30, 40, 50], [40, 50, 60]])
y = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 50, 60, 70])
x1_train = x[:10]
x2_train = x[10:]
y1_train = y[:10]
y2_train = y[10:]
# print(x)
# print("x.shape :", x.shape)
# print("y.shape :", y.shape)
# x = x.reshape((x.shape[0], x.shape[1], 1))
# print(x)
# print("x.shape :", x.shape)
print(x1_train)
print(x2_train)
print("x1_train.shape :", x1_train.shape)
print("x2_train.shape :", x2_train.shape)
x1_train = x1_train.reshape((x1_train.shape[0], x1_train.shape[1], 1))
x2_train = x2_train.reshape((x2_train.shape[0], x2_train.shape[1], 1))
print("x1_train.shape :", x1_train.shape)
print("x2_train.shape :", x2_train.shape)
# y1_train = y1_train.reshape((y1_train.shape[0], 1))
# y2_train = y2_train.reshape((y2_train.shape[0], 1))
print("y1_train.shape :", y1_train.shape)
print("y2_train.shape :", y2_train.shape)
#2. 모델 구성
# model = Sequential()
# model.add(LSTM(100, activation='relu', input_shape=(3, 1))) # (column, split)
# model.add(Dense(50))
# model.add(Dense(60))
# model.add(Dense(70))
# model.add(Dense(40))
# model.add(Dense(60))
# model.add(Dense(90))
# model.add(Dense(30))
# model.add(Dense(60))
# model.add(Dense(1))
input1 = Input(shape=(3, 1))
input1_lstm = LSTM(40)(input1)
hidden1 = Dense(50, activation='relu')(input1_lstm)
hidden1 = Dense(60)(hidden1)
hidden1 = Dense(70)(hidden1)
hidden1 = Dense(40)(hidden1)
middle1 = Dense(60)(hidden1)
input2 = Input(shape=(3, 1))
input2_lstm = LSTM(50)(input2)
hidden2 = Dense(90, activation='relu')(input2_lstm)
hidden2 = Dense(40)(hidden2)
hidden2 = Dense(60)(hidden2)
hidden2 = Dense(70)(hidden2)
middle2 = Dense(60)(hidden2)
# model.summary()
# concatenate를 할 때 input, target arrays의 크기를 맞춰야 한다.
from keras.layers.merge import concatenate
merge = concatenate([middle1, middle2])
output1 = Dense(60)(merge)
output1 = Dense(1)(output1)
output2 = Dense(80)(merge)
output2 = Dense(1)(output2)
model = Model(inputs=[input1, input2], outputs=[output1, output2])
#3. 실행
model.compile(optimizer='adam', loss='mse', metrics=['mse'])
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='loss', patience=100, mode='auto')
# x1_train = np.swapaxes(x1_train, 1, 0)
# x2_train = np.swapaxes(x2_train, 1, 0)
# model.fit(x, y, epochs=200, batch_size=1, verbose=2) # verbose = 1 default
# model.fit(x, y, epochs=10000, batch_size=1, verbose=2, callbacks=[early_stopping])
model.fit([x1_train, x1_train], [y1_train, y1_train], epochs=10000, batch_size=1,
verbose=2,
callbacks=[early_stopping])
# verbose = 0 : 결과만 보여줌
# verbose = 1 : 훈련과정 상세히
# verbose = 2 : 훈련과정 간략히
# x_input = np.array([25, 35, 45])
# x_input = x_input.reshape((1, 3, 1))
# yhat = model.predict(x_input)
# print(yhat) |
9a3a6a0f2b2ef12a06cac9ac23f397afba331605 | BurnFaithful/KW | /Programming_Practice/Python/Base/Bigdata_day1011/LIST03.py | 308 | 3.9375 | 4 | # 문자열 길이를 이용한 출력
letter = ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
print(letter)
length = len(letter)
for i in range(length):
print(letter[i], end=' ')
print(' '.join(letter))
shopping = []
shopping.append("두부")
shopping.append("양배추") |
5144e5d9fb45e8de24f2801c7dfeb3f0cb19cb16 | Anuragjain20/Data-structure-and-algo | /Queue/stackusingqueue.py | 922 | 3.9375 | 4 | from queue import Queue
class Stack:
def __init__(self):
self.q1 = Queue()
self.q2 = Queue()
self.curr_size = 0
def push(self, x):
self.curr_size += 1
self.q2.put(x)
while (not self.q1.empty()):
self.q2.put(self.q1.queue[0])
self.q1.get()
self.q = self.q1
self.q1 = self.q2
self.q2 = self.q
def pop(self):
if (self.q1.empty()):
return
data = self.q1.get()
self.curr_size -= 1
return data
def top(self):
if (self.q1.empty()):
return -1
return self.q1.queue[0]
def size(self):
return self.curr_size
def isEmpty(self):
return self.curr_size == 0
s = Stack()
s.push(12)
s.push(13)
s.push(14)
while s.isEmpty() is False:
print(s.pop())
|
b5a083008411fb0bef68ebabaee024e39eb3ea28 | Anuragjain20/Data-structure-and-algo | /Linked List/singlylinkedlist.py | 4,071 | 4.09375 | 4 | """
class Node:
def __init__(self,value =None):
self.value = value
self.next = Node
class SLinkedList:
def __init__(self):
self.head = None
self.tail = None
singlyLinkedList = SLinkedList()
node1 = Node(1)
node2 = Node(2)
singlyLinkedList.head = node1
singlyLinkedList.head.next = node2
singlyLinkedList.tail = node2
"""
class Node:
def __init__(self,value =None):
self.value = value
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
# insertion in sll
def insertSLL(self,value,location):
newNode = Node(value)
if self.head is None:
self.head = newNode
self.tail = newNode
else:
if location == 0:
newNode.next = self.head
self.head = newNode
elif location == 1:
newNode.next = None
self.tail.next = newNode
self.tail = newNode
else:
try:
tempNode = self.head
index =0
while index < location-1:
tempNode = tempNode.next
index +=1
nextNode = tempNode.next
tempNode.next = newNode
newNode.next = nextNode
except :
print("no such loaction "+ str(location))
#traversal
def traverseSLL(self):
if self.head is None:
print("The Singly Linked List does not exist")
else:
node = self.head
while node is not None:
print(node.value)
node = node.next
#search
def searchSLL(self,nodeValue):
if self.head is None:
return "the list does not exist"
else:
index = 0
node = self.head
while node is not None:
if node.value == nodeValue:
return "value is : " + str(node.value) + " it is present at : "+ str(index)
node= node.next
index+=1
return "The value does not exist in this list"
#delete node
def deleteNode(self,location):
if self.head is None:
print("the SLL does not exists")
else:
if location == 0:
if self.head == self.tail:
self.head = None
self.tail = None
else:
self.head = self.head.next
elif location == 1:
if self.head == self.tail:
self.head = None
self.tail = None
else:
n = self.head
while n is not None:
if n.next == self.tail:
break
n = n.next
n.next = None
self.tail = n
else:
try:
index = 0
n = self.head
while index<location-1:
n = n.next
index +=1
n1 = n.next
n.next = n1.next
except:
print("no such location : " + str(location))
#delete entire list
def deleteEntireSLL(self):
if self.head is None:
print("the sll does not exits")
else:
self.head = None
self.tail = None
s = SLinkedList()
s.insertSLL(1,1)
s.insertSLL(2,1)
s.insertSLL(3,1)
s.insertSLL(4,1)
print([node.value for node in s])
s.deleteNode(4)
s.traverseSLL()
s.searchSLL(3)
s.deleteEntireSLL()
print([node.value for node in s]) |
7211d015be01620d979bd50c16fe4dfc85b97ec1 | Anuragjain20/Data-structure-and-algo | /Queue/queueUsingStack.py | 970 | 3.8125 | 4 | class QueueStack:
def __init__(self):
self.__s1 = []
self.__s2 = []
def enqueue(self,data):
if self.__s1 == []:
self.__s1.append(data)
return
while self.__s1 != []:
r= self.__s1.pop()
self.__s2.append(r)
self.__s1.append(data)
while self.__s2 != []:
r= self.__s2.pop()
self.__s1.append(r)
def dequeue(self):
if self.__s1 == []:
print("empty queue")
return
return self.__s1.pop()
def front(self):
if self.__s1 == []:
print("empty queue")
return
return self.__s1[-1]
def size(self):
return len(self.__s1)
def isEmpty(self):
return len(self.__s1) == 0
st = QueueStack()
st.enqueue(10)
st.enqueue(11)
st.enqueue(12)
st.enqueue(13)
while st.isEmpty() == False:
print(st.dequeue()) |
edeec7a377a1133c62ab763a5f214706d29c0493 | Anuragjain20/Data-structure-and-algo | /Queue/reverseKqueue.py | 508 | 3.796875 | 4 | from queue import Queue
def reverseKqueue(q,k):
if q.empty() == True or k > q.qsize():
return
if k<= 0:
return
stack = []
for i in range(k):
stack.append(q.queue[0])
q.get()
while len(stack) != 0:
q.put(stack[-1])
stack.pop()
for i in range(q.qsize()- k ):
q.put(q.queue[0])
q.get()
q = Queue()
for i in range(10,40,3):
q.put(i)
reverseKqueue(q,3)
for i in range(10):
print(q.get()) |
985645ba73baf9e3e4e0e0891124f47843c4214b | Aakash-Rajbhar/Calculator | /Calculator.py | 4,677 | 4.125 | 4 | import tkinter
from tkinter import *
root = Tk()
root.geometry('303x467')
root.title("Aakash's Calculator")
e = Entry(root, width=25,font=("Callibary",15) ,bg="light grey" ,borderwidth=10)
e.grid(row=0, column=0, columnspan=10)
def btn_click(number):
c = e.get()
e.delete(0,END)
e.insert(0,str(c)+str(number))
def clear():
return e.delete(0, END)
def add():
try:
first_number = e.get()
global f_num
global math
math = "addition"
f_num = float(first_number)
e.delete(0,END)
except:
e.insert(0,"INVALID!!!")
def subtract():
try:
first_number1 = e.get()
global f_num
global math
math = "subtraction"
f_num = float(first_number1)
e.delete(0,END)
except:
e.insert(0,"INVALID!!!")
def multiply():
try:
first_number1 = e.get()
global f_num
global math
math = "multiplication"
f_num = float(first_number1)
e.delete(0,END)
except:
e.insert(0,"INVALID!!!")
def divide():
try:
first_number1 = e.get()
global f_num
global math
math = "division"
f_num = float(first_number1)
e.delete(0,END)
except:
e.insert(0,"INVALID!!!")
def sqr_root():
try:
first_number1 = e.get()
global f_num
global math
math = "sqr root"
f_num = float(first_number1)
e.delete(0,END)
e.insert(0,f_num**(1/2))
except:
e.insert(0,"INVALID!!!")
def equal():
try:
second_number = e.get()
e.delete(0,END)
if math=="addition" :
e.insert(0,f_num + float(second_number))
elif math=="subtraction" :
e.insert(0,f_num - float(second_number))
elif math=="multiplication" :
e.insert(0,f_num * float(second_number))
elif math=="division":
e.insert(0,f_num / float(second_number))
except:
e.insert(0,"NOT DEFINED")
btn1 = Button(root, text="1",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(1))
btn2 = Button(root, text="2",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(2))
btn3 = Button(root, text="3",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(3))
btn4 = Button(root, text="4",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(4))
btn5 = Button(root, text="5",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(5))
btn6 = Button(root, text="6",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(6))
btn7 = Button(root, text="7",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(7))
btn8 = Button(root, text="8",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(8))
btn9 = Button(root, text="9",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(9))
btn0 = Button(root, text="0",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click(0))
btndot = Button(root, text=".",font=("callibary",11, "bold"), padx=40, pady=20, command= lambda:btn_click("."))
btn_clear = Button(root,text="clear", font=("callibary",11, "bold"),padx=26, pady=20, command= clear)
btn_add = Button(root, text="+",font=("callibary",11, "bold"), padx=40, pady=20,command=add )
btn_subtract = Button(root, text="-",font=("callibary",11, "bold"), padx=42, pady=20, command=subtract)
btn_multiply = Button(root, text="*",font=("callibary",11, "bold"), padx=40, pady=20, command=multiply )
btn_divide = Button(root, text="/",font=("callibary",11, "bold"), padx=42, pady=20, command=divide )
btn_sqr_root = Button(root, text="sqr root",font=("callibary",11, "bold"), padx=16, pady=20, command=sqr_root )
btn_equal = Button(root, text="=",font=("times new roman",12,"bold") ,padx=39, pady=20, command=equal)
btn1.grid(row=3, column=0)
btn2.grid(row=3, column=1)
btn3.grid(row=3, column=2)
btn4.grid(row=2, column=0)
btn5.grid(row=2, column=1)
btn6.grid(row=2, column=2)
btn7.grid(row=1,column=0)
btn8.grid(row=1,column=1)
btn9.grid(row=1,column=2)
btn0.grid(row=4, column=0)
btn_clear.grid(row=4, column=1, columnspan=1)
btn_add.grid(row=4, column=2)
btn_subtract.grid(row=5, column=0)
btn_multiply.grid(row=5,column=1)
btn_divide.grid(row=5, column=2)
btn_equal.grid(row=6, column=1,columnspan=1)
btn_sqr_root.grid(row=6,column=0)
btndot.grid(row=6, column=2, columnspan=2)
root.mainloop()
|
a5d8b66c92ada51e44ca70d2596a30f0da6f7482 | jmlippincott/practice_python | /src/16_password_generator.py | 639 | 4.1875 | 4 | # Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main method.
import random, string
chars = string.ascii_letters + string.digits + string.punctuation
def generate(length):
psswd = "".join(random.choice(chars) for i in range(length))
return psswd
while True:
num = input("How long would you like your new password? ")
num = int(num)
print(generate(num)) |
a1bfb994c2cdf4ec03bb660500a757538d67be1f | jmlippincott/practice_python | /src/12_list_ends.py | 397 | 4.09375 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
from os import system
import random
lst_length = random.randint(1,100)
lst = [random.randint(0,100) for i in range(lst_length)]
print(lst)
lst.sort()
lst = [lst[0], lst[-1]]
print(lst) |
58517d054f5f5430f675947ee6f102ca51c42d21 | jmlippincott/practice_python | /src/18_cows_and_bulls.py | 958 | 3.859375 | 4 | import random, string
from os import system
chars = string.digits
def generate(digits):
return list("".join(random.choice(chars) for i in range(digits)))
while True:
num_digits_solution = int(input("Enter puzzle size (0-9): "))
solution = generate(num_digits_solution)
# print(f"Solution: {solution}") #uncomment to debug
guesses = 0
correct = False
while correct == False:
guesses += 1
bulls = 0
cows = 0
guess = list(input(f"Please enter a {num_digits_solution} digit guess: "))
for i in range(num_digits_solution):
if guess[i] == solution[i]:
bulls += 1
else:
cows += 1
if bulls == num_digits_solution:
correct = True
else:
print(f"Bulls: {bulls}\nCows: {cows}\nGuesses: {guesses}")
input(f"Your solution {guess} is correct! Please press <Enter> to start over.")
system("clear") |
9d5dd5789a533ed84d8f11c82331a87b32095d2d | JagadishThalwar/Python3 | /if-else.py | 200 | 3.9375 | 4 | i=20
if(i<15):
print("i is smaller than 15")
print(" i am in if block")
else:
print("i is greater than 15")
print("i am in else block")
print(" i am not in if block and not in else block") |
d1e7712d91d57eb33e693963bd33a3cccda59151 | Oxidiz3/PythonOneOffs | /FinishedProjects/interpreter.py | 3,475 | 4.0625 | 4 | """
Command Comprehender
summary: be able to get a command in a sentence and then understand what
it wants and do something with it
"""
import json
data_dict = {}
word_type_names = ["action", "object", "target", "actor", "ignore"]
command_hint_length = 2
class WordType:
def __init__(self, name, d_saved_words):
self.name = name
try:
self.word_list = d_saved_words[name]
except KeyError:
self.word_list = []
data_dict[self.name] = self
def to_dict(self):
return {
self.name: self.word_list
}
def read_json_file():
with open("data.json", mode="r+") as json_file:
return json.load(json_file)
def declare_word_types(read_dict):
for name in word_type_names:
WordType(name, read_dict)
def get_command():
command = input("What is your command? Or x to stop\n").lower()
return command
def disect_command(command):
command_word_list = []
start_num = 0
end_num = 0
for word in command:
# If there is a space then that is one word
if word == " ":
command_word_list.append(command[start_num:end_num])
# Move the start num to the letter after the space
start_num = end_num + 1
end_num += 1
# Do once at the end so it gets the last word
command_word_list.append(command[start_num:end_num])
return command_word_list
def determine_word_type(command_word_list) -> list:
l_saved_words = []
l_unsaved_words = []
for key in data_dict:
# get every word in the dictionary
for word in data_dict[key].word_list:
l_saved_words.append(word)
# Create a list of all saved words
for word in command_word_list:
# see if word is in the list of all saved words
if word in l_saved_words or word in l_unsaved_words:
print(word, "has been saved")
else:
l_unsaved_words.append(word)
return l_unsaved_words
def get_word_type(l_unsaved_words):
# ask user to input the matching first letters
for word in l_unsaved_words:
# set a new line
print("\n")
# label each list from 0 to length
wi = 0
# print out data type hints
for keys in data_dict:
print(keys[0:command_hint_length] + ":" + keys, end="")
# if not at the end yet then add a comma
if wi < len(data_dict) - 1:
print(", ", end="")
wi += 1
indicator_letters = input("\nWhat type of word is " + str(word) + "?\n").lower()
# then append word using matching list number
for key in data_dict:
if indicator_letters == key[0:command_hint_length].lower():
data_dict[key].word_list.append(word)
def write_to_json():
new_dict = {}
for key in data_dict:
new_dict.update(data_dict[key].to_dict())
with open("data.json", "w") as write_file:
json.dump(new_dict, write_file, indent=2)
def __main__():
# setup data
d_saved_words = read_json_file()
declare_word_types(d_saved_words)
# receive input
command = get_command()
if command.lower() == "x":
exit()
# interpret input
command_word_list = disect_command(command)
l_unsaved_words = determine_word_type(command_word_list)
get_word_type(l_unsaved_words)
# save data
write_to_json()
__main__()
__main__()
|
f6a05a3977cf18e0a5b424eaec8eb0da10188817 | Autonomous-Agent-25/pybits | /sorting/demo/bubble.py | 800 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
#--------------------
"""
Bubble sort (Exchange sort family)
"""
N = 10
import random
def bubble_sort(x):
print 'Illustrated bubble sort'
num_tests = 0
num_swaps = 0
num_passes = 0
unsorted = True
while unsorted:
num_passes += 1
print 'Pass %i' % num_passes
unsorted = False
for j in range(1,len(x)):
print x
num_tests += 1
if x[j-1] > x[j]:
num_swaps += 1
x[j-1], x[j] = x[j], x[j-1]
unsorted = True
print 'Number of tests: %i' % num_tests
print 'Number of swaps: %i' % num_swaps
return x
def main():
a = range(N)
random.shuffle(a)
a = bubble_sort(a)
if __name__ == '__main__':
main()
|
549c2e397f3f0b30aeab13e254242faf8a74f4a1 | VYuLinLin/studying-notes | /Python3k/class/dog.py | 543 | 4.03125 | 4 | # 2.7版本呢需要定义object形参
class Dog():
# 一次模拟小狗的简单尝试
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
# 模拟小狗命令式蹲下
print(self.name.title() + ' is now sitting.')
def roll_over(self):
# 模拟小狗命名时打滚
print(self.name.title() + ' rolled over!')
my_dog = Dog('willie', 6)
print('我的小狗的名字是' + my_dog.name.title())
print('我的小狗今年' + str(my_dog.age) + '岁了')
my_dog.sit()
my_dog.roll_over() |
98e13a99f5f668d14d16315f689a6cf5b8981fed | VYuLinLin/studying-notes | /Python3k/pythonCase/hello.py | 216 | 4.0625 | 4 | print("hello world,", "my is python3")
name = input('亲,请输入您的姓名,好吗?')
# 单行注释
'''
多行注释
'''
# if name:
# else:
# print('您还没有输入您的姓名哦!')
print(name) |
2f20c8687a9fadfe8589c10b3de7c0df51f5b9c8 | luiszugasti/adventOfcode2020 | /day8/day8.py | 2,022 | 3.671875 | 4 | # day8.py
import copy
from typing import Tuple
from day2.day2 import open_file
def parse_input_to_puzzle_scope(puzzle_input):
parsed_instructions = []
for entry in puzzle_input:
parsed_instructions.append(parse_instruction(entry))
return parsed_instructions
def parse_instruction(input):
action = input[:3]
value = int(input[4:])
return (action, value)
def find_value_accumulator(instructions) -> Tuple[int, bool]:
seen = [False] * len(instructions)
accumulator = 0
program_counter = 0
def _is_cycle():
return seen[program_counter]
while (program_counter < len(instructions)):
if _is_cycle():
return accumulator, True
action, value = instructions[program_counter]
seen[program_counter] = True
if action == "acc":
program_counter = program_counter + 1
if action == "nop":
program_counter = program_counter + 1
if action == "jmp":
program_counter = program_counter + value
if action == "acc":
accumulator = accumulator + value
return accumulator, False
def fix_the_program(instructions):
for i in range(len(instructions)):
action, value = instructions[i]
if action == "nop" or action == "jmp":
temp_instructions = copy.deepcopy(instructions)
if action == "nop":
temp_instructions[i] = "jmp", instructions[i][1]
if action == "jmp":
temp_instructions[i] = "nop", instructions[i][1]
value, isCycle = find_value_accumulator(temp_instructions)
if not isCycle:
return value
if __name__ == '__main__':
puzzle_input = open_file("day8_input.txt")
parsed_instructions = parse_input_to_puzzle_scope(puzzle_input)
answer = find_value_accumulator(parsed_instructions)
print("answer: {}".format(answer))
answer = fix_the_program(parsed_instructions)
print("answer: {}".format(answer))
|
7897a1f57d210d621f6262132a6a1e8968ceb34e | allptics/software | /draw.py | 1,658 | 3.96875 | 4 | """
Description:
Functions used to render visuals
"""
import numpy as np
import matplotlib.pyplot as plt
def draw_paraxial_system(ax, sys):
"""
Draws a paraxial system
ax: plot
sys: system
"""
# plot optical axis
ax.axhline(y=0,color="black",dashes=[5,1,5,1],linewidth=1)
# plot starting point
p = 0
ax.axvline(p, c="green", ls="--", lw=1)
# plot lenses
for i in sys.elements:
if i.id == "thickness":
p = p + i.t
else:
ax.axvline(p, ls=":", lw=1)
# plot rays
y_max = 0
for ray in sys.rays:
x = []
y = []
for pt in ray.pts:
x.append(pt[0])
y.append(pt[1])
if pt[1] > abs(y_max):
y_max = abs(pt[1])
ax.plot(x, y, lw=1)
# plot ending point
ax.axvline(p, c="red", ls="--", lw=1)
plt.ylim(-y_max*1.2, y_max*1.2)
def draw_surface(ax, x, y):
"""
Description:
Used to draw a surface
ax: Plot to draw surface on
x: x points
y: y points
"""
ax.plot(x, y, 'b', linewidth = 1)
def draw_lens(ax, coords):
"""
Description:
Used to draw a lens (mainly just to connect the surfaces)
ax: Plot to draw surface on
coords: Points from surfaces
"""
for i in range(len(coords) - 1):
ax.plot([coords[i][0][0], coords[i + 1][0][0]], [coords[i][0][1], coords[i + 1][0][1]], 'b', linewidth=1)
ax.plot([coords[i][-1][0], coords[i + 1][-1][0]], [coords[i][-1][1], coords[i + 1][-1][1]], 'b', linewidth=1) |
fde121bae6e3a8993cd846d8337644a8b8cc3f0e | lizy90/Learn-Project | /Task2.py | 1,682 | 3.546875 | 4 | """
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。
输出信息:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
提示: 建立一个字典,并以电话号码为键,通话总时长为值。
这有利于你编写一个以键值对为输入,并修改字典的函数。
如果键已经存在于字典内,为键所对应的值加上对应数值;
如果键不存在于字典内,将此键加入字典,并将它的值设为给定值。
"""
num_time_dic = {}
number_list = []
for i in range(len(calls)):
if calls[i][0] not in number_list:
number_list.append(calls[i][0])
num_time_dic[calls[i][0]] = int(calls[i][-1])
else:
num_time_dic[calls[i][0]] += int(calls[i][-1])
if calls[i][1] not in number_list:
number_list.append(calls[i][1])
num_time_dic[calls[i][1]] = int(calls[i][-1])
else:
num_time_dic[calls[i][1]] += int(calls[i][-1])
#将字典分离出来放到一个list中,key和value位置调换,排序取最大值。
items = num_time_dic.items()
sort_list = sorted([[v[1],v[0]] for v in items])
l_number = sort_list[-1][1]
longesttime = sort_list[-1][0]
print("<{}> spent the longest time, <{}> seconds, on the phone during September 2016.".format(l_number,longesttime))
|
4c15d5aa19f8c081321df60ba1d0fa1e21bf01fc | biof309/03-loop-example-watkinsta | /airdata.py | 632 | 3.65625 | 4 | import numpy as np
import pandas as pd
airdata = pd.read_excel('airdata.xlsx')
#Data are measurements of air pollution levels from thousands of
#regions throughout the world recorded on WHO. This loop will count how many of
#these regions either do or do not meet guidelines - limit is 20
under_count = 0
over_count = 0
for i in airdata['PM10 Annual mean, ug/m3']:
if i <= 20:
under_count = under_count + 1
elif i > 20:
over_count = over_count + 1
print('%d recorded regions do not meet WHO air quality guidelines.' %(over_count))
print('%d recorded regions meet WHO air quality guidelines.' %(under_count))
|
9d057f9b4c79e82df90153757e7797f593adb009 | TasosVellis/Zero | /8.Object Oriented Programming/4_OOPHomework.py | 1,425 | 4.21875 | 4 | import math
# Problem 1
#
# Fill in the Line class methods to accept coordinates as a
# pair of tuples and return the slope and distance of the line.
class Line:
"""
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
li.distance() = 9.433981132056603
li.slope() = 1.6
distance formula = square((x2-x1)^2 + (y2-y1)^2)
slope formula = y2-y1 / x2-x1
"""
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1, y1 = self.coor1
x2, y2 = self.coor2
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def slope(self):
x1, y1 = self.coor1
x2, y2 = self.coor2
return (y2 - y1) / (x2 - x1)
coordinate1 = (3, 2)
coordinate2 = (8, 10)
li = Line(coordinate1, coordinate2)
print(li.distance())
print(li.slope())
# Problem 2
#
# Fill in the class
class Cylinder:
"""
c = Cylinder(2,3)
c.volume() = 56.52
c.surface_area() = 94.2
"""
pi = 3.14
def __init__(self, height=1, radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.pi * self.radius ** 2 * self.height
def surface_area(self):
top_bottom = 2 * self.pi * self.radius**2
return top_bottom + 2 * self.pi * self.radius * self.height
c = Cylinder(2, 3)
print(c.volume())
print(c.surface_area())
|
f1b22aa04b5b7dd47063d11989529775142c3f88 | TasosVellis/Zero | /6.Methods_Functions_builtin/3cardmonty.py | 600 | 4.03125 | 4 | #!/usr/bin/env python
from random import shuffle
def shuffle_list(mylist):
shuffle(mylist)
return mylist
def player_guess():
guess = ''
while guess not in ['0', '1', '2']:
guess = input("Pick a number :0, 1 or 2 ")
return int(guess)
def check_guess(mylist, guess):
if mylist[guess] == "O":
print("Correct")
else:
print("Wrong guess")
print(mylist)
# Initial list
my_list = [' ', 'O', ' ']
# Shuffle list
mixedup_list = shuffle_list(my_list)
# User guess
guess = player_guess()
# Check guess
check_guess(mixedup_list, guess)
|
95728488a63a49f8260cdb346507a16789e42d7a | TasosVellis/Zero | /6.Methods_Functions_builtin/functiopracticeproblems.py | 5,789 | 4.1875 | 4 | # WARMUP SECTION
def lesser_of_two_evens(a, b):
"""
a function that returns the lesser of two given numbers if both numbers are even,
but returns the greater if one or both numbers are odd
:param a: int
:param b: int
:return: int
lesser_of_two_evens(2,4) --> 2
lesser_of_two_evens(2,5) --> 5
"""
if a % 2 == 0 and b % 2 == 0:
return min(a, b)
else:
return max(a, b)
def animal_crackers(text):
"""
a function takes a two-word string and returns True if both words begin with same letter
:param text: str
:return: bool
animal_crackers('Levelheaded Llama') --> True
animal_crackers('Crazy Kangaroo') --> False
"""
wordlist = text.split()
return wordlist[0][0] == wordlist[1][0]
def makes_twenty(n1, n2):
"""
Given two integers, return True if the sum of the integers is 20 or if one of the integers is 20.
If not, return False
:param n1: int
:param n2: int
:return: bool
makes_twenty(20,10) --> True
makes_twenty(12,8) --> True
makes_twenty(2,3) --> False
"""
return n1 == 20 or n2 == 20 or (n1 + n2) == 20
# LEVEL 1
def old_macdonald(name):
"""
Write a function that capitalizes the first and fourth letters of a name¶
:param name: str
:return:str
old_macdonald('macdonald') --> MacDonald
"""
if len(name) > 3:
return name[:3].capitalize() + name[3:].capitalize()
else:
return "Name is too short!"
def master_yoda(text):
"""
Given a sentence, return a sentence with the words reversed
:param text: str
:return: str
master_yoda('I am home') --> 'home am I'
master_yoda('We are ready') --> 'ready are We'
"""
return " ".join(text.split()[::-1])
def almost_there(n):
"""
Given an integer n, return True if n is within 10 of either 100 or 200
:param n:int
:return: bool
almost_there(90) --> True
almost_there(104) --> True
almost_there(150) --> False
almost_there(209) --> True
"""
return (abs(100 - n) <= 10) or (abs(200 - n) <= 10)
# LEVEL 2
def has_33(nums):
"""
Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.
has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False
:param nums:list of ints
:return:bool
"""
for i in range(0, len(nums) - 1):
if nums[i] == 3 and nums[i + 1] == 3:
return True
return False
def paper_doll(text):
"""
Given a string, return a string where for every character in the original there are three characters
:param text:str
:return:str
paper_doll('Hello') --> 'HHHeeellllllooo'
paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
"""
new_text = ""
for ch in text:
new_text += ch * 3
return new_text
def blackjack(a, b, c):
"""
Given three integers between 1 and 11, if their sum is less than or equal to 21,
return their sum.
If their sum exceeds 21 and there's an eleven, reduce the total sum by 10.
Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'
:param a: int
:param b: int
:param c: int
:return: int or str
blackjack(5,6,7) --> 18
blackjack(9,9,9) --> 'BUST'
blackjack(9,9,11) --> 19
"""
if sum((a, b, c)) <= 21:
return sum((a, b, c))
elif sum((a, b, c)) <= 31 and 11 in (a, b, c):
return sum((a, b, c)) - 10
else:
return 'BUST'
def summer_69(arr):
"""
Return the sum of the numbers in the array,
except ignore sections of numbers starting
with a 6 and extending to the next 9 (every 6 will be followed by at least one 9).
Return 0 for no numbers.
:param arr: list of integers
:return: int
"""
get_result = 0
add = True
for num in arr:
while add:
if num != 6:
get_result += num
break
else:
add = False
while not add:
if num != 9:
break
else:
add = True
break
return get_result
# CHALLENGING PROBLEMS
def spy_game(nums):
"""
Write a function that takes in a list of integers and returns True if it contains 007 in order
:param nums: array
:return: bool
"""
code = [0, 0, 7, "x"]
for num in nums:
if num == code[0]:
code.pop(0) # code.remove(num) also works
return len(code) == 1
def count_primes(num):
"""
Write a function that returns the number
of prime numbers that exist up to and including a given number
:param num: int
:return: int
"""
count = 0
lower = int(input())
upper = int(input())
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
count += 1
return count
# def count_primes(num):
# primes = [2]
# x = 3
# if num < 2: # for the case of num = 0 or 1
# return 0
# while x <= num:
# for y in range(3,x,2): # test all odd factors up to x-1
# if x%y == 0:
# x += 2
# break
# else:
# primes.append(x)
# x += 2
# print(primes)
# return len(primes)
def print_big(letter):
patterns = {1: ' * ', 2: ' * * ', 3: '* *', 4: '*****', 5: '**** ', 6: ' * ', 7: ' * ', 8: '* * ', 9: '* '}
alphabet = {'A': [1, 2, 4, 3, 3], 'B': [5, 3, 5, 3, 5], 'C': [4, 9, 9, 9, 4], 'D': [5, 3, 3, 3, 5], 'E': [4, 9, 4, 9, 4]}
for pattern in alphabet[letter.upper()]:
print(patterns[pattern])
print_big('c')
|
cabd94e59e8e1dfc0bcb93ca204b7627426279a6 | Reiich/Raquel_Curso | /Ejercicio06_MasterMind/main.py | 2,591 | 3.96875 | 4 | # Ejercicio 2
# Escribe un programa que te permita jugar a una versión simplificada del juego
# Master Mind. El juego consistirá en adivinar una cadena de números distintos.
# Al principio, el programa debe pedir la longitud de la cadena (de 2 a 9 cifras).
# Después el programa debe ir pidiendo que intentes adivinar la cadena de números.
# En cada intento, el programa informará de cuántos números han sido acertados
# (el programa considerará que se ha acertado un número si coincide el valor y la posición).
from random import randrange
import random
def jugar():
len = int(input("Dime una longitud de cadena de numeros entre 2 y 9 cifras:"))
probarN = input("Prueba con una cifra : ")
aleatorio = crearAleatorio(len) # creo una VAR llamada aleatorio que ejecuta la funcion crear aleatorio
print("prueba trampa " + aleatorio)
while probarN != aleatorio: #es decir, que no lo adivine COMPLETAMENTE EL NÚM. ALEATORIO
eval = evaluar(len, aleatorio, probarN) # creo otra variable total, que llama a la función evaluar
print("Con el número " + probarN + " has tenido " + str(eval) + " aciertos.")
probarN = input("Intenta adivinar la cadena, dame otro número :")
print("FELICIDADES, HAS GANADO!")
def crearAleatorio(cad):
n_aleat = '' #numero aleatroio debe ser un string para poder concaternar el n1 que resulta. Valor nulo ahora mismo
for i in range(cad):
x= random.randint(0,9) #tiene que ser string , me devuelve un número entre 0 y 9. Por cada una de las veces que se indica en len
x = str(x)
n_aleat += x
return n_aleat
def evaluar(cad, aleatorio, probarN): # creo esta función para que diga si el string (numero) puesto, tiene algun acierto o no
cont = 0
a = 0 #empieza desde el cero comprobando si a = b
b = 0
for i in range(cad): # va a realizar las comprobaciones hasta alcanzar el rengo dado por len
if aleatorio[a] == probarN[b]:
cont += 1 #contea el número de veces que sí coinciden los números
a += 1 #va avanzando de posición en la comprobación
b += 1 #cambia el valor de aleatorio[A] y b. de uno en uno.
else: #si no adivina no contea, si no que avanza al siguiente item de la comparación
a += 1
b += 1
return cont
#una vez que ya ha realizado el bucle FOR, el numero de veces de la longitud de cadena. Devuelve el cont. (contador)
# fin de funciones
#arranco juego
jugar()
|
599ee94087dc1f1ecca3f354fbcfdaade4bd02b8 | Reiich/Raquel_Curso | /receta_15_barrasDesplazamiento/main15.py | 2,277 | 3.5 | 4 | '''
uso de la BARRA DE DESPLAZAMIENTO
aquí para obtener el valor de la barra, donde el usuario la ha dejado parada
se usa:
.valueChanged
hay que tener en cuenta, que éste método devuelve el valor, que se optine.
Automáticamente, si tener que programar nada. Por ello, ucnado definamos la función
que mostrará el valor elegido por pantalla, sólo necesitaremos pasar ese valor
como parámentro en la función: (de esta manera)
def mostrar_azucar(self, valor):
self.ui.txt_resultado.setText("Nivel de azucar: {}".format(valor))
#el "valor" lo recoge del parámetro que viene de entrada
Es decir, es como si .valueChanged() hiciera un return del punto (Valor) en el que
ha quedado la selección.
'''
from PyQt5.QtWidgets import QApplication, QDialog, QWidget
import sys
from niveles_dialog import NivelesDialog
class NivelesApp(QDialog):
def __init__(self): #todos estos valores se cargan sólo por iniciar la ventana
super().__init__()
self.ui = NivelesDialog()
self.ui.setupUi(self)
self.ui.scroll_azucar.valueChanged.connect(self.mostrar_azucar)
self.ui.scrollPulso.valueChanged.connect(self.mostrar_pulso)
self.ui.sliderColesterol.valueChanged.connect(self.mostrar_colesterol)
self.ui.sliderPresion.valueChanged.connect(self.mostrar_presion)
self.show() #mostramos la interfaz
def mostrar_azucar(self, valor): #este parámetro va a corresponder el el valor de la barra de desplazamiento
self.ui.txt_resultado.setText("Nivel de azucar: {}".format(valor)) #el valor lo recoge del parámetro que viene de entrada
def mostrar_pulso(self, valor):
self.ui.txt_resultado.setText("Pulso: {}".format(valor))
def mostrar_colesterol(self, valor):
self.ui.txt_resultado.setText("Nivel colesterol: {}".format(valor))
def mostrar_presion(self, valor):
self.ui.txt_resultado.setText("Presión: {}".format(valor))
###############
#inicio aplicacion
if __name__ == "__main__":
app = QApplication(sys.argv)
ventana_inicio = NivelesApp()
ventana_inicio.show()
sys.exit(app.exec_()) |
9b5b7c70619cfb3ec1d41bc5288d6a227b7d244d | Reiich/Raquel_Curso | /Ejercicios_ALF_Ficheros/main.py | 3,383 | 3.75 | 4 | '''
Created on 21 mar. 2020
@author: Raquel
EJERCICIOS - FICHEROS
'''
# Ejercicio 1
# Escribir una función que pida un número entero entre 1 y 10 y guarde en un
# fichero con el nombre tabla-n.txt la tabla de multiplicar de ese número,
# done n es el número introducido.
def pideNumero():
n = int(input("Dame un número entero entre el 1 y el 10 : "))
f = open("tabla-" + str(n) + ".txt", "a") #debe se (a) para añadir linea a liea el bucle y no se sobrescriba.
for i in range(1, 11):
f.write(str(n) + ' x ' + str(i) + ' = ' + str(n * i) + '\n')
#puede hacerse todo en una sola línea #la operación tb. Concatenada con STR
f.close() #se cierra el archivo
### fin de la función
#arranco la función. Programa
pideNumero()
# Ejercicio 2
# Escribir una función que pida un número entero entre 1 y 10, lea el fichero tabla-n.txt
# con la tabla de multiplicar de ese número, done n es el número introducido, y la muestre
# por pantalla. Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello.
import os
def muestraTabla():
while True: # este while hará que pida todo el tiempo un número hasta que el archivo SI SEA ENCONTRADO
n = int(input("Dime qué tabla quieres que muestre 1 y el 10 : "))
archivo = "tabla-" + str(n) + ".txt"
try: #intenta abrir el archivo para leer "r"
archivo = open(archivo, 'r')
except FileNotFoundError: # si no encuentra el archivo indicado:
print('No existe el fichero con la tabla del', n)
else:
print(archivo.read()) #si no da error, haz esto. Lee el archivo e imprime por consola
break
### fin de la función
#arranco la función. Programa
muestraTabla()
# Ejercicio 3
# Escribir una función que pida dos números n y m entre 1 y 10, lea el fichero tabla-n.txt
# con la tabla de multiplicar de ese número, y muestre por pantalla la línea m del fichero.
# Si el fichero no existe debe mostrar un mensaje por pantalla informando de ello.
import os
def muestraTabla():
while True: # este while hará que pida todo el tiempo un número hasta que el archivo SI SEA ENCONTRADO
n = int(input("Dime qué tabla quieres que muestre 1 y el 10 : "))
m = int(input("Por qué multiplo? (del 1-10)"))
archivo = "tabla-" + str(n) + ".txt"
try: #intenta abrir el archivo para leer "r"
archivo = open(archivo, 'r')
except FileNotFoundError: # si no encuentra el archivo indicado:
print('No existe el fichero con la tabla del', n)
else:
lineas =archivo.readlines() # o convierto en una lista
print(lineas[m-1]) # imprimo sólo el elemento de esa lista.
break
### fin de la función
#arranco la función. Programa
muestraTabla()
# Ejercicio 4 #
# Escribir un programa que acceda a un fichero de internet mediante su url y
# muestre por pantalla el número de palabras que contiene.
from urllib import request
f = request.urlopen('https://raw.githubusercontent.com/asalber/asalber.github.io/master/README.md')
f = f.read()
print(len(f.split()))
|
f74f2b5d8ec3cc78ed956c9ad432cf6b428646ac | bhishan/FacebookAutomationDoubleDownCasino | /buychips.py | 3,082 | 3.546875 | 4 | '''
Author : Bhishan Bhandari
bbhishan@gmail.com
The program uses following modules
selenium to interact and control the browser
time to create pause in the program to behave like we are human
pyautogui to find the location of buy chips button in the game to click
time is a default module in python which comes installed when installing python.
pyautogui and selenium can be installed as follows.
In command prompt/terminal type the following and hit enter to install selenium
pip install selenium
In command prompt/terminal type the following and hit enter to install pyautogui
pip install pyautogui
'''
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
import pyautogui
def main(username, password):
try:
browser = webdriver.Chrome()
except:
print "requirement not satisfied."
browser.maximize_window()
try:
browser.get("http://www.codeshareonline.com/doubledown.html")
time.sleep(10)
codes_paragraph = browser.find_element_by_class_name("paragraph")
all_codes = codes_paragraph.find_elements_by_tag_name("a")
count = 0
final_codes = []
for codes in all_codes:
if "facebook" in codes.get_attribute("href"):
print codes.text
final_codes.append(codes.text)
count += 1
print "Total coupon codes collected : ", count
except:
print "Could not get coupon codes. "
browser.get("https://facebook.com")
time.sleep(15)
email_field = browser.find_element_by_id("email")
password_field = browser.find_element_by_id("pass")
email_field.send_keys(username)
time.sleep(3)
password_field.send_keys(password)
password_field.send_keys(Keys.RETURN)
time.sleep(20)
web_body = browser.find_element_by_tag_name('body')
web_body.send_keys(Keys.ESCAPE)
for i in range(5):
web_body.send_keys(Keys.PAGE_DOWN)
time.sleep(2)
for i in range(10):
web_body.send_keys(Keys.PAGE_UP)
time.sleep(2)
browser.get("https://apps.facebook.com/doubledowncasino")
time.sleep(50)
web_body = browser.find_element_by_tag_name('body')
web_body.send_keys(Keys.ESCAPE)
stat = 0
for i in range(3000):
try:
time.sleep(5)
buy_chips = pyautogui.locateOnScreen("/home/bhishan/bhishanworks/programmingblog/fiverr/facebookgame/buychips.png")
button7x, button7y = pyautogui.center(buy_chips)
pyautogui.click(button7x, button7y)
print "found and clicked"
stat = 1
except:
print "could not find image of buy chips to click"
if stat == 1:
break
time.sleep(5)
for each_code in final_codes:
promo_entry = browser.find_element_by_id("package_promo_input")
promo_entry.send_keys(each_code)
promo_button = browser.find_element_by_id("package_promo_button")
promo_button.click()
if __name__ == '__main__':
main("bbhishan@gmail.com", "password")
|
162cc8d2c7562d4ca175908fae458dda6b86969c | lmokto/py-designpattern | /singleton/ejemplo-singleton.py | 501 | 3.78125 | 4 | class Singleton (object):
instance = None
def __new__(cls, *args, **kargs):
if cls.instance is None:
cls.instance = object.__new__(cls, *args, **kargs)
return cls.instance
"""definimos el objecto"""
MySingletonUno = Singleton()
MySingletonDos = Singleton()
MySingletonUno.nuevo = "hola"
print MySingletonDos.nuevo
"""Creamos otra instancia del mismo objecto, que almacena la variable nuevo"""
NuevoSingleton = Singleton()
print NuevoSingleton.nuevo
|
71fb6615811b40c8877b34456a98cdc34650dc92 | arvimal/DataStructures-and-Algorithms-in-Python | /04-selection_sort-1.py | 2,901 | 4.5 | 4 | #!/usr/bin/env python3
# Selection Sort
# Example 1
# Selection Sort is a sorting algorithm used to sort a data set either in
# incremental or decremental order.
# How does Selection sort work?
# 1. Iterate through the data set one element at a time.
# 2. Find the biggest element in the data set (Append it to another if needed)
# 3. Reduce the sample space to `n - 1` by the biggest element just found.
# 4. Start the iteration over again, on the reduced sample space.
# 5. Continue till we have a sorted data set, either incremental or decremental
# How does the data sample reduces in each iteration?
# [10, 4, 9, 3, 6, 19, 8] - Data set
# [10, 4, 9, 3, 6, 8] - [19] - After Iteration 1
# [4, 9, 3, 6, 8] - [10, 19] - After Iteration 2
# [4, 3, 6, 8] - [9, 10, 19] - After Iteration 3
# [4, 3, 6] - [8, 9, 10, 19] - After Iteration 4
# [4, 3] - [6, 8, 9, 10, 19] - After Iteration 5
# [3] - [4, 6, 8, 9, 10, 19] - After Iteration 6
# [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set
# Let's check what the Selection Sort algorithm has to go through in each
# iteration
# [10, 4, 9, 3, 6, 19, 8] - Data set
# [10, 4, 9, 3, 6, 8] - After Iteration 1
# [4, 9, 3, 6, 8] - After Iteration 2
# [4, 3, 6, 8] - After Iteration 3
# [4, 3, 6] - After Iteration 4
# [4, 3] - After Iteration 5
# [3] - After Iteration 6
# [3, 4, 6, 8, 9, 10, 19] - After Iteration 7 - Sorted data set
# Observations:
# 1. It takes `n` iterations in each step to find the biggest element.
# 2. The next iteration has to run on a data set of `n - 1` elements.
# 3. Hence the total number of overall iterations would be:
# n + (n - 1) + (n - 2) + (n - 3) + ..... 3 + 2 + 1
# Since `Selection Sort` takes in `n` elements while starting, and goes through
# the data set `n` times (each step reducing the data set size by 1 member),
# the iterations would be:
# n + [ (n - 1) + (n - 2) + (n - 3) + (n - 4) + ... + 2 + 1 ]
# Efficiency:
# We are interested in the worse-case scenario.
# In a very large data set, an `n - 1`, `n - 2` etc.. won't make a difference.
# Hence, we can re-write the above iterations as:
# n + [n + n + n + n ..... n]
# Or also as:
# n x n = n**2
# O(n**2)
# Final thoughts:
# Selection Sort is an algorithm to sort a data set, but it is not particularly
# fast. For `n` elements in a sample space, Selection Sort takes `n x n`
# iterations to sort the data set.
def find_smallest(my_list):
smallest = my_list[0]
smallest_index = 0
for i in range(1, len(my_list)):
if my_list(i) < smallest:
smallest = my_list(i)
smallest_index = i
return smallest_index
def selection_sort(my_list):
new_list = []
for i in range(len(my_list)):
smallest = find_smallest(my_list)
new_list.append(my_list.pop(smallest))
return new_list
print(selection_sort([10, 12, 9, 4, 3, 6, 100]))
|
06eed5f573e0c33e89a282600aead38f947dd078 | dgkimura/sudoku | /src/solver.py | 2,506 | 3.84375 | 4 | # solver.py
#
# A solver will insert numbers into a grid to solve the puzzle.
class Solver:
def __init__(self, grid):
self._grid = grid
def populate(self, nums):
for i, n in enumerate(nums):
if n is not None:
# print i
self._grid.cells[i].insert(n)
def solve(self):
# a = SingleEntry()
# a.run(self._grid)
b = BruteForce()
b.run(self._grid)
#print self._grid
class SingleEntry:
"""
Single entry algorithm passes over all cells and marks any cell
that has a single valid answer.
"""
def run(self, grid):
updated = True
while updated:
updated = False
for i, c in enumerate(grid.cells):
if c.num is not None:
continue
valid = c.POSSIBLE_ANSWERS - c._row.union(c._col) \
.union(c._box)
if (len(valid) == 1):
c.num = valid.pop()
print "SINGLE ENTRY {0} {1}".format(c.num, i)
updated = True
class BruteForce:
"""
Brute force algorithm that tries every possibility and returns the
first found answer.
"""
def run(self, grid):
stack = []
while (not self.is_solved(grid.cells)):
for i, c in enumerate(grid.cells):
if c.num is not None:
continue
if self.increment(c):
stack.append(c)
else:
while len(stack) > 1:
c = stack.pop()
if self.increment(c):
stack.append(c)
break
else:
c.erase()
if len(stack) == 1:
c = stack.pop()
c.disallow()
break
def is_solved(self, cells):
for c in cells:
if c.num is None:
return False
return True
def increment(self, cell):
start = (cell.num or 0) + 1
for n in range(start, len(cell.POSSIBLE_ANSWERS) + 1):
if n not in cell.disallowed and cell.can_insert(n):
if cell.num:
cell.erase()
cell.insert(n)
# print "INCREMENT END {0}".format(self.num)
return True
return False
|
3eea539c849e14f831231c3bdceb2193c6138bdb | evgenyneu/ASP3162 | /10_integration_python/src/exact_solution.py | 1,740 | 3.9375 | 4 | import numpy as np
def exact(x, n):
"""
Calculate exact solution of Lane-Emden equation.
Parameters
----------
x : float or ndarray
Value or values of independent variable
n : integer
Parameter 'n' of the Lane-Emden equation
Returns : float or ndarray
-------
Value or values of the exact solution
"""
if n == 0:
return 1 - 1/6 * np.power(x, 2)
elif n == 1:
# We need to calculate sin(x)/x
# when x=0, this is equal to 1
a = np.sin(x)
b = np.array(x)
return np.divide(a, b, out=np.ones_like(a), where=b != 0)
elif n == 5:
return np.power(1 + 1/3 * np.power(x, 2), -0.5)
else:
raise ValueError(f"Incorrect n value: {n}")
def exact_derivative(x, n):
"""
Calculate exact values for the derivatives of the solutions
of Lane-Emden equation.
Parameters
----------
x : float or ndarray
Value or values of independent variable
n : integer
Parameter 'n' of the Lane-Emden equation
Returns : float or ndarray
-------
Value or values of the exact solution
"""
if n == 0:
return -x/3
elif n == 1:
a = np.cos(x)
b = np.array(x)
# Assign value 0 to terms that have division by zero
term1 = np.divide(a, b, out=np.zeros_like(a), where=b != 0)
a = np.sin(x)
b = np.power(x, 2)
# Assign value 0 to terms that have division by zero
term2 = np.divide(a, b, out=np.zeros_like(a), where=b != 0)
return term1 - term2
elif n == 5:
return -x / (3 * np.power(1 + np.power(x, 2) / 3, 3/2))
else:
raise ValueError(f"Incorrect n value: {n}")
|
465d7a23163f564c85cbc09aa09657a310e95393 | evgenyneu/ASP3162 | /07_upwind_wendroff/plotting/create_movies.py | 3,225 | 3.53125 | 4 | # Create movies of solutions of advection equation
import matplotlib.animation as animation
from compare_animated import animate, prepare_for_animation
import matplotlib
import os
from plot_utils import create_dir
matplotlib.use("Agg")
def create_movie(methods, initial_conditions, courant_factor,
movie_dir, filename, t_end, nx, fps, ylim):
"""
Create a movie of solution of advection equation
Parameters
----------
methods : list of str
Numerical methods to be used: ftcs, lax, upwind, lax-wendroff
initial_conditions : str
Type of initial conditions: square, sine
courant_factor : float
Parameter used in the numerical methods
movie_dir : str
Directory where the movie file is saved
filename : str
Movie file name
t_end : float
The largest time of the solution.
nx : int
Number of x points.
fps : int
Frames per second for the movie
ylim : tuple
Minimum and maximum values of the y-axis.
"""
print("...")
Writer = animation.writers['ffmpeg']
writer = Writer(fps=fps,
metadata=dict(artist='Evgenii Neumerzhitckii'),
bitrate=1800)
fig, lines, text, x, y, z = \
prepare_for_animation(methods=methods,
initial_conditions=initial_conditions,
t_end=t_end, nx=nx, ylim=ylim,
courant_factor=courant_factor)
timesteps = z[0].shape[0]
create_dir(movie_dir)
path_to_file = os.path.join(movie_dir, filename)
with writer.saving(fig, path_to_file, dpi=300):
for i in range(timesteps):
animate(i=i, lines=lines, text=text, x_values=x,
t_values=y, solution=z)
writer.grab_frame()
def make_movies():
"""
Create movies of solutions of advection equation
"""
movies_dir = "movies"
print(
(f"Creating movies in '{movies_dir}' directory.\n"
"This will take a couple of minutes.")
)
methods = ['Exact', 'Lax-Wendroff', 'Lax', 'Upwind']
t_end = 2
fps = 10
create_movie(methods=methods,
initial_conditions='sine',
courant_factor=0.5,
movie_dir=movies_dir, filename='01_sine_c_0.5.mp4',
t_end=t_end, nx=100, ylim=(-1.5, 1.5), fps=fps)
create_movie(methods=methods,
initial_conditions='square',
courant_factor=0.5,
movie_dir=movies_dir, filename='02_square_c_0.5.mp4',
t_end=t_end, nx=100, ylim=(-0.5, 1.5), fps=fps)
create_movie(methods=methods,
initial_conditions='sine',
courant_factor=1,
movie_dir=movies_dir, filename='03_sine_c_1.mp4',
t_end=t_end, nx=200, ylim=(-1.5, 1.5), fps=fps)
create_movie(methods=methods,
initial_conditions='square',
courant_factor=1,
movie_dir=movies_dir, filename='04_square_c_1.mp4',
t_end=t_end, nx=200, ylim=(-0.5, 1.5), fps=fps)
if __name__ == '__main__':
make_movies()
|
da6ff2dc49a425b99fde124769ba8fe2567d0b6d | evgenyneu/ASP3162 | /05_advection_equation/parts/02_numerical/plotting/solver.py | 3,346 | 3.5 | 4 | # Solve a heat equation
import subprocess
from plot_utils import create_dir
import numpy as np
import os
import struct
import array
def read_solution_from_file(path_to_data):
"""
Read solution from a binary file. Please refer to README.md
for description of the binary file format used here.
Parameters
----------
path_to_data : str
Path to the binary file containing solution data.
Returns
-------
(x, y, z) tuple
x, y, and z values of the solution,
where x and y and 1D arrays, and z is a 2D array.
"""
data = open(path_to_data, "rb").read()
# nx: number of x points
# ----------
start = 0
end = 4*3
(_, nx, _) = struct.unpack("@iii", data[start: end])
# nt: number of t points
# ----------
start = end
end = start + 4*3
(_, nt, _) = struct.unpack("@iii", data[start: end])
# x values
# ---------
start = end + 4
end = start + nx * 8
x_values = array.array("d")
x_values.frombytes(data[start:end])
# t values
# ---------
start = end + 8
end = start + nt * 8
t_values = array.array("d")
t_values.frombytes(data[start:end])
# Solution: 2D array
# ---------
start = end + 8
end = start + nx * nt * 8
solution = array.array("d")
solution.frombytes(data[start:end])
solution = np.reshape(solution, (nt, nx), order='C')
return (x_values, t_values, solution)
def solve_equation(x_start, x_end, nx,
t_start, t_end, nt, method):
"""
Runs Fortran program that solves equation
v_t + v v_x = 0
and returns the solution.
Parameters
----------
x_start : float
The smallest x value
x_end : float
The largest x value
nx : int
The number of x points in the grid
t_start : float
The smallest t value
t_end : float
The largest t value
nt : int
The number of t points in the grid
method : str
Numerical method to be used: centered, upwind
Returns
-------
(x, y, z, dx, dt, courant) tuple
x, y, z : values of the solution,
where x and y and 1D arrays, and z is a 2D array.
dx, dt : position and time steps
dt_dx : ratio dt / dx
"""
subdir = "tmp"
create_dir(subdir)
path_to_data = os.path.join(subdir, "data.bin")
parameters = [
(
f'../build/main {path_to_data}'
f' --x_start={x_start}'
f' --x_end={x_end}'
f' --nx={nx}'
f' --t_start={t_start}'
f' --t_end={t_end}'
f' --nt={nt}'
f' --method={method}'
)
]
child = subprocess.Popen(parameters,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True)
message = child.communicate()[0].decode('utf-8')
rc = child.returncode
success = rc == 0
if not success:
print(message)
return None
x, y, z = read_solution_from_file(path_to_data)
dx = x[1] - x[0]
dt = y[1] - y[0]
os.remove(path_to_data)
os.rmdir(subdir)
dt_dx = dt/dx
z = np.nan_to_num(z)
return (x, y, z, dx, dt, dt_dx)
|
671a2d1b58e546d9b38a7499d231412d53418de1 | systembase-kikaku/python-learn | /deep_learning1/numpy1.py | 269 | 3.53125 | 4 | import numpy as np
x = np.array([1.0, 2.0, 3.0])
print(x)
v1 = np.array([3, 4, 5])
v2 = np.array([1, 2, 3])
print(v1 + v2)
print(v1 - v2)
print(v1 * v2)
print(v1 / v2)
A = np.array([[1, 2], [3, 4], [5, 6]])
print(A.shape)
print(A.dtype)
print(A + 10)
print(A * 10)
|
48e3534a6cc05a5068103994a6599a20f50c6f39 | davidsekielyk/frro-soporte-2018-07 | /practico-02/ejercicio-01.py | 544 | 3.984375 | 4 | #Ejercicio 1
print("""Ejercicio 1
Escribir una clase llamada rectángulo que contenga una base y una altura, y que contenga un
método que devuelva el área del rectángulo.
""")
class Triangulo():
def __init__(self, base, altura):
self.base = base
self.altura = altura
def area(self):
print("El area del triangulo es:", self.base * self.altura)
triangulo = Triangulo(int(input("Ingrese la base del triangulo: ")),int(input("Ingrese la altura del triangulo: ")))
print()
triangulo.area()
|
7d53e8a283b5c82d079752eee3465214cbf683da | davidsekielyk/frro-soporte-2018-07 | /practico-01/ejercicio-12.py | 293 | 3.859375 | 4 | #Ejercicio 12
print("Ejercicio 12: Determinar la suma de todos los numeros de 1 a N. N es un número que se ingresa por consola.\n")
a = int(input("ingrese un numero: "))
rdo = 0
for i in range(a):
rdo = rdo + (a - i)
print("La suma de todos los numeros de 1 a",a, "es:",rdo)
|
d528adcaaa0b77ae7adfd71829542fa02eedc1dd | gomgomigom/Exercise_2 | /w_1-2/201210_0.py | 281 | 3.703125 | 4 | i = 1
current = 1
previous = 0
while i <= 10:
print(current)
temp = previous
previous = current
current = current + temp
i += 1
i = 1
current = 1
previous = 0
while i <= 10:
print(current)
previous, current = current, current + previous
i += 1
|
a287c15b12ed3e3194c5aedac6b2fbb8adeb629b | gomgomigom/Exercise_2 | /w_1-2/201210_4.py | 2,013 | 4.125 | 4 | # numbers라는 빈 리스트를 만들고 리스트를 출력한다.
# append를 이용해서 numbers에 1, 7, 3, 6, 5, 2, 13, 14를 순서대로 추가한다. 그 후 리스트를 출력한다.
# numbers 리스트의 원소들 중 홀수는 모두 제거한다. 그 후 다시 리스트를 출력한다.
# numbers 리스트의 인덱스 0 자리에 20이라는 수를 삽입한 후 출력한다.
# numbers 리스트를 정렬한 후 출력한다.
# 빈 리스트 만들기
numbers = []
print(numbers)
numbers.append(1)
numbers.append(7)
numbers.append(3)
numbers.append(6)
numbers.append(5)
numbers.append(2)
numbers.append(13)
numbers.append(14)
print(numbers)
# numbers에서 홀수 제거
i = 0
while i < len(numbers):
if numbers[i] % 2 == 1:
del numbers[i]
i -= 1
i += 1
print(numbers)
# numbers의 인덱스 0 자리에 20이라는 값 삽입
numbers.insert(0, 20)
print(numbers)
# numbers를 정렬해서 출력
numbers.sort()
print(numbers)
print(type(numbers))
for num in numbers:
print(num)
for x in range(2, 10, 2):
print(x)
numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
print(range(len(numbers)))
for num in range(len(numbers)):
print(f"{num} {numbers[num]}")
print(1,2)
print(1, 2)
for i in range(1,11):
print(f'2^{i} = {2 ** i}')
i = 1
while i <= 10:
print(f'2^{i} = {2 ** i}')
i += 1
for i in range(11):
print("2^{} = {}".format(i, 2 ** i))
for i in range(1, 10):
for j in range(1, 10):
print(f"{i} * {j} = {i * j}")
i = 1
while i < 10:
j = 1
while j < 10:
print(f"{i} * {j} = {i * j}")
j += 1
i += 1
for i in range(1,10):
if i < 10 :
a = 1
print("{} * {} = {}".format(a, i, a * i))
print("if문이 실행!")
else :
a += 1
i = 1
print("else문이 실행!")
for a in range(1,1001):
for b in range(a,1001):
c = 1000 - a - b
if a ** 2 + b ** 2 == c ** 2 and a + b + c == 1000 and a < b < c:
print(a * b * c)
print("완료")
|
7d9ae260ebd619e69325316d76119ad2ce0b010d | gomgomigom/Exercise_2 | /w_1-2/201212_3.py | 519 | 3.65625 | 4 | import random
guess = -1
ANSWER = random.randint(1,20)
NUM_TRIES = 4
tries = 0
while guess != ANSWER and NUM_TRIES > tries:
guess = int(input(f"기회가 {NUM_TRIES - tries}번 남았습니다. 1-20 사이의 숫자를 맞혀 보세요: "))
tries += 1
if ANSWER > guess:
print("Up")
elif ANSWER < guess:
print("Down")
if guess == ANSWER:
print(f"축하합니다. {tries}번 만에 숫자를 맞히셨습니다.")
else:
print(f"아쉽습니다. 정답은 {ANSWER}입니다.")
|
2929a547ca339b6226756026a221d48a7482b5d8 | eriksylvan/PythonChallange | /1/1.py | 430 | 3.578125 | 4 | # http://www.pythonchallenge.com/pc/def/map.html
# print (ord('a'))
# print (ord('.'))
#
# print (ord('A'))
# print (ord('z'))
# print (ord(' '))
#hej
with open("input") as f:
for line in f:
for ch in line:
asciiNo = ord(ch)
if ord('A') <= asciiNo <= ord('z'):
print(chr((asciiNo - ord('a') + 2) % 26 + ord('a')), end = '')
else:
print(ch, end = '')
|
393888cb2cb65dc22e7c369dc786dd89618d772d | JoseLuisAcv2/Algoritmos-II-Proyecto-II | /listaReproduccion.py | 4,251 | 3.59375 | 4 | #
# ALGORITMOS II - PROYECTO II
#
# REPRODUCTOR DE MUSICA
#
# AUTORES:
# - Jose Acevedo 13-10006
# - Pablo Dario Betancourt 13-10147
# TAD Lista de reproduccion. Implementado con lista circular doblemente enlazada
# Modulo
from cancion import *
# Clase para nodos de la lista enlaada
class nodoLista:
# Constructor:
# Un nodo tiene apuntador al siguiente, al anterior y los datos satelites con la informacion de la cancion
def __init__(self,cancion):
self.cancion = cancion
self.prev = None
self.next = None
# Implementacion del TAD Lista de Reproduccion
class listaReproduccion:
# Constructor:
# Se implementa con una lista enlazada. Inicialmente vacia
def __init__(self):
self.head = None
self.size = 0
# Funcion para agregar canciones a la lista de reproduccion
def agregar(self,cancion):
node = nodoLista(cancion)
if self.head == None:
node.next = node
node.prev = node
self.head = node
self.size += 1
else:
if self.buscar(cancion) == None:
node.next = self.head
self.head.prev.next = node
node.prev = self.head.prev
self.head.prev = node
self.head = node
self.size+=1
# Funcion para agregar canciones a la lista de reproduccion al final de la lista
def agregar_final(self,cancion):
node = nodoLista(cancion)
if self.head == None:
node.next = node
node.prev = node
self.head = node
self.size += 1
else:
if self.buscar(cancion) == None:
self.head.prev.next = node
node.prev = self.head.prev
self.head.prev = node
node.next = self.head
self.size+=1
# Funcion para buscar si una determinada cancion se encuentra en la lista de reproduccion
# En caso de estar presente retorna un apuntador a la cancion. En caso contrario retorna None
def buscar(self,cancion):
x = self.head
for i in xrange(self.size):
if x.cancion.esIgual(cancion) : return x
x = x.next
return None
# Funcion que recibe una cancion y la elimina de la lista de reproduccion
def eliminar(self,cancion):
x = self.buscar(cancion)
if x != None:
x.prev.next = x.next
x.next.prev = x.prev
if x == self.head : self.head = x.next
self.size-=1
# Funcion que compara dos TADs cancion.
# Se pueden comparar por titulo de cancion o por artista de cancion
def comp(self,a,b,c):
# Comparar por titulo
if c == 0:
return a.cancion.esMenorTitulo(b.cancion)
# Comparar por artista
else:
return a.cancion.esMenorArtista(b.cancion)
# Funcion que ordena la lista de reproduccion por orden lexicografico del titulo
# de las canciones. Para ordenar la lista se utiliza el algoritmo Mergesort
def ordenarTitulo(self):
self.head.prev.next = None
self.head.prev = None
self.head = self.mergesort(self.head,0)
x = self.head
while x!=None and x.next != None:
x = x.next
self.head.prev = x
x.next = self.head
# Funcion que ordena la lista de reproduccion por orden lexicografico del artista
# de las canciones. Para ordenar la lista se utiliza el algoritmo Mergesort
def ordenarArtista(self):
self.head.prev.next = None
self.head.prev = None
self.head = self.mergesort(self.head,1)
x = self.head
while x!=None and x.next != None:
x = x.next
self.head.prev = x
x.next = self.head
# Algoritmo Mergesort para ordenar la lista de reproduccion
def mergesort(self,head,flag):
if head == None or head.next == None:
return head
second = self.split(head)
head = self.mergesort(head,flag)
second = self.mergesort(second,flag)
return self.merge(head,second,flag)
# Sub procedimiento de Mergesort para hacer merge de dos
# listas enlazadas
def merge(self,head,second,flag):
if head == None : return second
if second == None : return head
if self.comp(head,second,flag):
head.next = self.merge(head.next,second,flag)
head.next.prev = head
head.prev = None
return head
else:
second.next = self.merge(head,second.next,flag)
second.next.prev = second
second.prev = None
return second
# Sub procedimiento de Mergesort para dividir una lista
# enlazada en dos listas enlazadas
def split(self,head):
fast = head
slow = head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
tmp = slow.next
slow.next = None
return tmp |
4e3f98f1e05289dc88477754d42d26ec0d7c82ec | DoyKim-20/DoyKim-20.github.io | /Practice02.py | 269 | 3.640625 | 4 | print("2번 과제 시작!")
year = 19
pin = '990329-1083599'
if pin[7]==3 or pin[7]==4 :
year = year + 1
print('김멋사군의 탄생일은 ' + str(year) + str(pin[0:2]) + '년 ' + str(pin[2:4]) + '월 ' + str(pin[4:6]) + '일 입니다')
#60192164 김도영 |
6dd28e4f0b0e2b51deb6a51d4ed0ee636b321616 | kevinkepp/ann | /ann/act.py | 1,279 | 3.609375 | 4 | import numpy as np
import scipy.special
def linear(z):
return z
def d_linear(a):
return 1
def relu(z):
return z * (z > 0)
def d_relu(a):
return a > 0
def tanh(z):
return np.tanh(z)
def d_tanh(a):
return 1 - a ** 2
def sigmoid(z):
return scipy.special.expit(z)
def d_sigmoid(a):
return a * (1 - a)
def sigmoid_with_binary_xentropy(z):
"""To be used in conjunction with loss.binary_xentropy_with_sigmoid"""
return sigmoid(z)
def softmax(z):
exps = np.exp(z - np.max(z, axis=1, keepdims=True))
return exps / np.sum(exps, axis=1, keepdims=True)
def softmax_with_xentropy(z):
"""To be used in conjunction with loss.xentropy_with_softmax"""
return softmax(z)
def get_d_act(act):
if act == linear:
return d_linear
elif act == relu:
return d_relu
elif act == tanh:
return d_tanh
elif act == sigmoid:
return d_sigmoid
elif act == softmax:
# derivative depends on derivative of loss function and thus will be calculated in layer backward method
return None
elif act == softmax_with_xentropy or act == sigmoid_with_binary_xentropy:
# derivative can be simplified and thus will be calculated in layer backward method
return None
else:
raise NotImplementedError("No derivative for activation function '{}'".format(act.__name__))
|
fa8385e10ce82dcce011f7f0c8b3384c4b4e75f9 | Abe27342/project-euler | /src/65.py | 583 | 3.734375 | 4 | import fractions
def get_frac(continued_fraction_list):
x = continued_fraction_list[::-1]
y = fractions.Fraction(x[0])
x.remove(x[0])
while(len(x) > 0):
y = x[0] + 1/y
x.remove(x[0])
return(y)
def get_continued_frac(n, de):
d = fractions.Fraction(n,de)
x = []
while(int(d) != d):
x.append(int(d))
d = 1/(d-int(d))
x.append(int(d))
return(x)
def sum_of_digits(n):
return(sum([int(i) for i in str(n)]))
e = [1]*100
e[0] = 2
for i in range(1,34):
e[3*i-1] = 2*i
print sum_of_digits(get_frac(e).numerator) |
581970e71a706fc9c2eefc33ca0f9afe28042361 | Abe27342/project-euler | /src/359.py | 2,443 | 3.71875 | 4 | '''
First, a simulation...
Evidently, floor 1 contains all triangular numbers.
Looking on oeis,...
floor 2 contains numbers 2, 7, 9, 16 and then a(n) = 2a(n-1) - 2a(n-3) + a(n-4)
a(1) = 2
a(2) = 7
a(3) = 9
a(4) = 16
floor 3 contains a(0) = 1 then a(n) = n^2 - a(n-1) for n >= 1.
floor 4 contains blah blah blah
it turns out that P(f, r) is something like (r + f)(r + f - 1)/2 + f/2 * (-1)^(r + f).
This formula works for even f, and then for odd ones you have to modify it slightly. Should be evident by the simulation.
Why it works, I have no idea.
Also note that the given number is 2^27 * 3^12. That's how we arrive at the answer.
'''
from collections import defaultdict
from random import randint
squares = {i**2 for i in range(10000)}
def is_square(n):
return n in squares
class Hotel:
def __init__(self):
self.floors = defaultdict(list)
self.next_person_num = 1
def try_place_in_floor(self, person_num, floor_num):
floor = self.floors[floor_num]
if len(floor) == 0:
floor.append(person_num)
return True
else:
last_person = floor[-1]
if is_square(last_person + person_num):
floor.append(person_num)
return True
return False
def place_person(self, person_num):
floor_num = 1
while not self.try_place_in_floor(person_num, floor_num):
floor_num += 1
def place_next_person(self):
self.place_person(self.next_person_num)
self.next_person_num += 1
hotel = Hotel()
def P(f, r):
while not (f in hotel.floors and r-1 < len(hotel.floors[f])):
hotel.place_next_person()
return hotel.floors[f][r - 1]
def fast_P(f, r):
if f == 1:
return r * (r + 1) / 2
negative_one_coeff = f / 2
negative_one_power = r + (f % 2)
a1 = f - (f % 2)
a2 = a1 - 1
return (r + a1) * (r + a2) / 2 + negative_one_coeff * (-1)**(negative_one_power)
'''
print P(25, 75)
hotel.floors[1] = 0
hotel.floors[2] = 0
hotel.floors[3] = 0
hotel.floors[4] = 0
hotel.floors[5] = 0
print hotel.floors
print [fast_P(11, i) for i in range(1, 5)]
print hotel.floors[11]
experimentation
'''
def try_random_sample_case():
f = randint(40, 150)
r = randint(100, 200)
assert P(f, r) == fast_P(f, r)
for i in range(1000):
try_random_sample_case()
print [fast_P(1, i) for i in range(1, 101)]
print [P(1, i) for i in range(1, 101)]
n = 2**27 * 3**12
print n
total = 0
for p2 in range(28):
for p3 in range(13):
d = 2**p2 * 3**p3
n_over_d = n / d
total += fast_P(n_over_d, d)
total %= 10**8
print total |
2e31593ab0115bab5ac39d77731cef845f299b4c | Abe27342/project-euler | /src/51.py | 1,520 | 3.609375 | 4 | '''
this code sucks
also used this:
from helpers import isPrime
x = sum([isPrime(101010*k+20303) for k in range(1,10)])
print(x)
'''
from helpers import sieve
import itertools
num_set = ['0','1','2','3','4','5','6','7','8','9','*']
primes = sieve(10000000)
print('primes generated')
def triple_digit(n):
n = str(n)[0:-1]
x = [n.count(i) for i in n]
if(3 in x):
indices = [i for i in range(len(x)) if x[i] == 3]
return(indices)
#print(triple_digit(3221125))
m = [p for p in primes if triple_digit(p) != None]
m.sort(key=lambda x:triple_digit(x))
print('first stage done')
#print(m)
paired_m = []
i = 0
while(i < len(m)):
p = m[i]
count = 0
while(i+count < len(m) and triple_digit(p) == triple_digit(m[i+count])):
count += 1
#print(triple_digit(p),triple_digit(p+count))
paired_m.append([m[j] for j in range(i,i+count)])
i += count
#print(paired_m)
print('second stage done')
for triple_list in paired_m:
if(len(triple_list) == 1):
print(triple_list)
for i in range(len(triple_list)):
element = triple_list[i] #i could use enumerate but it's 1am gg
indices = triple_digit(element)
element = list(str(element))
for c in indices:
element[c] = '*'
triple_list[i] = ''.join(element)
#print(triple_list)
for s in triple_list:
if(triple_list.count(s) > 5):
print(s)
break
else:
triple_list.remove(s)
|
5dc34de95e32b2e08f8f504fda056c1febfcc5cb | Abe27342/project-euler | /src/287.py | 2,675 | 3.59375 | 4 | # (0,0) is bottom_left
# Because I'm too lazy to precompute lmao
from helpers import memoize
@memoize
def get_pow_2(n):
return pow(2, n)
def is_top_left(N, bottom_right):
x,y = bottom_right
return x < get_pow_2(N - 1) and y >= get_pow_2(N - 1)
def is_bottom_left(N, top_right):
x,y = top_right
return x < get_pow_2(N - 1) and y < get_pow_2(N - 1)
def is_bottom_right(N, top_left):
x,y = top_left
return x >= get_pow_2(N - 1) and y < get_pow_2(N - 1)
def is_top_right(N, bottom_left):
x,y = bottom_left
return x >= get_pow_2(N - 1) and y >= get_pow_2(N - 1)
def square_is_black(N, square):
x,y = square
middle = get_pow_2(N - 1)
return (x - middle) * (x - middle) + (y - middle) * (y - middle) <= middle * middle
# Returns the encoding length for block with the given top_left and bottom_right corners in the 2^N by 2^N image.
def encoding_length(N, top_left, bottom_right):
x_left, y_top = top_left
x_right, y_bottom = bottom_right
bottom_left = (x_left, y_bottom)
top_right = (x_right, y_top)
if is_top_left(N, bottom_right):
if not square_is_black(N, bottom_right):
return 2 # because 11 encoding gets all of the white parts.
if square_is_black(N, bottom_right) and square_is_black(N, top_left):
return 2
elif is_top_right(N, bottom_left):
if not square_is_black(N, bottom_left):
return 2
if square_is_black(N, bottom_left) and square_is_black(N, top_right):
return 2
elif is_bottom_left(N, top_right):
if not square_is_black(N, top_right):
return 2
if square_is_black(N, bottom_left) and square_is_black(N, top_right):
return 2
elif is_bottom_right(N, top_left):
if not square_is_black(N, top_left):
return 2
if square_is_black(N, bottom_right) and square_is_black(N, top_left):
return 2
current_square_size = y_top - y_bottom + 1 # Fuck this coordinate system :P
if current_square_size == 1:
return 2
assert current_square_size % 2 == 0
divided_size = current_square_size / 2
top_left1 = top_left
top_left2 = (x_left + divided_size, y_top)
top_left3 = (x_left, y_bottom + divided_size - 1)
top_left4 = (x_left + divided_size, y_bottom + divided_size - 1)
bottom_right1 = (x_left + divided_size - 1, y_bottom + divided_size)
bottom_right2 = (x_right, y_bottom + divided_size)
bottom_right3 = (x_left + divided_size - 1, y_bottom)
bottom_right4 = bottom_right
return 1 + encoding_length(N, top_left1, bottom_right1) + encoding_length(N, top_left2, bottom_right2) + encoding_length(N, top_left3, bottom_right3) + encoding_length(N, top_left4, bottom_right4)
def D(N):
return encoding_length(N, (0, pow(2, N) - 1), (pow(2, N) - 1, 0))
print [D(i) for i in range(2, 12)]
print D(24) |
bb1e8d8a320464f802cd28823c3b551f15906dfe | MilletPu/IR-hw | /IR-hw/index.py | 11,196 | 3.53125 | 4 | # -*- encoding: utf8 -*-
from __future__ import absolute_import, division, print_function
import VB
import collections
import functools
import math
DOCUMENT_DOES_NOT_EXIST = 'The specified document does not exist'
TERM_DOES_NOT_EXIST = 'The specified term does not exist'
class HashedIndex(object):
"""
InvertedIndex structure in the form of a hash list implementation.
"""
def __init__(self, initial_terms=None):
"""
Construct a new HashedIndex. An optional list of initial terms
may be passed which will be automatically added to the new HashedIndex.
"""
self._documents = collections.Counter()
self._terms = {}
self._inverted_index = {}
self._freeze = False
if initial_terms is not None:
for term in initial_terms:
self._terms[term] = {}
def __getitem__(self, term):
return self._terms[term]
def __contains__(self, term):
return term in self._terms
def __repr__(self):
return '<HashedIndex: {} terms, {} documents>'.format(
len(self._terms), len(self._documents)
)
def __eq__(self, other):
return self._terms == other._terms and self._documents == other._documents
def add_term_occurrence(self, term, document):
"""
Adds an occurrence of the term in the specified document.
"""
if isinstance(term, tuple):
term = term[0]
if isinstance(document, tuple):
document = document[0]
if isinstance(term, unicode):
term = term.encode('utf-8')
if isinstance(document, unicode):
document = document.encode('utf-8')
if document not in self._documents:
self._documents[document] = 0
if term not in self._terms:
if self._freeze:
return
else:
self._terms[term] = collections.Counter()
if document not in self._terms[term]:
self._terms[term][document] = 0
self._documents[document] += 1
self._terms[term][document] += 1
def get_total_term_frequency(self, term):
"""
Gets the frequency of the specified term in the entire corpus
added to the HashedIndex.
"""
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
return sum(self._terms[term].values())
def get_term_frequency(self, term, document, normalized=False):
"""
Returns the frequency of the term specified in the document.
"""
if document not in self._documents:
raise IndexError(DOCUMENT_DOES_NOT_EXIST)
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
result = self._terms[term].get(document, 0)
if normalized:
result /= self.get_document_length(document)
return result
def get_document_frequency(self, term):
"""
Returns the number of documents the specified term appears in.
"""
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
else:
return len(self._terms[term])
def get_dict(self):
"""
Dict with words and its df
"""
dict = self.items()
for postlist in dict:
dict[postlist] = len(dict[postlist])
return dict
def get_longword(self):
dict = self.get_dict().keys()
longword = ''
for words in dict:
longword += str(words)
return longword
def get_document_length(self, document):
"""
Returns the number of terms found within the specified document.
"""
if document in self._documents:
return self._documents[document]
else:
raise IndexError(DOCUMENT_DOES_NOT_EXIST)
def get_documents(self, term):
"""
Returns all documents related to the specified term in the
form of a Counter object.
"""
if term not in self._terms:
raise IndexError(TERM_DOES_NOT_EXIST)
else:
return self._terms[term]
def terms(self):
return list(self._terms)
def documents(self):
return list(self._documents)
def items(self):
return self._terms
def get_tfidf(self, term, document, normalized=False):
"""
Returns the Term-Frequency Inverse-Document-Frequency value for the given
term in the specified document. If normalized is True, term frequency will
be divided by the document length.
"""
tf = self.get_term_frequency(term, document)
# Speeds up performance by avoiding extra calculations
if tf != 0.0:
# Add 1 to document frequency to prevent divide by 0
# (Laplacian Correction)
df = 1 + self.get_document_frequency(term)
n = 2 + len(self._documents)
if normalized:
tf /= self.get_document_length(document)
return tf * math.log10(n / df)
else:
return 0.0
def get_total_tfidf(self, term, normalized=False):
result = 0
for document in self._documents:
result += self.get_tfidf(term, document, normalized)
return result
def generate_feature_matrix(self, mode='tfidf'):
"""
Returns a feature matrix in the form of a list of lists which
represents the terms and documents in this Inverted Index using
the tf-idf weighting by default. The term counts in each
document can alternatively be used by specifying scheme='count'.
A custom weighting function can also be passed which receives a term
and document as parameters.
The size of the matrix is equal to m x n where m is
the number of documents and n is the number of terms.
The list-of-lists format returned by this function can be very easily
converted to a numpy matrix if required using the `np.as_matrix`
method.
"""
result = []
for doc in self._documents:
result.append(self.generate_document_vector(doc, mode))
return result
def prune(self, min_value=None, max_value=None, use_percentile=False):
n_documents = len(self._documents)
garbage = []
for term in self.terms():
freq = self.get_document_frequency(term)
if use_percentile:
freq /= n_documents
if min_value is not None and freq < min_value:
garbage.append(term)
if max_value is not None and freq > max_value:
garbage.append(term)
for term in garbage:
del (self._terms[term])
def from_dict(self, data):
self._documents = collections.Counter(data['documents'])
self._terms = {}
for term in data['terms']:
self._terms[term] = collections.Counter(data['terms'][term])
def inverted_index(self):
"""
return a dict object
of the inverted index with 'unsorted' terms and corresponding 'unsorted' postings
:return: unsorted inverted index
"""
for terms in self._terms.keys():
self._inverted_index[terms] = {}
self._inverted_index[terms][self.get_document_frequency(terms)] = self.get_documents(terms)
return self._inverted_index
def get_sorted_inverted_index(self):
"""
return an OrderedDict object
of the inverted index with 'sorted' terms and corresponding 'sorted' postings
:return: sorted inverted index
"""
for terms in self._terms.keys():
self._inverted_index[terms] = {}
self._inverted_index[terms][self.get_document_frequency(terms)] = sorted(self.get_documents(terms)) #or: not sorted documents
return collections.OrderedDict(sorted(self._inverted_index.items(), key=lambda t: t[0]))
def get_sorted_inverted_index_VB(self):
"""
return an OrderedDict object
of the inverted index with 'sorted' terms and corresponding 'sorted' postings
:return: sorted inverted index
"""
for terms in self._terms.keys():
self._inverted_index[terms] = {}
self._inverted_index[terms][self.get_document_frequency(terms)] = sorted(VB.VB(self.get_documents(terms))) #or: not sorted documents
return collections.OrderedDict(sorted(self._inverted_index.items(), key=lambda t: t[0]))
def get_sorted_posting_list(self, term):
"""
return a posting list of a single term (i.e. its own inverted index).
:param term: term
:return: posting list
"""
posting_list = {term: {}}
posting_list[term][self.get_document_frequency(term)] = sorted(self.get_documents(term))
return posting_list
def get_corpus_statistics(self, corpus):
"""
get the statistics about the corpus and index:
1, number of terms
2, number of documents
3*, number of tokens
4*, documents average length
*: input "corpus" variable to get tokens_count and documents_average_len
:param corpus: corpus
:return:
"""
statistics = {}
statistics['terms_count'] = len(self._terms)
statistics['documents_count'] = len(self._documents)
statistics['tokens_count'] = len(corpus)
statistics['documents_average_len'] = int(statistics['tokens_count']/statistics['documents_count'])
return statistics
def write_index_to_disk(self, filepath):
global output
try:
output = open(filepath, 'w+')
output.write(str(self.get_sorted_inverted_index()))
output.close()
print ('Successfylly write to: ' + filepath)
except:
print ('An error occurs when writing to: ' + filepath)
finally:
output.close()
def write_index_to_disk_VB(self, filepath):
global output
try:
output = open(filepath, 'w+')
output.write(str(self.get_sorted_inverted_index_VB()))
output.close()
print ('Successfylly write to: ' + filepath)
except:
print ('An error occurs when writing to: ' + filepath)
finally:
output.close()
def merge(index_list):
result = HashedIndex()
for index in index_list:
first_index = result
second_index = index
assert isinstance(second_index, HashedIndex)
for term in second_index.terms():
if term in first_index._terms and term in second_index._terms:
result._terms[term] = first_index._terms[term] + second_index._terms[term]
elif term in second_index._terms:
result._terms[term] = second_index._terms[term]
else:
raise ValueError("I dont know how the hell you managed to get here")
result._documents = first_index._documents + second_index._documents
return result
|
1c1c21233ee084db1004816005357985b6166e39 | lior-ohana/TDD | /test_bubble_sort.py | 877 | 3.734375 | 4 | import unittest
from bubble_sort import *
class testbublesort(unittest.TestCase):
#tests of the function name-bubbleSort(arr)
def test_bubblesort1(self):
arr1=[4,2,1,7]
expected=[1,2,4,7]
bubbleSort(arr1)
self.assertEqual(expected,arr1)
def test_bubblesort2(self):
arr1 = ['w', 'a', 'v', 'o']
expected = ['a', 'o', 'v', 'w']
bubbleSort(arr1)
self.assertEqual(expected, arr1)
def test_bubblesort3(self):
arr1 = []
expected = "No array insert"
result=bubbleSort(arr1)
self.assertEqual(expected, result)
# If no elements are lost from the array
def test_bubblesort4(self):
arr1 = [4, 2, 1, 7]
expected = len([1, 2, 4, 7])
bubbleSort(arr1)
self.assertEqual(expected,len(arr1))
|
e0f974c5b42c9c4279fb0ddf8f7030860557ce32 | imknott/python_work | /guest_book.py | 441 | 4 | 4 | filename = 'text_files/guestbook.txt'
print("Welcome to the terminal, we ask that you please enter the following: \n")
while True:
name = input("What is your name? ")
with open(filename, 'a') as file_object:
file_object.write(f'{name} \n')
#Find out if someone else would like to take the poll.
repeat = input("Would you like to let another person respond? (yes/no)")
if repeat == 'no':
break
|
7d2fe2f51f6759be77661c2037c7eb4de4326375 | rbrook22/otherOperators.py | /otherOperators.py | 717 | 4.375 | 4 | #File using other built in functions/operators
print('I will be printing the numbers from range 1-11')
for num in range(11):
print(num)
#Printing using range and start position
print("I will be printing the numbers from range 1-11 starting at 4")
for num in range(4,11):
print(num)
#Printing using range, start, and step position
print("I'll print the numbers in range to 11, starting at 2, with a step size of 2")
for num in range(2,11,2):
print(num)
#Using the min built in function
print('This is the minimum age of someone in my family:')
myList = [30, 33, 60, 62]
print(min(myList))
#Using the max built in function
print('This is the maximum age of someone in my family:')
print(max(myList))
|
126fac3a8f4a79d89830c94e722f8f7082e816b5 | Hiurge/reader | /app_scripts/reader_input_helpers.py | 1,225 | 3.59375 | 4 | import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import re
# Reader input helpers:
# - Turns reader input into one string text contents weather its a link contents or a pasted text.
# Main function to import: get_input_text(contents)
# Gets website contents and turns into list of paragraphs (sentences).
def url_to_txt(url):
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser') # "lxml")
sentences = soup.find_all('p')
sentences = [s.get_text() for s in sentences if s]
return sentences
# Decides if reader input string is a link or pure text to be taken as a contents.
def url_or_text(input_string):
if ' ' in input_string:
return 'text'
else:
try:
link = re.search("(?P<url>https?://[^\s]+)", input_string).group("url")
return 'link'
except:
try:
link = re.search("(?P<url>www.[^\s]+)", input_string).group("url")
return 'link'
except:
return 'text'
# Turns link contents into one string of text.
def get_input_text(contents):
if url_or_text(contents) == 'link':
link = contents
list_of_p = url_to_txt(link)
full_text = ' '.join(list_of_p)
return full_text
else:
full_text = contents
return full_text
|
193df65365239df519e955afc7487f0435628433 | Sjord/matasano | /set2/pkcs.py | 182 | 3.5 | 4 |
def pad(data, length):
pad_length = length - len(data)
return data + pad_length * chr(pad_length)
assert(pad("YELLOW SUBMARINE", 20) == "YELLOW SUBMARINE\x04\x04\x04\x04")
|
71876e59efb677256adbcd6ddd99bc483b3f6e30 | ktemirbekovna/Moduli | /slide_2.2.py | 379 | 3.890625 | 4 | '''Спросите у пользователя 2 значения через input() а затем через модуль sys
проверьте какое из 2-х значений занимает больше памяти.'''
import sys
a = input("Введите данные: ")
b = input("Введите данные: ")
print(sys.getsizeof(a))
print(sys.getsizeof(b))
|
20c9fb839eb1b852be94e76ea437c479b78f0415 | hackett123/chess | /model/FEN.py | 1,922 | 3.75 | 4 | """
https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
Fen notation: slashes (/) divide rank information. Within each rank, a lowercase letter
denotes black pieces and uppercase denotes white. A number represents a sequence of empty
squares in the board.
The last segment contains the final rank and extra metadata:
- whose turn it is (w or b)
- castling information - a dash (-) if nobody can castle, K and/or Q for white can castle
king or queen side, and a k and/or q for black can castle king or queen side
- en passant target square - a dash(-) if none available currently
- halfmoves since last capture
- # of full moves, which increases after black moves
"""
def read_fen(fen):
board = []
rank_infos = fen.split('/')
last_rank = rank_infos[-1].split(' ')[0]
for rank_info in rank_infos:
if rank_info == rank_infos[-1]:
rank_info = last_rank
rank = []
for c in rank_info:
if str.isnumeric(c):
for i in range(int(c)):
rank.append(' ')
else:
rank.append(c)
board.append(rank)
return board
def castle_info(fen):
"""
From a FEN, return a tuple of four boolean values denoting if white can castle king/queen side,
black can castle king/queen side.
"""
board_metadata = read_board_metadata(fen)
availablity = board_metadata[1]
return 'K' in availablity, 'Q' in availablity, 'k' in availablity, 'q' in availablity
def who_moves(fen):
board_metadata = read_board_metadata(fen)
return board_metadata[0] == 'w'
def plies_since_capture(fen):
board_metadata = read_board_metadata(fen)
return int(board_metadata[3])
def move_number(fen):
board_metadata = read_board_metadata(fen)
return int(board_metadata[4])
def read_board_metadata(fen):
return fen.split('/')[-1].split(' ')[1:]
|
ee45660537cff37311a6081eee6082209b998ea4 | shukur-alom/Guess_Game | /Guess game.py | 2,180 | 3.953125 | 4 | #Guess Game
print('\n\n --WELCOME TO GUESS GAME-- \n\n')
my_hide=23
l=1
Tring_Time=10
try:
while l<=100:
User_input=int(input("Enter Your Guess: "))
if User_input <=5:
print('Incrise the number more more,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input==my_hide:
print('Successful,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
break
elif User_input<=15:
print('Incrise the number more,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input >=16 and User_input<=20:
print('Incrise the number less,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input >=21 and User_input<=22:
print("Incrise the number a little more,",end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input >=24 and User_input<=27:
print("Decrease the number a little more,",end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input >=28 and User_input<=35:
print('Decrease the number less,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input >=36 and User_input<=41:
print('Decrease the number more,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
elif User_input >=42:
print('Decrease the number more more,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
if l==Tring_Time:
print('Game Over,',end='')
print('\t\tYou have tring',':',l,'\t','You have',':',Tring_Time-l,'try')
break
l+=1
except:
print('\n\t\t\t\tInput a number\n')
|
6db878c7906c9fecbd5f7f9703f2108cbf626976 | nasjp/atcoder | /arc065_a.py | 962 | 3.8125 | 4 | # Me
def check(s):
words = [
'dream',
'dreamer',
'erase',
'eraser',
]
while len(s) != 0:
flag = False
for w in words:
if s[-len(w):] == w:
s = s[:-len(w)]
flag = True
break
if not flag:
return 'NO'
return 'YES'
print(check(input()))
# Other
# これじゃだめだよな
def check(s):
s = s.replace('eraser', '')
s = s.replace('erase', '')
s = s.replace('dreamer', '')
s = s.replace('dream', '')
if len(s) != 0:
return 'NO'
return 'YES'
print(check(input()))
# Other
S = input()
while S:
for x in ['dreamer', 'eraser', 'dream', 'erase']:
if S.endswith(x):
S = S[:-len(x)]
break
# for に else 節を書ける
# for を抜けたあとに実行される
else:
print('NO')
exit()
print('YES')
|
b86322bff277a38ee7165c5637c72d781e9f6ee2 | Bbenard/python_assesment | /ceaser/ceaser.py | 678 | 4.34375 | 4 | # Using the Python,
# have the function CaesarCipher(str, num) take the str parameter and perform a Caesar Cipher num on it using the num parameter as the numing number.
# A Caesar Cipher works by numing all letters in the string N places down in the alphabetical order (in this case N will be num).
# Punctuation, spaces, and capitalization should remain intact.
# For example if the string is "Caesar Cipher" and num is 2 the output should be "Ecguct Ekrjgt".
# more on cipher visit http://practicalcryptography.com/ciphers/caesar-cipher/
# happy coding :-)
def CaesarCipher(string, num):
# Your code goes here
print "Cipertext:", CaesarCipher("A Crazy fool Z", 1)
|
e026278e161656a19b0d93ec074cbb7d8b0c1a11 | hirosato223/Exercism.io-Problems | /python/hangman/hangman.py | 1,372 | 3.65625 | 4 | STATUS_WIN = "win"
STATUS_LOSE = "lose"
STATUS_ONGOING = "ongoing"
class Hangman(object):
def __init__(self, word):
self.remaining_guesses = 9
self.status = STATUS_ONGOING
self.word = word
self.maskedWord = '_' * len(word)
self.previousGuesses = set()
def guess(self, char):
if self.remaining_guesses < 0:
raise ValueError('No remaining guesses!')
if self.status == STATUS_WIN:
raise ValueError('You already won the game!')
isSuccessfulGuess = False
if char not in self.previousGuesses:
self.previousGuesses.add(char)
for i in range(len(self.word)):
if char == self.word[i]:
maskedWordCharList = list(self.maskedWord)
maskedWordCharList[i] = char
self.maskedWord = ''.join(maskedWordCharList)
isSuccessfulGuess = True
if self.maskedWord == self.word:
self.status = STATUS_WIN
if isSuccessfulGuess == False:
self.remaining_guesses-= 1
if self.remaining_guesses < 0:
self.status = STATUS_LOSE
else:
self.status = STATUS_ONGOING
def get_masked_word(self):
return self.maskedWord
def get_status(self):
return self.status |
ca33de76147ae37ebd77a1f66b4d5bdabf1e94c9 | nicholas-eden/python-algorithms | /sort/selection_sort.py | 393 | 4.0625 | 4 | from typing import List
data = [3, 6, 12, 6, 7, 4, 23, 7, 2, 1, 7, 4, 3, 2, 5, 3, 1]
def selection_sort(arr: List[int]):
low: int
for left in range(len(arr) - 1):
low = left
for right in range(left + 1, len(arr)):
if arr[right] < arr[low]:
low = right
arr[left], arr[low] = arr[low], arr[left]
selection_sort(data)
print(data)
|
5165e39c4ff20f645ed4d1d725a3a6becd002778 | ashishbansal27/DSA-Treehouse | /BinarySearch.py | 740 | 4.125 | 4 | #primary assumption for this binary search is that the
#list should be sorted already.
def binary_search (list, target):
first = 0
last = len(list)-1
while first <= last:
midpoint = (first + last)//2
if list[midpoint]== target:
return midpoint
elif list[midpoint] < target :
first = midpoint + 1
else :
last = midpoint - 1
return None
#summary of above code :
#two variables named first and last to indicate the starting and ending point
#of the list.
# the while loop would run till the first value is less than or equal to last
# then we update the values of first and last.
a= [x for x in range(1,11)]
print(a)
print(binary_search(a,1))
|
b99316dcaf95db6d42f80537e0c6cb57acb2e107 | lgaultie/BT_Machine_learning | /Day02/ex01/main.py | 1,507 | 3.921875 | 4 | #!/usr/bin/env python
'''Implement the what_are_the_vars function that returns an object with the
right attributes. You will have to modify the "instance" ObjectC, NOT THE CLASS.
Have a look to getattr, setattr.'''
class ObjectC(object):
def __init__(self):
pass
def what_are_the_vars(*args, **kwargs):
"""Your code"""
obj = ObjectC()
for i in range(len(args)):
# creating a new attribute in the instance of obj: var_i
setattr(obj, "var_{}".format(i), args[i])
for x in kwargs:
# dir() gets all attributes/methods/fields/etc of an object
if x in dir(obj):
return
setattr(obj, x, kwargs[x])
return (obj)
def doom_printer(obj):
if obj is None:
print("ERROR")
print("end")
return
# dir() gets all attributes/methods/fields/etc of an object
for attr in dir(obj):
if attr[0] != '_':
# The getattr() method returns the value of the named attribute of an object.
# class Person:
# age = 23
# name = "Adam"
# person = Person()
# print('The age is:', getattr(person, "age"))
# print('The age is:', person.age)
# >> The age is: 23
# >> The age is: 23
value = getattr(obj, attr)
print("{}: {}".format(attr, value))
print("end")
if __name__ == "__main__":
obj = what_are_the_vars(7)
doom_printer(obj)
obj = what_are_the_vars("ft_lol", "Hi")
doom_printer(obj)
obj = what_are_the_vars()
doom_printer(obj)
obj = what_are_the_vars(12, "Yes", [0, 0, 0], a=10, hello="world")
doom_printer(obj)
obj = what_are_the_vars(42, a=10, var_0="world")
doom_printer(obj)
|
f3607d3692bbe899356d1cf3b053468de24bcbd5 | lgaultie/BT_Machine_learning | /Day02/ex00/ft_map.py | 374 | 3.90625 | 4 | #!/usr/bin/env python
def addition(n):
return n + n
def ft_map(function_to_apply, list_of_inputs):
result = []
for i in list_of_inputs:
result.append(function_to_apply(i))
return result
numbers = [1, 2, 3, 4]
res = ft_map(addition, numbers)
print (res)
chars = ['s', 'k', 'k', 'a', 'v']
converted = list(ft_map(lambda s: str(s).upper(), chars))
print(converted)
|
b0f1ac0ab7122c36d4a2fb94e42bf018228827c3 | cugis2019nyc/cugis2019nyc-jadabaeda | /day1code.py | 1,007 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
print("hello world")
print("my name is jada")
print("1226")
5*2
5/2
5-2
5**2
8/9*3
def add(a,b):
add = a+b
print(add)
add(2,3)
print("the sum of 23,70,and 97 is")
def add(a,b,c):
add = a+b+c
print("the sum is ", add)
add(23,70,97)
def aqua(a,b,c):
aqua = a*b*c
print("the product of" ,a,b, "and" ,c, "is" ,aqua)
aqua(5,5,5)
1/2*2*1
1/2*11*19
def area(b,h):
area = 1/2*b*h
print(area)
print("the area of a triangle with base", b, "and height", h, "is volume", area)
area(11, 19)
print("cwhite chocolate")
print("milk chocolate")
chocolate1="milk"
chocolate2="dark"
chocolate3="white"
milk=5
dark=6
white=8
milk = milk+3
milk
milk = milk-3
milk
print(milk+2)
import math
dir(math)
math.factorial(7)
math.sqrt(350)
math.exp(1)
math.pow(2.718281828459045,2)
|
343570c2210214071c5e400f4cce9820346e7ace | SergioO21/intermediate_python | /list_and_dicts.py | 778 | 3.765625 | 4 | def run():
my_list = {1, "Hello", True, 4.5}
my_dict = {"firstname": "Sergio", "lastname": "Orejarena"}
super_list = [
{"firstname": "Sergio", "lastname": "Orejarena"},
{"firstname": "Alberto", "lastname": "Casas"},
{"firstname": "Maria", "lastname": "Castillo"},
{"firstname": "Alan", "lastname": "Contreras"},
{"firstname": "Sara", "lastname": "Roman"}
]
super_dict = {
"natural_nums": [1, 2, 3, 4, 5],
"integer_nums": [-1, -2, 0, 1, 2],
"floating_nums": [1.1, 4.5, 6.43]
}
for key, value in super_dict.items():
print(key, "-", value)
# for key, value in super_list:
# print(key, "-", value)
if __name__ == "__main__":
run()
|
23ead3ddd7505cecc2cef56fd2e793407481e32d | AnshulPatni/CMPE255 | /Activity-classification-1.py | 10,622 | 3.578125 | 4 |
# coding: utf-8
# # kNN Classification using k-mer frequency representation of text
#
# In this project, we will create a program to transform text into vectors using a slightly different technique than previously learned, and then perform kNN based classification on the resulting vectors. We will be using the badges UCI dataset (https://archive.ics.uci.edu/ml/machine-learning-databases/badges/badges.data), which contains names of some conference attendees along with a "+" or "-" class for each name. We will first make the text lowercase and separate the class from the badge name for each object, e.g., "+ Naoki Abe" should be turned into the object "naoki abe" with class "+". We will keep track of the original name ("Naoki Abe") associated with the vector.
#
# Our program will have two input parameters, c and k. Given the input parameter c, for each name, it will construct a vector of c-mer terms (usually called k-mers, but I am calling them c-mers since the input variable k is being used for kNN) of the required c length, by enumerating all subsequences of length c within the name. For example, if c=3, “naoki abe” becomes < “nao”, “aok”, “oki”, “ki “, “i a”, “ ab”, “abe” >. Finally, we will use the same technique we learned for word-based terms to construct sparse term-frequency vectors for each of the objects.
#
# Using the constructed vectors and their associated classes, given the input parameter k, we will construct a program that should perform kNN based classification using cosine similarity and 10-fold cross-validation and report the average classification accuracy among all tests. The class of the test sample should be chosen by majority vote, with ties broken in favor of the class with the highest average similarity. In the rare case that the test sample does not have any neighbors (no features in common with any training samples), we will assign a predicted class label by drawing a random value from a uniform distribution over [0,1) and classifying the test sample as “+” if the value is greater than 0.5 and “-“ otherwise.
#
# In[1]:
import numpy as np
import pandas as pd
import scipy.sparse as sp
from numpy.linalg import norm
from collections import Counter, defaultdict
from scipy.sparse import csr_matrix
# The code below reads the badges dataset into the variable `df` and extracts the string data associated with each person in the `vals` variable. Write code to split the strings in vals into their component names and classes. The `names` and `cls` lists should hold those components such that the $i$th person's name will be in `names[i]` and their associated class in `cls[i]`.
# In[2]:
# read in the dataset
df = pd.read_csv(
filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/badges/badges.data',
header=None,
sep=',')
# separate names from classes
vals = df.iloc[:,:].values
vals_list = vals.tolist()
cls = []
names = []
for x in vals_list:
cls.append(x[0].split(' ', 1)[0])
names.append(x[0].split(' ', 1)[1])
### FILL IN THE BLANKS ###
# Write a function that, given a name and a `c-mer` length parameter `c`, will create the list of `c-mers` for the name.
# In[3]:
def cmer(name, c=3):
r""" Given a name and parameter c, return the vector of c-mers associated with the name
"""
name = name.lower()
### FILL IN THE BLANKS ###
v = []
for x in range(0, len(name)-c+1):
v.append(name[x:x+c])
return v
# The following functions will be useful in later tasks. Study them carefully.
# In[4]:
def build_matrix(docs):
r""" Build sparse matrix from a list of documents,
each of which is a list of word/terms in the document.
"""
nrows = len(docs)
idx = {}
tid = 0
nnz = 0
for d in docs:
nnz += len(set(d))
for w in d:
if w not in idx:
idx[w] = tid
tid += 1
ncols = len(idx)
# set up memory
ind = np.zeros(nnz, dtype=np.int)
val = np.zeros(nnz, dtype=np.double)
ptr = np.zeros(nrows+1, dtype=np.int)
i = 0 # document ID / row counter
n = 0 # non-zero counter
# transfer values
for d in docs:
cnt = Counter(d)
keys = list(k for k,_ in cnt.most_common())
l = len(keys)
for j,k in enumerate(keys):
ind[j+n] = idx[k]
val[j+n] = cnt[k]
ptr[i+1] = ptr[i] + l
n += l
i += 1
mat = csr_matrix((val, ind, ptr), shape=(nrows, ncols), dtype=np.double)
mat.sort_indices()
return mat
def csr_info(mat, name="", non_empy=False):
r""" Print out info about this CSR matrix. If non_empy,
report number of non-empty rows and cols as well
"""
if non_empy:
print("%s [nrows %d (%d non-empty), ncols %d (%d non-empty), nnz %d]" % (
name, mat.shape[0],
sum(1 if mat.indptr[i+1] > mat.indptr[i] else 0
for i in range(mat.shape[0])),
mat.shape[1], len(np.unique(mat.indices)),
len(mat.data)))
else:
print( "%s [nrows %d, ncols %d, nnz %d]" % (name,
mat.shape[0], mat.shape[1], len(mat.data)) )
def csr_l2normalize(mat, copy=False, **kargs):
r""" Normalize the rows of a CSR matrix by their L-2 norm.
If copy is True, returns a copy of the normalized matrix.
"""
if copy is True:
mat = mat.copy()
nrows = mat.shape[0]
nnz = mat.nnz
ind, val, ptr = mat.indices, mat.data, mat.indptr
# normalize
for i in range(nrows):
rsum = 0.0
for j in range(ptr[i], ptr[i+1]):
rsum += val[j]**2
if rsum == 0.0:
continue # do not normalize empty rows
rsum = 1.0/np.sqrt(rsum)
for j in range(ptr[i], ptr[i+1]):
val[j] *= rsum
if copy is True:
return mat
def namesToMatrix(names, c):
docs = [cmer(n, c) for n in names]
return build_matrix(docs)
# Compare the sparse matrix statistics (via `csr_info`) for c-mer representations of the names given $c\in\{1,2,3\}$.
# In[12]:
for c in range(1, 4):
mat = namesToMatrix(names, c)
csr_info(mat)
# We'll now define a function to search for the top-$k$ neighbors for a given name (one of the objects the dataset), where proximity is computed via cosine similarity.
# In[13]:
def findNeighborsForName(name, c=1, k=1):
# first, find the document for the given name
id = -1
for i in range(len(names)):
if names[i] == name:
id = i
break
if id == -1:
print("Name %s not found." % name)
return []
# now, compute similarities of name's vector against all other name vectors
mat = namesToMatrix(names, c)
csr_l2normalize(mat)
x = mat[id,:]
dots = x.dot(mat.T)
dots[0,id] = -1 # invalidate self-similarity
sims = list(zip(dots.indices, dots.data))
sims.sort(key=lambda x: x[1], reverse=True)
return [names[s[0]] for s in sims[:k] if s[1] > 0 ]
# Let c=2 and k=5. Which are the closest neighbors for “Michael Kearns”, in decreasing order of similarity?
# In[14]:
findNeighborsForName("Michael Kearns", c=2, k=5)
# Finally, we'll define a couple functions to perform $d$-fold cross-validation, defaulting to $d=10$. Double-check the code for errors. What does the line
# ```python
# tc = Counter(clstr[s[0]] for s in sims[:k]).most_common(2)
# ```
# do?
# In[15]:
def splitData(mat, cls, fold=1, d=10):
r""" Split the matrix and class info into train and test data using d-fold hold-out
"""
n = mat.shape[0]
r = int(np.ceil(n*1.0/d))
mattr = []
clstr = []
# split mat and cls into d folds
for f in range(d):
if f+1 != fold:
mattr.append( mat[f*r: min((f+1)*r, n)] )
clstr.extend( cls[f*r: min((f+1)*r, n)] )
# join all fold matrices that are not the test matrix
train = sp.vstack(mattr, format='csr')
# extract the test matrix and class values associated with the test rows
test = mat[(fold-1)*r: min(fold*r, n), :]
clste = cls[(fold-1)*r: min(fold*r, n)]
return train, clstr, test, clste
def classifyNames(names, cls, c=3, k=3, d=10):
r""" Classify names using c-mer frequency vector representations of the names and kNN classification with
cosine similarity and 10-fold cross validation
"""
docs = [cmer(n, c) for n in names]
mat = build_matrix(docs)
# since we're using cosine similarity, normalize the vectors
csr_l2normalize(mat)
def classify(x, train, clstr):
r""" Classify vector x using kNN and majority vote rule given training data and associated classes
"""
# find nearest neighbors for x
dots = x.dot(train.T)
sims = list(zip(dots.indices, dots.data))
if len(sims) == 0:
# could not find any neighbors
return '+' if np.random.rand() > 0.5 else '-'
sims.sort(key=lambda x: x[1], reverse=True)
tc = Counter(clstr[s[0]] for s in sims[:k]).most_common(2)
if len(tc) < 2 or tc[0][1] > tc[1][1]:
# majority vote
return tc[0][0]
# tie break
tc = defaultdict(float)
for s in sims[:k]:
tc[clstr[s[0]]] += s[1]
return sorted(tc.items(), key=lambda x: x[1], reverse=True)[0][0]
macc = 0.0
for f in range(d):
# split data into training and testing
train, clstr, test, clste = splitData(mat, cls, f+1, d)
# predict the class of each test sample
clspr = [ classify(test[i,:], train, clstr) for i in range(test.shape[0]) ]
# compute the accuracy of the prediction
acc = 0.0
for i in range(len(clste)):
if clste[i] == clspr[i]:
acc += 1
acc /= len(clste)
macc += acc
return macc/d
# Given $c \in \{1,\ldots,4\}$ and $k \in \{1,\ldots,6\}$, which meta-parameters result in the highest accuracy?
# In[28]:
c = [1, 2, 3, 4]
k = [1, 2, 3, 4, 5, 6]
list_accuracy = []
for x in range(0, len(c)):
for y in range(0, len(k)):
temp = classifyNames(names, cls, c[x], k[y], d=10)
if(list_accuracy):
if(temp > max(list_accuracy)):
c_max = c[x]
k_max = k[y]
list_accuracy.append(temp)
print(list_accuracy)
print("\n")
print("Highest accuracy is " + str(max(list_accuracy)) + " for c = " + str(c_max) + " and k = " + str(k_max))
|
b0d01c99a84369fd367d3116a6b4f978b20851d6 | cdew888/Documents | /Average rainfall.py | 327 | 4.03125 | 4 | #Corey Dew
#cs21
#question 5
total = 0
n = int(input("Enter number of years: "))
for x in range(1, n + 1):
print("for year" ,x,)
for months in range(1,13):
rainfall = float(input("Enter rainfall amount for month in inches: "))
total += rainfall
print(total)
print("average rainfall: ",total / (12 * n))
|
c134eb7a7374a36f8bfc00605f59f69c14bbddc2 | cdew888/Documents | /Test Average and Grade.py | 1,298 | 4 | 4 | #Corey Dew
#cs21
#chp.5 question 15
def main():
score1 = float(input("Enter score 1: "))
score2 = float(input("Enter score 2: "))
score3 = float(input("Enter score 3: "))
score4 = float(input("Enter score 4: "))
score5 = float(input("Enter score 5: "))
average = calc_average(score1, score2, score3, score4, score5)
print("score\t\tnumeric grade\tletter grade")
print("-------------------------------------------")
print("score 1:\t\t", score1, "\t\t", determine_grade(score1))
print("score 2:\t\t", score2, "\t\t", determine_grade(score2))
print("score 3:\t\t", score3, "\t\t", determine_grade(score3))
print("score 4:\t\t", score4, "\t\t", determine_grade(score4))
print("score 5:\t\t", score5, "\t\t", determine_grade(score5))
print("------------------------------------------------------")
print("Average score:\t", average, "\t\t", determine_grade(average))
def calc_average(s1, s2, s3, s4, s5):
return (s1 + s2 + s3 +s4 + s5) / 5.0
def determine_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
main()
|
f70cc10b2c5b38a1e8efb4b2aeb92eb8e4ab72d5 | cdew888/Documents | /paint_job.py | 586 | 3.875 | 4 | #Corey Dew
#cs21
#exercise 8
def main():
wall_space = int(input("Enter wall space in square feet: "))
paint_price = int(input("Enter paint price per gallon: "))
paint_gallon = int(input("Gallons of paint: "))
labor_hours = paint_gallon * 8
paint_charges = paint_price * paint_gallon
print("Paint charges: $", format(paint_charges, '.2f'))
labor_charges = paint_gallon * labor_hours
print("Labor charges: $", format(labor126_charges, '.2f'))
total_cost = paint_charges + labor_charges
print("Total cost: $", format(total_cost, '.2f'))
main()
|
744ebbfbc67fb3e79d08e00a6e6d0ff2535d40e7 | cdew888/Documents | /driver_test.py | 2,212 | 3.734375 | 4 | #Corey Dew
#cs21
#Exercise 7
def main():
tot_score = 0
tot_correct = 0
tot_wrong = 0
wrong_list = []
try:
answer_sheet = ['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']
student_answers = open("student_solution.txt", 'r')
student_answer_list = []
wrong_list = []
for line in student_answers:
line = line.rstrip("\n")
student_answer_list.append(line)
print("Your answer sheet: ", student_answer_list)
for i in range(len(answer_sheet)):
if answer_sheet[i] == student_answer_list[i]:
tot_correct += 1
else:
tot_wrong += 1
wrong_list.append(i + 1)
if tot_correct >= 15:
print("You have passed the test.")
else:
print("You have failed the test.")
print("You have", tot_correct, "questions correct")
print("You have", tot_wrong, "questions correct")
print("These are the questions you have wrong: ", wrong_list)
except:
print()
##
##
## for line in student_answers:
## line = student_answers.rstrip("\n")
## student_answers.append(line)
##
## while tot_score < len(answer_sheet):
## if answer_sheet[tot_score] == student_answers:
## tot_correct += 1
## tot_score += 1
## else:
## tot_wrong += 1
## wrong_list.append(tot_score)
## tot_score += 1
##
## if tot_score >= 15:
## print("You have passed the test")
## print("You have", tot_correct, "correct answers")
## print("You have", tot_wrong, "wrong answers")
## else:
## print("You have failed the test")
## print("You have", tot_correct, "correct answers")
## print("You have", tot_wrong, "wrong answers")
##
## student_answers.close()
## except IOError:
## print("Error: File does not exist")
##
main()
|
8c3ac2c382b67088973a4f8eb276bfebe63068e6 | cdew888/Documents | /baseball2.py | 1,652 | 3.6875 | 4 | #Corey Dew
#cs21
#Baseball question
#Global constant for the base year
BASE_YEAR = 1903
SKIP_YEAR1 = 1904
SKIP_YEAR2 = 1994
def main():
#Local dictionary variables
year_dict = {}
count_dict = {}
#Open the file for reading
input_file = open('WorldSeriesWinners.txt', 'r')
#Read all the lines in the file into a list
winners = input_file.readlines()
#Fill the dictionaries with the team information.
for i in range(len(winners)):
team = winners[i].rstrip('\n')
#Figure out in which year the team won
#(take into account skipped years)
year = BASE_YEAR + i
#print(year,end=' ')
if year >= SKIP_YEAR1:
year += 1
if year >= SKIP_YEAR2:
year += 1
#print(year)
# Add information to year dictionary
year_dict[str(year)] = team
#Update counting dictionary
if team in count_dict:
count_dict[team] += 1
else:
count_dict[team] = 1
#Recieve user input
year = input("Enter a year in the range 1903-2009: ")
#print results
if year == '1904' or year == '1994':
print("The world series wasn't played in the year", year)
elif year < '1903' or year > '2009':
print("The data for the year", year, "is not included in out database.")
else:
winner = year_dict[year]
wins = count_dict[winner]
print("The team that won the world series in ", year, "is the ", winner, '.', sep='')
print("They won the world series", wins, "times.")
#Call the main function.
main()
|
71ffb03026b7ab5725616862d8b0818c1c099e79 | cdew888/Documents | /temps.py | 1,924 | 3.703125 | 4 | #Corey Dew
#cs21
#Question 4 on pg 562
import tkinter
class MyGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.left_frame = tkinter.Frame(self.main_window)
self.mid_frame = tkinter.Frame(self.main_window)
self.right_frame = tkinter.Frame(self.main_window)
self.label1 = tkinter.Label(self.left_frame, \
text="Enter the Celsius temperature: ")
self.celsius_entry = tkinter.Entry(self.left_frame, \
width=10)
self.label2 = tkinter.Label(self.mid_frame, \
text="Fahrenheit temperature: ")
self.convert_button = tkinter.Button(self.right_frame, \
text="Convert to Fahrenheit", \
command=self.convert)
self.quit_button = tkinter.Button(self.right_frame, \
text="Quit", \
command=self.main_window.destroy)
self.label1.pack(side='top')
self.label2.pack(side='top')
self.celsius_entry.pack(side='bottom')
self.value = tkinter.StringVar()
self.faren_heit_label = tkinter.Label(self.mid_frame, \
textvariable=self.value)
self.faren_heit_label.pack(side='bottom')
self.left_frame.pack(side='left')
self.mid_frame.pack(side='left')
self.right_frame.pack(side='left')
self.convert_button.pack(side='top')
self.quit_button.pack(side='bottom')
tkinter.mainloop()
def convert(self):
try:
c = float(self.celsius_entry.get())
f = (9 / 5) * c + 32
self.value.set(format(f,'.2f'))
except:
self.value.set("Invalid input")
my_gui = MyGUI()
|
40db8a974a3ce0c6592897f13469565275f98439 | mariomanalu/singular-value-decomposition | /svd-test.py | 1,376 | 3.609375 | 4 | import os
import numpy as np
from PIL import Image
from svd import svd
import matplotlib.pyplot as plt
#%matplotlib inline
# Test file for image reduction
#Load image of Waldo the dog
path = 'WaldoasWaldo.jpg'
img = Image.open(path)
s = float(os.path.getsize(path))/1000
#Print the size of the image
print("Size(dimension): ",img.size)
#plt.title("Original Image (%0.2f Kb):" %s)
#Show the image
#plt.imshow(img)
#Convert the image into matrix
imggray = img.convert('LA')
imgmat = np.array( list(imggray.getdata(band = 0)), float)
imgmat.shape = (imggray.size[1], imggray.size[0])
imgmat = np.matrix(imgmat)
plt.figure()
#plt.imshow(imgmat, cmap = 'gray')
#plt.title("Image after converting it into the Grayscale pattern")
#plt.show()
print("After compression: ")
#Execute the Singular Value Decomposition process
U, S, Vt = np.linalg.svd(imgmat)
#NOTE: One can change the numberOfSingularValues as one wish. Greater number means greater quality.
numberOfSingularValues = 5
cmpimg = np.matrix(U[:, :numberOfSingularValues]) * np.diag(S[:numberOfSingularValues]) * np.matrix(Vt[:numberOfSingularValues,:])
plt.imshow(cmpimg, cmap = 'gray')
plt.show()
result = Image.fromarray((cmpimg ).astype(np.uint8))
imgmat = np.array( list(img.getdata(band = 0)), float)
imgmat.shape = (img.size[1], img.size[0])
imgmat = np.matrix(imgmat)
plt.figure()
plt.imshow(imgmat)
plt.show()
|
62d58103b04775afc2075d0cb84721ebc50dff59 | rohezal/buildings | /converter.py | 1,139 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 00:06:57 2020
@author: rohezal
"""
import csv
import sys
number_of_arguments = len(sys.argv)
if(number_of_arguments == 2):
filename = sys.argv[1]
else:
print("usage: converter.py name_of_the_file.csv. Using now converted_BRICS.csv as a default file")
filename = 'BRICS_orignal_.csv'
outfile = open('converted_'+filename, 'w', newline="")
csvwriter = csv.writer(outfile )
with open(filename, newline="", encoding='ISO-8859-1') as csv_file_brics:
csv_reader_brics = csv.reader(csv_file_brics, delimiter=';')
for row in csv_reader_brics:
newrow = []
if(len(row) > 0):
if((row[0][0]).isnumeric()):
for element in row:
if (element == "" or element == "MV"):
element="NaN"
elif(":" not in element):
try:
element = float(element.replace(',', '.'))
except Exception as e:
print("Element: " + element)
print(e)
sys.exit(1)
else:
element = "\"" + element + "\""
newrow.append(element)
if(len(newrow) > 0):
csvwriter.writerow(newrow)
outfile.close
|
568ff4916ba0f33b5d07db164aad2caa0f74cb2a | JediChou/Jedi-Py3Promming | /Piy0102/Piy010202_Ref1.py | 485 | 3.578125 | 4 | # coding: utf-8
if __name__ == '__main__':
"""演示对象引用操作: 赋值"""
# 初始化
x = "blue"
y = "red"
z = x
# 步骤1
print("step 1: initialize")
print("x", x)
print("y", y)
print("z", z)
# 步骤2
z = y
print("step 2: z = y")
print("x", x)
print("y", y)
print("z", z)
# 步骤3
x = z
print("step 3: x = z")
print("x", x)
print("y", y)
print("z", z)
|
d9116da4e1b3116f73b714ea06e1338b3e001d42 | R-Saxena/Hackerearth | /Practice Problems/Basic Programming/Basics of Input-Output/cipher.py | 741 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 17:20:44 2020
@author: rishabhsaxena01
"""
small = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
cap = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
num = ['0', '1', '2', '3','4','5','6','7','8','9']
# Write your code here
text = input()
ans = ''
number = int(input())
for i in text:
if i in cap:
ans += cap[(cap.index(i)+number)%26]
elif i in small:
ans += small[(small.index(i)+number)%26]
elif i in num:
ans += num[(num.index(i)+number)%10]
else:
ans+=i
print(ans) |
643a5249e39344f8b47d65d96c0ee1e2d8af2bbd | R-Saxena/Hackerearth | /Practice Problems/Basic Programming/Basics of Input-Output/seven segment.py | 520 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 9 17:21:55 2020
@author: rishabhsaxena01
"""
matchsticks = [6,2,5,5,4,5,6,3,7,6]
def get_machis(x):
su = 0
for i in x:
su+=matchsticks[int(i)]
return su
# Write your code here
for _ in range(int(input())):
x = input()
machis = get_machis(x)
no = ''
if machis%2==0:
for i in range(int(machis/2)):
no += '1'
else:
no+='7'
for i in range(int(machis/2-1)):
no += '1'
print(no) |
f3358fdeb73065519eafe11fd2755677ddaa5ba3 | R-Saxena/Hackerearth | /Practice Problems/Basic Programming/Basics of Input-Output/Motu_patlu.py | 301 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 8 06:48:11 2020
@author: rishabhsaxena01
"""
n = int(input())
i=1
while True:
if i >= n:
print('Patlu')
break
else:
n=n-i
if 2*i >= n:
print('Motu')
break
else:
n=n-2*i
i+=1 |
dc7d32b8b45e63f775fa3641108037e4d240641a | thehellz/Programming | /Py/sum.py | 124 | 4.125 | 4 | number = input("Please eneter a number: ")
sum = 0
for i in range(1, number+1):
sum = sum + i
print 'The sum is', sum
|
9550275c4642ff6209cd2261f06d215b34740c48 | huzhiwen/Graybar_Jobsite_Automation | /lib/notification.py | 1,008 | 3.53125 | 4 | #This code sends the email notification whenever sendmail() function is called
import smtplib
from lib.weight import getWeight
def sendmail(product, jobsite_no):
content = "Hi there, \n"
#content += getWeight(product)
content =content + product + " is running below threshold at jobsite no. " + str(jobsite_no)
#content = "hello"
mail = smtplib.SMTP('smtp.gmail.com', port = 587) #Set up the smtp mail server port
mail.ehlo() #Identify yourself to the server
mail.starttls() #Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted
mail.login('autonotif2017@gmail.com', 'ilab2017') #Login with your email id and password
mail.sendmail('autonotif2017@gmail.com' , 'autonotif2017@gmail.com', content) #This sends the mail. First parameter is from, second is to, and third is the content of the mail
mail.close() #Close the server
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.