blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
96e9ef1c4195f85fe75038978f21e3ab8863f64c | hepimen/learn-python | /lists_delete_item.py | 621 | 3.921875 | 4 | animals = ["Ayam", "Bebek", "Cicak"]
# Menghapus item tertentu (Bebek) pada "Lists" dengan method "remove"
animals.remove("Bebek")
print(animals) # ["Ayam", "Cicak"]
# Menghapus item terakhir pada "Lists" dengan method "pop"
animals = ["Ayam", "Bebek", "Cicak"]
animals.pop()
print(animals) # ["Ayam", "Bebek"]
# Menghapus item berdasarkan posisinya (indexing) pada "Lists" dengan method "pop"
animals = ["Ayam", "Bebek", "Cicak"]
animals.pop(0)
print(animals) # ["Bebek", "Cicak"]
# Menghapus semua item pada "Lists" dengan method "clear"
animals = ["Ayam", "Bebek", "Cicak"]
animals.clear()
print(animals) # []
|
d6af1dcd6df170f1fdfbcdaee7019ace1149b8c8 | zhanglintc/leetcode | /Python/Remove Duplicates from Sorted Array II.py | 1,045 | 3.71875 | 4 | # Remove Duplicates from Sorted Array II
# for leetcode problems
# 2014.10.20 by zhanglin
# Problem Link:
# https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
# Problem:
# Follow up for "Remove Duplicates":
# What if duplicates are allowed at most twice?
# For example,
# Given sorted array A = [1,1,1,2,2,3],
# Your function should return length = 5, and A is now [1,1,2,2,3].
class Solution:
# @param A a list of integers
# @return an integer
def removeDuplicates(self, A):
if A == []:
return 0
new_idx = 0
times = 1
for i in range(1, len(A)):
# if new digit occurred
if A[new_idx] != A[i]:
new_idx += 1
A[new_idx] = A[i]
times = 1
# this digit occurred before
else:
# but less than twice
if times < 2:
new_idx += 1
A[new_idx] = A[i]
times += 1
return new_idx + 1
|
3b87eba24bae73e89563e8aa597d617ed8d638b3 | wagner30023/fundamentos_python | /mundo1/cores.py | 212 | 3.53125 | 4 | '''print('\033[7;33;46mOlá, Mundo\033[m')
print('{}Olá, Mundo{}'.format('\033[4;34m', '\033[m'))
'''
x = 'carlos wagner pereira de morais'
convert = x.split()
print(' O ultimo valor do array: {} '.format(convert[len(convert)-1]))
|
ee38d90620cfa2c264ce20b35198b170dbce8769 | Ahmad-Magdy-Osman/IntroComputerScience | /Files/mOsmanWk09P1.py | 1,137 | 4.15625 | 4 | ################################################################
#
# CS 150 - Worksheet #09 --- Problem #1
# Purpose: Practicing how to read a file's content into a list,
# sort the list alphabetically, and write the sorted
# list to another file
#
# Author: Ahmad M. Osman
# Date: November 21, 2016
#
# Filename: mOsmanWk09P1.py
#
################################################################
#Reading states' file into a list and returning the list
def readStates(file):
infile = open(file, "r")
states = [state.rstrip() for state in infile]
infile.close()
return states
#Writing sorted alphabetical states into a file
def writeSortedStates(file, sortedStates):
outfile = open(file, "w")
states = [state + '\n' for state in sortedStates]
outfile.writelines(states)
outfile.close()
#main function - program execution instructions
def main():
#Openning states' file and reading it into a list
states = readStates("states.txt")
#Sorting the states' list alphabetically
states.sort()
#Writing sorted states to a file
writeSortedStates("statesAlpha.txt", states)
#Calling main function for program execution
main() |
0c748061c2c6b54760d3f4f429790fd2650fb6fc | jnepal/CS101-udacity | /Basics/Dictionary.py | 622 | 4.15625 | 4 | '''
Dictionary is Key value pair
It is mutable like list
It is analogous to Hash Table
'''
elements = { 'hydrogen': 1, 'helium': 2, 'carbon': 6 }
print(elements['hydrogen'])
elements['nitrogen'] = 7
print(elements)
#Checking whether the key is present in Dictionary or not
print('boron' in elements)
print('boron' not in elements)
elementWithDetails = {}
elementWithDetails['H'] = {'name': 'Hydrogen', 'number': 1, 'weight': 1.00794}
elementWithDetails['He'] = { 'name': 'Helium', 'number': 2, 'weight': 4.002602, 'noble gas': True}
print(elementWithDetails['H'])
print(elementWithDetails['H']['name']) |
58d04146562af9bb51f370533b307abc4a564e0f | VCloser/CodingInterviewChinese2-python | /36_ConvertBinarySearchTree.py | 1,270 | 3.9375 | 4 | class TreeNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def convert(root):
if not root:
return []
last_node = None
last_node = convert_core(root, last_node)
while last_node and last_node.left:
last_node = last_node.left
return last_node
def convert_core(root, last_node):
if not root:
return
cur = root
if cur.left:
last_node = convert_core(cur.left, last_node)
if last_node:
cur.left = last_node
last_node.right = cur
last_node = cur
if cur.right:
last_node = convert_core(cur.right, last_node)
return last_node
def display(head):
p = head
while p:
print(p.value, end=" ")
if p.left:
print(p.left.value, end=" ")
if p.right:
print(p.right.value, end=" ")
print()
p = p.right
if __name__ == "__main__":
node7 = TreeNode(16)
node6 = TreeNode(12)
node5 = TreeNode(8)
node4 = TreeNode(4)
node3 = TreeNode(14, node6, node7)
node2 = TreeNode(6, node4, node5)
node1 = TreeNode(10, node2, node3)
root = node1
head = convert(root)
display(head)
|
d37da4637c2a33af51fa564ea778efe0fe2d6d55 | yemao616/summer18 | /Google/2. medium/757. Pyramid Transition Matrix.py | 2,182 | 4.03125 | 4 | # We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`.
# For every block of color `C` we place not in the bottom row, we are placing it on top of a left block of color `A` and right block of color `B`. We are allowed to place the block there only if `(A, B, C)` is an allowed triple.
# We start with a bottom row of bottom, represented as a single string. We also start with a list of allowed triples allowed. Each allowed triple is represented as a string of length 3.
# Return true if we can build the pyramid all the way to the top, otherwise false.
# Example 1:
# Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]
# Output: true
# Explanation:
# We can stack the pyramid like this:
# A
# / \
# D E
# / \ / \
# X Y Z
# This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples.
# Example 1:
# Input: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"]
# Output: false
# Explanation:
# We can't stack the pyramid to the top.
# Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D.
# Note:
# bottom will be a string with length in range [2, 100].
# allowed will have length in range [0, 350].
# Letters in all strings will be chosen from the set {'A', 'B', 'C', 'D', 'E', 'F', 'G'}.
class Solution(object):
def pyramidTransition(self, bottom, allowed):
"""
:type bottom: str
:type allowed: List[str]
:rtype: bool
"""
T = [[0] * 7 for _ in xrange(7)]
for triple in allowed:
u, v, w = map(ord, triple)
T[u - ord('A')][v - ord('A')] |= 1 << (w - ord('A'))
state = [1 << (ord(c) - ord('A')) for c in bottom]
for loops in xrange(len(bottom) - 1):
for i in xrange(len(state) - 1):
k = 0
for b1 in xrange(7):
if (state[i] >> b1) & 1:
for b2 in xrange(7):
if (state[i+1] >> b2) & 1:
k |= T[b1][b2]
state[i] = k
state.pop()
return bool(state[0]) |
8848a43da2880285f0e0faddc137ab9cf28677a4 | pacharapol1454/robotics_lab3 | /week2.py | 294 | 3.609375 | 4 | def validate_pin(psw):
c=0
state=0
for i in psw:
if i.isalpha():
c=c+1
if c==0:
psw_int = int(psw)
digit = 0
while(psw_int > 0):
psw_int = psw_int//10
digit = digit + 1
if digit == 4 or digit == 6:
state=state+1
if state==1:
return True
else:
return False
|
d97b1ab5b1894189dee826bffccbf5fd79dd2983 | duanwandao/PythonBaseExercise | /Day18(核心编程)/Test06.py | 1,089 | 4.1875 | 4 | """
创建生成器的方式:
1.
列表推导式
g = (列表推导式)
generator
2.
yield
定义任意一个方法,在方法中加入yield关键字
生成器生成数据3中方式:
next(g)
g.__next__()
g.send()
如果使用send生成第一个数据的时候,必须有一个None参数
yield:
携程
"""
# def test():
# for x in range(10):
# print(x)
# g = test()
# print(type(g))
def test():
for x in range(10):
#加入yield关键字,函数调用变成生成器
yield x
print("----")
# print(x)
g = test()
# print(type(g))
#生成一个数据
print(g.send(None))
print(next(g))
print(g.__next__())
print(g.send(""))
def save_money():
while True:
print("存入¥1999")
yield None
def draw_money():
while True:
print("取出Y1999")
yield None
g_save = save_money()
g_draw = draw_money()
while True:
# save_money()
# draw_money()
g_save.__next__()
g_draw.__next__()
|
318165271f55dba013e7b596934cdc9ff05fcd4d | yzhong52/AdventOfCode | /2020/day24.py | 2,052 | 3.65625 | 4 | import collections
from typing import List, Iterator, Dict, Tuple
directions = {"e": (2, 0), "se": (1, -1), "sw": (-1, -1), "w": (-2, 0), "nw": (-1, 1), "ne": (1, 1)}
def parse() -> Iterator[List[str]]:
file = open("day24.txt")
lines = file.read().splitlines()
for line in lines:
instruction = []
i = 0
while i < len(line):
if i + 1 < len(line) and line[i: i + 2] in directions:
instruction.append(line[i: i + 2])
i += 2
else:
instruction.append(line[i])
i += 1
yield instruction
def navigate(steps: List[str]) -> (int, int):
x, y = 0, 0
for step in steps:
dx, dy = directions[step]
x += dx
y += dy
return x, y
def part1_flip_tiles() -> Dict[Tuple[int, int], bool]:
tiles = collections.defaultdict(bool)
for instruction in parse():
pos = navigate(instruction)
tiles[pos] = not tiles[pos]
return tiles
def daily_flip_tile_rule(x: int, y: int, state: Dict[Tuple[int, int], bool]) -> bool:
black_tiles = sum(state[(x + dx, y + dy)] for dx, dy in directions.values())
if state[(x, y)] and (black_tiles == 0 or black_tiles > 2):
return False
elif not state[(x, y)] and black_tiles == 2:
return True
else:
return state[(x, y)]
def part2_mutate(state: Dict[Tuple[int, int], bool], days: int):
for day in range(days):
new_state: Dict[(int, int), bool] = collections.defaultdict(bool)
for x, y in list(state.keys()):
for x1, y1 in [(x, y)] + [(x + dx, y + dy) for dx, dy in directions.values()]:
if (x1, y1) not in new_state:
new_state[(x1, y1)] = daily_flip_tile_rule(x1, y1, state)
state = new_state
print(f"Day {day + 1}: {sum(state.values())}")
return state
day1 = part1_flip_tiles()
part1 = sum(day1.values())
print(part1) # 455
day100 = part2_mutate(day1, days=100)
part2 = sum(day100.values())
print(part2) # 3904
|
4288fe9870048fa9a851df0fb08afa06148eea8f | Felienne/spea | /7183 Python Basics/11 Chapter 2.3 - About For/03 Accumulating to new lists and better translation/86912_05_code.py | 1,021 | 3.734375 | 4 | # For reference, here is the original code:<div>
</div><div><pre><code>calculations_to_letters = {'2':'two', '+': 'plus', '=':'equals', '4':'four'}
input = "2 + 2 = 4"
calculation_elements = input.split()
element_1 = calculation_elements[0]
word_1 = calculations_to_letters[element_1]
element_2 = calculation_elements[1]
word_2 = calculations_to_letters[element_2]
element_3 = calculation_elements[2]
word_3 = calculations_to_letters[element_3]
element_4 = calculation_elements[3]
word_4 = calculations_to_letters[element_4]
element_5 = calculation_elements[4]
word_5 = calculations_to_letters[element_5]
output = word_1 + ' ' + word_2 + ' ' + word_3 + ' ' + word_4 + ' ' + word_5
print(output)</code></pre>
</div><div>Can you do it with just 10 lines?</div>
calculations_to_letters = {'2':'two', '+': 'plus', '=':'equals', '4':'four'}
input = "2 + 2 = 4"
calculation_elements = input.split()
output = __
for i in __:
word = calculations_to_letters[__]
__ #<-- do something with word here.
print(output) |
4d19343cf3c08d9b515dccf340eb6cb6d18537b6 | Nicolas-Fernandez/grid_path_challenge | /myAntsArmyAnswerYourQuestion.py | 5,607 | 3.640625 | 4 | """
myAntsArmyAnswerYourQuestion is a python script that try to answer the question:
"How many paths do you have from point A to point B in a square of 10 per 10 ?"
With fact that you can just use 2 movings : to the Right and to the Bottom!
This question was asked to Nicolas by Fabrice in 2017 the Wednesday 22th of november.
See below, the square :
A -----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
-----------------------------------------
| | | | | | | | | | |
----------------------------------------- B
Here we try to answere with an original aproach base on probabilistic ants exploration.
Yeah ...
Because the first proposition below, with exact mathematic aproach and permutations
was rejected by the Emperor ...
-----------------------------------------------------------------------------
# import math library to use "factorial" function
"""
import math as mp
# definition C function, return number of combinations k among N note C(n,k)
def C(n,k):
return(mp.factorial(n)/(mp.factorial(n-k)*mp.factorial(k)))
"""
# ask user for grid height h and width w of this dreams
h = int(input("grid height ? "))
w = int(input("grid width ? "))
# combinations calculation with C function
c = C((w+h),h)
# print result
print(c, "ways on a", h, "per", w, "grid")
-----------------------------------------------------------------------------
Note : myAntsArmyAnswerYourQuestion was righted with EMACS.
"""
# import random.py library to generate ants decisions
import random as rd
# ask user for grid height h and width w of this dreams
height = int(input('Grid height ? '))
width = int(input('Grid width ? '))
print()
# ask user how many agents used for aproximation
ants = int(input('How many ants in my army ? '))
print()
# declare list of all paths
all_paths = []
# declare lenght of paths
paths_lenght = width + height
# for each agent
for agent in range (ants):
# declare initial position of ant
# x = position in abscisse -
# y = postion in ordonate |
# Starting A point is at (0,0)
# Ending B point is at (width,heigth)
ant_x = 0
ant_y = 0
# declare ant path, note with R for right move and D for down move.
ant_path = []
# for each step in the path
for step in range (paths_lenght):
# "random" choice to go Down on the grid.
choice = rd.randint(0,1)
# if ant reach far right, just go Down and record path
if ant_x == width:
ant_y += 1
ant_path.append('D')
# or if ant reach deep bottom, just go Right and record path
elif ant_y == height:
ant_x += 1
ant_path.append("R")
else:
# if 0, ant don't go Down, go Right, and path is recorded
if choice == 0:
ant_x += 1
ant_path.append('R')
# and if 1, ant go Down, don't go Right, and path is recorded
elif choice == 1:
ant_y += 1
ant_path.append('D')
# final path of ant is recorded in list as string in all_paths
all_paths.append(''.join(ant_path))
# count how many UNIQUE path (convert list all_paths in a set) recorded and print it
print ('My ants found at least', len(set(all_paths)), 'uniques paths in a', height, 'x', width, 'grid')
print ('If you found a number of unique path equal or to close of the number of ants,')
print ('you should probably increase the number of ants...')
print ('In nature, some species neasts can provide more than billion of ants !!!')
print ('For better estimation and find (maybe) more unique path, increase ants number !')
print ('Advice, at least', C((height+width),height)*10,'for a', height, 'x', width, 'grid')
print ()
# Queen corection !
queen_paths = []
for path in range(len(all_paths)):
queen_paths.append(all_paths[path])
for path in range(len(queen_paths)):
queen_paths[path] = queen_paths[path].replace("R", "A")
queen_paths[path] = queen_paths[path].replace("D", "B")
queen_paths[path] = queen_paths[path].replace("A", "D")
queen_paths[path] = queen_paths[path].replace("B", "R")
new_paths = all_paths + queen_paths
print ('The queen found at least', len(set(new_paths)), 'uniques paths in a', height, 'x', width, 'grid')
print ('If you found a number of unique path equal or to close of the number of ants,')
print ('you should probably increase the number of ants...')
print ('The queen is smarter, she take all inverts paths founded by ants and add it to the set')
print ('For better estimation and find (maybe) more unique path, increase ants number !')
print ('For Queen, just', C((height+width),height)*2,'for a', height, 'x', width, 'grid')
print ()
print ('For information, answear is', C((height+width),height), 'uniques paths')
print ('... end of script ...')
|
8d496315e98ce7d62cb80a170db65e7ed457a62f | ubante/poven | /projects/odds/nba_finals.py | 1,588 | 3.609375 | 4 | from __future__ import print_function
import random
from collections import defaultdict
iterations = 999
odds_game_for_t1 = 0.90
win_count = defaultdict(int)
for i in range(1, iterations+1):
print("Iteration #{0:2}: ".format(i), end="")
t1_wins = 0
t2_wins = 0
scores = ""
game_number = 1
while t1_wins < 4 and t2_wins < 4:
# if random.randomdom < 0.5
# if random.randint(0,9) < 5:
# if random.randint(0, 1) < 0.5:
# score = random.randint(0, 1)
score = random.uniform(0, 1)
scores = "{} {}".format(scores, score)
if score < odds_game_for_t1:
# print("1 ", end="")
# print("Team 1 wins game #{}".format(game_number))
t1_wins += 1
else:
# print("2 ", end="")
# print("Team 2 wins game #{}".format(game_number))
t2_wins += 1
game_number += 1
# print("")
if t1_wins == 4:
win_count["t1"] += 1
print("Team 1 wins the series {} to {} ({}/{}) {}."
.format(t1_wins, t2_wins, win_count["t1"], win_count["t2"], scores))
if t2_wins == 4:
win_count["t2"] += 1
# print("Team 2 wins the series {} to {}.".format(t2_wins, t1_wins))
print("Team 2 wins the series {} to {} ({}/{}) {}."
.format(t2_wins, t1_wins, win_count["t1"], win_count["t2"], scores))
print("\n\nAfter {} iterations with Team 1 winning each game with the odds of {}, the final results are {}/{}:"
.format(iterations, odds_game_for_t1, win_count["t1"], win_count["t2"]))
|
b5eac55ac4fb3752c7a63db3153d832dbc54dd41 | nathan29849/pirogramming13 | /algorithm_class_3_0711.py | 1,985 | 3.578125 | 4 | count = int(input())
#aabb -> ["a", "b"]
def check_group(word): # input = str,output = Boolean
last_alphabet = ""
alphabets =[]
for letter in word:
if letter == last_alphabet:
continue
else:
if letter in alphabets: # 문자가 이미 있는지 없는지 검사
return False
else:
alphabets.append(letter)
last_alphabet = letter
return True #다 돌게되면 그룹단어가 맞는거라 True.
result = 0
for _ in range(count): # for문에선 리스트에 해당하는 아이템값을 안쓰려면 _ (언더바) 처리를 해주면 됨
word = input()
if check_group(word):
result += 1
print(result)
# 1. letter 연속적인가? (aabb가 나올 때 연속적인지 보려면 직전 알파벳이 letter가 같은지 보면 됨.)
# 2. 이미 나왔던 단어인가? (aabbaa가 나올 때
# 3. 연속을 깨뜨릴때, 이미 나왔던 알파벳인지 검사 -> False이면 그룹단어가 아님.
# <---------------------------------------->
# 제로 문제 : stack 과 관련있음 first-in, last-out
다시 한 번 봐보기:
# 4. 제로
class Stack:
def __init__(self):
self.__arr = []
self.__top = 0
def push(self, item):
self.__arr.append(item)
self.__top += 1
def isEmpty(self):
if self.__arr == []:
return True
else:
return False
def pop(self):
if self.isEmpty():
return False
else:
self.__top -= 1
item = self.__arr[self.__top]
del(self.__arr[self.__top])
return item
def total_sum(self):
sum = 0
for num in self.__arr:
sum += num
return sum
count = int(input())
stack = Stack()
for _ in range(count):
num = int(input())
if num == 0:
stack.pop()
else:
stack.push(num)
print(stack.total_sum()) |
25ddb1301b2cd37c3e0eced96499bcbfc9a007b4 | suhyeonjin/CodePractice | /Baekjoon/4344.py | 492 | 3.96875 | 4 | testCase = input('')
CaseList = []
for i in range(testCase):
CaseList.append(raw_input(''))
def get_AVG(ArrayList, aver):
result = []
for i in ArrayList:
if float(i) > float(aver):
result.append(i)
return '%.3f'%((float(len(result))/len(ArrayList))*100)
for k in CaseList:
k = k.split(' ')
n = int(k[0])
HeightList = map(int, k[1::])
average = '%.3f'%(float(sum(HeightList))/len(HeightList))
print get_AVG(HeightList, average)+"%"
|
671463991f05b4e70215a0a68e6532dfc857a0bc | juansalvatore/algoritmos-1 | /ejercicios/2-programas-sencillos/2.3.py | 354 | 3.953125 | 4 | # Ejercicio 2.3.
# Utilice el programa anterior para generar una tabla de conversión de temperaturas,
# desde 0 °F hasta 120 °F, de 10 en 10.
from helpers import fahrenheit_to_celsius
def generar_tabla():
for i in range(0, 13):
fahrenheit = i * 10
print(str(fahrenheit) + 'F', fahrenheit_to_celsius(fahrenheit))
generar_tabla() |
f4cdb53b55a79b6002dab67b58be4523c9431708 | Aadesh-Shigavan/Python_Daily_Flash | /Day 13/13-DailyFlash_Solutions/28_Jan_Solution_Three/Python/Program1.py | 519 | 3.875 | 4 | '''
Problem Statement
Write a Program which detects whether the entered number is perfect or not
A Perfect number is a number which is equal to the sum of its Perfect divisor
A perfect divisor of x is the number giving remainder 0 on dividing x by number, where number != x
'''
num = int(input("Enter a Number\n"))
sum = 0
for x in range(1,num):
if num % x == 0 :
sum = sum + x
if sum == num :
print("Entered Number is a Perfect Number")
else:
print("Entered Number is not a Perfect Number")
|
47e93fba32e6f979c70fad33f8ce8cb8e8a0733d | Mattiezilaie/TicTacToe.py | /k.py | 5,411 | 3.765625 | 4 |
class TicTacToe:
def __init__(self):
self._board = [['','',''],['','',''],['','','']]
self._current_state = "UNFINISHED"
self._num = 0
def horizontal_win(self, row, player):
if row>2 or row<0:
return False
if self._board[row] != "":
return False
if self._current_state != "UNFINISHED":
return False
self._board[row] = player
return True
if self._board[row] == player:
self._num = self._num + 1
if self._board[row][0] == player and self._board[row][1] == player and self._board[row][2] == player:
self._current_state = str(player) + "_Won"
return True;
def vertical_win(self, col, player):
if row > 2 or row < 0 or col > 2 or col < 0:
return False
if self._board[row][col] != "":
return False
if self._current_state != "UNFINISHED":
return False
self._board[row][col] = player
return True
if self._board[row] == player:
self._board[col] = player
self._num = self._num + 1
if self._board[0][col] == player and self._board[1][col] == player and self._board[2][col] == player:
self._current_state = str(player) + "_Won"
return True
def diagonal_win(self, row, col, player):
if row > 2 or row < 0 or col > 2 or col < 0:
return False
if self._board[row][col] != "":
return False
if self._current_state != "UNFINISHED":
return False
self._board[row][col] = player
return True
if self._board[row] == player:
self._board[row][col] = player
self._num = self._num + 1
if self._board[0][0] == player and self._board[1][1] == player and self._board[2][2] == player:
self._current_state = str(player) + "_Won"
elif self._board[0][2] == player and self._board[1][1] == player and self._board[2][0] == player:
self._current_state = str(player) + "_Won"
return True
def make_move(self, row, col, player):
if row > 2 or row < 0 or col > 2 or col < 0:
return False
if self._board[row][col] != "":
return False
if self._current_state != "UNFINISHED":
return False
self._board[row][col] = player
return True
count = 0
while tic._current_state == "UNFINISHED":
if count % 2 == 0:
flag = tic.make_move(int(row), int(col), "X")
else:
flag = tic.make_move(int(row), int(col), "O")
else:
count = count + 1
if tic.get_current_state() == "DRAW":
print("Match is Draw")
elif tic.get_current_state() == "X_WON":
print("Player X Won the Match")
elif tic.get_current_state() == "O_WON":
print("Player O Won the Match")
def get_current_state(self):
return self._current_state
def print_Table(self):
print("\nPresent Status of TicTacToe board is : \n")
l = " 0 1 2"
count=0
print(l)
for i in self._board:
print(str(count)+str(i))
count=count+1
print()
tic = TicTacToe()
tic.print_Table()
count = 0
while tic._current_state == "UNFINISHED":
if count % 2 == 0:
print("Player-x it's your turn")
row = input("Enter Row In which You want to insert (0-2) : ")
col = input("Enter Column In which You want to insert (0-2) : ")
flag = tic.make_move(int(row), int(col), "X")
if flag is False:
tic.print_Table()
while flag is False:
print("Move is Not Successful")
print("Player-x it's your turn")
row = input("Enter Row In which You want to insert (0-2) : ")
col = input("Enter Column In which You want to insert (0-2) : ")
flag = tic.make_move(int(row), int(col), "X")
tic.print_Table()
else:
print("Move is Successful")
tic.print_Table()
else:
print("Player-O it's your turn")
row = input("Enter Row In which You want to insert (0-2) : ")
col = input("Enter Column In which You want to insert (0-2) : ")
flag = tic.make_move(int(row), int(col), "O")
if flag is False:
tic.print_Table()
while flag is False:
print("Move is Not Successful")
print("Player-O it's your turn")
row = input("Enter Row In which You want to insert (0-2) : ")
col = input("Enter Column In which You want to insert (0-2) : ")
flag = tic.make_move(int(row), int(col), "X")
tic.print_Table()
else:
print("Move is Successful")
tic.print_Table()
count = count + 1
if tic.get_current_state() == "DRAW":
print("Match is Draw")
elif tic.get_current_state() == "X_Won":
print("Player X Won the Match")
else:
print("Player O Won the Match") |
64b746060c53e94de3fe592241352a153d6a88a1 | django-group/python-itvdn | /домашка/starter/lesson 6/Aliona Baranenko/task_2.py | 377 | 4.53125 | 5 | def reversed(string):
reversed_string = ''
for i in string:
reversed_string = i+reversed_string
print('reversed string is: ', reversed_string)
if string == reversed_string:
print("it's a palindrome")
else:
print("it's not a palindrome")
string = input('enter a string: ')
print('entered string', string)
reversed(string) |
9e4a73ffe8f3c2a9e4ae0ef7cd10242d3ca237f3 | GYGeorge/py | /leetcode/129SumRootToLeft.py | 1,263 | 4.09375 | 4 | # * @Author: gaoyuan
# * @Date: 2020-07-01 16:57:08
# * @Last Modified by: gaoyuan
# * @Last Modified time: 2020-07-01 16:57:08
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
"""
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
"""
def sumNumbers(self, root: TreeNode):
self.sum = 0
self.recursive(root, 0)
return self.sum
def recursive(self, node: TreeNode, v):
if not node:
return
node.val += v*10
if (not node.left) and (not node.right):
self.sum += node.val
return
if node.left != None:
self.recursive(node.left, node.val)
if node.right != None:
self.recursive(node.right, node.val)
if __name__ == "__main__":
a = TreeNode(5)
b = TreeNode(1)
a_b = TreeNode(9, a, b)
d = TreeNode(0)
root = TreeNode(4, a_b, d)
so = Solution()
so.sumNumbers(root)
|
27f7cbdea2eb1fa0bc784e265787d1c8c3895270 | prasun-biswas/python_assignments | /named_parameters.py | 681 | 3.96875 | 4 | # TIE-02107: Programming 1: Introduction
# MAHABUB HASAN, mahabub.hasan@student.tut.fi, Student No.: 281749
# Solution of Task - 4.5.2
# A program that prints box
def print_box(width, height, border_mark="#", inner_mark=" "):
for x in range(1, height+1):
for y in range(1, width+1):
if x == 1 or x == height:
print(border_mark, end="")
elif y == 1 or y == width:
print(border_mark, end="")
else:
print(inner_mark, end="")
print()
print()
def main():
print_box(5, 4)
print_box(3, 8, "*")
print_box(5, 4, "O", "o")
print_box(width=6, height=4, border_mark="O", inner_mark=".")
main()
|
75ab30b66ddab88e4de956cd5a79675918056d83 | SagarKulk539/APS_Lib_2020 | /CodeChef/LECANDY.py | 303 | 3.5625 | 4 | '''
APS-2020
Problem Description, Input, Output : https://www.codechef.com/problems/LECANDY
Code by : Sagar Kulkarni
'''
n=int(input())
for _ in range(0,n):
N,C = map(int,input().split())
list1=[int(x) for x in input().split()]
if sum(list1)<=C:
print('Yes')
else:
print('No')
|
49f31990fc0ee1550fbd71aee2f7292fcea55115 | ege-erdogan/comp125-jam-session-02 | /24_11/strings.py | 1,021 | 4.03125 | 4 | '''
COMP 125 - Programming Jam Session #2
November 23-24-25, 2020
1. Write a function dna_replica, which takes a DNA sequence of arbitrary length as input, and returns the complementary sequence as a string.
2. Implement a function, remove_whites, which takes a string as input and returns a new string by removing the extra white space characters (“ “, tab character, newline character). In the return string all words should be separated by just a single space character.
'''
def dna_replica(dna):
complement = ''
for char in dna:
if char == 'A':
complement += 'T'
elif char == 'T':
complement += 'A'
elif char == 'G':
complement += 'C'
else:
complement += 'G'
return complement
def remove_whites(text):
result = ''
for char in text:
if char == ' ':
if result[-1] != ' ':
result += char
elif char not in ['\n', '\t']:
result += char
return result
|
1338ed44634d2ed9c976699a97b786cd29acf252 | Whitie/AdventOfCode | /2019/Day_10/day10p1.py | 1,340 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import sys
from collections import defaultdict, namedtuple
Point = namedtuple('Point', 'x y')
def read_file(filename):
coordinates = []
with open(filename, 'r') as fp:
for y, line in enumerate(fp):
line = line.strip()
if line:
for x, place in enumerate(line):
if place == '#':
coordinates.append(Point(x, y))
return coordinates
def angle(point_1, point_2):
return math.atan2(point_1.y - point_2.y, point_1.x - point_2.x)
def main(filename):
asteroids = read_file(filename)
# print(asteroids)
angles = defaultdict(set)
for asteroid_1 in asteroids:
for asteroid_2 in asteroids:
if asteroid_1 == asteroid_2:
continue
angles[asteroid_1].add(angle(asteroid_1, asteroid_2))
point = None
count = 0
for asteroid, angles_ in angles.items():
a_count = len(angles_)
if a_count > count:
point = asteroid
count = a_count
return count, point
if __name__ == '__main__':
try:
count, point = main(sys.argv[1])
print(f'X: {point.x}, Y: {point.y} DETECTION: {count}')
except IndexError:
print(f'Usage: {sys.argv[0]} <filename>')
|
ac344e36f3dce324aae4767dc22ef38ce73d50d6 | SebastianThomas1/coding_challenges | /hackerrank/data_structures/linked_lists/merge_two_sorted_linked_lists.py | 892 | 3.578125 | 4 | # Sebastian Thomas (coding at sebastianthomas dot de)
# https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists
#
# Merge two sorted linked lists
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
def merge_lists(head1, head2):
if head1 is None and head2 is None:
return None
if head1 and head2 and head1.data <= head2.data or head2 is None:
head = head1
tail = head1
head1 = head1.next
else:
head = head2
tail = head2
head2 = head2.next
while head1 or head2:
if head1 and head2 and head1.data <= head2.data or head2 is None:
tail.next = head1
tail = tail.next
head1 = head1.next
else:
tail.next = head2
tail = tail.next
head2 = head2.next
return head
|
7a1befdca37081fe4fbbeb9efaf89862b0f16a3c | eprj453/algorithm | /KAKAO/2019winterIntern/크레인인형뽑기.py | 797 | 3.5625 | 4 | def solution(board, moves):
answer = 0
basket = []
for m in moves:
i = 0
while i < len(board):
doll1 = board[i][m-1]
if doll1 != 0:
if not basket:
basket.append(doll1)
else:
doll2 = basket[-1]
if doll1 == doll2:
print(basket)
print(doll1, doll2)
basket.pop()
answer += 2
else:
basket.append(doll1)
board[i][m-1] = 0
break
i += 1
return answer
print(solution([[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]], [1,5,3,5,1,2,1,4])) |
f84db76a017f0ffd5a28c8c62b969c9616b8f92a | rnarodit/100daysofcode | /Day 16/objectOriantedProgramming.py | 1,331 | 4.4375 | 4 | #OOP -> instead of having one long an complicated code (procedural). you simplify the relationships in your code by seprating it into different components that can later reused in other code.
#OOP tries to model real world objects -> divide to what object has (attributes -> fancy way to say variable) and what object does(methods -> functions)
# we use the object blueprint to generate multiple versions of the object-> the blue print is a class and the versions generated are objects
#object is the actual thing that we will be using in the code
# creating an object -> car = CarBluePrint() -> note the pascal case of the class
# from turtle import Turtle , Screen
# timmy = Turtle()
# print (timmy)
# myScreen= Screen ()
# #accessing attributes -> car.speed
# print (myScreen.canvheight)
# #using methods -> car.stop()
# timmy.shape("turtle")
# timmy.color("red")
# timmy.forward(100)
# timmy.speed("normal")
# myScreen.exitonclick()
#python package is a whole bunch of code that other people have written -> serve a particular purpose
#to use packages you find you need to install it
from prettytable import PrettyTable
table = PrettyTable()
table.add_column("Pokemon Name",["Pikachu","Squirtle", "Charmander"])
table.add_column("Type",["Electric","Water", "Fire"])
table.align="l"
#table.add_column("Type")
print(table)
|
d5f2dd3a507ace4c76d9f881262c331e6313d1d4 | dilyanpenev/advent-of-code | /python/day2.py | 1,454 | 3.65625 | 4 | def check_occurrences(str, letter, min_chars, max_chars):
count = 0
for char in str:
if char == letter:
count += 1
if count >= min_chars:
if count <= max_chars:
return True
else:
return False
def check_positions(str, letter, pos1, pos2):
if len(str) < pos2:
return False
pos1 = pos1 - 1
pos2 = pos2 - 1
if str[pos1] == letter:
if str[pos2] == letter:
return False
else:
return True
else:
if str[pos2] == letter:
return True
else:
return False
if __name__ == "__main__":
with open('../inputs/day2.txt') as f:
lines = []
for line in f:
line = line.split()
if line:
lines.append(line)
minRange = [int(i[0].split('-')[0]) for i in lines]
maxRange = [int(i[0].split('-')[1]) for i in lines]
letters = [i[1][0] for i in lines]
passwords = [i[2] for i in lines]
# Task 1
correct_passwords = 0
for k in range(len(lines)):
if (check_occurrences(passwords[k], letters[k], minRange[k], maxRange[k])):
correct_passwords += 1
print(correct_passwords)
# Task 2
valid_passwords = 0
for n in range(len(lines)):
if (check_positions(passwords[n], letters[n], minRange[n], maxRange[n])):
valid_passwords += 1
print(valid_passwords)
|
e11e6db8f7fa8ad886a7ec287ed9d04c7b334287 | Vladimir-Surta/Vladimir-Surta | /task_1_3.py | 142 | 3.515625 | 4 | # Task №3
l = int(input('Введите значение "l_длина ребра куба:"'))
v = l ** 3
s = 4 * l ** 2
print({v, s})
|
b95c0c7a7440c0b57e89b77d74da70ee8a390bec | masterchief164/schoolprojects | /l5q3.py | 226 | 3.5625 | 4 | def fibo():
a = 1
b = 1
def fib():
nonlocal a, b
n = a + b
b = a
a = n
return b
return fib
f = fibo()
inp = int(input())
for i in range(inp):
print(f(), end=" ")
|
cb92340dda44cb84fd10dcc8f13506b10604a5cd | SURGroup/UQpy | /docs/code/surrogates/pce/plot_pce_ishigami.py | 5,479 | 3.765625 | 4 | """
Ishigami function (3 random inputs, scalar output)
======================================================================
In this example, we approximate the well-known Ishigami function with a total-degree Polynomial Chaos Expansion.
"""
# %% md
#
# Import necessary libraries.
# %%
import numpy as np
import math
import numpy as np
from UQpy.distributions import Uniform, JointIndependent
from UQpy.surrogates import *
# %% md
#
# We then define the Ishigami function, which reads:
# :math:`f(x_1, x_2, x_3) = \sin(x_1) + a \sin^2(x_2) + b x_3^4 \sin(x_1)`
# %%
# function to be approximated
def ishigami(xx):
"""Ishigami function"""
a = 7
b = 0.1
term1 = np.sin(xx[0])
term2 = a * np.sin(xx[1])**2
term3 = b * xx[2]**4 * np.sin(xx[0])
return term1 + term2 + term3
# %% md
#
# The Ishigami function has three random inputs, which are uniformly distributed in :math:`[-\pi, \pi]`. Moreover, the
# input random variables are mutually independent, which simplifies the construction of the joint distribution. Let's
# define the corresponding distributions.
# %%
# input distributions
dist1 = Uniform(loc=-np.pi, scale=2*np.pi)
dist2 = Uniform(loc=-np.pi, scale=2*np.pi)
dist3 = Uniform(loc=-np.pi, scale=2*np.pi)
marg = [dist1, dist2, dist3]
joint = JointIndependent(marginals=marg)
# %% md
#
# We now define our PCE. Only thing we need is the joint distribution.
#
# We must now select a polynomial basis. Here we opt for a total-degree (TD) basis, such that the univariate
# polynomials have a maximum degree equal to :math:`P` and all multivariate polynomial have a total-degree
# (sum of degrees of corresponding univariate polynomials) at most equal to :math:`P`. The size of the basis is then
# given by :math:`\frac{(N+P)!}{N! P!}`
# where :math:`N` is the number of random inputs (here, :math:`N+3`).
# %%
# maximum polynomial degree
P = 6
# construct total-degree polynomial basis
polynomial_basis = TotalDegreeBasis(joint, P)
# check the size of the basis
print('Size of PCE basis:', polynomial_basis.polynomials_number)
# %% md
#
# We must now compute the PCE coefficients. For that we first need a training sample of input random variable
# realizations and the corresponding model outputs. These two data sets form what is also known as an
# ''experimental design''. It is generally advisable that the experimental design has :math:`2-10` times more data points
# than the number of PCE polynomials.
# %%
# create training data
sample_size = int(polynomial_basis.polynomials_number*5)
print('Size of experimental design:', sample_size)
# realizations of random inputs
xx_train = joint.rvs(sample_size)
# corresponding model outputs
yy_train = np.array([ishigami(x) for x in xx_train])
# %% md
#
# We now fit the PCE coefficients by solving a regression problem. There are multiple ways to do this, e.g. least
# squares regression, ridge regression, LASSO regression, etc. Here we opt for the _np.linalg.lstsq_ method, which
# is based on the _dgelsd_ solver of LAPACK.
# %%
# fit model
least_squares = LeastSquareRegression()
pce = PolynomialChaosExpansion(polynomial_basis=polynomial_basis, regression_method=least_squares)
pce.fit(xx_train, yy_train)
# %% md
#
# By simply post-processing the PCE's terms, we are able to get estimates regarding the mean and standard deviation
# of the model output.
# %%
mean_est = pce.get_moments()[0]
var_est = pce.get_moments()[1]
print('PCE mean estimate:', mean_est)
print('PCE variance estimate:', var_est)
# %% md
#
# Similarly to the mean and variance estimates, we can very simply estimate the Sobol sensitivity indices, which
# quantify the importance of the input random variables in terms of impact on the model output.
# %%
from UQpy.sensitivity import *
pce_sensitivity = PceSensitivity(pce)
pce_sensitivity.run()
sobol_first = pce_sensitivity.first_order_indices
sobol_total = pce_sensitivity.total_order_indices
print('First-order Sobol indices:')
print(sobol_first)
print('Total-order Sobol indices:')
print(sobol_total)
# %% md
#
# The PCE should become increasingly more accurate as the maximum polynomial degree :math:`P` increases. We will test
# that by computing the mean absolute error (MAE) between the PCE's predictions and the true model outputs, given a
# validation sample of :math:`10^5` data points.
# %%
# validation data sets
np.random.seed(999) # fix random seed for reproducibility
n_samples_val = 100000
xx_val = joint.rvs(n_samples_val)
yy_val = np.array([ishigami(x) for x in xx_val])
mae = [] # to hold MAE for increasing polynomial degree
for degree in range(16):
# define PCE
polynomial_basis = TotalDegreeBasis(joint, degree)
least_squares = LeastSquareRegression()
pce_metamodel = PolynomialChaosExpansion(polynomial_basis=polynomial_basis, regression_method=least_squares)
# create training data
np.random.seed(1) # fix random seed for reproducibility
sample_size = int(pce_metamodel.polynomials_number * 5)
xx_train = joint.rvs(sample_size)
yy_train = np.array([ishigami(x) for x in xx_train])
# fit PCE coefficients
pce_metamodel.fit(xx_train, yy_train)
# compute mean absolute validation error
yy_val_pce = pce_metamodel.predict(xx_val).flatten()
errors = np.abs(yy_val.flatten() - yy_val_pce)
mae.append(np.linalg.norm(errors, 1) / n_samples_val)
print('Polynomial degree:', degree)
print('Mean absolute error:', mae[-1])
print(' ')
|
7a7bf09f18ddb37cb36ca832c5b198f6ac76bde0 | lineva642/08.11.2016 | /vector2.py | 531 | 3.5 | 4 | class Vector:
def __init__(self, x, y):
self.x=x
self.y=y
def __str__(self):
return str(self.x)+', ' + str(self.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y + other.y)
n=int(input())
a=[]
m=0
im=0
for i in range(n):
a.append(Vector(input()))
if float(abs(a[i])) > m:
m=abs(a[i])
im=i
print('Наибольшее расстояние:',a[im])
|
b6106da3ddd902d597a38c8dc95034144fafa904 | webclinic017/algorithmic_trading_in_python | /hult_classes/class_5/bt_loops.py | 2,499 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 28 22:33:04 2019
Showing looping with bt.py
This is a very inelegant way of looping. I did it this way to make it very
clear what was going on and how it relates to the steps described in class.
It is often useful to start with an inelegant program when you are trying new
things. It is also often useful to code something 'quick and dirty' when you
have a limited time to work on it.
@author: MichaelRolleigh
"""
# import pandas
import pandas as pd
# must import bt to use bt
import bt
"""
Use custom function to make it easier to repeatedly use the same strat
Note how I changed the start date so that it was very short to make program
run faster while debugging.
"""
def above_sma(tickers, sma_per=50, start='2018-01-01', name='above_sma'):
"""
Long securities that are above their n period
Simple Moving Averages with equal weights.
"""
# download data
data = bt.get(tickers, start=start)
# calc sma
sma = data.rolling(sma_per).mean()
# create strategy
s = bt.Strategy(name, [bt.algos.SelectWhere(data > sma),
bt.algos.WeighEqually(),
bt.algos.Rebalance()])
# now we create the backtest
return bt.Backtest(s, data)
# Create a result_df to store results
result_df = pd.DataFrame(columns = ['SMA','CAGR','daily_sharpe'])
# Our simple investment universe
tickers = 'aapl,msft'
"""
Loop over SMA_number; It would be more elegant to define an object at the top
including SMA and loop over that column. That is more pythony. This 'for in range'
style is more like the math books on numerical recipes. It is sometimes useful to
write things this way to link it more easily with the model in your mind.
"""
for SMA_number in range(13,20):
# create a string that is the name of our SMA strategy
SMA_name='sma'+ str(SMA_number)
# generate result feeding the above_sma function variables that change in the loop
result = bt.run(above_sma(tickers, sma_per=SMA_number, name= SMA_name))
# There is a more elegant way to do this, but this works
result_df = result_df.append({'SMA':SMA_number,'CAGR':result.stats.at['cagr',SMA_name],
'daily_sharpe': result.stats.at['daily_sharpe',SMA_name]},ignore_index=True)
# Set the index to SMA. The other arguments are there because StackOverflow suggested them and they work
result_df.set_index('SMA',inplace=True, drop=True)
|
9a727f2e5801d2a62157cfc3b1fd53cda89e1593 | martanunesdea/coding-club | /encryption/encrypt_file.py | 482 | 3.640625 | 4 | from cryptography.fernet import Fernet
key = Fernet.generate_key()
# Saving the key in a separate file for later usage
file = open('key.key', 'wb') # Open the file as wb to write bytes
file.write(key) # The key is type bytes still
file.close()
# Open the file to encrypt
f = open('test.txt', 'rb')
data = f.read()
# Encrypt data
fernet = Fernet(key)
encrypted = fernet.encrypt(data)
# Write the encrypted file
f = open('test.txt.encrypted', 'wb')
f.write(encrypted)
f.close() |
762f3b2d29a68b57e19b968fec445eef5d580685 | gtg7784/2020_summer_algoritim | /2110.py | 637 | 3.71875 | 4 | import sys
N,C = map(int, sys.stdin.readline().split())
home = [int(sys.stdin.readline()) for _ in range(N)]
home.sort()
def routerInstall(distance):
count = 1
cur_home = home[0]
for i in range(1,N):
if (distance <= home[i] - cur_home):
count+=1
cur_home = home[i]
return count
def BinarySearch(target):
start = 1
end = home[-1] - home[0]
while(start<=end):
mid = (start+end)//2
router_cnt = routerInstall(mid)
if router_cnt < target:
end = mid - 1
elif router_cnt >= target:
answer = mid
start = mid + 1
return answer
print(BinarySearch(C)) |
265b10d854421b80c83bb3443102728859e04f77 | PRINCEHR/Python | /c5.py | 189 | 3.734375 | 4 | '''def f(int ):
#print ("i")
pass
f()'''
m= input("enter no")
def f():
for x in range(1, 11):
list1 = x *m
print ("%s x %s = %s" %(m,x,list1))
f()
|
2927a7a7deaace222d66fde9a6e365523614c2ff | ShalomVanunu/SelfPy | /Targil6.1.2.py | 240 | 3.5625 | 4 |
def shift_left(my_list):
a , b ,c = my_list
new_my_list = [b ,c, a]
print(new_my_list)
def main(): # Call the function func
shift_left([0, 1, 2])
shift_left(['monkey', 2.0, 1])
if __name__ == "__main__":
main()
|
583347c741490cc0c06113b46ea51462df16fa53 | Jeetuyadav82/Take-Home-Coding-Challange-consultadd | /Exercise_3_Balance Bots/Balance Bot.py | 1,178 | 3.796875 | 4 | import collections
import re
bots = collections.defaultdict(list)
outputs = dict()
# here we are taking input as .txt file
lines = open('input3.txt')
rules = [line.split() for line in lines] # input3.txt is file name
while rules:
for r in rules:
if r[0] == 'value':
bots[int(r[5])].append(int(r[1]))
rules.remove(r)
else:
a = int(r[1])
if len(bots[a]) == 2:
bots[a].sort()
low, high = bots[a]
if r[5] == 'bot':
bots[int(r[6])].append(low)
else:
outputs[int(r[6])] = low
if r[10] == 'bot':
bots[int(r[11])].append(high)
else:
outputs[int(r[11])] = high
rules.remove(r)
for n, value in bots.items():
if value == [17, 61]:
print("# Answer of part 1")
print("bot which compares value-17 and value-61 microchips is =", n)
break
print("\n# Answer of part 2")
print("The product of the microchip values is", outputs[0] * outputs[1] * outputs[2])
|
13856a934d9a3a29416b107262c9a0abae850957 | santhosh-kumar/AlgorithmsAndDataStructures | /python/problems/string/add_two_binary_strings.py | 1,620 | 3.796875 | 4 | """
Add two binary strings
Given two binary strings, return their sum (also a binary string).
Example:
a = "100"
b = "11"
Return a + b = “111”.
"""
from common.problem import Problem
class AddTwoBinaryStrings(Problem):
"""
AddTwoBinaryStrings
"""
PROBLEM_NAME = "AddTwoBinaryStrings"
NOT_FOUND = -1
def __init__(self, input_string1, input_string2):
"""AddTwoBinaryStrings
Args:
input_string1: First binary string
input_string1: Second binary string
Returns:
None
Raises:
None
"""
super().__init__(self.PROBLEM_NAME)
self.input_string1 = input_string1
self.input_string2 = input_string2
def solve(self):
"""Solve the problem
Note:
Args:
Returns:
string
Raises:
None
"""
print("Solving {} problem ...".format(self.PROBLEM_NAME))
max_len = max(len(self.input_string1), len(self.input_string2))
self.input_string1.zfill(max_len)
self.input_string2.zfill(max_len)
carry = 0
result = ''
for i in range(max_len - 1, -1, -1):
char1 = self.input_string1[i]
char2 = self.input_string2[i]
r = carry
if char1 == '1':
r = r + 1
if char2 == '1':
r = r + 1
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry != 0:
result = '1' + result
return result.zfill(max_len)
|
f4da423a210e5c34c7152a6f0f2c2a371177757a | labulel/python-challenge | /PyPoll/main-LL.py | 3,065 | 3.859375 | 4 | import os
import csv
csvpath = os.path.join("Resources","03-Python_Homework_Instructions_PyPoll_Resources_election_data.csv")
#Import and read csvfile:
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#skip header:
csv_header = next(csvreader)
#set starting value of running votes count:
votes_count = 0
khan_count = 0
correy_count = 0
li_count = 0
otooley_count = 0
#create a list of candidates:
candidates = []
#create a dictionary of candidates and votes received:
candidate_votes ={}
#loop through the rows in the csv file:
for row in csvreader:
#update the running votes count:
votes_count = votes_count+1
if row[2] == "Khan":
khan_count = khan_count + 1
if row[2] == "Correy":
correy_count = correy_count + 1
if row[2] == "Li":
li_count = li_count + 1
if row[2] == "O'Tooley":
otooley_count = otooley_count + 1
#update the dictionary with candidates and their votes count:
if row[2] not in candidates:
candidates.append(row[2])
candidate_votes[row[2]]=0
else:
votes = candidate_votes[row[2]]+1
candidate_votes[row[2]] = votes
#define the winning candidate name as a string:
winning_candidate = ""
#set the starting point of the winner total votes count:
winning_count = 0
#looping through the candidiate_votes dictionary to identify the candidiate with the max vote count:
for i in candidate_votes:
if candidate_votes[i] > winning_count:
winning_candidate = i
winning_count = candidate_votes[i]
#calculate the total votes per candidate and percentage of total votes:
khan_percent = "{0:.2f}".format((khan_count/votes_count)*100)
correy_percent = "{0:.2f}".format((correy_count/votes_count)*100)
li_percent = "{0:.2f}".format((li_count/votes_count)*100)
otooley_percent = "{0:.2f}".format((otooley_count/votes_count)*100)
#print summary results:
print ("Election Results")
print ("-------------------------")
print(f"Total Votes: {votes_count}")
print(f"Khan: {khan_percent}% {khan_count}")
print(f"Correy: {correy_percent}% {correy_count}")
print(f"Li: {li_percent}% {li_count}")
print(f"O'Tooley: {otooley_percent}% {otooley_count}")
print(f"Winner: {winning_candidate}")
#write results to a new txt file:
PyPoll = os.path.join("..","PyPoll","Analysis","PyPoll_analysis.txt")
with open(PyPoll,"w") as csvfile:
csvfile.write("Election Results\n")
csvfile.write("-------------------------\n")
csvfile.write(f"Total Votes: {votes_count}\n")
csvfile.write(f"Khan: {khan_percent}% {khan_count}\n")
csvfile.write(f"Correy: {correy_percent}% {correy_count}\n")
csvfile.write(f"Li: {li_percent}% {li_count}\n")
csvfile.write(f"O'Tooley: {otooley_percent}% {otooley_count}\n")
csvfile.write("-------------------------\n")
csvfile.write(f"Winner: {winning_candidate}\n") |
e1f4dfe9b1fe22f5512e9f871af89110f097ae41 | nihao-hit/leetcode | /Third Maximum Number.py | 619 | 3.8125 | 4 | import sys
class Solution:
def thirdMax(self,nums):
'''
:type nums:List[int]
:rtype:int
'''
nums = set(nums)
first = second = third = -sys.maxsize
for n in nums:
if n > first:
first,second,third = n,first,second
elif n > second:
second,third = n,second
elif n > third:
third = n
return third if first != second != third != -sys.maxsize else first
'''
技巧1:sys.maxsize
技巧2:链式比较,例:first != second != third != -sys.maxsize
可以用dis分析
''' |
3eb60a27fc3fb4d66b948e572654a1e2c2573665 | dpneko/algorithmTest | /11. 盛最多水的容器.py | 903 | 3.734375 | 4 | """
给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
max_contain = 0
i, j = 0, len(height)-1
while i < j:
max_contain = max(max_contain, min(height[i], height[j])*(j-i))
if height[i] >= height[j]:
j -= 1
else:
i += 1
return max_contain
Solution().maxArea([1,2,1]) |
049f7cf9cf2f79c47332d7e5b8829df985c1d122 | Leonardo-KF/Python3 | /ex018.py | 315 | 4.09375 | 4 | from math import cos, sin, radians, tan
a1 = float(input('Digite um ângulo: °'))
cos = cos(radians(a1))
sen = sin(radians(a1))
tg = tan(radians(a1))
print(f'O seno do angulo {a1}° é: {sen:.2f}°')
print(f'O cosseno do angulo {a1}° é: {cos:.2f}°')
print(f'A tangente do angulo {a1}° é: {tg:.2f}°')
|
0cf10137a153ee33f9c87707b2004d6f03fee738 | aditiwalia350/100DaysOfAlgorithms | /Recursion/factorial.py | 185 | 3.828125 | 4 | def factorial(n):
if n == 0:
return 1
elif n > 0:
return n * factorial(n - 1)
print(factorial(5))
print(factorial(0))
print(factorial(1))
print(factorial(-1))
|
4924e290786a88fc322fde9d374f1e53a243f184 | Venkatesh123-dev/Python_Basics | /Day_15.py | 1,939 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 16:30:03 2020
#itertools.product()
@author: venky
A = [1, 2]
B = [3, 4]
AxB = [(1, 3), (1, 4), (2, 3), (2, 4)]
"""
from itertools import product
A = [int(x) for x in input().split() ]
B = [int(y) for y in input().split() ]
print (*product(A,B))
from itertools import product
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in product(a,b):
print(i, end = " ")
#itertools.permutations()
"""
print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')
Sample Input
HACK 2
Sample Output
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH
"""
from itertools import permutations
s,n = input().split()
s = sorted(s)
n = int(n)
for i in list( permutations(s,n)):
print(''.join(i))
import itertools
string, permutation_size = input().split()
for permutation in itertools.permutations(sorted(string), int(permutation_size)):
print(''.join(permutation))
#itertools.combinations()
"""
Sample Input
HACK 2
Sample Output
A
C
H
K
AC
AH
AK
CH
CK
HK
"""
import itertools
from itertools import combinations
s,n = input().split()
s = sorted(s)
n = int(n)
for length in range(1,n+1):
for combination in itertools.combinations(s,length):
print(''.join(combination))
#second approach
import itertools
sk = input().split()
s = sk[0]
k = int(sk[1])
for i in range(1,k+1):
output = list(itertools.combinations(sorted(s),i))
for i in output:
for m in i:
print(m, end = '')
print()
#itertools.combinations_with_replacement()
"""
Sample Input
HACK 2
Sample Output
AA
AC
AH
AK
CC
CH
CK
HH
HK
KK
"""
import itertools
string,combination_size = input().split()
for combination in itertools.combinations_with_replacement(sorted(string),int(combination_size)):
print(''.join(combination))
|
f907f3db9cc16d24930aa482b05a2e2f65b5f932 | Ruslan5252/all-of-my-projects-byPyCharm | /курсы пайтон модуль 3/Задание 22.py | 186 | 3.53125 | 4 | a=1
s=0
k=0
while a != 0:
a = int(input("введите число"))
s += a
k+=1
print("среднее значение суммы введенных чисел ",s/(k-1))
|
0cc63017e465bb328a4f0618c683edc113a33229 | yuzurunishimiya/python-trick-01 | /merging_dict.py | 243 | 3.625 | 4 | dict1 = {
"name": "Hanekawa Tsubasa",
"meta": 50,
}
dict2 = {
"friend": "Senjougahara Hitagi",
"meta": 100
}
merged = {**dict1, **dict2}
print(merged)
# NOTE:
# If there are overlapping keys, the keys from the first dictionary will be overwritten. |
7e14676a28e7c764f566e3a74539ed6e8e8f282b | gabrielos307/cursoPythonIntersemestral17-2 | /Básico/ProgramaciónFuncional/recursion.py | 424 | 4 | 4 | ######
#Recursion
######
def factorial(num):
if num<1:
return 1
else:
return num*factorial(num-1)
#print(factorial(5))
#####
# Iteracion
#####
def factorial2(num):
fack=1
for i in range(2,num+1):
fack*=i
return fack
#print(factorial2(5))
######
#Map
#####
items = list(range(1,11))
print(items)
cuadrados=[]
cuadrados= list(map(lambda x: x ** 2, items))
print(cuadrados) |
7d94ac2d577d301eaff7eafc052476ed630d64ae | SandeepShewalkar/Demonstrations | /Python/generator.py | 835 | 3.890625 | 4 | # A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1,-1,-1):
# print("i : ",my_str[i])
yield my_str[i]
# a = my_gen()
# next(a)
# next(a)
# next(a)
# next(a)
# Using for loop
# for item in my_gen():
# print(item)
for char in rev_str("esrever"):
print()
my_list = [1, 3, 6, 10]
# square each term using list comprehension
# Output: [1, 9, 36, 100]
[x**2 for x in my_list]
# same thing can be done using generator expression
# Output: <generator object <genexpr> at 0x0000000002EBDAF8>
(x**2 for x in my_list) |
6eb18f2ef10d9558abb045595b5bfc1b9fd8f4d6 | pyplusplusMF/202110_44 | /_44semana06clase18Matplotlib.py | 3,158 | 3.609375 | 4 | # clase martes 8 de junio
import matplotlib.pyplot as plt
def ejemplo1():
# grupo A
x1=[2,5,6,14]
y1= [11,22,33,44]
# grupo B
x2=[2,5,6,15]
y2=[4,12,18,45]
#Graficar 2 lineas en la misma grid
plt.plot(x1,y1, color="blue", linewidth = 3, label = 'Linea 1')
plt.plot(x2,y2, color="green", linewidth = 3, label = 'Linea 2')
plt.title('Dos Graficas juntas')
plt.xlabel('Eje X')
plt.ylabel('Eje Y')
plt.legend()
plt.grid()
plt.show()
# ejemplo1()
def ejemplo2():
# grupo A
x1=[2,5,6,14]
y1= [11,22,33,44]
# grupo B
x2=[2,5,6,15]
y2=[4,12,18,45]
#Grafico de barras. Cuando coinciden la misma X, las apila
plt.bar(x1,y1, color="blue", linewidth = 3, label = 'Barra 1')
plt.bar(x2,y2, color="green", linewidth = 3, label = 'Barra 2')
plt.title('Dos Barras juntas')
plt.xlabel('Eje X')
plt.ylabel('Eje Y')
plt.legend()
plt.grid()
plt.show()
# ejemplo2()
# Histograma
def ejemplo3():
#Histogramas
Datos = [20,22,21,20,23,25,28,40,22,23,22,15,16,18,18,19,21,22,24,4,12,17,17,22,30,]
Rangobin=[0,10,20,30,40]
plt.hist(Datos, Rangobin, histtype='bar',rwidth=0.8, color='lightgreen')
plt.title('Histograma')
plt.xlabel('Eje X')
plt.ylabel('Eje Y')
#plt.grid() #la grid no es necesaria (lineas horizontales y verticales)
plt.show()
# ejemplo3()
def ejemplo4():
# grupo A
x1=[2,5,6,14]
y1= [11,22,33,44]
#Scatter
plt.scatter(x1,y1, color="red", label = 'Puntos 1')
plt.title('Dos Graficas juntas')
plt.xlabel('Eje X')
plt.ylabel('Eje Y')
plt.legend()
plt.grid()
plt.show()
# ejemplo4()
# https://matplotlib.org/stable/gallery/color/named_colors.html
def ejemplo5():
#Pie
valores =[20,40,60,80]
plt.pie(valores, labels=['Prekinder', 'kinder', 'primaria', 'secundaria'], colors=['red','purple','blue','orange']
, startangle=90,shadow=True, explode=(0.1,0,0,0),autopct='%1.1f%%')
plt.title('Grafico circular')
plt.show()
# ejemplo5()
def ejemplo6():
# Carga dataset del Titanic
import pandas as pd
df = pd.read_csv('titanic3.csv')
cantidades=df.survived.value_counts()
plt.figure(figsize=(30,20)) #tamaño en pixeles? pulgadas? o una proporción?
plt.subplot2grid((2,2),(0,0))
plt.subplot2grid((2,2),(1,0))
plt.subplot2grid((2,2),(0,1))
plt.subplot2grid((2,2),(1,1))
print(cantidades[0],cantidades[1])
plt.figure(figsize=(30,20)) #tamaño en pixeles? pulgadas? o una proporción?
plt.subplot2grid((2,2),(0,0)) #Grid de 2x2. primer grafico en la posicion (0,0)
df.survived.value_counts().plot(kind='bar', alpha=0.5) #seriexxxx.plot()
plt.title('Sobrevivieron - Cantidad')
plt.subplot2grid((2,2),(0,1))
df.survived.value_counts(normalize=True).plot(kind='bar', alpha=0.5)
plt.title('Sobrevivieron- Porcentaje')
plt.subplot2grid((2,2),(1,0))
df.survived.value_counts().plot(kind='bar', alpha=0.5)
plt.title('Sobrevivieron - Cantidad')
plt.subplot2grid((2,2),(1,1))
plt.bar(cantidades[0],cantidades[1], color="blue", alpha=0.5, linewidth = 3, label = 'Barra 1')
plt.title('Dos Barras juntas')
plt.xlabel('Eje X')
plt.ylabel('Eje Y')
plt.legend()
plt.grid()
ejemplo6() |
6841b32c92e75fbf3237549a83a508ba03d87716 | swell1009/ex | /ForKids/appendixb/ch11-octagon.py | 138 | 3.84375 | 4 | import turtle
t = turtle.Pen()
def octagon(size):
for x in range(1, 9):
t.forward(size)
t.right(45)
octagon(100)
|
cdb70923c9882e7b8d52bfeffb2fe41673b9be9b | AmeyaChavre/py-01-rep | /Spreadsheets and PDFs/csv_data_extrct.py | 1,121 | 3.90625 | 4 | import csv
open_file = open("C:\\Users\\User-PC\\Desktop\\example.csv",encoding="utf-8")
csv_data = csv.reader(open_file)
extracted_data = list(csv_data)
print(f"Extracted Data : {extracted_data}\n")
print(f"Number of rows in the spreadsheet : {len(extracted_data)-1}\n")
print("List of Columns:\n")
column_count=0
for column_name in extracted_data[0]:
column_count+=1
print(f"\tColumn {column_count} : {column_name}")
print(f"\nNumber of columns in the spreadsheet : {column_count}\n")
mailing_list=[]
for emails in extracted_data[1:]:
mailing_list.append(emails[3])
print(f"List of all emails in spreadsheet : {mailing_list}")
amazon_accounts = []
for any_email in mailing_list:
if "amazon.com" in any_email:
amazon_accounts.append(any_email)
print(f"\nList of Amazon Accounts : {amazon_accounts}")
aws_accounts = open('C:\\Users\\User-PC\\Desktop\\aws_accounts.csv',mode='w',newline='')
csv_results = csv.writer(aws_accounts,delimiter=',')
csv_results.writerow(amazon_accounts)
aws_accounts.close()
print(f"Amazon accounts have been saved in aws_accounts.csv")
|
2927ee0097dec28d5bc943467f4cb2ab8bc2cff3 | pyaiveoleg/semester_4_python | /homeworks/homework_1/task_2/tail.py | 742 | 3.859375 | 4 | import argparse
from typing import List
def print_tail(file_names: List[str], rows_number: int = 10):
print_file_name = len(file_names) > 1
for file_name in file_names:
try:
with open(file_name) as f:
if print_file_name:
print(f"==> {file_name} <==")
print("".join(list(f)[-rows_number:]))
except FileNotFoundError:
print(f"No such file: {file_name}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-n", type=int, help="Quantity of lines", default=10)
parser.add_argument("files", type=str, nargs="+", help="List of files")
args = parser.parse_args()
print_tail(args.files, args.n)
|
148dc9af09011a332be81b4b788b99c0605b29a4 | MilindShingote/Python-Assignments | /Assignment6_1.py | 354 | 3.65625 | 4 | class Demo:
Value=10;
def __init__(self,Value1,Value2):
self.No1=Value1;
self.No2=Value1;
def Fun(self):
print(self.No1);
print(self.No2);
def Gun(self):
print(self.No1);
print(self.No2);
def main():
obj1=Demo(11,21);
obj2=Demo(51,101);
obj1.Fun();
obj2.Fun();
obj1.Gun();
obj2.Gun();
if(__name__=="__main__"):
main();
|
e652c9f1128135fe711a463b49f5597da6ec548e | ranguisheng/python_test_project | /test/itertest.py | 1,372 | 3.546875 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
'''
iter test
@author: Micahel Ran
'''
import itertools
import struct
import hashlib
# na=itertools.count(1)
# na=itertools.cycle('ABC')
na=itertools.repeat('A',10)
for n in na:
print(n)
natuals = itertools.count(1)
ns=itertools.takewhile(lambda x:x<=10,natuals)
print(list(ns))
for c in itertools.chain('ABC', 'XYZ'):
print(c)
for key, group in itertools.groupby('AAABBBCCAAA'):
print(key,list(group))
for key, group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
print(key, list(group))
#测试md5摘要算法
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
print(md5.hexdigest())
#分多次计算摘要
md5 = hashlib.md5()
md5.update('how to use md5 in '.encode('utf-8'))
md5.update('python hashlib?'.encode('utf-8'))
print(md5.hexdigest())
#sha1测试
sha1 = hashlib.sha1()
sha1.update('how to use sha1 in '.encode('utf-8'))
sha1.update('python hashlib?'.encode('utf-8'))
print(sha1.hexdigest())
#sha256测试
sha1 = hashlib.sha256()
sha1.update('how to use sha1 in '.encode('utf-8'))
sha1.update('python hashlib?'.encode('utf-8'))
print(sha1.hexdigest())
#sha512测试
sha1 = hashlib.sha512()
sha1.update('13426314653'.encode('utf-8'))
print(sha1.hexdigest())
#struct测试
aa=struct.pack('>I', 10240099)
print(aa)
bb=struct.unpack('>I', b'\x00\x9c@c')
print(bb) |
424c2b61704004f75119bffd0732a0d5d9f86238 | chidieberex/cfo-thinkcspy3-python | /numbers in the list-squares-total sum-total multiplication.py | 668 | 3.65625 | 4 | '''
# 3.8 Exercises, number 5a:
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for c in xs:
ca = str(c) + " is one of the numbers in the list."
print(ca)
'''
'''
# 3.8 Exercises; number 5b:
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for c in xs:
ca = str(
c) + " is one of the numbers in the list and its square is " + str(c * c) + "."
print(ca)
'''
'''
# 3.8 Exercises, number 5c:
total = 0
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for c in xs:
total += c
# print(total)
print(total)
'''
'''
# 3.8 Exercises, number 5d:
total = 1
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
for c in xs:
total *= c
print(total)
print(total)
'''
|
1cbe8ddb71242a8a573d8aabcc08218a308c49a5 | jntushar/leetcode | /1047. Remove All Adjacent Duplicates In String.py | 659 | 3.8125 | 4 | """
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
"""
"""---SOLUTION---"""
class Solution:
def removeDuplicates(self, S: str) -> str:
stack = []
for i in S:
if len(stack) == 0 or i != stack[-1]:
stack.append(i)
else:
stack.pop(-1)
res = ''
for i in stack:
res += i
return res |
d6a5071a1a7791e46d8730bfb8418c83df18498e | mkzia/eas503 | /old/spring2020/week7/oop_example2.py | 1,644 | 3.734375 | 4 | # Create a Person class with first name and last name
# Create a Student class that inherits from person name
# and adds credit_hours and q_point
# The Person class should define __repr__ function
# The student class must define get_gpa()
# Read from data.tsv each line and create a student object and
# store it in a list
#o do the same using in and max
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __repr__(self):
return '{}, {}'.format(self.last_name, self.first_name)
class Student(Person):
def __init__(self, first_name, last_name, credit_hours, q_point):
super().__init__(first_name, last_name)
self.credit_hours = credit_hours
self.q_point = q_point
def get_gpa(self):
return self.q_point/self.credit_hours
students = []
with open('data.tsv') as file:
for line in file:
if not line.strip():
continue
name, credit_hours, q_point = line.strip().split('\t')
last_name, first_name = name.split(',')
s = Student(first_name, last_name, int(credit_hours), int(q_point))
students.append(s)
max_student = students[0]
min_student = students[0]
for student in students:
if student.get_gpa() > max_student.get_gpa():
max_student = student
if student.get_gpa() < min_student.get_gpa():
min_student = student
print(max_student, max_student.get_gpa())
print(min_student, min_student.get_gpa())
l_func = lambda student: student.get_gpa()
print(min(students, key=l_func))
print(max(students, key=l_func))
|
1db308270debf19d1acb7f3a6a8d594b7cdd6ac2 | kaiCbs/pycookbook | /Chapter8/8.13.implementing_a_data_model_or_type_system.py | 2,061 | 3.65625 | 4 | class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for key, val in opts.items():
setattr(self, key, val)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
class Typed(Descriptor):
expected_type = type(None)
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError("expected", self.expected_type)
super().__set__(instance, value)
class Unsigned(Descriptor):
def __set__(self, instance, value):
if value < 0:
raise ValueError("Expected >= 0")
super().__set__(instance, value)
class MaxSized(Descriptor):
def __init__(self, name=None, **opts):
if "size" not in opts:
raise TypeError("missing size option")
super().__init__(name, **opts)
def __set__(self, instance, value):
if len(value) >= self.size:
raise ValueError("size must be <", str(self.size))
super().__set__(instance, value)
class Integer(Typed):
expected_type = int
class Float(Typed):
expected_type = float
class String(Typed):
expected_type = str
class UnsignedInteger(Integer, Unsigned):
...
class SizedString(String, MaxSized):
...
class UnsignedFloat(Float, Unsigned):
...
class Stock:
name = SizedString("name", size=8)
shares = UnsignedInteger("shares")
price = UnsignedInteger("price")
def __init__(self, name, shares, prices):
self.name = name
self.shares = shares
self.price = prices
s = Stock("Apple", 50, 201)
print(s.name, s.shares, s.price)
# s.shares = -1
# raise ValueError("Expected >= 0")
# class decorator
def check_attributes(**kwargs):
def decorate(cls):
for key, value in kwargs.items():
if isinstance(value, Descriptor):
value.name = key
setattr(cls, key, value)
else:
setattr(cls, key, value(key))
return cls
return decorate
|
f32428eb6c59c9e627541b0dc007c335aa3f8d22 | Vykstorm/numpy-examples | /creation.py | 2,184 | 4.21875 | 4 |
'''
This script shows different ways to create an numpy ndarray object
'''
import numpy as np
if __name__ == '__main__':
# Create an array from a iterable
np.array([3,1,4,1,5]) # dtype is guessed from value types
np.array([3,1,4,1,5], dtype=np.float64) # dtype can be specified as an argument.
# You can create an array from a previous one with different element type...
a = np.array([3,1,4,1,5], dtype=np.float64)
np.array(a, dtype=np.uint8)
a.astype(dtype=np.uint8)
# when a list of sublists is specified, the array will have 2 dimensions...
np.array([[1,0,0], [0,1,0], [0,0,1]])
# if its a list of sublists of sublits it will have 3, and so on
np.array([[
[1,0,0],
[0,1,0],
[0,0,1]],
[
[0,0,1],
[0,1,0],
[1,0,0]
]])
# This array creation syntax is wrong...
try:
np.array(1,2,3,4,5)
except:
pass
# You can create your own method to generate a 1D array with that syntax easily...
def vector(*args):
return np.array(args)
assert (vector(1,2,3) == np.array([1,2,3])).all()
np.zeros([3,3], dtype=np.uint64) # 3x3 array of zeros
np.ones([3,3], dtype=np.uint64) # 3x3 array of ones
np.empty([3,3], dtype=np.uint64) # 3x3 array of empty values
np.arange(0, 20, dtype=np.uint64) # 1D array with all numbers in [0, 20)
np.arange(1, 20, 2, dtype=np.uint64) # 1D array with eveny numbers in [0, 20)
# Creates a 1D array with 8 elements equally spaced between the range [0, 7/4 * pi]
np.linspace(0, 7 / 4 * np.pi, 8) # = ( 0, pi/4, pi/2, 3pi/4, pi, 5pi/4, 3pi/2, 7pi/4)
# Creates a 3x3 array with random values between [0, 1) using a uniform distribution
np.random.rand(3, 3)
# Creates a 3x3 array with random samples of the normal distribution.
np.random.randn(3,3)
# Saves an array to a file
with open('data.csv', 'w') as file:
np.arange(0, 10, dtype=np.uint64).tofile(file, sep=',')
# Read array from file
with open('data.csv', 'r') as file:
np.fromfile(file, sep=',', dtype=np.uint64)
|
1e1a71968beb46b216cefc57af3bd7f83a446b20 | diegotbl/Exercicios-How-to-Think-Like-a-Computer-Scientist | /Aula 2/Exercicio6.9.17.py | 753 | 4.0625 | 4 | import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
def is_multiple(a, b):
""" Checks if 'a' is a multiple of 'b' """
if a % b == 0:
return 1
return 0
test(is_multiple(12, 3))
test(is_multiple(12, 4))
test(not is_multiple(12, 5))
test(is_multiple(12, 6))
test(not is_multiple(12, 7))
# Yes, we can use is_factor from Exercise 6.9.16 in the definition of
# is_multiple like this:
#
# def is_multiple(a, b):
# """ Checks if 'a' is a multiple of 'b' """
# return is_factor(b, a)
|
d66326197f6de84d2dfea0f82c61552371da39f8 | duanzhihong/python--language | /algorithm/bucketSort.py | 287 | 3.828125 | 4 | #桶排序
def bucketSort(arr):
newArr = [0]*len(arr)
# print(newArr)
result =[]
for i in range(len(arr)):
newArr[arr[i]] += 1
for j in range(len(arr)):
result += [j]*newArr[j]
print(result)
arr = [5,3,6,1,2,7,5,4]
bucketSort(arr)
# print(result)
|
55d1127e6c17fe1d177aca515b287c84412b6329 | erbaowu/spider | /test1.py | 5,774 | 3.765625 | 4 | #判断字符串是否是整数、浮点数、复数
'''def isNum(str):
print(isinstance(str,(int,float,complex)))'''
#判断是否是质数
'''def isPrime(i):
l=[]
for x in range(2,i):
if i%x==0:
l.append(x)
if len(l)==0:
print(True)
else:
print(False)
isPrime(24)'''
#编写函数计算传入的数字、字母、空格和其他字符的个数
'''def counts(str):
m=n=x=y=0
for i in str:
if (i>='a'and i<='z') or (i>='A'and i<='Z'):
m=m+1
elif i>='0' and i<='9':
n=n+1
elif i==' ':
x=x+1
else:
y=y+1
print('字母的个数是:',m,'数字的个数是:',n,'空格的个数是:',x,'其他字符的个数是:',y,)
counts(' 1 x X ')'''
#打印200以内所有的质数
'''def printz():
for i in range(2,201):
l=[]
for x in range(2,i):
if i%x==0:
l.append(x)
if len(l)==0:
print(i)
else:
pass
printz()'''
#斐波那契数列的第n个数
'''def fib(n):
if n==1 or n==2:
return 1
else:
return fib(n-1)+fib(n-2)
'''
#随机密码生成
import random
'''ls=['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','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',1,2,3,4,5,6,7,8,9]
for i in range(1,11):
sj=random.sample(ls,8)
print (sj)'''
#英文字符频率统计
'''s=input('请输入一个英文字符串:')
#忽略大小写,简化问题
text=s.upper()
#解决符号问题
for ch in '!"#$%&()*+,-./;<=>?@[\\]^_{|}~`' or ' ':
text=text.replace(ch,'')
#引入空字典
counts={}
words=text
for word in words:
counts[word]=counts.get(word,0)+1
print(counts)'''
#中文字符频率统计
'''s=input('请输入一个中文字符串:')
#忽略大小写,简化问题
#解决符号问题
for ch in '!"#$%&()*+,-./;<=>?@[\\]^_{|}~`' or ' ':
s=s.replace(ch,'')
#引入空字典
counts={}
words=s
for word in words:
counts[word]=counts.get(word,0)+1
print(counts)'''
'''ls=[
['指标','2014年','2015年','2016年'],
['居民消费价格指数','102','101.4','102'],
['食品','103.1','102.3','104.6'],
['烟酒及用品','994','102.1','101.5'],
['衣着','102.4','102.7','101.4'],
['家庭设备和用品','101.2','101','100.5'],
['医疗保健和个人用品','101.3','102','101.1'],
['交通和通信','99.9','98.3','98.7'],
['娱乐教育文化','101.9','101.4','101.6'],
['居住','102','100.7','101.6']
]
f=open('test1.csv','w+',encoding='utf-8')
for row in ls:
f.write('-'.join(row))
a=f.read()
print(a)
f.close()'''
#文件中的大小写相反转化
'''f=open('eng.txt','r')
a=f.readlines()
z=open('test2.txt','a')
for lines in a:
for alpha in lines:
if alpha==alpha.upper():
z.write(alpha.lower())
else:
z.write(alpha.upper())
f.close()
z.close() '''
#查询某字符在文件中出现的次数
'''doc=input("请输入文件内容:")
f=open('test3.txt','w',encoding='utf-8')
f.write(doc)
zf=input('请输入需要查询的字符:')
ls=[]
for item in doc:
if item==zf:
ls.append(item)
else:
pass
print(len(ls))
f.close()'''
#生成随机矩阵
'''import random
f=open('test4.txt','w')
z=open('test2.csv','w')
ls=[]
for m in range(0,10):
for x in range(0,10):
ls=random.randint(1,100)
f.writelines('{:5}'.format(ls)+' ')
z.writelines('{:5}'.format(ls)+' ')
f.writelines('\n')
z.writelines('\n')
f.close()
z.close()'''
#生成10个随机数列表
'''import random
ls=[]
for i in range(10):
x=random.randint(0,101)
ls.append(x)
print(ls)'''
#时间格式化
'''import time
a=time.localtime()
b=time.strftime("%A,%m.%B %Y %H %M %p",a)
print(b)'''
#对字符串分词并且返回列表
'''import jieba
ls=[]
s='Python是最有意思的编程语言'
x=jieba.lcut(s)
ls=x
print(ls)'''
#分词并输出结果
'''import jieba
s='今天晚上我吃了意大利面'
jieba.add_word('意大利面')
i=jieba.lcut(s)
print(i)'''
#淘宝商品比价
import re
import requests
def getHTMLText (url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ''
def getHTMLTextFomFile(dir):
try:
with open(dir, encoding='utf-8') as f:
content=f.read()
return content
f.close()
except:
return ''
def parsepage(ilt,html):
try:
plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
tlt=re.findall(r'\"raw_title\"\:\".*?\"',html)
print(len(tlt))
for i in range(len(plt)):
print(i)
print(plt[i],tlt[i])
price=eval(plt[i].split(':')[1])
title=eval(tlt[i].split(':')[1])
ilt.append([title,price])
except:
print('')
def printgoodslist(ilt):
tplt='{:4}\t{:8}\t{:16}'
print(tplt.format('序号','价格','商品名称'))
count=0
for g in ilt:
count+=1
print(count,g[0],g[1])
def main():
goods='书包'
depth=2
start_url='https://s.taobao.com/search?q='+goods
infolist=[]
dir = 'sample.html'
html = getHTMLTextFomFile(dir)
parsepage(infolist, html)
printgoodslist(infolist)
"""
for i in range(depth):
try:
url=start_url+'&s='+str(44*i)
html=getHTMLText(url)
parsepage(infolist,html)
except:
continue
printgoodslist(infolist)
"""
if __name__ == "__main__":
main() |
2ac48c536296fb31ee5ec5856cae6c6ed56d7970 | ilkerthegeek/binary_search_compareTo_NaiveSearch | /main.py | 1,771 | 4.3125 | 4 | # implementation of binary search algorithm
# I will prove that binary search is faster than naive search
# Naive search basically search every index iteratively and ask if it is equal to target value
# if array consists the value it returns
# if it is not in the array it returns -1
import random
import time
def naive_search(l, target):
# example l = [1,2,3,4,18]
for i in range(len(l)):
if l[i] == target:
return i
return -1
# binary search uses divide and conquer method
# we will leverage the fact that our list is sorted.
def binary_search(l, target, low=None, high=None):
if low is None:
low = 0
if high is None:
high = len(l) - 1
if high < low:
return -1
midpoint = (low + high) // 2
if l[midpoint] == target:
return midpoint
elif target < l[midpoint]:
return binary_search(l, target, low, midpoint - 1)
else:
# target > l[midpoint]
return binary_search(l, target, midpoint + 1, high)
if __name__ == '__main__':
# l = [1, 15, 25, 60, 79, 90]
# target = 90
# print(naive_search(l, target))
# print(binary_search(l, target))
length = 1000
# build a sorted list of length 1000
sorted_list = set()
while len(sorted_list) < length:
sorted_list.add(random.randint(-3*length, 3 * length))
sorted_list = sorted(list(sorted_list))
start= time.time()
for target in sorted_list:
naive_search(sorted_list, target)
end = time.time()
print("Naive search time :", (end-start)/length, " seconds")
start = time.time()
for target in sorted_list:
binary_search(sorted_list,target)
end = time.time()
print("Binary search time :", (end-start)/length, " seconds")
|
9bfb65def6f62f01e66babcb2533f041769c0777 | HelloFranker/CS-Algorithms | /Recursive/sum.py | 476 | 3.796875 | 4 | # 数组求和的递归方法
# 如果列表为空,返回0
# 如果列表不为空,计算列表中第一个数字+数组中剩余其他的数字组成的数组
def sum_iter(lst):
if not lst:# 列表为空
return 0
else:# 列表不为空
return lst.pop(0)+sum_iter(lst)
l=[1,2,3,4,5,6]
print(sum_iter(l))
# 更简洁的写法
def sum(lst):
if lst == []:
return 0
return lst[0]+sum(lst[1:])
l2=[1,2,3,4,5,6]
print(sum(l2))
|
e5e2a52448c987abc55a0c65b9922b85bbdec091 | gameboy1024/ProjectEuler | /src/lib/math_utils.py | 4,424 | 3.796875 | 4 | import math
################################################################################
# Basic operations
################################################################################
def is_even(n):
return n % 2 == 0
def is_square(n):
root = math.sqrt(n)
return root == int(root)
def is_palindrome(n):
'''Test if a number/str is a palindrome, like 12321.'''
s = str(n)
length = len(s)
for i in xrange(0, length / 2):
if s[i] != s[length - i - 1]:
return False
return True
def reverse_str(s):
return s[::-1]
def reverse_number(n):
# Leading zeros are handled correctly by native casting.
if type(n) == int:
return int(reverse_str(str(n)))
elif type(n) == long:
return long(reverse_str(str(n)))
def gcd(a, b):
while b:
tmp = b
b = a % b
a = tmp
return a
################################################################################
# Large number operations
################################################################################
UNIT_LENGTH = 9
def add(a, b):
a = str(a)[::-1]
b = str(b)[::-1]
result = ''
i = 0
carry = 0
while carry != 0 or i < max(len(a), len(b)):
sum = carry
if i < len(a):
# ord('0') = 48
sum += ord(a[i]) - 48
if i < len(b):
sum += ord(b[i]) - 48
carry = sum / 10
result += str(sum % 10)
i += 1
return result[::-1]
def mul(a, b):
'''
Calculate the multiplication of two large int.
Args:
a: a list of int, representing digits of a large int. The digits are
reversed so 123 is [3, 2, 1]
b: same as a
Return:
Reversed list of digits of the multiplication.
'''
pass
def power_list(a, b, reverse=False):
result = [1]
for i in xrange(0, b):
carry = 0
j = 0
while carry != 0 or len(result) > j:
if j == len(result):
result.append(0)
result[j] = result[j] * a + carry
carry = result[j] / 10
result[j] %= 10
# print carry
j += 1
if not reverse:
result = result[::-1]
return result
################################################################################
# Prime related utils
################################################################################
def is_prime(n):
'''Naive way of prime checking, only use for occasional checks.'''
if n < 2: return False
if n == 2: return True
for i in xrange(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def totient(n, factors):
result = n
for f in factors:
n *= 1 - 1.0 / f
return int(n)
def get_prime_list(limit):
prime_checker = PrimeChecker(limit)
return prime_checker.get_prime_list()
class PrimeChecker(object):
'''A more advanced prime checker that uses seive.'''
def __init__(self, limit):
self._limit = int(limit)
self._prime_map = {}
self._prime_list = []
self.seive()
def seive(self):
numbers = [True] * (self._limit + 1)
for i in xrange(2, self._limit / 2 + 1):
if numbers[i] == True:
j = i * 2
while (j <= self._limit):
numbers[j] = False
j += i
for i in xrange(2, self._limit + 1):
if numbers[i] == True:
self._prime_map[i] = True
self._prime_list.append(i)
def get_prime_map(self):
return self._prime_map
def get_prime_list(self):
return self._prime_list
def is_prime(self, n):
if n > self._limit:
return is_prime(n)
else:
return n in self._prime_map
class PrimeFactorsGenerator(PrimeChecker):
'''A prime factors generator'''
def seive(self):
self._prime_factor = []
for i in xrange(0, self._limit + 1):
self._prime_factor.append([])
numbers = [True] * (self._limit + 1)
for i in xrange(2, self._limit / 2 + 1):
if numbers[i] == True:
self._prime_factor[i].append(i)
j = i * 2
while (j <= self._limit):
numbers[j] = False
self._prime_factor[j].append(i)
j += i
# The upper part from limit/2 to limit is not calculated yet.
for i in xrange(self._limit / 2 + 1, self._limit + 1):
if not len(self._prime_factor[i]):
self._prime_factor[i].append(i)
for i in xrange(2, self._limit + 1):
if numbers[i] == True:
self._prime_map[i] = True
self._prime_list.append(i)
def get_prime_factors(self):
return self._prime_factor
|
3a84883cd14817b44d2415370ccc6f109d47424a | WonyJeong/algorithm-study | /koalakid1/If/bj-9498.py | 151 | 3.53125 | 4 | import sys
input = sys.stdin.readline
n = int(input())
print(n >= 90 and "A" or n >= 80 and "B" or n >=
70 and "C" or n >= 60 and "D" or "F")
|
1fa093c69932f2b28279b0ec22b4bf551fc08a64 | learnerofmuses/slotMachine | /152Spr13/testp3.py | 387 | 3.890625 | 4 | def guess(my_list):
count = 0
sum = 0
new = []
for i in my_list:
if(i % 3 == 0):
count = count+1
sum = sum + i
new.append(i)
if(i % 2 == 0):
print("invalid input")
else:
average = float(sum)/count
return sum, average, new
def main():
my_list = [3, 6, 5, 7, 2, 45, 12, 9, 24, 27, 33]
sum, average, new = guess(my_list)
print(sum, average, new)
main()
|
da3b4e36b02d7e78bf084af4ff1e932f08405a47 | alaindet/learn-python | /courses/bootcamp_udemy/02-strings/string_methods.py | 1,342 | 4.375 | 4 | # This displays all the methods for strings
print(dir(str))
# Currently prints 81 methods!
# This displays an help about the given method
help(str.replace)
# replace(self, old, new, count=-1, /)
# Return a copy with all occurrences of substring old replaced by new.
#
# count
# Maximum number of occurrences to replace.
# -1 (the default value) means replace all occurrences.
#
# If the optional argument count is given, only the first count occurrences are
# replaced.
word = 'Hello'
# Note that .upper and .lower create a copy
print(word.upper(), word.lower(), word) # HELLO hello Hello
s = 'This is a String'
print(s.upper()) # THIS IS A STRING
print(s.lower()) # this is a string
print(' 192.168.1.1 '.strip()) # 192.168.1.1
print('$$Hello$$$$'.strip('$')) # Hello
print(s.replace('String', 'word')) # This is a word
print(s.count('s')) # 2
print(s.lower().count('s')) # 3
# vvv By default, splits uses whitespace characters as split boundaries
print(s.split()) # ['This', 'is', 'a', 'String']
print('192.168.1.1'.split('.')) # ['192', '168', '1', '1']
print('@'.join(['a', 'b', 'c'])) # a@b@c
# vvv Returns the first index of the first appearance
print('aa bb cc aa bb cc'.find('bb')) # 3
print('abcdef'.find('xx')) # -1
print('c' in 'abcdef') # True
print('x' not in 'abcdef') # True |
d1573c044b84608538aff708588a9547ee17901f | kfei/code2html | /code2html/util.py | 4,228 | 3.5 | 4 | # -*- coding: utf-8 -*-
import sys
import re
import os
import platform
from os.path import expanduser, isfile, isdir, exists, normcase, join
import glob
from shutil import rmtree
from fnmatch import fnmatch
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("Invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = raw_input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
pass
def which(program):
"""
Check if an executable program exists, in a platform-independent way.
Idea comes from: http://stackoverflow.com/a/377028/2504317
"""
if platform.system() == 'Windows':
program += '.exe'
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def check_color_scheme(color):
"""
Check whether the selected color scheme exists
"""
if platform.system() == 'Windows':
user_cs_file = normcase(join(expanduser('~'),
'vimfiles/colors', color + '.vim'))
builtin_cs_file = normcase('C:/Program Files*/Vim/vim*/colors/'
+ color + '.vim')
else:
user_cs_file = expanduser('~') + '/.vim/colors/' + color + '.vim'
builtin_cs_file = '/usr/share/vim/vim*/colors/' + color + '.vim'
if isfile(user_cs_file):
pass # Color scheme exists
elif glob.glob(builtin_cs_file):
pass # Color scheme exists
else:
sys.exit(u'ERROR: The selected color scheme does not exist, aborted.')
def check_input(source):
"""
Check the inupt path
"""
if isdir(source):
pass
else:
sys.exit(u'ERROR: The source directory does not exist, aborted.')
def check_output(output):
"""
Check the output path, create it if not exists.
"""
if exists(output):
if query_yes_no(u'The output directory exists,'
u' delete it first?'):
rmtree(output)
else:
sys.exit(u'Nothing happened.')
os.makedirs(output)
def check_includes(includes):
"""
Stop program if there is no include pattern
"""
if includes == []:
sys.exit(u'No include pattern specified, aborted.')
def get_subdir_name(root, dir_name):
regex = '(' + root + ')' + '(.+)'
match = re.search(regex, dir_name)
if match:
subdir_name = match.group(2)[1:] # Avoid the leading slash
else:
subdir_name = None
return subdir_name
def included(f, includes):
for pattern in includes:
if fnmatch(f, pattern):
return True
return False
def create_subdir(o_root, subdir):
print(u'Making directory %s' %
join(o_root, subdir))
try:
os.makedirs(join(o_root, subdir))
except Exception:
sys.exit(u'ERROR: Can not create directory, aborted.')
def get_shell():
"""
For Windows, the shell flag in subprocess.call must be True.
FIXME: Find a more general way.
"""
if platform.system() == 'Windows':
return True
else:
return False
|
ce740060323f833d882d4f4d009f85fb564d705e | PacktPublishing/Python-for-Beginners-Learn-Python-from-Scratch | /43.5. enum/figures.py | 268 | 3.578125 | 4 | import math
def area_of_square(a):
return a * a
def area_of_rectangle(a, b):
return a * b
def area_of_circle(r):
return math.pi * r ** 2
def area_of_triangle(a, h):
return 0.5 * a * h
def area_of_trapeze(a, b, h):
return (a + b) / 2 * h
|
b634aba393315a149b2fe7df7e021d7aa00799f7 | mandelina/algorithm | /baek_2675_문자열 반복.py | 152 | 3.515625 | 4 | n=int(input())
for i in range(0,n):
n,s=input().split()
n=int(n)
for j in range(0,len(s)):
print(n*s[j],end="")
print(end="\n")
|
2977283067bca4b05c4da030dba74083b3a328ff | pfiaux/PythonChallenge | /level3.py | 396 | 3.65625 | 4 | # Python Challenge Level 3
# http://www.pythonchallenge.com/pc/def/equality.html
# use Reg exp to tryyy
import re
inputfile = open("./level3_data.txt")
data = ""
#for line in inputfile:
# data = data + line.strip()
pattern = "[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]"
matches = re.findall(pattern, inputfile.read())
count = 0
for match in matches:
print match[4]
count+= 1
print "found:", count |
6e087a96e591402522cc1d3207686c96e9b4cf99 | szhmery/leetcode | /Offer/Offer21-OddBeforeEven.py | 793 | 3.59375 | 4 | from typing import List
class Solution:
# two pointers
def exchange(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums) - 1
while left <= right:
while left <= right and nums[left] % 2 == 1:
left += 1
while left <= right and nums[right] % 2 == 0:
right -= 1
if left > right:
break
nums[left], nums[right] = nums[right], nums[left]
return nums
# slow and fast pointer
def exchange2(self, nums: List[int]) -> List[int]:
slow = fast = 0
while fast < len(nums):
if nums[fast] % 2 == 1:
nums[slow], nums[fast] = nums[fast], nums[slow]
slow += 1
fast += 1
return nums
|
4a71aefcabfc34206d7c2a8a379fef14bdc5c8a8 | chyt123/cosmos | /coding_everyday/lc500+/lc836/RectangleOverlap.py | 762 | 4.03125 | 4 | from typing import List
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
# - - | |
if rec1[0] == rec1[2] or rec1[1] == rec1[3] or rec2[0] == rec2[2] or rec2[1] == rec2[3]:
return False
line1 = [rec1[1], rec1[3], rec1[0], rec1[2]]
line2 = [rec2[1], rec2[3], rec2[0], rec2[2]]
if line2[0] >= line1[1] or line2[1] <= line1[0] or line2[2] >= line1[3] or line2[3] <= line1[2]:
return False
return True
if __name__ == "__main__":
sol = Solution()
rec1 = [0, 0, 2, 2]
rec2 = [1, 1, 3, 3]
# rec1 = [0, 0, 1, 1]
# rec2 = [1, 0, 2, 1]
# rec1 = [0, 0, 1, 1]
# rec2 = [2, 2, 3, 3]
print(sol.isRectangleOverlap(rec1, rec2))
|
667f43f7f74b4735843e24cc47b0f0a793c6a7b8 | kyletau67/tauK | /03_occupation/portendGreatness_tangM-tauK.py | 1,294 | 3.5 | 4 | #Portends Greatness -- Michelle Tang and Kyle Tau
#SoftDev1 pd 6
#K06 -- StI/O: Divine your Destiny!
#2018-09-13
import csv
import random
file = open("occupations.csv", "r") #open and read the file
occupations = file.readlines() #lines of the file are put into the list, occupations
file.close() #close the file since we no longer need it
dictionary = {} #initialize dictionary!
for item in occupations[1:len(occupations)-1]: #add occupation into dictionary, skipping the first line (headers) and the last line (total)
key = item[:item.rfind(",")] #returns the occupation
value = float(item[item.rfind(",")+1:item.rfind("\\")]) #returns the percent corresponding with that application
dictionary[key] = value #input key and value into the dictionary
#Pre-condition: Assumes a csv file has been processed and made into a dictionary
#Post-condition: Returns an occupation where the results are weighted by the percentage given
def randOcc():
val = random.randint(0,998) #threshold
num = 0
occ = "" #occupation name
for i in dictionary: #iterate through the dictionary
occ = i; #record the occupation
num += dictionary[i]*10 #add onto num
if num >= val: #check to see if it has reached the threshold
break; #if threshold is met, stop
return occ
print (randOcc()) |
9d27515483c4ac217fc7d75da3e87bc484c4943d | ChandraSiva11/sony-presamplecode | /tasks/final_tasks/math/23.prime_no.py | 290 | 4.1875 | 4 | # Python Program to Check if a Number is a Prime Number
def main():
num = 13
flag = 0
for i in range(2, num):
if num % i == 0 :
flag += 1
if flag == 0:
print(num, "Number is a prime number")
else:
print(num, "Number is not a prime number")
if __name__ == '__main__':
main() |
957e20c26555c98cbb87e4fd7371edbfa8b81ef6 | hideyk/Challenges | /leetcode/26. diagonalSum/diagonalSum.py | 261 | 3.5625 | 4 | from typing import List
def diagonalSum(mat: List[List[int]]) -> int:
size = len(mat)
sum = 0
for i in range(size):
sum += mat[i][i]
sum += mat[i][size-1-i]
if size % 2 == 1:
sum -= mat[size//2][size//2]
return sum
|
3be371e620261cb9874190eafe9004fe2bc4a319 | butterfly1of4/python_CLI_project | /lib/main.py | 4,600 | 3.671875 | 4 | from peewee import *
from models import Contacts
on = True
while on == True:
print("-----------------------------------------------------")
print("***** My Contacts: *****")
def intro():
print("\nPlease choose from the following menu options: \n")
print("-----------------------------------------------------")
print("1: For a list of All Contacts: Type 'all'; \n")
print("2: To find One contact by first-name: Type the first name of the person you're looking for;\n ")
print("3: To create a New contact: Type 'new'\n")
print("4: To Update a contact: Type 'update'\n")
print("5: To Delete a contact: Type 'delete'\n")
print("6: To Exit the program: Type 'exit\n")
intro()
menu = input("Type your choice: \n")
# EXIT CHECK
def checkExit():
if menu == 'exit':
on == False
print("Goodbye")
else:
print('go on')
checkExit()
# FIND ALL
def findAll():
all = Contacts.select()
for entry in all:
print(entry.first_name, entry.last_name, entry.number, entry.email)
if menu == 'all':
findAll()
continue
# CREATE
def createContact():
first = input("First Name: ")
last = input("Last Name: ")
number = input("Phone Number: ")
email = input("Email: ")
Contacts.create(first_name=first, last_name=last,
number=number, email=email)
if (menu == 'new'):
createContact()
continue
#UPDATE
def updateContact():
updateName = input("Type the first name of the contact you would like to update: ")
person = Contacts.get(Contacts.first_name == updateName)
findField = input("Enter the number of the field you would like to update:\n"
"1. First Name\n"
"2. Last Name\n"
"3. Phone Number\n"
"4. Email Address: ")
if findField == "1":
print(f"First Name:\n {person.first_name}")
elif findField == "2":
print(f"Last Name:\n {person.first_name}: {person.last_name}")
elif findField == "3":
print(f"Phone Number:\n {person.first_name}: {person.number}: ")
elif findField == "4":
print(f"Email Address:\n {person.first_name}: {person.email}")
else:
print("Select Again")
newData = input("Please enter the new text of the field: ")
print(newData)
last = Contacts.get(Contacts.last_name == person.last_name)
num = Contacts.get(Contacts.number == person.number)
mail = Contacts.get(Contacts.email == person.email)
if findField == "1":
person = Contacts.get(Contacts.first_name == updateName)
person.first_name = newData
person.save()
elif findField == "2":
last = Contacts.get(Contacts.last_name == person.last_name)
last.last_name = newData
last.save()
# print(person.last_name, last.last_name, "three")
elif findField == "3":
num = Contacts.get(Contacts.number == person.number)
num.number = newData
num.save()
elif findField == "4":
mail = Contacts.get(Contacts.email == person.email)
mail.email = newData
mail.save()
print(person.first_name, last.last_name, num.number, mail.email)
if menu == 'update':
updateContact()
continue
#DELETE
def deleteContact():
deleteName = input("Type the name of the contact you wish to delete: ")
deleteContact = Contacts.get(Contacts.first_name == deleteName)
print(deleteContact.first_name, deleteContact.last_name, deleteContact.number, deleteContact.email)
deleteContact.delete_instance()
print("deleted")
all = Contacts.select()
for entry in all:
print(entry.first_name, entry.last_name, entry.number, entry.email)
if menu == 'delete':
deleteContact()
continue
# FIND ONE BY FIRST NAME
def findName():
person = Contacts.get(Contacts.first_name == menu)
print(person.first_name, person.last_name, person.number, person.email)
if menu == Contacts.first_name and menu != 'exit':
findName()
continue
elif menu == 'exit':
break
# EXIT
else:
on == False
menu == 'exit'
|
90ceed1beb564980fe57ee96c87d60616fa6636d | Blackdevil132/MachineLearning | /src/qrl/Qtable.py | 1,542 | 3.59375 | 4 | import pickle
class Qtable:
"""
base class for qtables
contains save/store functions
get/update have to be overridden if qtable has multi dimensional format
"""
def __init__(self):
self.table = {}
def fromFile(self, path):
"""
Loads QTable from given Path
:param path: path to load from
"""
with open(path + '.pkl', 'rb') as f:
self.table = pickle.load(f)
def toFile(self, path):
"""
Saves Qtable in .pkl file
:param path: Path to save file at
"""
with open(path + '.pkl', 'wb') as f:
pickle.dump(self.table, f, pickle.HIGHEST_PROTOCOL)
def get(self, state, action=None):
"""
:param state: state of environment
:param action: one possible action for given state
:return: QTable Value for state and action
"""
if action is None:
return self.table[state][:]
return self.table[state][action]
def update(self, state, action, newValue):
"""
:param state: state of environment
:param action: possible action for given state
:param newValue: Value to assign
"""
self.table[state][action] = newValue
def show(self):
"""
pretty prints the qtable
"""
for state in self.table.keys():
print("%i " % state, end='')
for action in self.table[state]:
print("\t%.3f, " % action, end='')
print()
|
54f473e64fd5ce2e3096181ad6cdb83db3f6f910 | SrikarValluri/Software_Engineering_2 | /hw7/q2_test.py | 432 | 3.5 | 4 | import unittest
from q2 import leapyear
class TestCase(unittest.TestCase):
def test1(self):
self.assertEqual(leapyear(2000), "Leap Year")
def test2(self):
self.assertEqual(leapyear(100), "Not Leap Year")
def test3(self):
self.assertEqual(leapyear(2320349), "Not Leap Year")
def test4(self):
self.assertEqual(leapyear(12), "Leap Year")
if __name__ == "__main__":
unittest.main() |
cb782b84104a2f6a37573982b28083f70bb977d3 | SandeepDevrari/py_code | /py_ds/examplebinarytree.py | 3,835 | 4.28125 | 4 | ##this is an implementation of Tree in python3
## Node class
class node:
def __init__(self,item):
self.data=item;
self.L=None;
self.R=None;
##Tree class
class binary_tree:
def __init__(self,items):
if items==None:
print("No Tree!!");
else:
i=0;
self.root=node(items[i]);
i+=1;
if len(items)>1:
self.built_tree(items[i:])
def built_tree(self,items):
if items!=None:
i=0;
temp=node(items[i]);
i+=1;
self.linker=self.root;
self.link_tree(temp);
if len(items)>1:
self.built_tree(items[i:])
def link_tree(self,link):
if self.linker.L!=link and self.linker.R!=link:
##p,s=str(link.data),str(self.linker.data);
if link.data<=self.linker.data:
if self.linker.L==None:
self.linker.L=link;
else:
self.linker=self.linker.L;
self.link_tree(link);
else:
if self.linker.R==None:
self.linker.R=link;
else:
self.linker=self.linker.R;
self.link_tree(link);
##tree traversing
##inorder
def inorder(self):
link=self.root;
def in_inorder(link):
if link!=None:
in_inorder(link.L);
print(str(link.data)+" ",end='');
in_inorder(link.R);
in_inorder(link);
print(" ");
##preorder
def preorder(self):
link=self.root;
def pre_preorder(link):
if link!=None:
print(str(link.data)+" ",end='');
pre_preorder(link.L);
pre_preorder(link.R);
pre_preorder(link);
print(" ");
##postorder
def postorder(self):
link=self.root;
def post_postorder(link):
if link!=None:
post_postorder(link.L);
post_postorder(link.R);
print(str(link.data)+" ",end='');
post_postorder(link);
print(" ");
##Insert && Delete Operations
##Insert
def insert(self,item):
link=node(item);
self.linker=self.root;
self.link_tree(link);
##Delete
def delete(self,item):
next,pre=self.in_search(item);
if next!=None:
if next.L==None and next.R==None:
if next==pre.L:
pre.L=None;
else:
pre.R=None;
elif next.L==None or next.R==None:
if next.L!=None:
if next==pre.L:
pre.L=next.L;
else:
pre.R=next.L;
else:
if next==pre.R:
pre.L=next.R;
else:
pre.R=next.R;
else:
successor,pre=next.R,next;
while successor.L!=None:
pre,successor=successor,successor.L;
else:
next.data=successor.data;
if pre==next:
pre.R=None;
else:
pre.L=None;
def in_search(self,item):
next,pre=self.root,self.root;
while next!=None:
if next.data==item:
return next,pre;
elif item<next.data:
pre,next=next,next.L;
else:
pre,next=next,next.R;
else:
return next,pre;
##Search
def search(self,item):
next,pre=self.in_search(item);
if next==None:
return False;
else:
return True; |
15b5a0a9d557b7bb82016088e9294a4ace70afd6 | MarinaFirefly/Python_homeworks | /OOP5/models/interview19.py | 929 | 3.5 | 4 | import datetime
class Interview:
def __init__(self,vacancy,programmer,recruiter,candidate,dt,feedback,result):
self.vacancy = vacancy
self.programmer = programmer
self.recruiter = recruiter
self.candidate = candidate
self.dt = dt
self.feedback = feedback
self.result = result
@classmethod
def next_day(cls,obj):
#method that will add interview to next day
vac = obj.vacancy
prog = obj.programmer
recr = obj.recruiter
cand = obj.candidate
real_dt = datetime.datetime.strptime(obj.dt,"%Y-%m-%d")
dt = datetime.datetime(real_dt.year, real_dt.month, real_dt.day + 1).strftime("%Y-%m-%d")
return cls(vac,prog,recr,cand,dt,"","")
#testing
new_int = Interview("C#","Ivanov","Zhorov","Alex","2020-01-12","","")
print(new_int.dt)
next_day_int = Interview.next_day(new_int)
print(next_day_int.dt)
|
fe699b780310ec113b02ade88f0504dae45cc2cc | GraceSnow/GraceSnow.github.io | /story.py | 1,972 | 4.21875 | 4 | startstory = '''
You wake up one morning and find that you aren’t in your bed; you aren’t even in your room.
You’re in the middle of a giant maze.
A sign is hanging from the ivy: “You have one hour. Don’t touch the walls.”
There is a hallway to your right and to your left.
Type 'left' to go left or 'right' to go right.
'''
leftfork_1 = '''
You decide to go left and you run into a dead end.
When you turn to go back, you find the way has been closed off.
You are trapped.
Will you find a way out or wait?
Type 'find a way out' or 'wait' to continue.
'''
leftfork_1a = '''
You are determined to escape and search all over for an exit and eventually find one.
You continue on and make it out of the maze.
The end.
'''
leftfork_1b = '''
You lose hope and give up.
Your time runs out and you are trapped in the maze.
The end.
'''
rightfork_1 = '''
You choose to go right and you eventually come to a room where a group of bandits have been waiting for you.
Will you fight or yield?
Type 'fight' or 'yield' to continue.
'''
rightfork_1a = '''
You won't go down easily and you decide to fight.
You defeat the bandits and are able to escape the maze.
The end.
'''
rightfork_1b = '''
You are outnumbered and no match for the bandits. You yield and give up all your belongings to them.
You are captured by them and can't escape the maze.
The end.
'''
print(startstory)
user_input = input()
user_error = True
while user_error is True:
user_input = input("Type 'left' or 'right'")
if user_input == "left" or user_input == "right":
user_error = False
if user_input == "left":
print(leftfork_1)
user_input = input()
if user_input == "find a way out":
print(leftfork_1a)
done = True
elif user_input == "wait":
print(leftfork_1b)
done = True
elif user_input == "right":
print(rightfork_1)
user_input = input()
if user_input == "fight":
print(rightfork_1a)
done = True
elif user_input == "yeild":
print(rightfork_1b)
done = True
|
0666f9c21ff16b21254e83d536818f8980ef23c7 | francoislegac/algorithms | /maze_puzzle.py | 4,720 | 4.40625 | 4 | import copy
import math
# This class is used to store the idea of a point in the maze and linking it to other points to create a path.
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.parent = None
self.cost = math.inf
def set_parent(self, p):
self.parent = p
def set_cost(self, c):
self.cost = c
def print(self):
print(self.x, ',', self.y)
# These constants are used to reference points on the maze that are in the respective direction of a point in question.
NORTH = Point(0, 1)
SOUTH = Point(0, -1)
EAST = Point(1, 0)
WEST = Point(-1, 0)
# The MazePuzzle class contains the mechanics of the game
class MazePuzzle:
WALL = '#'
EMPTY = '_'
GOAL = '*'
# Initialize the maze with a map containing; * at the goal, 0 as an empty unexplored point, and # as a point with
# a wall.
def __init__(self, maze_size_x=5, maze_size_y=5):
self.maze_size_x = maze_size_x
self.maze_size_y = maze_size_y
self.maze = ['*0000',
'0###0',
'0#0#0',
'0#000',
'00000']
def get_current_point_value(self, current_point):
return self.maze[current_point.x][current_point.y]
# Return all valid neighbors around a specific point, excluding points outside of the maze and walls.
def get_neighbors(self, current_point):
neighbors = []
# potential_neighbors = [[0, 1], [0, -1], [1, 0], [-1, 0]]
potential_neighbors = [[NORTH.x, NORTH.y], [SOUTH.x, SOUTH.y], [EAST.x, EAST.y], [WEST.x, WEST.y]]
for neighbor in potential_neighbors:
target_point = Point(current_point.x + neighbor[0], current_point.y + neighbor[1])
if 0 <= target_point.x < self.maze_size_x and 0 <= target_point.y < self.maze_size_y:
if self.get_current_point_value(target_point) != '#':
neighbors.append(target_point)
return neighbors
# A function to visually show a set of points visited in the maze
def overlay_points_on_map(self, points):
overlay_map = copy.deepcopy(self.maze)
for point in points:
new_row = overlay_map[point.x][:point.y] + '@' + overlay_map[point.x][point.y + 1:]
overlay_map[point.x] = new_row
result = ''
for x in range(0, self.maze_size_x):
for y in range(0, self.maze_size_y):
result += overlay_map[x][y]
result += '\n'
print(result)
return overlay_map
def print_maze(self):
result = ''
for x in range(0, self.maze_size_x):
for y in range(0, self.maze_size_y):
result += self.maze[x][y]
result += '\n'
print(result)
# Utility to get a path as a list of points by traversing the parents of a node until the root is reached.
def get_path(point):
path = []
current_point = point
while current_point.parent is not None:
path.append(current_point)
current_point = current_point.parent
return path
# Utility to find the length of a specific path given a point.
def get_path_length(point):
path = []
current_point = point
total_length = 0
while current_point.parent is not None:
path.append(current_point)
total_length += 1
current_point = current_point.parent
return total_length
# Utility to calculate the cost of a path if an additional cost of movement exists.
def get_path_cost(point):
path = []
current_point = point
total_cost = 0
while current_point.parent is not None:
path.append(current_point)
total_cost += get_cost(get_direction(current_point.parent, current_point))
current_point = current_point.parent
return total_cost
# Utility to determine the cost of a specific move.
def get_move_cost(origin, target):
return get_cost(get_direction(origin, target))
# Utility to determine the direction of movement given an origin and target point.
def get_direction(origin, target):
if target.x == origin.x and target.y == origin.y - 1:
return 'N'
elif target.x == origin.x and target.y == origin.y + 1:
return 'S'
elif target.x == origin.x + 1 and target.y == origin.y:
return 'E'
elif target.x == origin.x - 1 and target.y == origin.y:
return 'W'
# Utility to determine the cost of a move given a direction. In this case, North and South is 5, and East and West is 1.
STANDARD_COST = 1
GRAVITY_COST = 5
def get_cost(direction):
if direction == 'N' or direction == 'S':
return GRAVITY_COST
return STANDARD_COST |
8d0bfe0c06601b7543275ad0f6ea2df564aec199 | pfletcherhill/LING-227 | /Assignment1/sample.py | 902 | 4.375 | 4 | # this is a command line version of fib
# import sys to make command line arguments accessible
import sys
# The following is a multiline comment
'''
store first argument as 'num',
first check that user provided a number
if not, exit gracefully
'''
try:
num = int(sys.argv[1])
except ValueError:
print "Please provide a positive integer"
exit()
# set first two numbers to 0, 1
fib1,fib2 = 0,1
# check to make sure num is a valid position, otherwise exit
if num < 1:
print "Please give me a postive integer and try again"
exit()
# print first one or two numbers of the sequence, depending on num
print "The fib number at 1 is " + str(fib1)
if num>=2: print "The fib number at 2 is", fib2
# print out the fibonacci sequence from 3 to num
i=3
while i <= num:
fib1, fib2 = fib2, fib1 + fib2
print "The fib number at position " + str(i) + " is " + str(fib2)
i += 1
|
21f5c7232f5be6fe0dd59e18dc5c09a8e7b1e95d | NidhinAnisham/PythonAssignments | /pes-python-assignments-2x-master/FilePackage/52.py | 126 | 3.53125 | 4 | for line in reversed(open("example.txt").readlines()):
print line.rstrip()
fo = open("example.txt").read()
print fo[::-1]
|
e8a45317a45d64456f1de9442d68f3c5c031bf7e | shivani-tomar/Data_stuctures_with_python | /sorting/bubble.py | 644 | 3.9375 | 4 | class Bubble:
def __init__(self, lists):
print("this is bubble sort example")
self.lists = lists
def bubble(self):
size = len(self.lists)
print(self.lists , size)
swapcount =0;
for i in range(size):
for j in range(size-i-1):
if self.lists[j]>self.lists[j+1]:
self.lists[j] = self.lists[j]^self.lists[j+1];
self.lists[j+1] = self.lists[j]^self.lists[j+1];
self.lists[j] = self.lists[j] ^ self.lists[j+1];
swapcount+=1;
print (swapcount)
print(self.lists)
|
264fe720afe1d84aec32cac207dc8bb2501e00ab | 1054/Crab.Toolkit.michi2 | /test/test_py_copy/test_py_copy.py | 617 | 3.71875 | 4 | #!/usr/bin/env python
import numpy as np
from copy import copy, deepcopy
aa = []
a = {'var':np.array([1,1]),}
aa.append(a)
b = copy(a)
b['var'] += np.array([1,1])
print(a, b) # a value changed
aa = []
a = {'var':np.array([1,1]),}
aa.append(a)
b = copy(aa[0])
b['var'] += np.array([2,2])
print(a, b) # a value changed
aa = []
a = {'var':np.array([1,1]),}
aa.append(a)
b = copy(aa[0])
b['var'] = np.array([1,1]) + np.array([2,2])
print(a, b) # a value unchanged
aa = []
a = {'var':np.array([1,1]),}
aa.append(a)
b = deepcopy(aa[0])
b['var'] += np.array([3,3])
print(a, b) # a value unchanged
|
6a44635d136d3b511059097710bac41fe344c306 | MarsWilliams/PythonExercises | /practiceProblems/check_braces.py | 1,268 | 3.53125 | 4 | def check_braces(expressions):
l = len(expressions)
braces = {
'curly': {
"}": "cr",
"{": "cl",
"count": 0
},
'paren': {
")": "pr",
"(": "pl",
"count": 0
},
'square': {
"]": "cr",
"[": "cl",
"count": 0
}
}
for i in range(l):
q = len(expressions[i])
braces['curly']['count'] = 0
braces['paren']['count'] = 0
braces['square']['count'] = 0
for d in range(q):
t = expressions[i][d]
if t in braces['curly']:
braces['curly']['count'] += 1
continue
elif t in braces['paren']:
braces['paren']['count'] += 1
continue
elif t in braces['square']:
braces['square']['count'] += 1
continue
else:
continue
if (braces['curly']['count'] % 2 == 0):
if (braces['paren']['count'] % 2 == 0):
if (braces['curly']['count'] % 2 == 0):
print 1
else:
print 0
check_braces(["()", "[})"]) |
02e0388d289b6192c98ca47187a2bdaaa6eb9cc9 | hanjiuz/MyPython | /flashcard.py | 910 | 3.921875 | 4 | #sys is a module. it let us access command line arguments through sys.argv.
import sys
import random
#print(sys.argv)
if len(sys.argv) < 2:
print("Please supply a flashcard file.")
exit(1)
flashcard_filename = sys.argv[1]
f = open(flashcard_filename, "r")
question_dict = {}
for line in f:
entry = line.strip().split(",")
question = entry[0]
answer = entry[1]
question_dict[question] = answer
f.close()
print("Welcome to the flashcard quizzer.")
print("At any time, type 'quit' to quit.")
print("")
questions = list(question_dict.keys())
while True:
question = random.choice(questions)
answer = question_dict[question]
print("Question: " + question)
guess = input("Your Guess > ")
if guess == "quit":
print("Goodbye!")
break
elif guess == answer:
print("Correct!")
else:
print("Sorry the answer is: " + answer)
|
b61f1ca485b107a8a6e69ae113a43d89dbc6d458 | zyyxydwl/Python-Learning | /1-基础/eatPeach.py | 1,122 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2018/1/1 17:55
# @Author : zhouyuyao
# @File : eatPeach.py
# 2. 猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,
# 还不瘾,又多吃了一个,第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
# 以后每天早上都吃了前一天剩下的一半零一个。
# 到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
# 程序分析:采取逆向思维的方法,从后往前推断。
n=1 #'''定义第9天有n个桃'''
for day in range(0,9): #range(1,9)表示桃子吃了9天
n=2*(n+1) #n=2n+1+1前一天的桃子数
print(n)
# x = 1
# for day in range(0,9):
# x = (x+1)*2
# print(x)
day1 = 10 #开始有10天
peachNumber = 1 #桃子个数
while day1 > 1: #天数大于1的时候进行计算
day1 -= 1 #前一天
peachNumber = (peachNumber+1)*2 #前一天的桃子个数
print("day {0} peach {1}".format(day1,peachNumber) )
# x2 = 1
# for day in range(9,0,-1):
# x1 = (x2 + 1) * 2
# x2 = x1
|
8adec887b2f1dfca36b8abfef7c343b5bc32d1b5 | aronnax77/python_uploads | /tutor2.py | 1,342 | 3.5625 | 4 | #!/usr/bin/python3
#############################################################################################
# #
# PLEASE NOTE THAT THIS CODE WILL NOT RUN IN THE SOLOLEARN CODE PLAYGROUND. #
# #
# This is a cgi test script written in python. To see this code in action it will be #
# necessary to run a server. This is possible through a local server like apache but #
# can also be achieved through a server written in python. The code for such a server is #
# shown here xxxxxxxxxxxxxxx for those who may be interested. #
# #
#############################################################################################
text1 = """Content-type: text/html\n
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CGI 101</title>
</head>
<body>
<H1>A Third CGI Script</H1>
<HR>
<P>Hello, CGI World!</P>
<table>
"""
print(text1)
for i in range(5):
print('<tr>')
for j in range(4):
print('<td>%d.%d</td>' % (i, j))
print('</tr>')
print("""
</table>
</body>
</html>""")
|
c1d4df20e85c94d283c478f40d1b2174c419132f | rachelktyjohnson/treehouse-py-project3 | /phrasehunter/game.py | 2,827 | 3.609375 | 4 | import time
import random
from phrasehunter.phrase import Phrase
class Game:
def __init__(self):
self.active_phrase = None
self.missed = 0
self.phrases = [
"Knowledge is power",
"Whatever you do do it well",
"What we think we become",
"Turn your wounds into wisdom",
"And still I rise"
]
self.guesses = []
def start(self):
self.welcome()
play_game = True
while play_game:
self.active_phrase = Phrase(self.get_random_phrase())
while self.missed < 5:
if not self.active_phrase.check_complete():
self.active_phrase.display()
user_guess = self.get_guess()
if self.active_phrase.check_letter(user_guess):
print("Great! {} is in the phrase".format(user_guess))
else:
print("Oops! {} is not in the phrase. {} out of 5 lives remaining!".format(user_guess, 4-self.missed))
self.missed += 1
print()
else:
break
play_game = self.game_over()
def get_random_phrase(self):
return random.choice(self.phrases)
def welcome(self):
print("└[∵┌]└[ ∵ ]┘[┐∵]┘")
print("Welcome to Phrase Hunter!")
time.sleep(0.5)
print("You'll get a random phrase from a pool of {}".format(len(self.phrases)))
time.sleep(0.5)
print("Guess individual letters that make up the phrase")
time.sleep(0.5)
print("Ready? Let's go!")
time.sleep(1)
def get_guess(self):
while True:
user_guess = (input("Guess a letter: ")).lower()
if len(user_guess) == 1 and user_guess.isalpha():
break
else:
print("Make sure your guess is 1 letter!")
self.guesses.append(user_guess)
return user_guess
def game_over(self):
if self.missed < 5:
print("Well done! You guessed the phrase: {}".format(self.active_phrase.phrase))
else:
print("You guessed incorrect 5 times. Game over!")
print("The phrase was: {}".format(self.active_phrase.phrase))
print("\nWould you like to play again?")
again = input("YES, or enter any key to exit: ").upper()
if again == "YES":
print("New game... coming up!")
time.sleep(1)
self.active_phrase = None
self.missed = 0
self.guesses = []
return True
else:
print("\nThanks for playing. See you next time!")
print("└[∵┌]└[ ∵ ]┘[┐∵]┘")
return False
|
69376bef591ba742fb38562db388763ca3369229 | DevoteamDigitalFactory/code-sharing | /Data_structures/yield_from_example.py | 598 | 3.890625 | 4 | '''A function solving the problem of sums square
ie: Can order number from 1 to n so that each consecutive pair sums to a perfect square
This example is a DFS using the yield from syntax'''
def square_sums(n):
squares = {i**2 for i in range(2, math.ceil((2*n-1)**0.5))}
def dfs():
if not inp: yield res
for v in tuple(inp):
if not res or((res[-1]+v) in squares):
res.append(v)
inp.discard(v)
yield from dfs()
inp.add(res.pop())
inp, res = set(range(1,n+1)), []
return next(dfs(), False) |
cdef43e3b272fe475b7f6b8cbe801370122d8ff0 | ProjectHusky/CoreVal | /database_admin/course_parser.py | 8,166 | 3.53125 | 4 | from selenium import webdriver
import csv
import configparser
def setup_browser(is_headless):
"""
This methods sets up the browser object that is to be used for parsing.
:param is_headless: This boolean value determines whether the browser is displayed as it is browsing.
:return: A Google Chrome browser object.
"""
# Setup your browser object and its options.
options = webdriver.ChromeOptions()
options.add_experimental_option('prefs', {'credentials_enable_service': False})
# The parameter value determines whether or not the browser is visually shown.
if is_headless:
options.add_argument("headless")
browser = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=options)
# Setup a parser for the config
config = configparser.ConfigParser()
config.read("settings.ini")
username = config["credentials"]["username"]
password = config["credentials"]["password"]
# Navigate to a University of Washington page to login. Note that this username will be used to log in the entire
# time while scrapping.
browser.get("https://www.washington.edu/cec/a-toc.html")
# Input the username field.
username_location = browser.find_element_by_id("weblogin_netid")
username_location.send_keys(username)
# Input the password field.
password_location = browser.find_element_by_id("weblogin_password")
password_location.send_keys(password)
# Send the information.
send_button = browser.find_element_by_tag_name("input").submit()
return browser
def parse_site(course_link, browser):
"""
Gets the raw HTML code for a given course.
:param course_link: The course code for the course.
:param browser: The browser object to use.
:return: A list containing the lines of the HTML code.
"""
browser.get("https://www.washington.edu/cec/" + course_link)
return browser.page_source.split("\n")
def parse_letter(letter, browser):
"""
Parses the main directory for a given letter and returns a reference to all course that begin with said letter.
:param letter: The letter to query.
:param browser: The browser to use.
:return: A list containing the codes for all the course evaluations for the letter.
"""
# Navigate to the URL.
base_url = "https://www.washington.edu/cec/" + letter + "-toc.html"
browser.get(base_url)
# Get the HTML code for the page. Remove any irrelevant lines.
html = browser.page_source.split("\n")[58:]
# Cut off any lines that are needed.
html = html[:html.index("<p></p>")]
# Stores all the URLs in a list and return them.
courses = []
for line in html:
line = line[9:line.find(">") - 1]
# If actual course ID contains an ampersand we need to replace the parsed line because it will contain an HTML
# ampersand. Replace it with an actual ampersand.
if "&" in line:
line = line.replace('&', '&')
courses.append(line)
return courses
def parse_all_letters(browser):
"""
Goes through the entire directory for a letter and then returns a list containing all the links for all letters.
:param browser: The browser object to use.
:return: A list of list, where each list is the course links for a specific letter.
"""
all_links = []
# Note that 'a' in ASCII is 97 and 'z' is 122, so we need to loop from 97 - 122 inclusive.
for x in range(97, 123):
# chr(x) converts the integer to a character.
all_links.append(parse_letter(chr(x), browser))
return all_links
def get_course_id(course):
"""
This method takes in a course code for a class and then extracts the course ID from it.
:param course: The course code to parse.
:return: The course ID for the class.
"""
# This flag determines whether or not you have already seen a digit.
finish = False
# Note that we do not want the section letter i.e. we want CSE 142 rather than CSE 142B. The flag remedies this.
# Get rid of the first two letters. We do not want the / and the first letter of the course.
copy = course[2:]
# This holds the resulting string.
result = ""
# Loop through every character and decide whether to add it.
for x in copy:
# If you see have you already seen a digit and then you see a character, then you should stop.
if finish and x.isalpha():
return result
# If you see a digit, change the flag.
if x.isdigit():
finish = True
# If you have not already returned, add the character to the resulting string.
result = result + x
def parse_course(course, html):
"""
Parses the URL of a class for the relevant data and puts them into a return value.
:param course: The course code.
:param html: The HTML code of the course page.
:return: A list containing all our data.
"""
# Setup a list with dummy variables.
course_data = ["", "", "", "", ""]
# Parse the course ID.
course_data[1] = get_course_id(course)
# Setup an array to hold all the ratings.
ratings = []
# Go through every line in the HTML and check what kind of line it is. If its a special line then you should parse
# it for the relevant information.
for line in html:
# This means it is a ratings line.
if line.startswith("<tr><td>"):
# Delete any extra HTML code.
ratings.append(line[len(line) - 14:-11])
# This means it is the line containing the number of students.
elif line.startswith("<caption"):
# Delete all the text between the first 4 quotes.
for x in range(0, 3):
line = line[line.index("\"") + 1:]
# Delete anything from the start to the first quote.
line = line[:line.index("\"")]
# Add it to the list.
course_data[4] = line
# This means it is the line that contains both the teacher name and the date that they taught.
elif line.startswith("<h2>"):
# Replace the HTML hard spaces with normal spaces.
line = line.replace(u'\xa0', u' ')
# Delete any extra HTML characters and split it.
line = line[4:-5].split(" ")
# Do not add the second element in the line, it is the title of the professor. This is not really relevant
# to students so it is not required.
course_data[0] = line[0]
course_data[3] = line[2]
# Add the ratings after you have looped through everything.
course_data[2] = ratings
return course_data
def main(display):
"""
This is the main program that runs and connects all the methods together to parse the entire UW course catalog.
:param display: A boolean value that is passed into the setting up browser to determine whether or not the
browser is graphically displayed when the parsing occurs.
:return: N/A void.
"""
# Setup the browser.
browser = setup_browser(not display)
# Open a csv file to write and a csv writer.
csv_file = open("data.csv", "w")
csv_writer = csv.writer(csv_file)
# Gets all the courses.
all_courses = parse_all_letters(browser)
# Loop through every list in the list of all courses.
for letter_course in all_courses:
# Go through every course for each letter.
for course in letter_course:
# Get the HTML code for the course.
html = parse_site(course, browser)
# Parse the HTML code for the data needed.
course_data = parse_course(course, html)
# Decides whether or not the parsed information should be displayed to console.
if display:
print(course_data)
# Replace the list in the 3rd argument with a string and replace the commas with spaces for easier parsing.
course_data[2] = str(course_data[2]).replace(", ", " ")
# Write the list to disk as the csv file.
# csv_writer.writerow(course_data)
csv_file.close()
main(False)
|
d298f7b5f17b5bdf8dbd4ccb0d6b31980ff6644c | bhushanMahajan460/ineuron_assignment | /Assignment_2/assignment_2(b).py | 307 | 4.15625 | 4 | # ASSIGNMENT_2-B
# REVERSE THE INPUT STRING
l = input("-> Enter the string : ") # TAKE THE INPUT
reverse=l[::-1] # FUNCTION USED TO REVERSE THE STRING
print("-> Reversed String : {}".format(reverse)) # PRINT THR REVERSE STRING |
c681a26e9e3cecf37ea5bb146460de83b5347c68 | wangpengfeido/MyLearn3 | /LearnPython/010基础/030函数/030函数的参数/075参数组合.py | 291 | 3.65625 | 4 | # 任意函数都可以使用func(*args, **kw)的形式调用
# 函数调用的 * 和 ** 语法相当于将数组/元组和dict解构为参数
def f1(a, b=1, *c, **d):
print(a, b, c, d)
f1(*(1, 2,), **{'d': 3})
def f2(a, b=1, *c, d):
print(a, b, c, d)
f2(*(1, 2,), **{'d': 3})
|
b307187c5d292800d17929aa742b7616d07c0c7b | tianyu0901/code_basket | /algorithm/factorial.py | 798 | 3.578125 | 4 | # encoding: utf-8
# 输入整数求阶乘末尾的0的个数
# 输入为一行,n(1 ≤ n ≤ 1000)
# 解法:要判断末尾有几个0就是判断可以整除几次10。
# 10的因子有5和2,而在0~9之间5的倍数只有一个,
# 2的倍数相对较多,所以本题也就转换成了求N阶乘中有几个5的倍数。
# 也就是每多出来一个5,阶乘末尾就会多出来一个0,
# 这样n / 5就能统计完第一层5的个数,依次处理,就能统计出来所有5的个数。
# 如65 除以5 = 13, 25算两个5, 50算两个5,...,125 = 5*5*5 算三个5
import math
if __name__ == '__main__':
n = int(input("输入:"))
max_pow = 0
count = 0
while n // (5 ** max_pow) != 0:
max_pow += 1
count += n // (5 ** max_pow)
print(count)
|
8c37b5d1b2297d2c0d4ee1e6cc7a97d0652e25b7 | Rogerio-ojr/EstudosPython | /Exercicio28.py | 227 | 3.703125 | 4 | from random import randint, randrange
from time import sleep
n = int(input("Qual o numero? "))
numSorteado = randrange(5)
print('PROCESSANDO...')
sleep(2)
print(f'Você Ganhou!') if n == numSorteado else print(f'Você Perdeu!') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.