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 |
|---|---|---|---|---|---|---|
4b7dbbf640d118514fa306ca39a5ee336852aa05 | francoischalifour/ju-python-labs | /lab9/exercises.py | 1,777 | 4.25 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 9 - Functional Programming
# François Chalifour
from functools import reduce
def product_between(a=0, b=0):
"""Returns the product of the integers between these two numbers"""
return reduce(lambda a, b: a * b, range(a, b + 1), 1)
def sum_of_numbers(numbers):
"""Returns the sum of all the numbers in the list"""
return reduce(lambda a, b: a + b, numbers, 0)
def is_in_list(x, numbers):
"""Returns True if the list contains the number, otherwise False"""
return any(filter(lambda n: n == x, numbers))
def count(numbers, x):
"""Returns the number of time the number occurs in the list"""
return len(filter(lambda n: n == x, numbers))
def test(got, expected):
"""Prints the actual result and the expected"""
prefix = '[OK]' if got == expected else '[X]'
print('{:5} got: {!r}'.format(prefix, got))
print(' expected: {!r}'.format(expected))
def main():
"""Tests all the functions"""
print('''
======================
LAB 9
======================
''')
print('1. Multiplying values')
test(product_between(0, 1), 0)
test(product_between(1, 3), 6)
test(product_between(10, 10), 10)
test(product_between(5, 7), 210)
print('\n2. Summarizing numbers in lists')
test(sum_of_numbers([]), 0)
test(sum_of_numbers([1, 1, 1]), 3)
test(sum_of_numbers([3, 1, 2]), 6)
print('\n3. Searching for a value in a list')
test(is_in_list(1, []), False)
test(is_in_list(3, [1, 2, 3, 4, 5]), True)
test(is_in_list(7, [1, 2, 1, 2]), False)
print('\n4. Counting elements in lists')
test(count([], 4), 0)
test(count([1, 2, 3, 4, 5], 3), 1)
test(count([1, 1, 1], 1), 3)
if __name__ == '__main__':
main()
|
8a8d59fe9276270dada61e63ac8037f0dc580a2c | francoischalifour/ju-python-labs | /lab4/five-in-a-row/five_in_a_row.py | 5,086 | 4.21875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Five in a row
# François Chalifour
def print_game(game):
"""
Prints the game to the console.
"""
print(' y')
y = game['height'] - 1
while 0 <= y:
print('{}|'.format(y), end='')
for x in range(game['width']):
print(get_cell_value(game, x, y), end='')
print()
y -= 1
print('-+', end='')
for x in range(game['width']):
print('-', end='')
print('x')
print(' |', end='')
for x in range(game['width']):
print(x, end='')
print(' ')
def get_cell_value(game, x, y):
"""
Returns 'X' if a cross has been placed in the cell with the given
coordinates.
Returns 'O' if a circle has been placed in the cell with the given
coordinates.
Returns ' ' otherwise.
"""
moves = game.get('moves')
for move in moves:
if move.get('x') == x and move.get('y') == y:
return move.get('player')
return ' '
def make_move(game, x, y, player):
"""
Adds a new move to the game with the information in the parameters.
"""
new_move = {'x': x, 'y': y, 'player': player}
game.get('moves').append(new_move)
def does_cell_exist(game, x, y):
"""
Returns True if the game contains a cell with the given coordinates.
Returns False otherwise.
"""
return 0 <= x and x < game.get('width') and 0 <= y and y < game.get('height')
def is_cell_free(game, x, y):
"""
Returns True if the cell at the given coordinates doesn't contain a cross
or a circle.
Returns False otherwise.
"""
moves = game.get('moves')
for move in moves:
if move.get('x') == x and move.get('y') == y:
return False
return True
def get_next_players_turn(game):
"""
Returns 'X' if a cross should be placed on the board next.
Returns 'O' if a circle should be placed on the board next.
"""
if len(game.get('moves')) == 0: return 'X'
last_player = game.get('moves')[-1].get('player')
return 'X' if last_player == 'O' else 'O'
def has_won_horizontal(game):
"""
Returns 'X' if 5 crosses in a row is found in the game.
Returns 'O' if 5 circles in a row is found in the game.
Returns None otherwise.
"""
for y in range(game.get('height')):
for x in range(game.get('width') - 4):
player = get_cell_value(game, x, y)
if player != ' ':
is_same_player = True
for dx in range(1, 5):
if get_cell_value(game, x + dx, y) != player:
is_same_player = False
break
if is_same_player:
return player
return None
def has_won_vertical(game):
"""
Returns 'X' if 5 crosses in a row is found in a col of the game.
Returns 'O' if 5 circles in a row is found in a col of the game.
Returns None otherwise.
"""
for x in range(game.get('height')):
for y in range(game.get('width') - 4):
player = get_cell_value(game, x, y)
if player != ' ':
is_same_player = True
for dy in range(1, 5):
if get_cell_value(game, x, y + dy) != player:
is_same_player = False
break
if is_same_player:
return player
return None
def has_won_diagonal(game):
"""
Returns 'X' if 5 crosses in a row is found in a diagonal of the game.
Returns 'O' if 5 circles in a row is found in a diagonal of the game.
Returns None otherwise.
"""
def get_diagonal(m, x, y, d):
return [ m[(x + i - 1) % len(m)][(y + d * i - 1) % len(m[0])] for i in range(len(m)) ]
moves = game.get('moves')
board = [ [' ' for x in range(game.get('width'))] for x in range(game.get('height')) ]
# Fill the game board
for move in moves:
board[move.get('x')][move.get('y')] = move.get('player')
# Fill the diagonal board
diagonals = [ get_diagonal(board, i, 1, 1) for i in range(1, game.get('width') + 1) ]
diagonals_inversed = [ get_diagonal(board, 1, i, -1) for i in range(1, game.get('width') + 1) ]
for diagonal in diagonals:
last_player = None
count = 1
for player in diagonal:
if player != ' ' and player == last_player: count += 1
last_player = player
if count >= 5: return player
for diagonal in diagonals_inversed:
last_player = None
count = 1
for player in diagonal:
if player != ' ' and player == last_player: count += 1
last_player = player
if count >= 5: return player
return None
def get_winner(game):
"""
Returns 'X' if the X player wins.
Returns 'O' if the O player wins.
Returns None otherwise.
"""
winner = has_won_horizontal(game)
if not winner:
winner = has_won_vertical(game)
if not winner:
winner = has_won_diagonal(game)
return winner
|
ba5bce618d68b7570c397bc50d6f96766b600fd9 | francoischalifour/ju-python-labs | /lab4/exercises.py | 1,024 | 4.1875 | 4 | #!/usr/bin/env python3
# coding: utf-8
# Lab 4 - Dictionaries
# François Chalifour
def sums(numbers):
"""Returns a dictionary where the key "odd" contains the sum of all the odd
integers in the list, the key "even" contains the sum of all the even
integers, and the key "all" contains the sum of all integers"""
sums = {'odd': 0, 'even': 0, 'all': 0}
for x in numbers:
if x % 2 == 0:
sums['even'] += x
else:
sums['odd'] += x
sums['all'] += x
return sums
def test(got, expected):
"""Prints the actual result and the expected"""
prefix = '[OK]' if got == expected else '[X]'
print('{:5} got: {!r}'.format(prefix, got))
print(' expected: {!r}'.format(expected))
def main():
"""Tests all the functions"""
print('''
======================
LAB 4
======================
''')
print('1. Computing sums')
test(sums([1, 2, 3, 4, 5]), {"odd": 9, "even": 6, "all": 15})
if __name__ == '__main__':
main()
|
86c803756a5548226d81b32cbfc0e66b04e4b240 | nano13/tambi | /interpreter/structs.py | 950 | 3.5 | 4 | # -*- coding: utf_8 -*-
class Result:
# category is one of:
# - table
# - list
# - text
# - string
# - error
# (as a string)
category = None
payload = None
metaload = None
# header is a list or None
header = None
header_left = None
# name is a string or None
name = None
error = None
cursorPosition = None
def toString(self):
result = ""
if type(self.payload) == list:
for line in self.payload:
for column in line:
result += str(column)
if type(line) == tuple or type(line) == list:
result += " | "
if type(line) == tuple or type(line) == list:
result = result[:-3]
result += "\n"
result = result.strip()
else:
result = self.payload
return result
|
a81ce65a4df9304e652af161f5a00534b35cc844 | Abuubkar/python | /code_samples/p4_if_with_in.py | 1,501 | 4.25 | 4 | # IF STATEMENT
# Python does not require an else block at the end of an if-elif chain.
# Unlike C++ or Java
cars = ['audi', 'bmw', 'subaru', 'toyota']
if not cars:
print('Empty Car List')
if cars == []:
print('Empty Car List')
for car in cars:
if car == 'bmw':
print(car.upper())
elif cars == []: # this condition wont run as if empty FOR LOOP won't run
print('No car present')
else:
print(car.title())
age_0 = 10
age_1 = 12
if(age_0 > 1 and age_0 < age_1):
print("\nYoung")
if(age_1 > age_0 or age_1 >= 11):
print("Elder")
# Check presence in list
car = 'bmw'
print("\nAudi is presend in cars:- " + str('audi' in cars))
print(car.title()+" is presend in cars:- " + str(car in cars)+"\n")
# Another way
car = 'Suzuki'
if car in cars:
print(car+' is present')
if car not in cars:
print(car+' is not present\n')
# it does not check presence in 'for loop' as output of cars is
# overwritten by for loop
# for car in cars :
# print (car)
# Checking Multiple List
available_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping + ".")
else:
print("Sorry, we don't have " + requested_topping + ".")
print("\nFinished making your pizza!")
|
42a371f596cef5ecf7185254ca45b00fa737ecb4 | Abuubkar/python | /leet_code/week_1/counting_elements/counting_elements.py | 1,744 | 3.953125 | 4 | """
Authors
---------
Primary: Abubakar Khawaja
Description:
----------
Given an integer array arr, count element x such that
x + 1 is also in arr.
If there're duplicates in arr, counts them also.
"""
# Imports
from collections import defaultdict
class Solution:
arr = []
def set_arr(self, arr: [int]):
self.arr = arr.copy()
return len(self.arr)
def countElements(self):
"""
This function takes array of integers and sorts them in descending order.
And initializes dictionary based on element of array to zero if encountered first time,
and then checks if parent key exists in dictionary if so increments by one,
in the dictionary having key as its element
and prints sum of values in dictionary.
"""
# Step 1: Defining dictionary with default value type of int
dic = defaultdict(int)
# Step 2: Traversing list in sorted(Descending) manner
for element in sorted(self.arr, reverse=True):
# Step 3: Initializing dictionary with element of array as key
# When encountered First time
if element not in dic:
dic[element] = 0
# Step 4: Checking if element+1 key is present in dictionary
# If so then adding 1 to element 1 dictionary
if element+1 in dic:
dic[element] += 1
# Step 5: adding all the values in dictionary to get total count of
# values present
# print (sum(dic.values()))
return (sum(dic.values()))
# Providing call to count element with array of integer as parameter
#solution = Solution()
#solution.set_arr([1, 3, 2, 3, 5, 0])
# solution.countElements()
|
b117d36f9a8ce6959fcbea91ffb1878efea633b1 | Abuubkar/python | /leet_code/week_1/anagram/anagram.py | 1,357 | 4.03125 | 4 | """
Authors
----------
Primary: Abubakar Khawaja
Short Description:
----------
This file contains function that will group anagrams together from given array of strings.
"""
from collections import defaultdict
def groupAnagrams(strs: [str]):
"""
This function take array of string and adding new words by using key
made by their individual character in sorted order in form of tuple
"""
# it will contain Tuple as key and List of String as value
sets = defaultdict(list)
# Traversing each Word in String list given
for word in strs:
# Making Tuple to use as key and to use it for ease of saving its other anagrams
# Saving it in dictionary in list where key is characters of word
sets[tuple(sorted(word))].append(word)
# could also use sets[''.join(sorted(word))].append(word) its better
# ''.join(list) != str(list)
# Extract List of anagrams from dictionary
print(sets.values())
return (sets.values())
groupAnagrams(["hos", "boo", "nay", "deb", "wow", "bop", "bob", "brr", "hey", "rye", "eve", "elf", "pup", "bum", "iva", "lyx", "yap", "ugh", "hem", "rod", "aha", "nam", "gap",
"yea", "doc", "pen", "job", "dis", "max", "oho", "jed", "lye", "ram", "pup", "qua", "ugh", "mir", "nap", "deb", "hog", "let", "gym", "bye", "lon", "aft", "eel", "sol", "jab"])
|
bf49e0e95c9efd7a9b08d2421709159ef6e6bbae | lujun94/Name_Your_Own_Price_Simulation | /nyop.py | 4,684 | 3.59375 | 4 | import random
class NYOP:
def __init__(self):
self.profit = 0
#WeightedPick() is cited from
#http://stackoverflow.com/questions/2570690/python-algorithm-to-randomly-select-a-key-based-on-proportionality-weight
def weightedPick(self, d):
r = random.uniform(0, sum(d.itervalues()))
s = 0.0
for k, w in d.iteritems():
s += w
if r < s: return k
return k
def compute(self, consumerList, propertyDict):
for consumer in consumerList:
bidList = consumer.get_sortedBidList()
findADeal = False
for utility, star in bidList:
#print(consumer.id, star)
visited = []
#get all the qualified properties
qualifiedProperty = propertyDict[star]
if len(qualifiedProperty) == 0:
continue
while True:
firstRoundPro = random.choice(qualifiedProperty)
if firstRoundPro.availability > 0:
break
else:
visited.append(firstRoundPro)
if len(visited) == len(qualifiedProperty):
break
if len(visited) == len(qualifiedProperty):
continue
firstRoundProPrice = firstRoundPro.get_priceList()
#if there is a property price below consumer bid price
#pick the highest price below consumer bid price
if min(firstRoundProPrice) < consumer.bidDict[star]:
findPrice = False
for price in firstRoundProPrice:
if price < consumer.bidDict[star]:
findPrice = price
break
#transation occurs
firstRoundPro.transcation_occur(findPrice)
consumer.transcation_occur(star, consumer.bidDict[star])
self.profit += consumer.bidDict[star] - findPrice
findADeal = True
#break the for utility, star in bidList when find a deal
break
else:
firstRoundPro.firstRound_denial()
#remove the first round property from the list
visited.append(firstRoundPro)
#keep doing second Round if matches not found
while len(visited) < len(qualifiedProperty):
#Randomly select one based on their past success rate
dictWithWeight = {}
for p in qualifiedProperty:
if p not in visited:
if p.availability > 0:
dictWithWeight[p] = p.get_successRate()*100
else:
visited.append(p)
if dictWithWeight == {}:
continue
pickedPro = self.weightedPick(dictWithWeight)
pickedProPrice = pickedPro.get_priceList()
#if there is a property price below consumer bid price
#pick the highest price below consumer bid price
if min(pickedProPrice) < consumer.bidDict[star]:
findPrice = False
for price in pickedProPrice:
if price < consumer.bidDict[star]:
findPrice = price
break
#transation occurs
pickedPro.transcation_occur(findPrice)
consumer.transcation_occur(star,
consumer.bidDict[star])
self.profit += consumer.bidDict[star] - findPrice
findADeal = True
break
else:
visited.append(pickedPro)
#break the for utility, star in bidList when find a deal
if findADeal == True:
break
|
e20320e6e6486193eac99150b8501fed599cdf3e | IHautaI/game-of-sticks | /hard_mode.py | 788 | 3.53125 | 4 | from sticks import Computer
import random
proto = {}
end = [0 for _ in range(101)]
for i in range(101):
proto[i] = [1, 2, 3]
class HardComputer(Computer):
def __init__(self, name='Megatron'):
super().__init__(name)
self.start_hats = proto
self.end_hats = end
def reset(self):
for i in range(101):
self.end_hats[i] = 0
def turn(self, sticks):
num = random.choice(self.start_hats[sticks])
while not 1 <= num <= 3 or not sticks - num >= 0:
num = random.choice(self.start_hats[sticks])
self.end_hats[sticks] = num
return num
def finish(self):
for indx, val in enumerate(self.end_hats):
if val is not 0:
self.start_hats[indx].append(val)
|
e5bcd3a8455d4e189132665021f26e221155addd | maiduydung/Algorithm | /M_valid_sudoku.py | 833 | 3.84375 | 4 | # https://leetcode.com/problems/valid-sudoku/
# Each row must contain the digits 1-9 without repetition.
# Each column must contain the digits 1-9 without repetition.
# Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
check = set()
for i in range(9):
for j in range(9):
current = board[i][j]
if current != ".":
if (i,current) in check or (current,j) in check or (i/3,j/3,current) in check:
return False
check.add((i,current))
check.add((current,j))
check.add((i/3,j/3,current))
print(check)
return True |
f0c35498afbb6364b93c260ddea75e15ce4b8264 | maiduydung/Algorithm | /Array - String/isPalindrome.py | 394 | 3.9375 | 4 | import string
#two pointer approach
def isPalindrome(s):
s = s.lower()
s = s.replace(" ", "")
s = s.translate(str.maketrans('', '', string.punctuation))
end = len(s)-1
for start in range(len(s)//2):
if(s[start] != s[end]):
return False
end = end - 1
print(start, end)
return True
print (isPalindrome('A man, a plan, a canal: Panama')) |
e37c122f96ffabe7349ca690a11bac98a7898b7e | maiduydung/Algorithm | /Array - String/Tribonacci.py | 391 | 3.765625 | 4 | #https://leetcode.com/problems/n-th-tribonacci-number/
#using dynamic programming
class Solution:
def tribonacci(self, n: int) -> int:
if(n==0): return 0
elif(n==1) or (n==2): return 1
arr = [0]*(n+1)
arr[0] = 0
arr[1] = 1
arr[2] = 1
for i in range(3, n+1):
arr[i] = arr[i-3] + arr[i-2] + arr[i-1]
return arr[n] |
0e3213a15f8f4f2a7f9d1d03fa9e9d0f1d886c1a | maiduydung/Algorithm | /Network Flow/find_augmentpath.py | 743 | 3.5 | 4 | #Maximum flow problem
#if there is augment path, flow can be increased
import networkx as nx
import queue
N = nx.read_weighted_edgelist('ff.edgelist', nodetype = int)
def find_augmentpath(G, s, t): #graph, source, sink
P = [s] * nx.number_of_nodes(G)
visited = set()
stack = queue.LifoQueue()
stack.put(s)
while(not stack.empty()):
v = stack.get() #pop stack
if v == t:
return (P, True)
if not v in visited:
stack.put(v)
for w in G.neighbors(v):
if (not w in visited) and (G.edges[v,w]['weight'] > 0):
stack.put(w)
P[w] = v # previous node of w is v
return (P, False)
print(find_augmentpath(N, 0, 5)) |
098bc9cec885d3f67a8e6d972af59bf4bd1f4dc9 | thiekAR/Prog_VR | /directo_01/assigment_python_02.py | 878 | 3.859375 | 4 | # ex. 8.7
def make_album(artist_name, title_name, tracks = 0):
if tracks != 0:
return {'artist': artist_name, 'title': title_name, 'tracks': tracks}
return {'artist': artist_name, 'title': title_name}
print(make_album('Bob', 'album1', 9))
print(make_album('Jack', 'album2', 1))
print(make_album('John', 'album3', 4))
print(make_album('Peter', 'album4', 14))
# ex. 8.8
def make_album(artist_name, title_name, tracks = 0):
if tracks != 0:
return {'artist': artist_name, 'title': title_name, 'tracks': tracks}
return {'artist': artist_name, 'title': title_name}
while True:
print('Enter "q" any time to quit')
artist_name = input('Enter the of the artiste: ')
if artist_name == 'q':
break
album = input('Enter the of the album: ')
if album == 'q':
break
print(make_album(artist_name, album)) |
36762d67cf6ce86b5f091e3c6e261fb37f704224 | thiekAR/Prog_VR | /directo_01/C_08/Function2.py | 250 | 3.84375 | 4 | import this
print(this)
def print_separator(width):
for w in range(width):
print("*", end="")
def print_separator_2(width):
print("*" * width)
print("This is line 1")
print_separator(50)
print("\n")
print_separator_2(50)
|
2e68dd629dddfae3f29e44e12783594272c21131 | gacl97/Artificial-Intelligence | /Problem 1/tree.py | 6,891 | 3.59375 | 4 | from node import *
class Tree:
def createNode(self, qnt_m1, qnt_c1, qnt_mb, qnt_cb, qnt_m2, qnt_c2, flag, prev):
return Node(qnt_m1, qnt_c1, qnt_mb, qnt_cb, qnt_m2, qnt_c2, flag, prev)
def compare(self, node1, node2):
if(node1.side1[0] == node2.side1[0] and node1.side1[1] == node2.side1[1] and node1.side2[0] == node2.side2[0] and node1.side2[1] == node2.side2[1] and node1.boat[0] == node2.boat[0] and node1.boat[1] == node2.boat[1]):
return False
else:
return True
def print1(self, currentNode):
if(currentNode == None):
return
self.print1(currentNode.prev)
if (currentNode.prev == None):
print("------------------------------------")
print("Qnt Missionario: ", currentNode.side1[0], "Qnt Canibal: ", currentNode.side1[1])
print("Barco: ")
print("Qnt Missionario: ", currentNode.boat[0], "Qnt Canibal: ", currentNode.boat[1])
print("Destino: ")
print("Qnt Missionario: ", currentNode.side2[0], "Qnt Canibal: ", currentNode.side2[1])
print("------------------------------------")
return
if(not currentNode.flag):
print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<", end = "\n\n")
else:
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", end = "\n\n")
if(currentNode.boat[0] == 1 and currentNode.boat[1] == 1):
print("Embarca 1 missionario e 1 canibal")
elif(currentNode.boat[0] == 0 and currentNode.boat[1] == 2):
print("Embarca 2 canibais")
elif(currentNode.boat[0] == 2 and currentNode.boat[1] == 0):
print("Embarca 2 missionarios")
elif(currentNode.boat[0] == 1 and currentNode.boat[1] == 0):
print("Embarca 1 missionario")
else:
print("Embarca 1 canibal")
print()
print("Qnt Missionario: ", currentNode.side1[0], "Qnt Canibal: ", currentNode.side1[1])
print("Barco: ")
print("Qnt Missionario: ", currentNode.boat[0], "Qnt Canibal: ", currentNode.boat[1])
print("Destino: ")
print("Qnt Missionario: ", currentNode.side2[0], "Qnt Canibal: ", currentNode.side2[1])
print()
def boarding(self, currentNode):
#Embarque do lado esquerdo
if(not currentNode.flag):
mis = currentNode.side1[0] + currentNode.boat[0]
can = currentNode.side1[1] + currentNode.boat[1]
# Mandar 1 canibal e 1 missionario
if (mis >= can and mis >= 1 and can >= 1):
newNode = self.createNode(mis - 1, can - 1, 1, 1, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
#Mandar 2 missionarios
if(mis == 2 or (mis - 2 >= can and mis >= 2)):
newNode = self.createNode(mis - 2, can, 2, 0, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if(self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
#Mandar 2 canibais
if(can >= 2):
newNode = self.createNode(mis, can - 2, 0, 2, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 missionario
if ((mis >= 1 and mis - 1 >= can) or mis == 1):
newNode = self.createNode(mis - 1, can, 1, 0, currentNode.side2[0], currentNode.side2[1],
not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 canibal
if(can >= 1):
newNode = self.createNode(mis, can - 1, 0, 1, currentNode.side2[0], currentNode.side2[1], not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Embarque do lado direito
else:
mis = currentNode.side2[0] + currentNode.boat[0]
can = currentNode.side2[1] + currentNode.boat[1]
# Mandar 1 canibal e 1 missionario
if (can >= 1):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 0, 1, mis, can - 1,
not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 2 missionarios
if (mis == 2 or (mis - 2 >= can and mis >= 2)):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 2, 0, mis - 2, can, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 2 canibais
if (can >= 2):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 0, 2, mis, can - 2, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 missionario
if ((mis >= 1 and mis - 1 >= can) or mis == 1):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 1, 0, mis - 1, can, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
# Mandar 1 canibal
if (mis >= can and mis >= 1 and can >= 1):
newNode = self.createNode(currentNode.side1[0], currentNode.side1[1], 1, 1, mis - 1, can - 1, not currentNode.flag, currentNode)
if (self.compare(newNode, currentNode)):
currentNode.sons.append(newNode)
def generateStates(self, begin):
queue = []
queue.append(begin)
while(len(queue) != 0):
x = queue.pop(0)
#Se chegar num movimento inválido (Mais canibais que missionários)
if(x.flag == False and (x.side1[0] + x.boat[0] < x.side1[1] + x.boat[1] and x.side1[0] + x.boat[0] > 0)):
continue
elif(x.flag == True and (x.side2[0] + x.boat[0] < x.side2[1] + x.boat[1] and x.side2[0] + x.boat[0] > 0)):
continue
if(x.side2[0] + x.boat[0] == 3 and x.side2[1] + x.boat[1] == 3):
self.print1(x)
self.print1(Node(0, 0, 0, 0, 3, 3, False, None))
break
self.boarding(x)
for currentSon in x.sons:
queue.append(currentSon) |
2bfe1d887f9779dff2e87dcae17132899e851175 | gacl97/Artificial-Intelligence | /Problem 2/Graph.py | 3,565 | 3.671875 | 4 | from Node import *
from queue import PriorityQueue
class graph:
colors = [-1, [0,0],[0,1],[0,3],[0,2],[0,1],[0,0],[1,1],[1,2],[1,3],[1,1],[3,3],[2,2],[2,3],[2,2]]
def createNode(self, id1, heuristDist, dist, prevColor):
return Node(id1,heuristDist,dist,prevColor)
def createGraph(self, distances, end, fileAdjList):
graph = []
graph.append([])
# Azul = 0 Amarelo = 1 Verde = 2 Vermelho = 3
for i in range(14):
adjList = []
for j in fileAdjList.readline().split():
adjList.append(self.createNode(int(j),distances[int(j)-1][end-1],distances[i][int(j)-1],""))
graph.append(adjList)
return graph
def printGraph(self):
for i in range(15):
print(i,"-> ", end="")
for j in graph[i]:
print(j.id, " ", end="")
print()
def searchCommonColor(self, prev, current):
for i in self.colors[prev]:
for j in self.colors[current.id]:
if(i == j):
current.prevColor = i
break
def printPath(self,node):
if(node.prevNode.id == node.id):
print("----------- The best way is -----------")
print()
print("Passing by the station ",node.id, "with the cost ", node.dist)
else:
self.printPath(node.prevNode)
if (node.prevColor == 0):
color = "blue"
elif(node.prevColor == 1):
color = "yellow"
elif(node.prevColor == 2):
color = "green"
else:
color = "red"
print("Passing by the station ",node.id, "with the cost ", node.cost, "by the line ", color)
def bestPath(self, begin, end, graph, dist):
visited = [0]*15
queue = PriorityQueue()
count = 0
for i in graph[begin]:
self.searchCommonColor(begin,i)
currentDist = i.dist + i.heuristDist
visited[i.id] = 1
aux = self.createNode(begin,dist[begin-1][end-1],0,"")
aux.savePrevNode(aux)
i.savePrevNode(aux)
i.saveCost(currentDist)
queue.put([currentDist,i.id,begin,count])
count += 1
while(not queue.empty()):
currentNode = queue.get()
visited[currentNode[1]] = 1
if (currentNode[1] == end):
graph[currentNode[2]][currentNode[3]].saveCost(currentNode[0])
self.printPath(graph[currentNode[2]][currentNode[3]])
print("Final cost = ", currentNode[0])
break
count = 0
for node in graph[currentNode[1]]:
if(visited[node.id] == 0):
self.searchCommonColor(currentNode[1],node)
node.savePrevNode(graph[currentNode[2]][currentNode[3]])
if(graph[currentNode[2]][currentNode[3]].prevColor != node.prevColor):
currentDist = currentNode[0] + node.dist + node.heuristDist + 2
else:
currentDist = currentNode[0] + node.dist + node.heuristDist
node.saveCost(currentDist)
queue.put([currentDist,node.id,currentNode[1],count])
count += 1
def readDistances(distances):
dist = []
for i in range(14):
dist.append(list(map(int,distances.readline().split())))
return dist |
b64e7152f33c0f6b4b7b7b600b17d5259f65322b | asiya00/Exercism | /python/anagram/anagram.py | 325 | 3.734375 | 4 | def find_anagrams(word, candidates):
result = []
word = word.lower()
for i in candidates:
candi = i.lower()
if candi!=word and len(candi)==len(word) and word!='tapper':
if set(candi) == set(word):
result.append(i)
else:
continue
return result
|
035e394d57ef25672cced5b26f08d4694efddd07 | TheJust1ce/ML_lab1 | /lab2.py | 1,193 | 3.5625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path = 'data/ex1data2.txt'
data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
data.head()
data.describe()
data = (data - data.mean()) / data.std()
data.head()
data.insert(0, 'Ones', 1)
cols = data.shape[1]
X = data.iloc[:, 0:cols-1]
y = data.iloc[:, cols-1:cols]
X = np.matrix(X.values)
y = np.matrix(y.values)
def computeCost(X, y, theta):
inner = (X * theta - y).T * (X * theta - y)
return inner[0, 0] / (2 * len(X))
def gradientDescent(X, y, theta, alpha, iters):
cost = np.zeros(iters)
for i in range(iters):
cost[i] = computeCost(X, y, theta)
theta = theta - alpha / len(X) * X.T * (X*theta - y)
return theta, cost
alpha = 0.05
iters = 1000
theta = np.array([[0], [0], [0]])
th, c = gradientDescent(X, y, theta, alpha, iters)
th2, c2 = gradientDescent(X, y, theta, 0.01, iters)
th3, c3 = gradientDescent(X, y, theta, 0.001, iters)
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(np.arange(iters), c, 'r', label='Cost')
ax.plot(np.arange(iters), c2, 'g', label='Cost')
ax.plot(np.arange(iters), c3, 'b', label='Cost')
ax.legend(loc=1)
plt.show()
|
383c07aa7a0b5ed08ec2600f0046da8687448c90 | IvanLopezMedina/MapReduce | /shuffler.py | 766 | 3.53125 | 4 | # En aquesta classe processem la llista del map i agrupem les paraules
# Retornem llista paraula : { { paraula: 1 } , {paraula: 1 } }
class Shuffler:
def __init__(self, listMapped):
self.listMapped = listMapped
self.dictionary = {}
def shuffle(self):
# Per cada paraula, si existeis una entrada al diccionari
# La afegim a la llista de paraules d'aquesta entrada
# Sino existeix una entrada, creem una nova i afegim a la llista
for word in self.listMapped:
if self.dictionary.has_key(word[0]):
self.dictionary[word[0]].append(word)
else:
self.dictionary[word[0]] = []
self.dictionary[word[0]].append(word)
return self.dictionary |
b583554675d3ec46b424ac0e808a8281a339de67 | NandanSatheesh/Daily-Coding-Problems | /Codes/2.py | 602 | 4.21875 | 4 | # This problem was asked by Uber.
#
# Given an array of integers,
# return a new array such that each element at index i of the
# new array is the product of all the numbers in the original array
# except the one at i.
#
# For example,
# if our input was [1, 2, 3, 4, 5],
# the expected output would be [120, 60, 40, 30, 24].
# If our input was [3, 2, 1], the expected output would be [2, 3, 6].
def getList(l):
product = 1
for i in l:
product *= i
newlist = [product/i for i in l ]
print(newList)
return newList
l = [1,2,3,4,5]
getList(l)
getList([3,2,1])
|
7b805bc4acdb0409bab9c84388f8fc83f4bfbbed | nincube8/Hydroponic-Automation | /Turn on Feed Pump Feed Plant.py | 1,845 | 3.796875 | 4 | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# init list with pin numbers
#pinList = [7, 11, 13, 15, 19, 21, 29, 31, 33, 35, 37, 40, 38, 36, 32, 22]
pinList = [7, 11, 13, 15, 19, 21, 29, 31, 33, 35, 37, 40, 38, 36, 32, 22]
# loop through pins and set mode and state to 'low'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# time to sleep between operations in the main loop
#
SleepTimeL =60
# main loop
try:
#"Pin #"
#First Value is the Plant Valve Number, Second number is the Feeding Pump
#Valve 3 Is for Feeding Food Plants and drops water into Cheezits bucket to feed.
#Will cycle through to plant valves 1-6 skipping the 3rd valve
#Valve 1
GPIO.output(7, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 1")
time.sleep(SleepTimeL);
GPIO.output(7, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 2
GPIO.output(11, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 2")
time.sleep(SleepTimeL);
GPIO.output(11, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 4
GPIO.output(15, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 4")
time.sleep(SleepTimeL);
GPIO.output(15, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 5
GPIO.output(19, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 5")
time.sleep(SleepTimeL);
GPIO.output(19, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
#Valve 6
GPIO.output(21, GPIO.LOW)
GPIO.output(32, GPIO.LOW)
print ("Feeding Plant Valve 6")
time.sleep(SleepTimeL);
GPIO.output(21, GPIO.HIGH)
GPIO.output(32, GPIO.HIGH)
# Reset GPIO settings
GPIO.cleanup()
print ("End")
# End program cleanly with keyboard
except KeyboardInterrupt:
print ("Quit")
|
9e1d837c4a2f0998e3b1344331ff4ea407de6582 | IamWilliamWang/Leetcode-practice | /2020.8/爱奇艺-2.py | 629 | 3.59375 | 4 | def nextXY(ch: str):
if ch == 'N':
nextStep = (visited[-1][0] - 1, visited[-1][1])
elif ch == 'S':
nextStep = (visited[-1][0] + 1, visited[-1][1])
elif ch == 'E':
nextStep = (visited[-1][0], visited[-1][1] + 1)
elif ch == 'W':
nextStep = (visited[-1][0], visited[-1][1] - 1)
else:
raise ValueError
if nextStep in visited:
return None
return nextStep
path = input().strip()
visited = [(0, 0)]
for selection in path:
nextStep = nextXY(selection)
if not nextStep:
print('True')
exit(0)
visited.append(nextStep)
print('False')
|
9f531639340fbd945ed2ec054629ca12cfb30675 | IamWilliamWang/Leetcode-practice | /2020.6/SpiralOrder.py | 1,476 | 3.53125 | 4 | from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
x, y = 0, 0
restCount = len(matrix) * len(matrix[0])
clockwiseTraversal = []
while restCount and left <= right and top <= bottom:
while restCount and y <= right:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if y == right:
break
y += 1
top += 1
x += 1
while restCount and x <= bottom:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if x == bottom:
break
x += 1
right -= 1
y -= 1
while restCount and y >= left:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if y == left:
break
y -= 1
bottom -= 1
x -= 1
while restCount and x >= top:
clockwiseTraversal.append(matrix[x][y])
restCount -= 1
if x == top:
break
x -= 1
left += 1
y += 1
return clockwiseTraversal
print(Solution().spiralOrder([[1, 2, 3]]))
|
6c6b2f49a7531bbb887a4013e3a31268b5b24d03 | IamWilliamWang/Leetcode-practice | /2020.5/LargestNumber.py | 1,049 | 3.515625 | 4 | from typing import List
from functools import lru_cache
class Solution:
@lru_cache(maxsize=None)
def searchPotentialResult(self, restMoney: int, choicesInt: int) -> None:
if restMoney == 0:
if choicesInt > self.maxResult:
self.maxResult = choicesInt
for i in range(len(self.cost)):
if self.cost[i] == -1:
continue
if restMoney >= self.cost[i]:
choice = int(i + 1)
self.searchPotentialResult(restMoney - self.cost[i], choicesInt * 10 + choice)
def largestNumber(self, cost: List[int], target: int) -> str:
for i in range(len(cost)):
for j in range(0, i):
if cost[j] != -1 and cost[j] == cost[i]:
cost[j] = -1
self.maxResult = -2 ** 31
self.cost = cost
self.searchPotentialResult(target, 0)
return str(self.maxResult if self.maxResult != -2 ** 31 else 0)
print(Solution().largestNumber([70, 84, 55, 63, 74, 44, 27, 76, 34], 659))
|
046ec5426d71fba6f4665d11543b2af0071c4ebf | IamWilliamWang/Leetcode-practice | /2020.4/CanJump.py | 1,301 | 3.609375 | 4 | from functools import lru_cache
class Solution:
def canJump(self, nums: list) -> bool:
if nums == []:
return False
@lru_cache(maxsize=None)
def find(index: int) -> bool:
"""
寻找该位置出发有没有可能到达终点
:param index: 当前位置
:return:
"""
if index >= len(nums):
return False
if index == len(nums) - 1:
return True
for step in range(nums[index], 0, -1):
if find(index + step):
return True
return False
# 先看看每次以最大步伐向前进,有没有跨过终点
i = 0
while nums[i] > 0: # 如果碰到0就跳出
i += nums[i]
if i >= len(nums): # 如果跨过了终点,证明可能有解
return find(0) # 求解
if i == len(nums) - 1: # 如果刚好踩在终点了,完美
return True
return False
print(Solution().canJump(
[1,2,2,6,3,6,1,8,9,4,7,6,5,6,8,2,6,1,3,6,6,6,3,2,4,9,4,5,9,8,2,2,1,6,1,6,2,2,6,1,8,6,8,3,2,8,5,8,0,1,4,8,7,9,0,3,9,4,8,0,2,2,5,5,8,6,3,1,0,2,4,9,8,4,4,2,3,2,2,5,5,9,3,2,8,5,8,9,1,6,2,5,9,9,3,9,7,6,0,7,8,7,8,8,3,5,0]))
|
5a721e63b018a73a7ed2dd8a4cdfd2f3b719af9c | IamWilliamWang/Leetcode-practice | /2020.8/贝壳-最大公约数.py | 6,728 | 3.84375 | 4 | from functools import lru_cache
from itertools import islice
from math import sqrt
class Prime:
"""
获得素数数组的高级实现。支持 in 和 [] 运算符,[]支持切片
"""
def __init__(self):
self._list = [2, 3, 5, 7, 11, 13] # 保存所有现有的素数列表
def __contains__(self, n: int) -> bool:
"""
判断n是否是素数
:param n: 要判断的素数
:return: 是否是素数
"""
if not n % 2: # 偶数只有2是素数
return n == 2
a, b = self.indexOf(n) # 搜索n在素数列表中的位置
return a == b # 如果a b相同,代表这就是n在素数列表中的位置
def __getitem__(self, i):
"""
i为正整数时返回第i个元素;i为slice时返回切片数组(当i.stop=None时只返回迭代器)
:param i: index或者slice
:return: int或list或iterator
"""
if isinstance(i, slice): # 如果i是切片
it = self.range(i.start, i.stop, i.step) # 获得迭代器
if i.stop: # 如果指定了stop,则返回对应的数组
return list(it)
return it # 没指定就直接返回迭代器
else: # 如果n是正整数
self._extendToLen(i + 1) # 拓展list长度直到n
return self._list[i] # 返回第n个元素
def indexOf(self, n: int):
"""
获得数字n位于素数列表的第几个位置,或者哪两个位置之间
:param n: 要搜索的素数
:return: 如果搜到则返回(index, index);搜不到则返回n的大小在哪两个相邻位置之间(from, to)
"""
if n < 2:
return -1, 0
if n > self._list[-1]: # 需要拓展列表
self._extend(n)
import bisect
index = bisect.bisect(self._list, n) # 二分法搜索大于n的最左边位置
if self._list[index - 1] == n:
return index - 1, index - 1
else:
return index - 1, index
def range(self, start=0, stop=None, step=1) -> islice:
"""
获得素数数组的range迭代器
:return: 迭代器
"""
if stop: # 如果有指明stop的话
self._extendToLen(stop + 1) # 拓宽list到stop位置
return islice(self._list, start, stop, step) # 生成切片后的迭代器
return islice(self, start, None, step) # 只有没指定stop时制造迭代器的切片,返回指向n.start位置的迭代器
def primeRange(self, minN: int, maxN: int, step=1):
"""
返回包含[minN, maxN)内所有素数的迭代器
:param minN: 素数最小值
:param maxN: 素数最大值(不包括)
:param step: 遍历的步伐,默认为1
:return: 迭代器
"""
minN = max(2, minN) # 开始值合法化
if minN >= maxN: # 异常参数检查
return
self._extend(maxN) # 拓展list直到包含stop
i = self.indexOf(minN)[1] # 找到startN所在的位置,或者startN可以插入的位置
beginning_i = i
while i < len(self._list): # 防止数组越界(其实不会,因为extend过了,一定是break之前就return)
p = self._list[i] # 获取第i个元素
if p < maxN: # 每次必须小于maxN才能yield
if (i - beginning_i) % step == 0:
yield p
i += 1
else: # 超过范围就跳出
return
def _extend(self, n: int) -> None:
"""
拓展素数列表直到涵盖范围包括数字n就立刻停止
:param n: 将素数列表拓展到哪个数字为止
:return:
"""
if n <= self._list[-1]: # 如果list已经包含,则不需要拓展
return
maxSqrt = int(n ** 0.5) + 1 # 要拓展到的位置
self._extend(maxSqrt) # 如果列表没有拓展到sqrt(n),递归拓展
begin = self._list[-1] + 1 # 从哪里开始搜索
sizer = [i for i in range(begin, n + 1)] # 生成所有数字的数组
for prime in self.primeRange(2, maxSqrt): # 得到[2,maxSqrt)所有的素数
for i in range(-begin % prime, len(sizer), prime):
sizer[i] = 0 # 把所有非素数变为0
self._list += [x for x in sizer if x] # 删去所有的零,剩下的就是素数列表
def _extendToLen(self, listLen: int) -> None:
"""
将素数列表的长度至少拓展到listLen
:param listLen: 至少拓展到多长
:return:
"""
while len(self._list) < listLen: # 每次n*1.5,直到list长度符合要求
self._extend(int(self._list[-1] * 1.5))
prime = Prime()
def _input():
import sys
return sys.stdin.readline()
def get因子Set(number: int) -> set:
yinziList = [1, number]
for i in range(2, int(sqrt(number)) + 1):
if i not in prime: # 因子都是素数
continue
if number % i == 0:
yinziList.append(i)
yinziList.append(number // i)
return set(yinziList)
def main():
N = int(_input().strip())
array = list(map(int, _input().strip().split()))[:N]
if not N:
print(0)
return
array因子 = [get因子Set(num) for num in array]
tmp = array因子[0]
for yinzi in array因子:
tmp.intersection_update(yinzi)
if len(tmp) > 1: # 所有的set有公共区域
print(-1)
return
minDelete = 2 ** 31 - 1
interStack = []
@lru_cache(maxsize=None)
def dp(i: int, deleteCount: int):
nonlocal minDelete
if i >= len(array因子):
if interStack and interStack[-1] == {1}:
minDelete = min(minDelete, deleteCount)
return
stackEmpty = not interStack
interStack.append(array因子[i] if stackEmpty else array因子[i].intersection(interStack[-1]))
dp(i + 1, deleteCount) # 不删除该位置
interStack.pop()
if not stackEmpty:
interStack.append(interStack[-1])
dp(i + 1, deleteCount + 1)
if not stackEmpty:
interStack.pop()
# dp(0, 0)
array因子.sort(key=lambda x:list(x))
count=0
for i in range(len(array因子)-1,0,-1):
if i==0:
continue
yinzi = array因子[i]
if yinzi.issuperset(array因子[i-1]):
count+=1
del array因子[i]
dp(0,0)
minDelete+=count
print(minDelete if minDelete < 2 ** 30 else -1)
if __name__ == '__main__':
for round in range(int(_input().strip())):
main()
|
66d2376ad3932fea1810da8fcc2d4bf1863f31ef | murali-koppula/programming-problems | /python/bttest.py | 1,094 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test simple B-Tree implementation.
node values are provided as arguments.
"""
__author__ = "Murali Koppula"
__license__ = "MIT"
import argparse
from btnode import Node
from btree import BTree
def add(root=None, vals=[]) ->'Node':
# Walk through the tree in a breadth-first fashion to add vals.
#
if not root and vals:
root = Node(vals.pop(0))
q = [root] if root else []
while len(q) > 0:
n = q.pop()
if n.left:
q.insert(0, n.left)
elif vals:
n.left = Node(vals.pop(0))
q.insert(0, n.left)
if n.right:
q.insert(0, n.right)
elif vals:
n.right = Node(vals.pop(0))
q.insert(0, n.right)
return root
parser = argparse.ArgumentParser(description='Make a BTree using given list of values.')
parser.add_argument('vals', metavar='VALS', nargs='+',
help='comma separated values')
args = parser.parse_args()
root = add(vals=args.vals)
btree = BTree(root)
print("'{}'".format(btree))
|
42d12efe04c51bf489a6c252b2815811135e7de6 | 2Gken1029/graduateReserchProgram | /wordFind.py | 1,183 | 3.59375 | 4 | #! python3
# wordFind.py - 単語リストにある単語が文章ファイルにどれほどでてくるか
import os, sys
def wordFind(file_name):
word_file = open('frequentList.txt') # 単語リストを読み込み
word_list = word_file.readlines() # リストに書き込み
word_file.close()
voice_file = open(file_name) # 最初の引数を音声文章ファイルとする
voice_list = voice_file.readlines()
voice_file.close
# リスト内文字列の"\n"を削除
word_list = [s.replace('\n', '') for s in word_list]
voice_list = [s.replace('\n', '') for s in voice_list]
# 音声文章の中に特定の単語が含まれているか
appear_word = {}
for voice in voice_list:
for word in word_list:
if word in voice: # 有無
### print("・" + word + " " + voice) ###
if not word in appear_word: # 初めて特定の単語が含まれていたら記録
appear_word[word] = 1
else: # 再び単語が含まれていたらカウントを1増やす
appear_word[word] = appear_word[word] + 1
return appear_word |
c34644cf434d5bc7942b95f5b66548faa13a606c | 702criticcal/1Day1Commit | /Baekjoon/15815.py | 1,874 | 3.78125 | 4 | # 1차 시도. 런타임 에러.
mathExpression = input()
stack = []
for s in mathExpression:
stack.append(s)
if len(stack) >= 3 and stack[-1] in ['*', '/', '+', '-']:
operator = stack.pop()
num2 = stack.pop()
num1 = stack.pop()
stack.append(str(eval(num1 + operator + num2)))
print(stack[-1])
# 2차 시도. 실패.
mathExpression = input()
stack = []
for s in mathExpression:
if s.isdigit():
stack.append(int(s))
else:
if s == '+':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 + num2)
elif s == '-':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 - num2)
elif s == '*':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 * num2)
elif s == '/':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 / num2)
print(stack[-1])
# 3차 시도. 성공!
# Python의 나눗셈 연산자가 문제였던 것 같다. Python3에서는 정수끼리 나누어도 실수형으로 출력되기 때문!
mathExpression = input()
stack = []
for s in mathExpression:
if s.isdigit():
stack.append(int(s))
else:
if s == '+':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 + num2)
elif s == '-':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 - num2)
elif s == '*':
num2 = stack.pop()
num1 = stack.pop()
stack.append(num1 * num2)
elif s == '/':
num2 = stack.pop()
num1 = stack.pop()
if num1 % num2 == 0:
stack.append(num1 // num2)
else:
stack.append(num1 / num2)
print(stack[-1])
|
abe21d85d69621041f41f2124725c45a2e8e3c52 | 702criticcal/1Day1Commit | /Baekjoon/2941.py | 272 | 3.65625 | 4 | str = input()
str = str.replace("c=","1")
str = str.replace("c-","1")
str = str.replace("dz=","1")
str = str.replace("d-","1")
str = str.replace("lj","1")
str = str.replace("nj","1")
str = str.replace("s=","1")
str = str.replace("z=","1")
count = len(str)
print(count)
|
452845da256217de1bb1cde425dc1103ff25a97b | 702criticcal/1Day1Commit | /Baekjoon/1427.py | 119 | 3.59375 | 4 | n = input()
n_list = sorted(list(map(int, n)))
n_list.reverse()
n_list = list(map(str, n_list))
print(''.join(n_list))
|
905f2b287938bbb3d80cdce951ac736a26b15871 | 702criticcal/1Day1Commit | /Baekjoon/1193.py | 162 | 3.671875 | 4 | x = int(input())
line = 1
while x > line:
x -= line
line += 1
if line % 2 == 0:
print(f'{x}/{line - x + 1}')
else:
print(f'{line - x + 1}/{x}')
|
51f082d3dde89a5467ca199d24e848e3ee3aafe4 | 702criticcal/1Day1Commit | /Baekjoon/1225.py | 376 | 3.6875 | 4 | # 1차 시도. 시간 초과 실패.
A, B = input().split()
result = 0
for a in A:
for b in B:
result += int(a) * int(b)
print(result)
# 2차 시도. 성공. 형변환이 반복문 안에 있는 것이 문제였던 것 같다.
A, B = input().split()
A = list(map(int, A))
B = list(map(int, B))
result = 0
b = sum(B)
for a in A:
result += a * b
print(result)
|
0791b5afa28e707de3ddac9947e2aa0df5ab962f | 702criticcal/1Day1Commit | /Baekjoon/10988.py | 109 | 3.90625 | 4 | S = input()
reversedS = ''.join(list(reversed(list(S))))
if S == reversedS:
print(1)
else:
print(0)
|
deab3ceba37a0c163e0dcfa73c78fcfdd58dc32f | 702criticcal/1Day1Commit | /Baekjoon/14916.py | 158 | 3.84375 | 4 | n = int(input())
if n == 1 or n == 3:
print(-1)
elif (n % 5) % 2 == 0:
print(n // 5 + (n % 5) // 2)
else:
print((n // 5) - 1 + (n % 5 + 5) // 2)
|
adfa64097aeb927cd37d57f18b9570658350cc95 | 702criticcal/1Day1Commit | /Baekjoon/1343.py | 281 | 3.59375 | 4 | board = list(input())
for i in range(len(board)):
if board[i:i + 4] == ['X', 'X', 'X', 'X']:
board[i:i + 4] = ['A', 'A', 'A', 'A']
if board[i:i + 2] == ['X', 'X']:
board[i:i + 2] = ['B', 'B']
if 'X' in board:
print(-1)
else:
print(''.join(board))
|
98eb446e51c509fd9f82721cd874474d7738880d | 702criticcal/1Day1Commit | /Programmers/stringIWanted.py | 275 | 3.5625 | 4 | import string
def solution(strings, n):
answer = []
for j in string.ascii_lowercase:
for i in sorted(strings):
if i[n] == j:
print(i[n])
answer.append(i)
return answer
# print(solution(["sun","bed","car"], 1)) |
bf4e9fe092735101ec7d741d73d40e54d60b9a44 | allysonja/hangman_steps | /3/maingame.py | 855 | 3.53125 | 4 | import random
import pygame
import sys
from pygame import *
pygame.init()
fps = pygame.time.Clock()
# CONSTANTS #
# DIMENSIONS #
WIDTH = 600
HEIGHT = 400
# COLORS #
WHITE = (255, 255, 255)
BLACK = (0 ,0, 0)
# GAME VARIABLES #
word_file = "dictionary.txt"
WORDS = open(word_file).read().splitlines()
word = random.choice(WORDS).upper()[1:-1]
word_display = ""
for char in word:
word_display += "_ "
window = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption('Hangman')
def draw(canvas):
global word, word_display
canvas.fill(WHITE)
# create labels for gameplay #
# word display label #
myfont2 = pygame.font.SysFont(None, 20)
label2 = myfont2.render(word_display, 1, BLACK)
canvas.blit(label2, (WIDTH // 2 - WIDTH // 8, HEIGHT // 2 + HEIGHT // 8))
while True:
draw(window)
pygame.display.update()
fps.tick(60) |
1ef246ae4f95f6727d38c8e55dfbe69cc8ba1385 | susoooo/IFCT06092019C3 | /PedroL/ejercicios/multi/python/ejercicios/4/Respuestas.nonexec.py | 2,155 | 4.09375 | 4 | #1
words = []
n = int(input("palabras a incluir"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
#2
words = []
n = int(input("palabras a incluir:"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
q = input("palabra a contar:")
print(q, "aparece ", words.count(q), "veces")
#3
words = []
n = int(input("palabras a incluir:"))
for i in range(n):
print("palabra ", i, ": ")
word = input()
words += [word]
print(words)
q = input("palabra a reemplazar:")
r = input("palabra de reemplazo:")
while not(q in words):
words[words.index(q)] = r
#4
n1 = int(input("numero de nombres en lista 1:"))
names1 = []
for i in range(n1):
names1 += input("nombre:")
print("lista 1: ", names1)
n2 = int(input("numero de nombres en lista 2:"))
names2 = []
for i in range(n2):
names2 += input("nombre:")
print("lista 2:", names2)
print("eliminando elementos en lista 2 de lista 1")
for i in names1:
for j in names2:
names1.remove(names2)
print("lista 1:", names1)
#5
l = list(range(132, 139, 2))
#6
n1 = int(input("numero de nombres en lista 1:"))
names1 = []
names2 = []
for i in range(n1):
names1 += input("nombre:")
for i in range(n1, 0, -1):
names2 += [names1[i]]
print("lista 1:", names1)
print("lista 2:", names2)
#7
n1 = int(input("numero de nombres en lista 1:"))
names1 = []
for i in range(n1):
names1 += input("nombre:")
print("lista 1: ", names1)
n2 = int(input("numero de nombres en lista 2:"))
names2 = []
for i in range(n2):
names2 += input("nombre:")
print("lista 2:", names2)
res1 = []
res2 = []
res3 = []
for i in names1:
if i in names2:
res3 += i
else:
res1 += i
for i in names2:
if not(i in names1):
res2 += i
print("res1:", res1)
print("res2:", res2)
print("res3:", res3)
#8
x = int(input("numero hasta donde buscar primos:"))
p = []
for i in range(x + 1, 1, -1):
if (i % 2) and (i % 3) and (i % 5) and (i % 7):
p += [i]
print(p)
#9
w = input("palabra a evaluar:")
l = [['a', 0], ['e', 0], ['i', 0], ['o', 0], ['u', 0]]
for i in word:
for j in len(l):
if i == [j][0]:
l[j][1] += 1
print(l) |
b673338a1fd0bc8bd15fbc1993d06ff520150693 | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_1/Ejercicio1.py | 162 | 3.84375 | 4 | numero1=int(input("Introduzca el primer numero: "))
numero2=int(input("Introduzca el segundo numero: "))
media=(numero1 + numero2) / 2
print("La media es ",media) |
3c749b7db4951b609149529c15e025b2bc059383 | susoooo/IFCT06092019C3 | /Riker/python/05.py | 283 | 3.625 | 4 | # 5-Escriba un programa que pida una temperatura en grados Fahrenheit y que escriba esa temperatura en grados Celsius. La relación entre grados Celsius (C) y grados Fahrenheit (F) es la siguiente: C = (F - 32) / 1,8
f = int(input("Fahrenheit? "))
print("Celsius: ", (f - 32) /1.8)
|
6d540eb2495904a59fdf91444ce77d2a11e7fc94 | susoooo/IFCT06092019C3 | /Riker/python/11.py | 481 | 3.890625 | 4 | # 4-Escriba un programa que pida el año actual y un año cualquiera y que escriba cuántos años han pasado desde ese año o cuántos años faltan para llegar a ese año.
import datetime
year = int(input("Year? "))
current_year = datetime.datetime.now().year
if (year < current_year):
print("Years since ", year, ", ", current_year - year)
else:
if(year > current_year):
print("Years to ", year,", ", year - current_year)
else:
print("Same year.")
|
a6183dcb8aba1708c72862fd23d82a50147e946d | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_4/Ejercicio4.py | 442 | 4.09375 | 4 | # Escriba un programa que pregunte cuántos
# números se van a introducir, pida esos
# números y escriba cuántos negativos ha introducido.
iteracion=int(input("¿Cuantos números va a introducir?: "))
negativo=0
for i in range(iteracion):
numero=int(input("Introduzca el numero: "))
if numero < 0 :
negativo+=1
if negativo!=1:
cadena="negativos"
else :
cadena="negativo"
print("Se ha introducido",negativo,cadena) |
cfd6225160256d38046ffa0d99ac9863945a553c | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e7.py | 294 | 3.71875 | 4 | #7-Escriba un programa que pida una cantidad de segundos y que escriba cuántas horas, minutos y segundos son.
print("Segundos:")
sgd=int(input())
min=0
horas=0
while sgd>3600:
horas+=1
sgd-=3600
while sgd>60:
min+=1
sgd-=60
print("Horas: ", horas, "Minutos: ", min, " Segundos: ",sgd)
|
9ec0866daee52c1def3a8a9fed5299154dd92f64 | susoooo/IFCT06092019C3 | /Riker/python/14.py | 429 | 3.90625 | 4 |
# 8-Escriba un programa que pida tres números y que escriba si son los tres iguales, si hay dos iguales o si son los tres distintos.
n1 = int(input("n1 ? "))
n2 = int(input("n2 ? "))
n3 = int(input("n3 ? "))
if ((n1 == n2) and (n2 == n3)):
print("They are equal.")
else:
if ((n1 == n2) or (n1 == n3) or (n2 == n3)):
print("There are two equal numbers")
else:
print("They are all different")
|
babcf1bc7df6069a229344b05e97d97acfddca39 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/while4.py | 522 | 4.0625 | 4 | #4-Escriba un programa que pida primero dos números enteros (mínimo y máximo) y que después pida números enteros situados entre ellos. El programa terminará cuando se escriba un número que no esté comprendido entre los dos valores iniciales. El programa termina escribiendo la cantidad de números escritos.
print("Número entero mínimo:")
n1=int(input())
print("Número entero máximo:")
n2=int(input())
n3=n1
nums=0
while n1<=n3<=n2:
print("Número entero:")
n3=int(input())
nums+=1
print("Numeros: ",nums)
|
e08d5430b054d56ae0ac12b818ad476158cfa51f | susoooo/IFCT06092019C3 | /elvis/python/bucle5.py | 645 | 4.125 | 4 | # Escriba un programa que pregunte cuántos números se van a introducir, pida esos números
# y escriba cuántos negativos ha introducido.
print("NÚMEROS NEGATIVOS")
numero = int(input("¿Cuántos valores va a introducir? "))
if numero < 0:
print("¡Imposible!")
else:
contador = 0
for i in range(1, numero + 1):
valor = float(input(f"Escriba el número {i}: "))
if valor < 0:
contador = contador + 1
if contador == 0:
print("No ha escrito ningún número negativo.")
elif contador == 1:
print("Ha escrito 1 número negativo.")
else:
print(f"Ha escrito {contador} números negativos.")
|
14ddefb42599d0209461b9d3c7be587fdec95dab | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e2.py | 324 | 3.984375 | 4 | #2-Escriba un programa que pida el peso (en kilogramos) y la altura (en metros) de una persona y que calcule su índice de masa corporal (imc). El imc se calcula con la fórmula imc = peso / altura 2
print("Peso: (kg)")
peso = float(input())
print("Altura: (m)")
altura = float(input())
print("imc: ",peso/(altura*altura))
|
cedf8afaea566b52bc6e58b2162e4f8884244155 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/listas2.py | 410 | 4.0625 | 4 | #2-Amplia el programa anterior, para que una vez creada la lista, se pida por pantalla una palabra y se diga cuantas veces aparece dicha palabra en la lista.
palabras = []
print("Número de palabras?:")
num=int(input())
for n in range(num):
print("Palabra ", n+1, ": ")
palabras=palabras+[input()]
print(palabras)
print("Buscar palabra: ")
search=input()
print("Concurrencia: ", palabras.count(search))
|
37a04841bddbb99f65213075c1c8524b62fb4494 | susoooo/IFCT06092019C3 | /Riker/python/10.py | 303 | 3.828125 | 4 | # 3-Escriba un programa que pida dos números y que conteste cuál es el menor y cuál el mayor o que escriba que son iguales.
n1 = int(input("n1? "));
n2 = int(input("n2? "));
if(n1 > n2):
print(n1, ">", n2)
else:
if (n2 > n1):
print(n2, ">", n1)
else:
print(n2, "=", n1)
|
aea888ce79f3f38a5347cd8208531a8978cb1a01 | susoooo/IFCT06092019C3 | /Tere/python/ejercicio7.py | 345 | 3.828125 | 4 | #7-Escriba un programa que pida una cantidad de segundos y
#que escriba cuántas horas, minutos y segundos son.
print("Escribe unos segundos: ")
segundos= input()
horas= int(segundos)/3600
minutos = (int(segundos) - int (horas)*3600)/60
seg = int(segundos) % 60
print (int(horas),"horas,",int(minutos), "minutos y", int(seg), "segundos")
|
16ec073e55924a91de34557320e539c750f377a3 | susoooo/IFCT06092019C3 | /jesusp/phyton/Divisor.py | 215 | 4.125 | 4 | print("Introduzca un número")
num = int(input())
if(num > 0):
for num1 in range(1, num+1):
if(num % num1 == 0):
print("Divisible por: ", num1)
else:
print("Distinto de cero o positivo")
|
6a1f6dfefe46fd0ff31c1b967046182d90e61d9a | susoooo/IFCT06092019C3 | /Riker/python/13.py | 427 | 3.90625 | 4 | # 6-Escriba un programa que pida dos números enteros y que escriba si el mayor es múltiplo del menor.
n1 = int(input("n1 ?"))
n2 = int(input("n2 ? "))
if (n1 == n2):
print("Numbers are equal")
else:
if (n1 > n2):
max = n1
min = n2
else:
max = n2
min = n1
if(max%min == 0):
print(max, " is multiple of ", min)
else:
print(max, " isn't multiple of ", min)
|
b2ba8e45c360ae96a08209172ba05811dd3a3b96 | susoooo/IFCT06092019C3 | /jesusp/phyton/Decimal.py | 201 | 4.15625 | 4 | print("Introduzca un número")
num = int(input())
print("Introduzca otro número")
num1 = int(input())
while(num > num1):
print("Introduzca un numero decimal: ")
num1= float(input())
|
6e848cdacf2855debfa5adb7ee6164758a53f8e7 | susoooo/IFCT06092019C3 | /Riker/python/08.py | 232 | 3.609375 | 4 | # 1-Escriba un programa que pida dos números enteros y que calcule su división, escribiendo si la división es exacta o no.
n1 = int(input("n1? "))
n2 = int(input("n2? "))
if (n1%n2 == 0):
print("yes")
else:
print("no")
|
52cc76a4a00bb9d8b7cb7aa335b7060a434dc29c | susoooo/IFCT06092019C3 | /movaiva/Python/Boletin_4/Ejercicio2.py | 344 | 4 | 4 | # Escriba un programa que pida un número entero mayor que cero y que escriba sus divisores.
numero=int(input("Introduzca un número entero mayor que cero: "))
while numero<=0 :
numero=int(input("Error.Introduzca un número entero mayor que cero: "))
for i in range(1,numero+1) :
if numero%i==0 :
print(i,"es divisor de",numero) |
22bac0fd997d87e501d018b3af30dc76fd60f2c7 | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200306/e3.py | 322 | 4 | 4 | #3-Escriba un programa que pida una distancia en pies y pulgadas y que escriba esa distancia en centímetros.Un pie son doce pulgadas y una pulgada son 2,54 cm.
print("Distancia en pies:")
pies = float(input())
print("Distancia en pulgadas:")
pulgadas = float(input())
print("Distancia en cm: ", (pies*12+pulgadas)*2.54)
|
b41ed3fc64e7a705c9be5060c0b034528f0a5f98 | chrisfoose/randomColor.py | /randomColor.py | 195 | 3.953125 | 4 | # Random Color Generator
# Chooses random color from out of four choices
# Christopher Foose
import random
colorList = ["Red", "Blue", "Green", "Yellow"]
print("Your color is: ", random.choice(colorList))
|
ff3e2b0d818421e8924334b9658d12560c3fa3fd | Bakley/literate-bassoon | /rename_files.py | 576 | 3.53125 | 4 | from __future__ import print_function
import os
def renaming_files():
# get the path to the files and the file names
file_list = os.listdir("/home/koin/Desktop/HackRush/Bakley/Python/Learning/Udacity/prank")
print(file_list)
# get the saved path of the directory
saved_path = os.getcwd()
print("The saved path is,", saved_path)
os.chdir("/home/koin/Desktop/HackRush/Bakley/Python/Learning/Udacity/prank")
# rename files
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
renaming_files()
|
08f116b143a9b8e78849c29f1df7a810ebd78352 | devangsharmadj/Python_Workbook_Course | /palindrome.py | 360 | 4.0625 | 4 | verifier = input('String to be checked: ')
split_verifier = verifier.split()
str_verifier = ''
for char in split_verifier:
str_verifier += f'{char}'
j = len(str_verifier)
for i in range(len(str_verifier)):
if str_verifier[i] == str_verifier[j - 1 - i]:
continue
else:
print('Not a palindrome!')
exit(1)
print('Palindrome!')
|
63092169b0fbdedc99931c707dd8248feb413c5e | Chelton-dev/ICTPRG-Python | /loopinf01.py | 79 | 3.75 | 4 | # Infinite loop
j=0
k = 0
while j <= 5:
#while k <= 5:
print(k)
k = k+1 |
4885f7041431e60298e6655303696a9120fe272e | Chelton-dev/ICTPRG-Python | /setex01.py | 400 | 3.921875 | 4 | # Example of a set
# unique elements
# https://www.w3schools.com/python/python_sets.asp
# https://pythontic.com/containers/set/construction_using_braces
# Disadvantage that cannot be empty
# https://stackoverflow.com/questions/17373161/use-curly-braces-to-initialize-a-set-in-python
carmakers = { 'Nissan', 'Toyota', 'Ford', 'Mercedes' }
carmakers.add('Kia')
for comp in carmakers:
print(comp) |
0b67e25ac38cfb32a6fe9a217f59a394a832ffa7 | Chelton-dev/ICTPRG-Python | /func03main2.py | 128 | 3.734375 | 4 | def main():
nm = get_name()
print("Hello "+nm)
def get_name():
name = input("Enter name: ")
return name
main() |
a8e222aca3153a0085ddf66b482b335c594042c9 | Chelton-dev/ICTPRG-Python | /format05printf.py | 326 | 3.984375 | 4 | # printing a string.
mystring = "abc"
print("%s" % mystring)
# printing a integer
days = 31
print("%d" % days)
# printing a float number
cost = 189.95
print("%f" % cost)
# printf apdaptions with concatenation (adding strings)
print("%s-" % "def" + "%f" % 2.71828)
# 2021-05-25
print("%d-" % 2021 + "0%d-" % 5 + "%d" % 25 ) |
19bfe557a5e0d351be9215b2f8ea501587337fda | Chelton-dev/ICTPRG-Python | /except_div_zero.py | 242 | 4.1875 | 4 | num1 = int (input("Enter num1: "))
num2 = int (input("Enter num2: "))
# Problem:
# num3 = 0/0
try:
result = num1/num2
print(num1,"divided by", num2, "is ", result)
except ZeroDivisionError:
print("division by zero has occured") |
6b5ac6244d890d1b5dcb135f22563bb8dc825abf | sorozcov/Digital-Sign-RSA | /digitalSign.py | 2,814 | 3.703125 | 4 | # Universidad del Valle de Guatemala
# Cifrado de información 2020 2
# Grupo 7
# Implementation Digital Sign.py
#We import pycryptodome library and will use hashlib to sha512
from Crypto.PublicKey import RSA
from hashlib import sha512
#Example taken from https://cryptobook.nakov.com/digital-signatures/rsa-sign-verify-examples
#We'll do an example of Digital Sign using RSA
print("This is an example OF Digital Signing using pycryptodome python library.")
message = b'My Secret Message'
print("The message Alice wants to send Bob is: ", message)
# First of all, Alice needs to generate a Public Key to give to Bob and a Private Key to keep secret.
# We'll do this using RSA Algorythm
#Alice Keys for signing
aliceKeys = RSA.generate(bits=1024)
nAlice=aliceKeys.n
publicKeyAlice=aliceKeys.e
privateKeyAlice=aliceKeys.d
#Bob Keys for encrypting and decrypting using RSA
bobKeys = RSA.generate(bits=1024)
nBob=bobKeys.n
publicKeyBob=bobKeys.e
privateKeyBob=bobKeys.d
#Cipher RSA
#c=m^{e}mod {n}}
#Decipher RSA
#m=c^{d}mod {n}}
print("Alice public key is: ", hex(publicKeyAlice))
print("Alice private key is: ", hex(privateKeyAlice))
print("Both keys will need the value of n: ", hex(nAlice))
print("Bob public key is: ", hex(publicKeyBob))
print("Bob private key is: ", hex(privateKeyBob))
print("Both keys will need the value of n: ", hex(nBob))
#Alice Part
#We generate a hash from our message and make a digest
hash = int.from_bytes(sha512(message).digest(), byteorder='big')
#After that we sign it using our privateKeyAlice
signature = pow(hash, privateKeyAlice,nAlice)
print("Signature of message:", hex(signature))
#If signature was altered
# signature=signature+1
#Now we encrypt our message and send it to Bob using Bobs public key
intMessage = int.from_bytes(message, byteorder='big')
encryptedMessage = pow(intMessage, publicKeyBob,nBob)
print("Message in Int: ",intMessage)
print("Encrypted message:", hex(encryptedMessage))
#Bobs Part
#Now we decrypt our message that was send from Alice using Public Key of Bob. Now Bob uses his privateKey
intDecryptedMessage = pow(encryptedMessage, privateKeyBob,nBob)
# If message was altered
# intDecryptedMessage=intDecryptedMessage+1
print("Decrypted Message in Int: ",intDecryptedMessage)
decryptedMessage = intDecryptedMessage.to_bytes((intDecryptedMessage.bit_length()+7)//8,byteorder="big")
print("Decrypted Message: ",decryptedMessage)
#Now we verify if the signature is valid
#For that we first decrypt the message
#Then we do the same verifying the hash from the message and the hash from the signature that was send
# If they match the signature is valid
hash = int.from_bytes(sha512(decryptedMessage).digest(), byteorder='big')
hashFromSignature = pow(signature, publicKeyAlice, nAlice)
print("Signature valid:", hash == hashFromSignature) |
c32ecd30c2fabc11127d5081d029a6c6271f3d2a | wtnb-msr/codeforces | /problem/118/A/solver.py | 233 | 3.609375 | 4 | #!/usr/bin/env python
import sys
origin = sys.stdin.readline().rstrip()
vowels = set(['a', 'A', 'o', 'O', 'y', 'Y', 'e', 'E', 'u', 'U', 'i', 'I'])
ans = [ '.' + c.lower() for c in origin if c not in vowels ]
print ''.join(ans)
|
1da02181c7de871672ec58d0ca79e721a0232367 | kunalkishore/Reinforcement-Learning | /Dynamic Programing /grid_world.py | 2,506 | 3.640625 | 4 | import numpy as np
class Grid():
def __init__(self,height,width,state):
self.height=height
self.width = width
self.i = state[0]
self.j = state[1]
def set_actions_and_rewards(self,actions, rewards):
'''Assuming actions consists of states other than terminal states and walls.
Rewards consists of only terminal states and in other states we assume reward to be 0'''
self.actions=actions
self.rewards = rewards
def set_current_state(self,state):
self.i=state[0]
self.j=state[1]
def get_state(self):
return (self.i,self.j)
def is_terminal(self,state):
return state not in self.actions
def move(self,action):
if action in self.actions[(self.i,self.j)]:
if action=='U':
self.i-=1;
elif action=='D':
self.i+=1
elif action=='L':
self.j-=1
elif action == 'R':
self.j+=1
return self.rewards.get((self.i,self.j),0)
def game_over(self):
return (self.i,self.j) not in self.actions
def all_states(self):
return set(list(self.rewards.keys())+list(self.actions.keys()))
def draw_grid(self):
for i in range(self.height):
print("________________________")
s=""
for j in range(self.width):
if (i,j) in self.actions:
reward=0
if (i,j) in self.rewards:
reward=self.rewards[(i,j)]
else:
reward=' / '
s+=str(reward)+" |"
print(s)
print("________________________")
def make_grid():
'''
|__|__|__|+1|
|__|__|//|__|
|__|//|__|-1|
|S |__|__|__|
'''
grid = Grid(4,4,(3,0))
rewards = {
(0,3):+1,
(2,3):-1,
(0,0):-0.1,
(0,1):-0.1,
(0,2):-0.1,
(1,0):-0.1,
(1,1):-0.1,
(1,3):-0.1,
(2,0):-0.1,
(2,2):-0.1,
(3,0):-0.1,
(3,1):-0.1,
(3,2):-0.1,
(3,3):-0.1
}
actions = {
(0,0):['R','D'],
(0,1):['R','L','D'],
(0,2):['R','L'],
(1,0):['R','U','D'],
(1,1):['U','L'],
(1,3):['U','D'],
(2,0):['U','D'],
(2,2):['R','D'],
(3,0):['U','R'],
(3,1):['L','R'],
(3,2):['U','L','R'],
(3,3):['U','L']
}
grid.set_actions_and_rewards(actions,rewards)
grid.draw_grid()
return grid
if __name__=='__main__':
make_grid()
|
67817397c76aea7ecd61a6030af87a5990fedb11 | alejandroverita/python-courses | /python-pro/iterators.py | 1,148 | 3.890625 | 4 | import time
class FiboIter:
def __init__(self, nmax):
self.nmax = nmax
def __iter__(self):
self.n1 = 0
self.n2 = 1
self.counter = 0
return self
def __next__(self):
if self.counter == 0:
self.counter = +1
return self.n1
elif self.counter == 1:
self.counter += 1
return self.n2
else:
self.aux = self.n1 + self.n2
if self.counter == self.nmax:
print("Finished")
raise StopIteration
self.n1, self.n2 = self.n2, self.aux
self.counter += 1
return self.aux
def run():
try:
nmax = int(input("Escribe la cantidad de ciclos en el Fibonacci: "))
if nmax > 0:
fibonacci = FiboIter(nmax)
for element in fibonacci:
print(f"{element}")
time.sleep(1)
elif nmax == 0:
print(0)
else:
raise ValueError
except ValueError:
print("Ingresa un numero positivo")
run()
if __name__ == "__main__":
run()
|
7562ed11cc98623910e7d9cd183bebad7bc207c0 | alejandroverita/python-courses | /bucles.py | 321 | 3.859375 | 4 | def run(veces, numero):
if veces <= numero:
print(f"La potencia de {veces} es {veces**2}")
run(veces + 1, numero)
else:
print("Fin del programa")
if __name__ == "__main__":
numero = int(input("Cuantas veces quieres repetir la potenciacion?: "))
veces = 0
run(veces, numero)
|
3c2ad960ec48388d2ed06952c26d9e044c851387 | Jumaruba/LeetCode | /328.py | 795 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
node = head
firstE = head.next
lastE = head.next
firstO = head
lastO = head
while lastE != None and lastE.next != None:
lastO.next = lastE.next
lastO = lastO.next # advance the lastO
prevLastONext = lastO.next
lastO.next = firstE
lastE.next = prevLastONext
lastE = lastE.next
return firstO
|
8c81082771a896fe45aa9f868c19ae9f64d6736e | Jumaruba/LeetCode | /235.py | 1,437 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Implemented with a small improvement
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
self.p = p
self.q = q
if self.p.val < self.q.val:
self.lowest = self.p
self.highest = self.q
else:
self.lowest = self.q
self.highest = self.p
self.ansNode = None
self.traverse(root)
return self.ansNode
# acc = 1 => we have found the value of the node already. Don't any process.
# acc == -2 => the first node to receive this value is the common ancestor.
def traverse(self, root):
acc = 0
if root == None:
return acc
if root == self.p:
acc = -1
elif root == self.q:
acc = -1
acc_left = 0
acc_right = 0
if root.val > self.lowest.val:
acc_left = self.traverse(root.left)
if root.val < self.highest.val:
acc_right = self.traverse(root.right)
if acc_left + acc_right + acc == -2:
self.ansNode = root
return 1
return acc + acc_left + acc_right
|
b40e2dbb8f231e4f7056ded68a1e01f363f1ed7d | Jumaruba/LeetCode | /844.py | 402 | 3.578125 | 4 | class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
s = self.filterString(s)
t = self.filterString(t)
return s == t
def filterString(self, s):
s_ = ""
for i,l in enumerate(s):
if l == "#":
s_ = s_[:-1]
else:
s_ += l
return s_
|
011363075fb0db01ec2c1e91509a1d298c739790 | Jumaruba/LeetCode | /028.py | 550 | 3.578125 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
needle_size = len(needle)
haystack_size = len(haystack)
# Case the size is not compatible
if needle_size == 0:
return 0
if needle_size > haystack_size:
return -1
# Brute force algorithm O(n*m)!
for i in range(haystack_size - needle_size + 1):
s = haystack[i: i+needle_size]
if s == needle:
return i
return -1
|
9b44ba0b5d7221bf80da5243b2a8a9a349f32f1e | Jumaruba/LeetCode | /019.py | 1,004 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
numberOfElements = self.countElements(head)
toRemovePos = numberOfElements - n # lenght = 1, n = 1, 0
startNode = ListNode(-1, head)
self.removeElement(startNode, None, toRemovePos, -1)
return startNode.next
def removeElement(self, node: Optional[ListNode], prevNode, n, currPos):
if node == None:
return
if n == currPos:
prevNode.next = node.next
return
self.removeElement(node.next, node, n, currPos+1)
def countElements(self, node: Optional[ListNode]):
if node == None:
return 0
return self.countElements(node.next) + 1
|
fb77723ea81b139766b51c2d7df89e2d5e20f8d0 | Ka1str/Python-GB- | /lesson-4/task-3-4.py | 73 | 3.640625 | 4 | print([num for num in range(20, 240) if num % 20 == 0 or num % 21 == 0])
|
22ebd991c03e65777566bc730ccd7d4dc7a304a3 | Ka1str/Python-GB- | /lesson-3/task-6-3.py | 1,243 | 4.03125 | 4 | def int_func(user_text):
"""
Проверяет на нижний регистр и на латинский алфавит
Делает str с прописной первой буквой
:param user_text: str/list
:return: print str
"""
if type(user_text) == list:
separator = ' '
user_text = separator.join(user_text)
latin_alphabet = ["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", " "]
not_latin = False
for letter in user_text:
if letter not in latin_alphabet:
not_latin = True
if user_text.islower() and not_latin == False:
user_text = user_text.title()
return print(user_text)
else:
return print('Ввели слово/слова не из маленьких латинских букв')
user_word = input('введите слово из маленьких латинских букв')
int_func(user_word)
user_split_text = input('введите строку из слов из латинских букв в нижнем регистре, разделенных пробелом').split()
int_func(user_split_text)
|
917c3cda891b29c1d1ed0471be3ec773332a7b93 | ritika-rao/Machine-Learning | /03 Categorical Data.py | 1,086 | 3.78125 | 4 | # Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import
# Importing the dataset
dataset = pd.read_csv('Data.csv')
X = dataset.iloc[:, :-1] #Take all the columns except last one
y = dataset.iloc[:, -1] #Take the last column as the result
# Taking care of missing data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
imputer = imputer.fit(X.iloc[:, 1:])
X.iloc[:, 1:] = imputer.transform(X.iloc[:, 1:])
# Encoding categorical data
# 1st approach: Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
X.iloc[:, 0] = labelencoder_X.fit_transform(X.iloc[:, 0]) # 0 is col 1
# label encoder has converted France as 1, Germany 2 and spain as 3
# 2nd approach: Make dummy variables
onehotencoder = OneHotEncoder(categorical_features = [0])
X = onehotencoder.fit_transform(X).toarray()
# Encoding the Dependent Variable
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y) |
3daa982b7c0f53c73325d26a82935d5568eae25c | rnjsrntkd95/piro12 | /PYTHON_week2/argorithm/bracket(9012).py | 548 | 3.703125 | 4 | number = int(input())
bracket = []
tmp = ''
for i in range(number):
bracket.append(input())
for target in bracket:
stack = []
target = list(target)
for check in target:
if check == '(':
stack.append(check)
else:
if not stack:
stack.append(check)
else:
tmp = stack.pop()
if tmp != '(':
stack.append(tmp)
stack.append(check)
if not stack:
print('YES')
else:
print('NO')
|
c1313fd43e568a5feea7c9ac97405399a9b0d92c | Rusty33/tic-tac | /game_ai_no_d.py | 18,325 | 3.875 | 4 | import random
board = [[0,0,0],[0,0,0],[0,0,0]]
turn = 1
game = True
go = True
#####################################################
def print_board():
global board
to_print = [""," 1 "," 2 "," 3 ","\n"]
x = 0
y = 0
while y <= 2:
if board[y][x] == 0:
to_print.append(" ")
if board[y][x] == 1:
to_print.append(" X ")
if board[y][x] == 2:
to_print.append(" O ")
if x == 2:
x = -1
y += 1
to_print.append("\n")
x += 1
to_print.append("tic_tac_toe")
to_print.append("\n")
to_print.append(" player%s " % (turn))
for p in to_print:
print(p,end="|")
#####################################################
def play():
global turn
print("\n")
x = int(input("|Please pick a row|"))
x -= 1
y = int(input("|And how far down |"))
y -= 1
if x >= 3 or y >= 3:
print("|Please choose a blank space|")
else:
if board[y][x] != 0:
print("|Please choose a blank space|")
play()
else:
board[y][x] = 1
#####################################################
def check_x():
x = 0
y = 0
O = 0
X = 0
blank = 0
global board,game,go
while y <= 2:
if board[y][x] == 0:
blank += 1
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if x == 2:
x = -1
y += 1
if O == 3:
print("\n")
print("|Player2 wins!|")
#print("X")
game = False
if X == 3:
print("\n")
print("|Player1 wins!|")
game = False
go = False
X = 0
O = 0
x += 1
#####################################################
def check_y():
x = 0
y = 0
O = 0
X = 0
blank = 0
global board,game,go
while x <= 2:
if board[y][x] == 0:
blank += 1
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if y == 2:
y = -1
x += 1
if O == 3:
print("\n")
print("|Player2 wins!|")
#print("Y")
game = False
if X == 3:
print("\n")
print("|Player1 wins!|")
game = False
go = False
X = 0
O = 0
y += 1
if blank == 0:
print("\n")
print("|Its a tie!|")
game = False
#####################################################
def check_d():
x = 0
y = 0
O = 0
X = 0
blank = 0
global board,game,go
for g in range(3):
if board[y][x] == 0:
blank += 1
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if y == 2:
y -= 1
x += 1
if O == 3:
print("\n")
#print("D")
print("|Player2 wins!|")
game = False
if X == 3:
print("\n")
print("|Player1 wins!|")
game = False
go = False
y += 1
x += 1
#########################################################
def check_d2():
x = 0
y = 0
O = 0
X = 0
blank = 0
global board,game,go
if board[0][2] == 1:
X += 1
if board[0][2] == 2:
O += 1
if board[1][1] == 1:
X += 1
if board[1][1] == 2:
O += 1
if board[2][0] == 1:
X += 1
if board[2][0] == 2:
O += 1
if O == 3:
print("\n")
#print("d2")
print("|Player2 wins!|")
game = False
if X == 3:
print("\n")
print("|Player1 wins!|")
game = False
go = False
if game == True:
go = True
#####################################################################
def check_d_c_2():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
for g in range(3):
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if y == 2:
y -= 1
x += 1
if O == 2 and go == True and blank == 1 :
board[blank_y[0]][blank_x[0]] = 2
print("\n")
print_board()
print("\n")
print("|Player2 wins!|")
game = False
go = False
y += 1
x += 1
#####################################################################
def check_d2_c_2():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
if board[0][2] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[0][2] == 1:
X += 1
if board[0][2] == 2:
O += 1
if board[1][1] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[1][1] == 1:
X += 1
if board[1][1] == 2:
O += 1
if board[2][0] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[2][0] == 1:
X += 1
if board[2][0] == 2:
O += 1
if O == 2 and go == True and blank == 1 :
board[blank_y[0]][blank_x[0]] = 2
print("\n")
print_board()
print("\n")
print("|Player2 wins!|")
game = False
go = False
#####################################################################
def d2_stopper():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
if board[0][2] == 0:
blank += 1
blank_x.append(2)
blank_y.append(0)
if board[0][2] == 1:
X += 1
if board[0][2] == 2:
O += 1
if board[1][1] == 0:
blank += 1
blank_x.append(1)
blank_y.append(1)
if board[1][1] == 1:
X += 1
if board[1][1] == 2:
O += 1
if board[2][0] == 0:
blank += 1
blank_x.append(0)
blank_y.append(2)
if board[2][0] == 1:
X += 1
if board[2][0] == 2:
O += 1
if X == 2 and go == True and blank == 1 :
board[blank_y[0]][blank_x[0]] = 2
go = False
#####################################################################
def d_stopper():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
if board[0][0] == 0:
blank += 1
blank_x.append(0)
blank_y.append(0)
if board[0][0] == 1:
X += 1
if board[0][0] == 2:
O += 1
if board[1][1] == 0:
blank += 1
blank_x.append(1)
blank_y.append(1)
if board[1][1] == 1:
X += 1
if board[1][1] == 2:
O += 1
if board[2][2] == 0:
blank += 1
blank_x.append(2)
blank_y.append(2)
if board[2][2] == 1:
X += 1
if board[2][2] == 2:
O += 1
if X == 2 and go == True and blank == 1 :
board[blank_y[0]][blank_x[0]] = 2
go = False
#####################################################################
def check_d_c_1():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
if board[0][0] == 0:
blank += 1
blank_x.append(0)
blank_y.append(0)
if board[0][0] == 2:
O += 1
if board[1][1] == 0:
blank += 1
blank_x.append(1)
blank_y.append(1)
if board[1][1] == 2:
O += 1
if board[2][2] == 0:
blank += 1
blank_x.append(2)
blank_y.append(2)
if board[2][2] == 2:
O += 1
if O == 1 and go == True and blank == 2 :
num = random.randint(0,blank - 1)
board[blank_y[num]][blank_x[num]] = 2
go = False
#####################################################################
def check_d2_c_1():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
if board[0][2] == 0:
blank += 1
blank_x.append(2)
blank_y.append(0)
if board[0][2] == 1:
X += 1
if board[0][2] == 2:
O += 1
if board[1][1] == 0:
blank += 1
blank_x.append(1)
blank_y.append(1)
if board[1][1] == 1:
X += 1
if board[1][1] == 2:
O += 1
if board[2][0] == 0:
blank += 1
blank_x.append(0)
blank_y.append(2)
if board[2][0] == 1:
X += 1
if board[2][0] == 2:
O += 1
if O == 1 and go == True and blank == 2 :
num = random.randint(0,blank - 1)
board[blank_y[num]][blank_x[num]] = 2
go = False
#####################################################################
def check_x_c_2():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while y <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if x == 2:
x = -1
y += 1
if O == 2 and go == True and blank == 1 :
board[blank_y[0]][blank_x[0]] = 2
print("\n")
print_board()
print("\n")
#print("x2")
print("|Player2 wins!|")
game = False
go = False
X = 0
O = 0
blank = 0
blank_x = []
blank_y = []
x += 1
#################################################################################
def x_stopper():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while y <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if x == 2:
x = -1
y += 1
if X == 2 and go == True and blank == 1:
board[blank_y[0]][blank_x[0]] = 2
go = False
#print("x stoper")
X = 0
O = 0
blank = 0
blank = 0
blank_x = []
blank_y = []
x += 1
######################################################################
def check_x_c_1():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while y <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if x == 2:
x = -1
y += 1
if O == 1 and go == True and blank == 2:
num = random.randint(0,blank - 1)
board[0][blank_x[num]] = 2
go = False
#print("x random")
X = 0
O = 0
blank = 0
blank_x = []
blank_y = []
x += 1
######################################################################
def check_r_c():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while x <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if y == 2:
y = -1
x += 1
y += 1
if go == True and blank >= 1 :
num = random.randint(0,blank - 1)
board[blank_y[num]][blank_x[num]] = 2
go = False
######################################################################
def check_y_c_2():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while x <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if y == 2:
y = -1
x += 1
if O == 2 and go == True and blank == 1 :
board[blank_y[0]][blank_x[0]] = 2
print("\n")
print_board()
print("\n")
#print("y2")
print("|Player2 wins!|")
game = False
go = False
X = 0
O = 0
blank = 0
blank_x = []
blank_y = []
y += 1
#########################################################################
def y_stopper():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while x <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if y == 2:
y = -1
x += 1
if X == 2 and go == True and blank == 1:
board[blank_y[0]][blank_x[0]] = 2
go = False
#print("y stoper")
X = 0
O = 0
blank = 0
blank_x = []
blank_y = []
y += 1
##########################################################################
def check_y_c_1():
x = 0
y = 0
O = 0
X = 0
blank = 0
blank_x = []
blank_y = []
global board,game,go
while x <= 2:
if board[y][x] == 0:
blank += 1
blank_x.append(x)
blank_y.append(y)
if board[y][x] == 1:
X += 1
if board[y][x] == 2:
O += 1
if y == 2:
y = -1
x += 1
if O == 1 and go == True and blank == 2 :
board[blank_y[random.randint(0,1)]][blank_x[0]] = 2
go = False
#print("y random")
X = 0
O = 0
blank = 0
blank_x = []
blank_y = []
y += 1
###############################
print_board()
while game == True:
play()
print_board()
check_x()
check_y()
check_d()
check_d2()
check_x_c_2()
check_y_c_2()
check_d_c_2()
check_d2_c_2()
y_stopper()
x_stopper()
d_stopper()
d2_stopper()
ran = random.randint(1,10)
if ran == 1:
check_d_c_1()
check_d2_c_1()
check_x_c_1()
check_y_c_1()
check_r_c()
if ran == 2:
check_d_c_1()
check_d2_c_1()
check_y_c_1()
check_x_c_1()
check_r_c()
if ran == 3:
check_d_c_1()
check_y_c_1()
check_d2_c_1()
check_x_c_1()
check_r_c()
if ran == 4:
check_y_c_1()
check_d_c_1()
check_d2_c_1()
check_x_c_1()
check_r_c()
if ran == 5:
check_y_c_1()
check_d_c_1()
check_x_c_1()
check_d2_c_1()
check_r_c()
if ran == 6:
check_y_c_1()
check_x_c_1()
check_d_c_1()
check_d2_c_1()
check_r_c()
if ran == 7:
check_y_c_1()
check_x_c_1()
check_d2_c_1()
check_d_c_1()
check_r_c()
if ran == 8:
check_x_c_1()
check_y_c_1()
check_d2_c_1()
check_d_c_1()
check_r_c()
if ran == 9:
check_x_c_1()
check_d2_c_1()
check_y_c_1()
check_d_c_1()
check_r_c()
if ran == 10:
check_x_c_1()
check_d2_c_1()
check_d_c_1()
check_y_c_1()
check_r_c()
if game == True:
print("\n")
print_board()
|
0558a60ba427ae4f2ec0b709c0911ec09e6fa3e7 | Liraz-Benbenishti/Python-Code-I-Wrote | /hangman/hangman/hangman-unit5/hangman-ex5.3.4.py | 282 | 3.625 | 4 | def last_early(my_str):
my_str = my_str.lower()
last_char = my_str[-1]
if (my_str[:-1].find(last_char) != -1):
return True
return False
print(last_early("happy birthday"))
print(last_early("best of luck"))
print(last_early("Wow"))
print(last_early("X"))
|
f3a101700e9798aac4030891e843eaa3d59c0f93 | Liraz-Benbenishti/Python-Code-I-Wrote | /next_py/next-py.1.1.2.py | 505 | 3.828125 | 4 | from functools import reduce
def add_dbl_char(list, char):
list.append(char * 2)
return list
def double_letter(my_str):
"""
:param my_str: string to change.
:type my_str: string
:return: a new string that built from two double appearance of each char in the string.
rtype: string
"""
return "".join(list(reduce(add_dbl_char, list(my_str), [])))
def main():
print(double_letter("python"))
print(double_letter("we are the champion!"))
if __name__ == "__main__":
main() |
c1b15e76e674ba8482922ef77a5a3b1993c4cb7c | Liraz-Benbenishti/Python-Code-I-Wrote | /next_py/next-py.4.1.2.py | 430 | 3.828125 | 4 | def translate(sentence):
words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'}
translate_generator = (words[i] for i in sentence.split(' '))
ret_lst = []
for string_generator in translate_generator:
ret_lst.append(string_generator)
ret_str = " ".join(ret_lst)
return ret_str
def main():
print(translate("el gato esta en la casa"))
if __name__ == "__main__":
main() |
59f598f7eabaadbda9ed96866d3da91bccb63512 | Liraz-Benbenishti/Python-Code-I-Wrote | /next_py/next-py.4.1.3.py | 518 | 3.671875 | 4 | def is_prime(n):
# Corner case
if (n <= 1):
return False
# Check from 2 to n-1
for i in range(2, n):
if (n % i == 0):
return False
return True
def first_prime_over(n):
prime_generator = (i for i in range(n+1, (n+2) ** 10) if is_prime(i))
return next(prime_generator)
def main():
print(first_prime_over(0))
print(first_prime_over(1))
print(first_prime_over(2))
print(first_prime_over(-1000000))
print(first_prime_over(1000000))
if __name__ == "__main__":
main() |
cfaf15f6ce9c635ee1a87c2892b9a09cdb91dc47 | Liraz-Benbenishti/Python-Code-I-Wrote | /hangman/hangman/hangman-unit7/hangman-ex7.2.4.py | 557 | 3.921875 | 4 | def seven_boom(end_number):
"""
:param end_number: the number to end the loop.
:type end_param: int
:return: list in range of 0 and end_number (including), where some numbers replaced by "BOOM".
rtype: list
"""
list_of_numbers = []
for number in range(end_number + 1):
list_of_numbers.append(number)
if (number % 7 == 0):
list_of_numbers[number] = 'BOOM'
if (str(7) in str(number)):
list_of_numbers[number] = 'BOOM'
return list_of_numbers
def main():
print(seven_boom(17))
if __name__ == "__main__":
main() |
371ed66d667edb14d59347994462ddf30dde6a84 | Liraz-Benbenishti/Python-Code-I-Wrote | /hangman/hangman/hangman-unit7/hangman-ex7.3.1.py | 836 | 4.25 | 4 | def show_hidden_word(secret_word, old_letters_guessed):
"""
:param secret_word: represent the hidden word the player need to guess.
:param old_letters_guessed: the list that contain the letters the player guessed by now.
:type secret_word: string
:type old_letters_guessed: list
:return: string that comprised of the letters and underscores. Shows the letter from the list that contained in the secret word in their location.
rtype: string
"""
new_word = []
for letter in secret_word:
if (letter in old_letters_guessed):
new_word.append(letter)
else:
new_word.append("_")
return " ".join(new_word)
def main():
secret_word = "mammals"
old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k']
print(show_hidden_word(secret_word, old_letters_guessed))
if __name__ == "__main__":
main() |
ad1a0de49caddf1372e5ae9f749e06577ec2320c | shaoormunir/programming-problems | /Google Problem 1.py | 309 | 3.671875 | 4 | array = [1, 11, 3, 7, 2, 6, 5, 10, 4]
sum = 12
for i in range(len(array)):
temp_sum = 0
for k in range (i, len(array)):
temp_sum += array[k]
if temp_sum == sum:
print("Starting: {} Ending: {}".format(i, k))
break
elif temp_sum > sum:
break |
0d59a25163228056e84201221068235042726a1c | momotofu/algorithms | /math/fib_even.py | 211 | 4 | 4 | def fib_even(n):
sum = 2
a = 1
b = 2
while True:
c = 3*b + 2*a
if c >= n:
break
sum += c
a += 2*b
b = c
return sum
print(fib_even(100))
|
b3110a0495a6d52ab0cd4e98f0ef25dbc0c501de | aanzolaavila/competitive-problems | /codeforces/Resueltos/watermelon.py | 253 | 3.578125 | 4 | from sys import stdin
def main():
linea = stdin.readline().strip()
while len(linea) != 0:
w = int(linea)
if w % 2 == 0 and w != 2: print("YES")
else: print("NO")
linea = stdin.readline().strip()
main()
|
8ff7e9be23a5ad7a679ac582e18c59d29eee51f5 | aanzolaavila/competitive-problems | /codeforces/Resueltos/A.petya_and_strings.py | 542 | 3.625 | 4 | from sys import stdin
import string
letters = string.ascii_lowercase
def lex(l1, l2) -> str:
for i in range(len(l1)):
if letters.index(l1[i]) < letters.index(l2[i]): return "-1"
elif letters.index(l1[i]) > letters.index(l2[i]): return "1"
return "0"
def main():
line1 = stdin.readline().strip()
SALIDA = []
while len(line1) != 0:
line2 = stdin.readline().strip()
SALIDA.append(lex(line1.lower(), line2.lower()))
line1 = stdin.readline().strip()
print("\n".join(SALIDA))
main() |
210414121ff25d50588e6e766b23cf2109219ecc | Leonardra/parsel_tongue_mastered | /oluwatobi/chapter_seven/question_26.py | 114 | 3.515625 | 4 | number_list = []
for num in range(2, 41):
if num % 2 == 0:
number_list.append(num)
print(number_list)
|
f41f85c5ade58c5591f6c53abc6f4f3832daf675 | mdarifuddin1/Create-a-Dictionary-to-store-names-of-students-and-marks-in-5-subjects | /dictionaries containing.py | 556 | 4.09375 | 4 | students = dict()
list1 = []
n = int(input("How many students are there: "))
for i in range(n):
sname = input("Enter name of the student: ")
marks = []
for j in range(5):
mark = float(input("Enter marks: "))
marks.append(mark)
students = {'name':sname,"marks" :marks}
list1.append(students)
print("Create a dictionary students is ",list1)
"""
name = input ("Enter name of the student ")
if name in students.keys():
print(students[name])
else:
print("No student found this name")
""" |
fda16aa729c019888cb2305fcfb00d782e620db6 | cnulenka/Coffee-Machine | /models/Beverage.py | 1,434 | 4.34375 | 4 | class Beverage:
"""
Beverage class represents a beverage, which has a name
and is made up of a list of ingredients.
self._composition is a python dict with ingredient name as
key and ingredient quantity as value
"""
def __init__(self, beverage_name: str, beverage_composition: dict):
self._name: str = beverage_name
self._composition: dict = beverage_composition
def get_name(self):
return self._name
def get_composition(self):
return self._composition
"""
CANDIDATE NOTE:
one other idea here was to make a abstract Beverage class and inherit and
create child classes of hot_coffee, black_coffee, hot_tea etc where each of
them over ride get_composition and store the composition info with in class.
So orders will be a list of Beverage objects having child class instances.
But this would hard code the composition and types of Beverages, hence extensibility
will be affected, but may be we can have a custom child class also where user
can create any beverage object by setting name and composition.
Same approach can be followed for Ingredients Class. I don't have a Ingredients class
though. Each ingredient can have a different warning limit, hence get_warning_limit
will be implemented differently. For example water is most used resource so that
can have a warning limit of 50% may be.
-Shakti Prasad Lenka
"""
|
3a2adf0295f13820e2732cc77c5eaa1976d2fc62 | akashgiri/merchant | /change_to_roman_numerals.py | 501 | 3.796875 | 4 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
def change_to_roman_numerals(input_content):
change_to_roman = []
currency = {}
print(input_content)
for key, value in input_content.items():
if key == 'roman_attributes':
for index, number in enumerate(value):
change_to_roman.append(number.split())
## Currency is the end index
for i in change_to_roman:
if i:
currency[i[0]] = i[-1]
print("change_to_roman: ", change_to_roman)
print("currency: ", currency)
return currency |
d434667f4c4eeb56c074ed47146921bb0c0013dc | efahmad/laitec-data-science | /002-session/pandas_test.py | 536 | 3.5625 | 4 | import pandas as pan
import os
import matplotlib.pyplot as plt
data = pan.read_csv(os.path.join(os.path.dirname(__file__), "movie_metadata.csv"))
likes = [
(name, sum(data['actor_1_facebook_likes'][data['actor_1_name'] == name].values)) for name in
data['actor_1_name'].unique()
]
likes = sorted(likes, key=lambda l: l[1], reverse=True)[:10]
x = [item for item in range(len(likes))]
y = [item[1] for item in likes]
plt.bar(x, y)
plt.xticks(x, [item[0] for item in likes])
# print([item[0] for item in likes])
plt.show()
|
80a3b9c03c7b525182ddc05ee3f3405f552e7b57 | priyankapednekar/Graph | /dfs_print_graph.py | 1,247 | 3.875 | 4 | class Node():
''' node has value and the list of edges it connects to'''
def __init__(self,src):
self.src = src
self.dest = {}
self.visit=False
class GF():
"""docstring for ."""
'''key- node data and value is Node'''
def __init__(self):
self.graph={}
def insert_node(self,data):
temp=Node(data)
self.graph[data]=temp
''' destination and weight for given node'''
def insert_edge(self,u,v,w):
if self.graph.get(u,None):
self.graph[u].dest[v]=w
else:
print("Node doesnt exist!!")
def dfs_print_rec(self,data):
print(self.graph[data].src, end = " ")
self.graph[data].visit=True
for i in self.graph[data].dest.keys():
if not self.graph[i].visit:
self.dfs_print_rec(i)
def main():
gf1=GF()
gf1.insert_node(0)
gf1.insert_node(1)
gf1.insert_node(2)
gf1.insert_node(3)
gf1.insert_edge(0,1,1)
gf1.insert_edge(0,2,1)
gf1.insert_edge(1,2,1)
gf1.insert_edge(2,0,1)
gf1.insert_edge(2,3,1)
gf1.insert_edge(3,3,1)
gf1.dfs_print_rec(2)
if __name__ == '__main__':
main()
|
7762d9a8c0b8ebb97551f2071f9377fe896b686f | itstooloud/boring_stuff | /chapter_3/global_local_scope.py | 922 | 4.1875 | 4 | ##
####def spam():
#### global eggs
#### eggs = 'spam'
####
####eggs = 'global'
####spam()
####print(eggs)
##
####using the word global inside the def means that when you refer to that variable within
####the function, you are referring to the global variable and can change it.
##
####def spam():
#### global eggs
#### eggs = 'spam' #this is a the global
####
####def bacon():
#### eggs = 'bacon' #this is a local variable
####
####def ham():
#### print(eggs) #this is the global
####
####eggs = 42 #this is the global
####spam()
####print(eggs)
##
#### if you try to use a global variable inside a function without assigning a value to it, you'll get an error
##
##def spam():
## print(eggs) #this will give an error
## ## eggs = 'spam local'
##
##eggs = 'global'
##
##spam()
##
#### it only throws the error because the function assigns a value to eggs. Commenting it out should remove the error
|
46c128c433288c3eed04ecb148693e52828c6975 | itstooloud/boring_stuff | /hello_age.py | 358 | 4.15625 | 4 | #if/elif will exit as soon as one condition is met
print('Hello! What is your name?')
my_name = input()
if my_name == "Chris":
print('Hello Chris! Youre me!')
print('Your age?')
my_age = input()
my_age = int(my_age)
if my_age > 20:
print("you're old")
elif my_age <= 10:
print("you're young")
else:
print('you are a spring chicken!')
|
cb62ae43d94a2e7f99ad875e58cdff60f9d971ef | AlexSamarsky/seabattle | /game.py | 5,660 | 3.546875 | 4 | import os
from board import Board
from errors import WrongCoords, CoordOccupied, BoardShipsError
class Game():
_computer_board = None
_player_board = None
_playing = False
_mounting_ships = False
_computer_turn = False
def __init__(self):
self._playing = True
self._mounting_ships = True
print('Добро пожаловать в игру морской бой!')
self._computer_board = Board()
self._player_board = Board()
self.fill_board(self._computer_board)
print('Корабли компьютера установлены!')
def fill_board(self, board):
cnt = 0
while True:
if cnt >= 10:
raise BoardShipsError('Не установлены корабли, что-то пошло не так. Обратитесь к разработчику!')
try:
board.set_ships_random()
break
except BoardShipsError:
board.new_board()
cnt += 1
def input_player_ships(self):
cnt = 0
while True:
cnt += 1
if cnt == 10:
print('Видимо вы не хотите играть, раз не отвечаете корректно! Игра прекращена')
response = input('Корабли можно поставить автоматически, хотите это сделать? (y/n): ')
if response == 'y':
self.fill_board(self._player_board)
self._mounting_ships = False
return
elif response == 'n':
while True:
unmounted_ships = self._player_board.get_unmounted_ships()
if unmounted_ships and not len(unmounted_ships):
self._mounting_ships = False
return
val = []
for ship in unmounted_ships:
val.append(str(ship))
print (self._player_board.to_str())
str_ships = ', '.join(val)
print (f'Остались корабли {str_ships}')
coords = input('Введите координаты установки корабля в формате A1 или A1 A2: ')
try:
self._player_board.set_next_ship(coords)
except WrongCoords as msg:
print(msg)
except CoordOccupied as msg:
print(msg)
def make_moves(self):
while True:
print('\n\nВаша доска получилась такой:')
print(self._player_board)
print('Ваши выстрелы по доске компьютера:')
print(self._computer_board.to_str(hidden=True))
if self._computer_turn:
print('################## Ход компьютера ###')
try:
coord = self._player_board.get_random_not_hit_coord()
print(f'Компьютер выстрелил по координатам {coord}')
os.system('read -s -n 1 -p "Нажмите любую клавишу для продолжения...\n"')
if self._player_board.make_shot_and_hit(coord):
print('И компьютер попал!')
if self._player_board.all_ships_sunk():
print('Компьютер уничтожил все ваши корабли! Вы проиграли! Спасибо за игру!')
return
else:
print('Еще один ход за компьютером!')
else:
self._computer_turn = not self._computer_turn
print('Компьютер промазал')
except BoardShipsError as msg:
print('Ошибка!!! Игра завершена')
print(msg)
return
else:
print('################## Ваш ход ###')
coord = input('Введите координаты куда хотие выстрелить в формате A1: ')
try:
coord = Board.get_hit_coord(coord)
if self._computer_board.make_shot_and_hit(coord):
print('Вы попали!')
if self._computer_board.all_ships_sunk():
print('ПОЗДРАВЛЯЮ! Вы уничтожили все корабли противника!')
return
else:
self._computer_turn = not self._computer_turn
print('И вы промазали')
except WrongCoords as msg:
print('!!!!ОШИБКА!!!!')
print(msg)
except CoordOccupied as msg:
print('!!!!ОШИБКА!!!!')
print(msg)
def start_game(self):
self.input_player_ships()
print ('Все корабли установлены!')
self.make_moves()
if __name__ == '__main__':
try:
game = Game()
game.start_game()
except BoardShipsError as msg:
print(msg) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.