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 |
|---|---|---|---|---|---|---|
debdc0fe04ed974773677932ed48fab64ffef54d | sulai1/parseq | /parseq/src/parser.py | 1,308 | 3.515625 | 4 | import re
class parser(object):
"""The Parser parses a code file for its components."""
ERROR_GRP = "err"
ESCAPE = '[\^$.|?*+(){}"'
id = 0
def __init__(self,regex,groups=[]):
self.groups = groups
self.regex = regex
def parse(self,string):
""" Parse the string and return the matches. The matches can be searched for the groups stored in the parser """
res = re.finditer(self.regex,string)
return res
@staticmethod
def dup_grp(name):
parser.id += 1
return "{0}{1}".format(name,parser.id)
@staticmethod
def error_grp():
parser.id += 1
return "{0}{1}".format(parser.ERROR_GRP,parser.id)
@staticmethod
def group_name(name):
newname = ""
for c in name :
if c.isalnum() :
newname+=c
else :
newname+=""
return newname
def __add__(self,other):
g = self.groups[:]
if len(other.groups) > 0:
while self.rename_dups(other):
pass
g.extend(other.groups)
return parser(self.regex + other.regex,g)
def rename_dups(self,other):
b_dups = False
if len(self.groups) > 0 and len(other.groups) > 0 :
for gs in self.groups :
for i in range(0, len(other.groups)) :
if gs == other.groups[i] :
other.regex = other.regex.replace(other.groups[i],other.groups[i] + "I")
other.groups[i]+="I"
b_dups = True
return b_dups |
5f824d8fe3fcf51d8550f1d7bb78a43694e2f037 | BeniyamL/alx-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 447 | 4.34375 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
"""
print_matrix_integer - print matrix of an integer
@matrix: the given matrix
@Return : nothing
"""
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if j == len(matrix[i]) - 1:
print("{:d}".format(matrix[i][j]), end="")
else:
print("{:d}".format(matrix[i][j]), end=" ")
print()
|
a19ee324078a41a9ec52a7ba73ed315c13f1d6ee | habibor144369/python-all-data-structure | /dictionary-3.py | 1,285 | 3.8125 | 4 | # dictionary data structure--
marks = {
1:{'name': 'Habibor Rahaman', 'roll': 14, 'result':{'Bangla': {'first': {'sahitto': 77, 'kobita': 76}, 'second': 65}, 'English': 79, 'Programing': 98, 'Math': 92, 'Science': 80}},
2:{'name': 'Abdullah', 'roll': 17, 'result':{'Bangla': 78, 'English': 79, 'Programing': 80, 'Math': 87, 'Science': 89}},
3:{'name': 'Mohammodullah', 'roll': 13, 'result':{'Bangla': 74, 'English': 73, 'Programing': 90, 'Math': 85, 'Science': 84}},
4:{'name': 'Wahidur rahman', 'roll': 23, 'result':{'Bangla': 77, 'English': 79, 'Programing': 60, 'Math': 78, 'Science': 89}},
5:{'name': 'siyam', 'roll': 44, 'result':{'Bangla': 56, 'English': 79, 'Programing': 70, 'Math': 79, 'Science': 81}},
6:{'name': 'soron', 'roll': 24, 'result':{'Bangla': 75, 'English': 76, 'Programing': 60, 'Math': 74, 'Science': 82}}
}
# particuler key access in dictionary--- simple 1 person data here
print(marks[1]['result']['Bangla']['first']['sahitto'])
print(marks[1]['result']['Bangla']['first'])
print(marks[1]['result']['Bangla'])
print(marks[1]['result'])
print(marks[1])
print(marks)
# particuler person key call----
print(marks[2])
print(marks[3])
print(marks[4])
print(marks[5])
print(marks[6])
# for loop use in dictionary ----
for i in marks:
print(i, marks[i])
|
225cc1a1097052b861c48073c96566a1a23618fa | TetianaHrunyk/DailyCodingProblems | /challenge28.py | 2,507 | 4.125 | 4 | """
Write an algorithm to justify text. Given a sequence of words and an integer
line length k, return a list of strings which represents each line,
fully justified.
More specifically, you should have as many words as possible in each line.
There should be at least one space between each word. Pad extra spaces
when necessary so that each line has exactly length k.
Spaces should be distributed as equally as possible, with the extra spaces,
if any, distributed starting from the left.
If you can only fit one word on a line, then you should pad
the right-hand side with spaces.
Each word is guaranteed not to be longer than k.
For example, given the list of words
["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
and k = 16, you should return the following:
["the quick brown", # 1 extra space on the left
"fox jumps over", # 2 extra spaces distributed evenly
"the lazy dog"] # 4 extra spaces distributed evenly
"""
def distribute(words: list, k: int) ->list:
lines = []
line = ""
for word in words:
if len(line) + (len(word)) == k:
line += word
lines.append(line)
line = ""
elif len(line) + (len(word)) < k:
word_with_space = word + ' '
line += word_with_space
else:
lines.append(line)
line = word + ' '
if line:
lines.append(line)
evenly_distributed_lines = []
new_line = ""
for line in lines:
if line[-1] == ' ':
line = line[:-1]
spaces_to_add = k - len(line)
if spaces_to_add == 0:
continue
else:
spaces_in_line = line.count(' ')
spaces_to_distribute = spaces_to_add // spaces_in_line
extra_spaces = spaces_to_add % spaces_in_line
for char in line:
if char != ' ':
new_line += char
else:
new_line += ' ' + ' '*spaces_to_distribute
if extra_spaces != 0:
new_line += ' '*extra_spaces
extra_spaces = 0
evenly_distributed_lines.append(new_line)
new_line = ""
return evenly_distributed_lines
def print_lines(lines: list):
for line in lines:
print(line)
if __name__ == "__main__":
words = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
k = 16
print_lines(distribute(words, k)) |
970ae608a12d199e1a55f189e86820be9422f871 | hamidhmz/python-exercises | /basic.py | 110 | 3.5625 | 4 | """basic"""
items = [1, 2, 3, 4]
afterMapping = list(map(lambda item: item+1, items))
print(afterMapping)
|
92c30a32bbd6e010f67b522a5eb14d89365492c8 | FlorianMuller/bootcamp-machine-learning-day03 | /ex01/data_spliter.py | 2,995 | 3.8125 | 4 | import numpy as np
def data_spliter(x, y, proportion):
"""
Shuffles and splits the dataset (given by x and y) into a training and a
test set, while respecting the given proportion of examples to be kept in
the traning set.
Args:
x: has to be an numpy.ndarray, a matrix of dimension m * n.
y: has to be an numpy.ndarray, a vector of dimension m * 1.
proportion: has to be a float, the proportion of the dataset that will
be assigned to the training set.
Returns:
(x_train, x_test, y_train, y_test) as a tuple of numpy.ndarray
None if x or y is an empty numpy.ndarray.
None if x and y do not share compatible dimensions.
Raises:
This function should not raise any Exception.
"""
if x.ndim == 1:
x = x[:, np.newaxis]
if y.ndim == 2 and y.shape[1] == 1:
y = y.flatten()
if (x.size == 0 or y.size == 0
or x.ndim != 2 or y.ndim != 1
or x.shape[0] != y.shape[0]):
return None
# copy to not shuffle original x and y
x = x.copy()
y = y.copy()
# Shuffling x and y the same way
seed = 42
r = np.random.RandomState(seed)
r.shuffle(x)
r.seed(seed)
r.shuffle(y)
# Slicing
i = np.ceil(x.shape[0] * proportion).astype(int)
return (x[:i], x[i:], y[:i], y[i:])
def print_res(splited, **kwargs):
print(
(f"x_train: {splited[0]}\n"
f"x_test: {splited[1]}\n"
f"y_train: {splited[2]}\n"
f"y_test: {splited[3]}"),
**kwargs
)
if __name__ == "__main__":
x1 = np.array([1, 42, 300, 10, 59])
y = np.array([0, 1, 0, 1, 0])
# Example 1:
print_res(data_spliter(x1, y, 0.8), end="\n\n")
# Output:
# (array([1, 59, 42, 300]), array([10]), array([0, 0, 0, 1]), array([1]))
# Example 2:
print_res(data_spliter(x1, y, 0.5), end="\n\n")
# Output:
# (array([59, 10]), array([1, 300, 42]), array([0, 1]), array([0, 1, 0]))
x2 = np.array([[1, 42],
[300, 10],
[59, 1],
[300, 59],
[10, 42]])
y = np.array([0, 1, 0, 1, 0])
# Example 3:
print_res(data_spliter(x2, y, 0.8), end="\n\n")
# Output:
# (array([[10, 42],
# [300, 59],
# [59, 1],
# [300, 10]]), array([[1, 42]]), array([0, 1, 0, 1]), array([0]))
# Example 4:
print_res(data_spliter(x2, y, 0.5), end="\n\n")
# Output:
# (array([[59, 1],
# [10, 42]]), array([[300, 10],
# [300, 59],
# [1, 42]]), array([0, 0]), array([1, 1, 0]))
# Be careful! The way tuples of arrays are displayed
# could be a bit confusing...
#
# In the last example, the tuple returned contains the following arrays:
# array([[59, 1],
# [10, 42]])
#
# array([[300, 10],
# [300, 59]
#
# array([0, 0])
#
# array([1, 1, 0]))
|
4200f0a7ccc3699f2ec2af733432ff0939222686 | cwavesoftware/python-ppf | /ppf-ex05/moreless.py | 170 | 4.15625 | 4 | num = int(input('Enter number? '))
if(num<0):
print("Number is less than zero")
elif(num>0):
print("Number is higher than zero")
else:
print("Number is zero") |
4064b17b933d9825ece9f1869cb5fc31429112a2 | jvillega/App-Academy-Practice-Problems-II | /OrderedVowelWords.py | 2,046 | 4.34375 | 4 | #!/usr/bin/env python3
# Write a method, `ordered_vowel_words(str)` that takes a string of
# lowercase words and returns a string with just the words containing
# all their vowels (excluding "y") in alphabetical order. Vowels may
# be repeated (`"afoot"` is an ordered vowel word).
#
# You will probably want a helper method, `ordered_vowel_word?(word)`
# which returns true/false if a word's vowels are ordered.
#
# Difficulty: 2/5
def get_vowels( word ):
vowels = [ "a", "e", "i", "o", "u" ]
vowelsInWord = ""
for char in word:
if vowels.count( char ) != 0:
vowelsInWord += char
return vowelsInWord
def check_vowel_order( word ):
length = len( word )
for indexOuter in range( length - 1 ):
for indexInner in range( length - indexOuter - 1 ):
indexToTestAgainst = indexInner + indexOuter + 1
if ord( word[ indexOuter ] ) > ord( word[ indexToTestAgainst ] ):
return False
return True
def ordered_vowel_word( array ):
vowels = [ "a", "e", "i", "o", "u" ]
orderWordsString = ""
for word in array:
strOfVowelsInWord = get_vowels( word )
isOrdered = check_vowel_order( strOfVowelsInWord )
if isOrdered:
if orderWordsString == "":
orderWordsString += word
else:
orderWordsString += " " + word
return orderWordsString
def ordered_vowel_words( string ):
splitString = []
orderedVowelWords = []
splitString = string.split( " " )
return ordered_vowel_word( splitString )
print( ordered_vowel_words("amends" ) )
if ordered_vowel_words("complicated" ) == "": print( "No in order vowels words" )
print( ordered_vowel_words("afoot" ) )
print( ordered_vowel_words("ham" ) )
print( ordered_vowel_words("crypt" ) )
print( ordered_vowel_words("o" ) )
print( ordered_vowel_words("tamely" ) )
phrase = "this is a test of the vowel ordering system"
result = "this is a test of the system"
print( ordered_vowel_words(phrase) )
|
8b577e25449fc3c16300e2b55bbe21f91282d0e5 | Austin-Bell/PCC-Exercises | /Chapter_4/threes.py | 185 | 4.21875 | 4 | # Make a lsit of the myltiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
threes = list(range(3,31))
for three in threes:
three = three * 3
print(three)
|
16ba80d504687e4de4ae0b6e758938b16a6d55d7 | alblaszczyk/python | /simplepythonexercises/longest_word.py | 248 | 3.953125 | 4 | x = ['chuj', 'matrioszka', 'oj']
def longest_word(x):
lst = []
for i in x:
lst.append(len(i))
max_value = lst[0]
for i in lst:
if max_value < i:
max_value = i
return max_value
print longest_word(x)
|
951076ff342a7f68944c928250c809c2668fadfb | efrainc/data_structures | /linked_list.py | 3,315 | 4.46875 | 4 | #! /usr/bin/env python
# Linked List Python file for Efrain, Mark and Henry
class Node(object):
"""Class identifying Node in linked list
with a pointer to the next node and a value
"""
def __init__(self, value, pointer=None):
"""Constructor for node
which requires a value, and an optional pointer
If no pointer is specified, it's set to None
"""
self.pointer = pointer
self.value = value
class Linked_list(object):
"""Class defining a linked list data structure."""
def __init__(self):
"""Constructor for linked list
Initializing a pointer to a head of an empty linked list.
"""
self.head = None
def insert(self, value):
"""Insert new node with value at the head of the list.
"""
self.head = Node(value, self.head)
def __str__(self):
"""Returns list as a Python tuple literal.
"""
output = ""
currentposition = self.head
while currentposition:
if isinstance(currentposition.value, str):
value = "'{}'".format(currentposition.value.encode('utf-8'))
output = "{}{}".format(output, value)
else:
output = "{}{}".format(output, currentposition.value)
currentposition = currentposition.pointer
if currentposition:
comma = ", "
output = "{}{}".format(output, comma)
output = "({})".format(output)
return output
def display(self):
"""Print list as a Python tuple literal.
"""
print str(self)
def pop(self):
"""Pop the first value off the head of the list and return value.
Raises attribute error if called on an empty linked list.
"""
old_head_value = self.head.value
self.head = self.head.pointer
return old_head_value
def size(self):
"""Return the length of the list.
"""
count = 0
currentposition = self.head
while currentposition:
count += 1
currentposition = currentposition.pointer
return count
def search(self, value):
"""Return the node containing value in the list, if present, else None.
"""
currentposition = self.head
while currentposition:
if currentposition.value == value:
return currentposition
currentposition = currentposition.pointer
return None
def remove(self, node):
"""Remove the given node from the list, assuming node is in list.
"""
currentposition = self.head
previousposition = None
# for case when we are removing first node
if currentposition == node:
self.head = currentposition.pointer
return None
while currentposition:
if currentposition == node:
previousposition.pointer = currentposition.pointer
return None
previousposition = currentposition
currentposition = currentposition.pointer
# def __iter__(self):
# current = self.head
# while current:
# yield current
# current = current.pointer
# for node in self |
d17020af0c45849006328be4364c6309fdd8d4c0 | michaelvwu/Introduction-to-Programming | /Python Projects/lo_shu.py | 1,654 | 3.734375 | 4 | # Nancy Zhang (nz2bc)
# Michael Wu (mvw5mf)
num = [['', '', ''], ['', '', ''], ['', '', '']]
a, b, c, d, e, f, g, h, i = input("Numbers: ").split()
row1 = [a, b, c]
row2 = [d, e, f]
row3 = [g, h, i]
num_square1 = [int(x) for x in row1]
num_square2 = [int(y) for y in row2]
num_square3 = [int(z) for z in row3]
summation_row1 = sum(num_square1)
summation_row2 = sum(num_square2)
summation_row3 = sum(num_square3)
column_01 = [a, d, g]
column_11 = [b, e, h]
column_21 = [c, f, i]
column_0 = [int(x) for x in column_01]
column_1 = [int(y) for y in column_11]
column_2 = [int(z) for z in column_21]
summation_col1 = sum(column_0)
summation_col2 = sum(column_1)
summation_col3 = sum(column_2)
summations = summation_col1, summation_col2, summation_col3, summation_row1, summation_row2, summation_row3
diagonal1 = [a, e, i]
diagonal2 = [g, e, c]
diag_0 = [int(x) for x in diagonal1]
diag_1 = [int(y) for y in diagonal2]
if sum(diag_0) == 15:
if sum(diag_1) == 15:
while summations != 15:
if summation_row1 != 15:
print(row1, "fails the test!")
if summation_row2 != 15:
print(row2, "fails the test!")
if summation_row3 != 15:
print(row3, "fails the test!")
if summation_col1 != 15:
print("Column 0 fails the test!")
if summation_col2 != 15:
print("Column 1 fails the test!")
if summation_col3 != 15:
print("Column 2 fails the test!")
print("This is not a Lo Shu Magic Square")
break
else:
print("This is a valid Lo Shu Magic Square!") |
18efca361cd1e33413c9a0f890c00f42f442771e | danamulligan/APTsPython | /ps2/PortManteau.py | 438 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 12:40:55 2018
@author: danamulligan
"""
def combine(first,flen,second,slen):
length = flen + slen
final = [0] * length
counter = 0
end = len(second)
for k in range(0, flen):
final[k] = first[k]
counter += 1
for n in range(slen, 0, -1):
final[counter] = second[end - n]
counter += 1
return ''.join(final) |
1a33f76741af88b32104558937187e4d56af938b | balturu/SmartCoding | /HomeworkAssignments/Ex2_phone_book.py | 428 | 3.796875 | 4 | names = ["Peter", "Mary", "Jane", "Mark"]
locations = ["Stockholm", "Gothenburg", "Helsingborg", "Umea"]
phones = [46701111111, 46702222222, 46703333333, 46704444444]
#for n, l, p in zip(names, locations, phones):
#print('{0}, {1}, {2}'.format(n, l, p))
phoneBook = {}
count = 0
for name in names:
phoneBook[name] = {'location': locations[count], 'phone': phones[count]}
count = count + 1
print(phoneBook.items())
|
1852540df4630e62782444bfec667bb0bec224d2 | ecastillob/project-euler | /051 - 100/80.py | 1,142 | 3.875 | 4 | """
It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.
The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475.
For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.
"""
from decimal import Decimal, getcontext
from math import trunc, sqrt
getcontext().prec = 105
cuadrados = [i*i for i in range(1, 10+1)]
numeros = [i for i in range(1, 100+1) if i not in cuadrados]
print(numeros, end="\n\n")
sumatoria = 0
acumulados = []
for valor in numeros:
d = Decimal(valor).sqrt()
d_str = str(d)
begin_index = d_str.index('.')
parte_decimal = d_str[begin_index+1:begin_index+100]
suma = sum([int(c) for c in parte_decimal]) + trunc(d)
sumatoria += suma
acumulados.append(suma)
print(valor, '\t', len(parte_decimal), suma, '\t', len(str(trunc(d))), trunc(d))
sumatoria # 40886 |
a6a8a3c87fe930c93693cb273ff7968047f05f31 | YolieQQQ/AtCoder | /abc174/c.py | 326 | 3.609375 | 4 | def sevens():
num = 7
while True:
num = num*10+7
yield num
if __name__ == '__main__':
K = int(input())
for i, sv in enumerate(sevens()):
if sv%K==0:
print(sv)
print(i+2)
quit()
if K<=i:
print(-1)
quit()
|
4fdf08b69859547541561d5a15e76082d0f865d1 | ccsandhanshive/Practics-Code | /Practics/returnMissingNumber.py | 482 | 3.546875 | 4 |
'''def getMissingVal(numbers):
return ((max(numbers)*(max(numbers)+1))//2)-(sum(numbers))'''
def getMissingVal(numbers,count):
ans=[]
for i in range(1,count):
if i not in numbers:
ans.append(i)
return ans
n=int(input())
for _ in range(n):
numbers=input()
count=int(input())
numbers=numbers.split(",")
for i in range(len(numbers)):
numbers[i]=int(numbers[i])
print(getMissingVal(numbers,count)) |
d307cf7f1e96abda54b4f140240767d3043088e2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/7c93fa4e609349ef8806bc92ab59953d.py | 602 | 3.859375 | 4 | import calendar
from datetime import date
def meetup_day(year, month, day, week):
day_int = list(calendar.day_name).index(day)
cal = calendar.Calendar()
cal_iterator = cal.itermonthdays2(year, month)
if week[0].isnumeric():
week_index = int(week[0]) - 1
elif week == 'last':
week_index = -1
if week == 'teenth':
date_int = next(filter(lambda x: 12 < x[0] < 20 and x[1] == day_int, cal_iterator))[0]
else:
date_int = [day for day in cal_iterator if day[1] == day_int and day[0] != 0][week_index][0]
return date(year, month, date_int)
|
5648b3f543947f1fb15ba0fdab2df999da2cb63f | derick-droid/codingbat | /warm up 2/first_half/first_half.py | 343 | 4.1875 | 4 | """
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc'
"""
def first_half(str):
if len(str) % 2 == 0:
index = str[:int(len(str) / 2)]
return index
else:
return False
|
cf5654c32fdfcb93bdea7c4e8935a30af0fd188e | siggame/MegaMinerAI-15 | /server/game_app/maze.py | 5,251 | 3.5625 | 4 | import random
#directions
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
#map array states
EMPTY = 0
SPAWN = 1
WALL = 2
class Wall:
def __init__(self, x, y, wallDir):
self.x = x
self.y = y
self.wallDir = wallDir
class BFSTile:
def __init__(self, x, y):
self.x = x
self.y = y
self.data = -1
#implement breadth-first search. thanks again, wikipedia
def getPathLength(map, startX, startY, endX, endY):
queue = []
tiles = [[BFSTile(x,y) for y in range(len(map))] for x in range(len(map))]
tiles[startX][startY].data = 4
queue.append(tiles[startX][startY])
while len(queue) != 0:
v = queue[0]
del queue[0]
if v.x == endX and v.y == endY:
break
if v.x > 0 and map[v.x-1][v.y] == EMPTY:
if tiles[v.x-1][v.y].data == -1:
queue.append(tiles[v.x-1][v.y])
tiles[v.x-1][v.y].data = EAST
if v.y > 0 and map[v.x][v.y-1] == EMPTY:
if tiles[v.x][v.y-1].data == -1:
queue.append(tiles[v.x][v.y-1])
tiles[v.x][v.y-1].data = SOUTH
if v.x < len(map)-1 and map[v.x+1][v.y] == EMPTY:
if tiles[v.x+1][v.y].data == -1:
queue.append(tiles[v.x+1][v.y])
tiles[v.x+1][v.y].data = WEST
if v.y < len(map)-1 and map[v.x][v.y+1] == EMPTY:
if tiles[v.x][v.y+1].data == -1:
queue.append(tiles[v.x][v.y+1])
tiles[v.x][v.y+1].data = NORTH
length = 0
runBack = tiles[endX][endY]
while runBack.data != 4:
if runBack.data == NORTH:
runBack = tiles[runBack.x][runBack.y-1]
if runBack.data == EAST:
runBack = tiles[runBack.x+1][runBack.y]
if runBack.data == SOUTH:
runBack = tiles[runBack.x][runBack.y+1]
if runBack.data == WEST:
runBack = tiles[runBack.x-1][runBack.y]
length += 1
return length
#generate maze using prim's algorithm. thanks wikipedia
def generate(size):
map = [[WALL for y in range(size)] for x in range(size)]
walls = []
#choose starting position and add walls
firstX = random.randint(0,size/2-1)*2+1;
firstY = random.randint(0,size/2-1)*2+1;
map[firstX][firstY] = EMPTY
if firstX > 1:
walls.append(Wall(firstX-1, firstY, WEST))
if firstY > 1:
walls.append(Wall(firstX, firstY-1, NORTH))
if firstX < size-2:
walls.append(Wall(firstX+1, firstY, EAST))
if firstY < size-2:
walls.append(Wall(firstX, firstY+1, SOUTH))
while len(walls) != 0:
#randomly choose wall from list
chosenIndex = random.randint(0,len(walls)-1);
chosenWall = walls[chosenIndex]
otherSideIsInMaze = False
otherSideX = chosenWall.x
otherSideY = chosenWall.y
#get tile on other side of wall
if chosenWall.wallDir == NORTH:
otherSideY -= 1
elif chosenWall.wallDir == EAST:
otherSideX += 1
elif chosenWall.wallDir == SOUTH:
otherSideY += 1
else:
otherSideX -= 1
otherSideIsInMaze = map[otherSideX][otherSideY] == EMPTY
#break down wall to other side
if not otherSideIsInMaze:
map[otherSideX][otherSideY] = EMPTY
map[chosenWall.x][chosenWall.y] = EMPTY
#add surrounding walls to wall list
if otherSideX > 1 and chosenWall.wallDir != 1 and map[otherSideX-1][otherSideY] == WALL:
walls.append(Wall(otherSideX-1, otherSideY, WEST))
if otherSideY > 1 and chosenWall.wallDir != 2 and map[otherSideX][otherSideY-1] == WALL:
walls.append(Wall(otherSideX, otherSideY-1, NORTH))
if otherSideX < size-2 and chosenWall.wallDir != 3 and map[otherSideX+1][otherSideY] == WALL:
walls.append(Wall(otherSideX+1, otherSideY, EAST))
if otherSideY < size-2 and chosenWall.wallDir != 0 and map[otherSideX][otherSideY+1] == WALL:
walls.append(Wall(otherSideX, otherSideY+1, SOUTH))
del walls[chosenIndex]
#build list of dead-ends (3+ adjacent walls)
deadEndList = []
for x in range(1, size-1):
for y in range(1, size-1):
if map[x][y] == WALL:
continue
adjacentWallCount = 0
if x > 0 and map[x-1][y] == WALL:
adjacentWallCount += 1
if y > 0 and map[x][y-1] == WALL:
adjacentWallCount += 1
if x < size-1 and map[x+1][y] == WALL:
adjacentWallCount += 1
if y < size-1 and map[x][y+1] == WALL:
adjacentWallCount += 1
if adjacentWallCount >= 3:
deadEndList.append(Wall(x,y,0))
for tile in deadEndList:
if tile.x > 2 and getPathLength(map, tile.x, tile.y, tile.x-2, tile.y) >= size:
map[tile.x-1][tile.y] = EMPTY
if tile.y > 2 and getPathLength(map, tile.x, tile.y, tile.x, tile.y-2) >= size:
map[tile.x][tile.y-1] = EMPTY
if tile.x < size-3 and getPathLength(map, tile.x, tile.y, tile.x+2, tile.y) >= size:
map[tile.x+1][tile.y] = EMPTY
if tile.y < size-3 and getPathLength(map, tile.x, tile.y, tile.x, tile.y+2) >= size:
map[tile.x][tile.y+1] = EMPTY
map[0][size/2+1] = SPAWN
map[size/2+1][size-1] = SPAWN
map[size-1][size/2-1] = SPAWN
map[size/2-1][0] = SPAWN
return map |
bb79a65544913ca54d0845a598613b3a2854a5cb | balajipothula/python | /fraction.py | 355 | 3.703125 | 4 | import fractions
from fractions import Fraction as fr
print(fractions.Fraction(1.5)) # 3/2
print(fractions.Fraction(5)) # 5
print(fractions.Fraction(1,3)) # 1/3
print(fractions.Fraction(1.1))
print(fractions.Fraction('1.1')) # 11/10
print(fr(1,3) + fr(1,3)) # 2/3
print(1 / fr(5,6)) # 6/5
print(fr(-3,10) > 0) # False
print(fr(-3,10) < 0) # True
|
750f67d881e555c51cb5f834b305c3c58914c82c | ravi4all/PythonAugReg_1-30 | /02-Inheritance/03-Multiple.py | 1,265 | 3.984375 | 4 | class Person:
def __init__(self):
self.company = "HCL"
self.bank = "HDFC"
self.name = ""
self.age = None
self.gender = ""
self.salary = None
class Emp:
def __init__(self, name, age, gender, salary):
super().__init__()
self.name = name
self.age = age
self.gender = gender
self.salary = salary
def printEmp(self):
print(self.name,"Works in %s"%(self.company))
print(self.name,"Has a account in %s"%(self.bank))
def printPerson(self):
print("Name : {}, Age : {}, Gender : {}, Salary : {} ".format(self.name, self.age, self.gender, self.salary))
class Department(Person, Emp):
def __init__(self, name, age, gender, salary):
super().__init__()
self.name = name
self.age = age
self.gender = gender
self.salary = salary
self.dept = "IT"
Emp.__init__(self, self.name, self.age, self.gender, self.salary)
def printEmp(self):
print(self.name, "is in {} department".format(self.dept))
print(self.name,"Has a account in %s"%(self.bank))
obj = Department("Ram", 21, "Male", 15000)
obj.printPerson()
obj.printEmp()
|
50f11daf72924c09b2d348d235f36ec02d42a42a | JoanRamallo1/RESER_VAVOL | /ES/src/Hotels.py | 1,010 | 3.5 | 4 | class Hotels:
def __init__(self):
self.code = []
self.nom = []
self.hostes = []
self.habitacions = []
"""Numero de dies"""
self.durada = []
self.Price = []
def add_Hotel(self, nom, code = 0, hostes = 0, habitacions = 0, durada = 0, price = 0):
self.code.append(code)
self.nom.append(nom)
self.hostes.append(hostes)
self.habitacions.append(habitacions)
self.durada.append(durada)
self.Price.append(price)
def get_price_habitacions(self):
sum = 0
for i in self.Price:
sum = sum + i
return sum
def del_hotel(self, nom):
if nom in self.nom:
i = self.nom.index(nom)
self.code.pop(i)
self.nom.pop(i)
self.hostes.pop(i)
self.habitacions.pop(i)
self.durada.pop(i)
self.Price.pop(i)
|
3d9ad55a1e76660c59519431c17077156a23ef23 | Amar0589/Session6_12_assigment | /palindrome.py | 143 | 3.859375 | 4 | def ispalindrome(ip):
s=str(ip)
print("Input string is:",s)
rev=s[::-1]
if s == rev:
print("string is palindrome") |
4e32c7d9c70ed77c454de096f0a22952abb7330d | DarelShroo/eoi | /05-libs/external/pillow/payaso.py | 247 | 3.578125 | 4 | from PIL import Image, ImageDraw
leon = Image.open("leon.jpg")
width, height = leon.size
x, y = width //2, height // 2
y += 80
rect = (x-55, y-55, x+55, y+55)
draw = ImageDraw.Draw(leon)
draw.ellipse(rect, fill=(255, 0, 0), width=3)
leon.show()
|
a188a512e3698c43336e0f210be56a4416556edb | namnt14/practice-python | /char_input.py | 384 | 3.90625 | 4 | import time
def years():
name = input("Enter your name: ")
age = int(input("Input your age: "))
curYear = time.localtime(time.time())
year = str(int(curYear[0]) + (100 - age))
times = int(input ("How many times would you like the message to print out: "))
message = name + " would turn into 100 years old in the year " + year + "\n"
print(times * message)
|
87d14a779960a30d87d2994f251ea79f0cdfc378 | xiangyang0906/python_lianxi | /zuoye5/集合推导式01.py | 424 | 4.125 | 4 | set01 = {1, 2, 3, 3, 4, 5, 6, 6, 7, 2}
print(set01)
for i in set01:
print(i, end=" ")
print()
set02 = {i for i in set01}
print(set02)
list01 = [1, 2, 3, 3, 4, 5, 6, 6, 7, 2]
set03 = {i for i in list01}
print(set03)
# 计算列表中list01中每个值的平方,并去重
set07 = {i * i for i in list01}
set08 = {i * i for i in list01}
print(set07)
print(set08)
set66 = {"xi", "an", "g", "ya", "an", "g"}
print(set66) |
fd42fc6a0c04a76a0e134aa7569b2c2be4b12c67 | jingyiZhang123/leetcode_practice | /partition/Kth_largest_element_in_an_array_215.py | 1,472 | 4 | 4 | """
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
"""
from random import randint
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return self._find_rank(nums, 0, len(nums) - 1, len(nums) - k + 1)
def _partition(self, arr, left, right):
swap = left + randint(0, (right-left))
arr[left], arr[swap] = arr[swap], arr[left]
pivot = arr[left]
lt = left
for i in range(left + 1, right + 1):
if arr[i] < pivot:
lt += 1
arr[i], arr[lt] = arr[lt], arr[i]
arr[left], arr[lt] = arr[lt], arr[left]
return lt
def _find_rank(self, arr, left, right, target):
if left >= right:
return arr[left]
p = self._partition(arr, left, right)
cur_rank = p - left + 1
if cur_rank == target:
return arr[p]
elif cur_rank > target:
return self._find_rank(arr, left, p-1, target)
else:
return self._find_rank(arr, p+1, right, target - cur_rank)
print(Solution().findKthLargest([1], 1))
|
f064552bf961f453cef9d2a20e3b873f05bae6e1 | OokGIT/pythonproj | /stochastic/roll_die.py | 861 | 3.84375 | 4 | import random
'''
random - uses time in milliseconds since January 1, 1968.
That is called seed generating
Given a seed you always get the same sequence
'''
random.seed(0) # use zero as seed
def rollDie():
'''
Returns a randomly chosen int beween 1 and 6
'''
return random.choice([1, 2, 3, 4, 5, 6])
def testRoll(n = 10):
result = ''
for i in range(n):
result += str(rollDie())
print(result)
def runSim(goal, numTrials):
total = 0
for i in range(numTrials):
result = ''
for j in range(len(goal)):
result += str(rollDie())
if result == goal:
total += 1
print("Actual probability=",
round(1/(6**len(goal)), 8))
estProbability = round(total/numTrials, 8)
print('Estimated Probability =',
round(estProbability, 8))
runSim('66', 1000) |
3b78aeaf3d738cc6d5b416eee1c61bff85af6d34 | sotrnguy92/udemyPython | /udemy4/pythonPrinting/homework1.py | 804 | 3.53125 | 4 | ###
# Part 1
###
print('Practice', " Makes Perfect.")
# Practice Makes Perfect.
print("Children must be taught\n how to think\n NOT\n what to think")
#Children must be taught
# how to think
# NOT
# what to think
print("\"\"")
#""
print('2 * 3 * 4 * 5 / 10 = ')
#2 * 3 * 4 * 5 / 10 =
print(2 * 3 * 4 * 5 / 10)
#12.0
###
#Part 2
###
print('Print("Me")')
print("Print('Me')")
print('Print(\'Me\")')
print("You will learn\n a LOT")
###
#Part 3
###
print("*\n* *\n* * *\n* * * *")
###
#Part 4
###
print(" * \n * * * \n * * * * * \n * * * * * * * \n* * * * * * * * *")
###
#Part 5
###
print(" * \n * * * \n * * * * * \n * * * * * * * \n* * * * * * * * *\n * * * * * * * \n * * * * * \n * * * \n * ")
|
daa30ab2b8cc42616613d552c4e8d41253753cf6 | ivancete66/M01-2016-2017 | /M03/bucles_for/ejercicio-bucle-for-contar2.py | 119 | 3.890625 | 4 | #coding: utf8
numero = 1
final=input("Introduce el final del contador: ")
for numero in range(1,final):
print numero
|
6419a504a30690b864264b1e013cd4eb7a4f4a9e | mpcalzada/data-science-path | /3-PROGRAMACION-ORIENTADA-OBJETOS/algoritmos_ordenamiento/ordenamiento_burbuja.py | 590 | 3.59375 | 4 | import random
def ordenamiento_burbuja(lista):
n = len(lista)
for i in range(n):
for j in range(0, n - i - 1):
if lista[j] > lista[j + 1]: # O(n) * O(n - i -1) = O(n) * O(n) = O(n ** 2)
lista[j], lista[j + 1] = lista[j + 1], lista[j]
return lista
if __name__ == '__main__':
tamano_lista = int(input('Tamaño de la lista: '))
lista = [random.randint(0, 100) for i in range(tamano_lista)]
print(f'La lista desordenada es: {lista}')
ordenada = ordenamiento_burbuja(lista)
print(f'La lista ordenada es: {ordenada}')
|
f6de31f7f84fedb3573cc8e0863c050393886091 | paulosrlj/PythonCourse | /Módulo 1 - Python Básico/Aula13/Exercicio03.py | 269 | 3.828125 | 4 | nome = input('Informe o seu primeiro nome: ')
try:
if len(nome) <= 4:
print('Seu nome é curto.')
elif len(nome) <= 6:
print('Seu nome é normal.')
else:
print('Seu nome é maior que o normal.')
except:
print('Nome inválido.') |
43a7a0f57ecb78f05eb45bad6ddd514b132b39fb | bunmiaj/CodeAcademy | /Python/Tutorials/Loops/enumerate.py | 796 | 4.625 | 5 | # Counting as you go
# A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at.
# Generally this isn't an issue, but at times it is useful to know how far into the list you are.
# Thankfully the built-in enumerate function helps with this.
# enumerate works by supplying a corresponding index to each element in the list that you
# pass it. Each time you go through the loop, index will be one greater, and item will be the next item
# in the sequence. It's very similar to using a normal for loop with a list,
# except this gives us an easy way to count how many items we've seen so far.
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index + 1, item |
3a591ec7ab4727c5e4a54b7c40495c925c8ef6b0 | jaeheehur/algorithm-programmers | /src/practice/12906.py | 228 | 3.671875 | 4 | '''
Programmers - 같은 숫자는 싫어
https://programmers.co.kr/learn/courses/30/lessons/12906
'''
import itertools
def solution(arr):
return list(map(int, (''.join(map(str, (i for i, _ in itertools.groupby(arr)))))))
|
4e17c944ff2d96f134bee8242076c315cdb2c375 | Jesper-dev/madlibGame | /main.py | 506 | 4.28125 | 4 | # This will read a random Mad Lib
import random
# Opens the text file
f = open('madlibs.txt', 'r')
# Reads the whole file and stores it in a list
madlibText = f.readlines()
# Choose a random line from that list
madlib = random.choice(madlibText)
# Shows the users what the text will be
print(madlib)
# Ask the user to write a noun
noun = input("Enter a noun: ")
# Replace the blank with the users input
madlib = madlib.replace("blank", noun)
# Print out the madlib with the users noun
print(madlib)
|
1554708b0d7e4f1997e74481a510dc2211dcbf89 | chenyang1999/coding | /python100/tm04.py | 655 | 3.765625 | 4 | '''
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
程序源代码:
'''
y=int(input("year:"))
m=int(input("month:"))
d=int(input("day:"))
months = (31,28,31,30,31,30,31,31,30,31,30,31)
sum=0
if 0 < m <= 12:
for i in range(m-1):
sum+=months[i]
else:
print ('data error')
sum+=d
leap =0
if (y % 400 == 0) or ((y % 4 == 0) and (y % 100 != 0)):
leap = 1
if (leap == 1) and (m > 2):
sum += 1
print ('it is the %dth day.' % sum) |
0221f1d669d47f137ba169d16634330962bc8aa4 | akshaa5197/chatbot-in-python | /CHATBOT.py | 776 | 3.78125 | 4 | import math
import random
naameq=['what is your name','what is your name?','what\'s your name','your name','Who are you']
greetings=['hi','hello','welcome','hey nice to meet you']
greets=['hi','hello','hey']
shoplist={'soap':20,'shampoo':30,'mascara':40,'cream':180,'bindi':50,'eyeliner':100}
print("products for shopping")
sell=0
for i in shoplist:
print(i)
item=shoplist.keys()
price=shoplist[i]
data=input("enter item to buy\n")
price=shoplist[data]
bid=int(input("enter what price you bid\n"))
print(data,":","rs",bid)
print(price)
discount=float (0.2*price)
sell=float(price-discount)
print(bid,sell)
if (bid>sell):
print("you can buy the product at",bid,"rs")
else :
print("sorry cant sell")
|
75bd87c19305bbcfbbb7157ff33cb3b974c2e6bc | ITkachenko799/itstep-python-web | /python/lesson2/conditions.py | 800 | 4.3125 | 4 | # if/else, or and not, ternary
# > < == >= <= !=
# and or not
# if "":
# print("Hello")
# print(bool(0.0))
# print(bool("123"))
# a = 12
# b = "abc"
# if a and b:
# print("Values: " + str(a) + " " + str(b))
# print(type (None or ''))
# car_speed = 100
# motorcycle_speed = 50
# if car_speed > motorcycle_speed:
# print("Car is faster then motorcycle")
# elif car_speed == motorcycle_speed:
# print("Equals...")
# else:
# print("Motorcycle is faster then car")
# if 50 < car_speed < 150:
# print("OK")
# year = 2001
# if year % 4 == 0 and year % 100 or year % 400 == 0:
# print("This year is leap")
# else:
# print("This year is not leap")
# print("This year is leap" if year % 4 == 0 and year % 100 or year % 400 == 0 else "This year is not leap") |
0e01ccdfae50686ebba65e9fd7436ec076bdc0e2 | pasinimariano/masterUNSAM | /clase04/4.13Extraccion.py | 1,202 | 3.765625 | 4 | # Ejercicio 4.13: Extracción de datos
# 4.13Extraccion.py
import csv
def carga_camion(nombre_archivo):
'''Devuelve una lista del lote del camion, recibe como parametro un archivo .csv'''
f = open(nombre_archivo, encoding= 'utf8')
rows = csv.reader(f)
headers = next(rows)
lote = []
try:
for row in rows:
carga = dict (nombre = row[0],
cajones = int(row[1]),
precio = float(row[2]))
lote.append(carga)
except Exception as error:
print('-------------------------------------------------------------------------')
print('Surgio un error al cargar los datos, en el archivo: ', nombre_archivo, '.\n'
'Error: ', error.args)
print('-------------------------------------------------------------------------')
return lote
camion = carga_camion('../Data/camion.csv')
print(camion)
nombre_cajones =[ (s['nombre'], s['cajones']) for s in camion ]
print(nombre_cajones)
nombres = { s['nombre'] for s in camion }
print(nombres)
stock = { nombre: 0 for nombre in nombres }
for s in camion:
stock[s['nombre']] += s['cajones']
print(stock)
|
ccb31fe0db45c12c06a3c3acc8bc34c090bb272e | mastan-vali-au28/My-Code | /coding-challenges/week08/Day01/Q3.py | 381 | 4.21875 | 4 | '''
Q-3 ) Reverse a string using recursion:(5 marks)
If we have a string, write a function that prints reverse of that string, using
recursion.
Sample Input:
ABCD
Sample Output:
DCBA
'''
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))
print(reverse(a)) |
e74f97075b373d4777049e13e9917d4ea3a77f38 | jjbnunez/HW-CIS4361-Fuzzer | /defaults/runthrough.py | 3,062 | 4.125 | 4 | # Basics to know about Python from a C perspective:
#
# * Semicolons have been replaced by line breaks.
#
# * Whitespace matters if you don't want to get yelled at by the interpreter.
#
# * Python doesn't need to be compiled, hence why I'll call it an interpreter
# and not a compiler.
#
# * Most places that you would expect to use a set of {}, you instead use a
# ':', followed by indenting anything that should be in the block.
#
# * () are rarer than usual, but for the most part just get used for function
# calls, including class instantiation. (They don't get used in loops or if
# statements, and I believe the interpreter doesn't allow it.)
#
# * Classes are defined by class Name(object):
#
# * Functions are defined by def funcName(arguments):
#
# * You usually don't have to worry about types.
#
# * You can try out anything Python can execute, by starting the interpreter
# in the command line (just type python, or python3. My system defaults to
# python2).
#
# * Last but not least, Python doesn't need any of the structures in this file
# to run. If you create a file.py and put only a print("something")
# statement in it, it will work.
# One of the included Python modules.
import subprocess
# "Object" stands in the class definition essentially as a placeholder for
# where we could specify a parent class.
class Fuzzer(object):
# Initializer for the class.
def __init__(self, instanceVariable):
# This is essentially how you "declare" class variables.
self.instanceVariable = instanceVariable
# The easiest way to explain 'self' being first in the function parameter
# lists is that it is one of the quirks of how Python decided to make it's
# syntax.
#
# For __init__, after the class is instantiated, Python will pass the class
# instance into the first variable of __init__, thus creating your object.
# Not something we have to worry about.
#
# For class functions, standard practice is to include self as the first
# parameter. When the function gets called from somewhere, it will act
# kind of like a static function and you will pass your object for the
# self parameter. (It has to do with the fact that Python does not have
# "declarations" for variables, so it's useful to have self when you need
# to distinguish between an instance variable (passed to the function in
# self) and a local variable (used in the function)).
def launchProcess(self):
# Specific to Bash Unix shell
subprocess.call(["gcc", "-o", "fuzzer", "fuzzer.c"])
subprocess.call([".\\fuzzer.exe"])
localVariable = 'localVariable, because its inside a function'
# Mostly used for importing purposes, but not much concern for us if we keep
# everything in one file. As far as we're concerned, this will act as main()
# when this file is executed by the Python interpreter, and we can define
# everything we need above.
if __name__ == "__main__":
fuzzer = Fuzzer('instanceVariable')
Fuzzer.launchProcess(fuzzer)
|
1297359167ac925025a6676f080c2eb46e0180b8 | kwadrat/equ2 | /draw_eis.py | 3,032 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
from turtle import (
backward,
back,
color,
down,
forward,
hideturtle,
left,
mainloop,
onclick,
right,
showturtle,
speed,
up,
)
width = 16
height = 11
edge_len = 30
debug_centering = 0
invisible_turtle = 1
def triangle_lr():
down()
for i in range(3):
forward(edge_len)
left(120)
up()
forward(edge_len)
def triangle_rl():
down()
for i in range(3):
forward(edge_len)
right(120)
up()
forward(edge_len)
def draw_from_left_to_right():
for j in range(width):
triangle_lr()
right(60)
forward(edge_len)
right(120)
def draw_from_right_to_left():
for j in range(width):
triangle_rl()
left(60)
forward(edge_len)
left(120)
def stop_code(*argv):
onclick(None)
sys.exit(0)
def make_skos_travel():
skos_steps = height + 1
left(60)
for i in range(skos_steps):
forward(edge_len)
right(60)
def make_horiz_travel():
dst_pos = width / 2
if debug_centering:
tmp_format = 'dst_pos'
print('Eval: %s %s' % (tmp_format, eval(tmp_format)))
horiz_pos = (height) / 2
if debug_centering:
tmp_format = 'horiz_pos'
print('Eval: %s %s' % (tmp_format, eval(tmp_format)))
difference = dst_pos - horiz_pos
if debug_centering:
tmp_format = 'difference'
print('Eval: %s %s' % (tmp_format, eval(tmp_format)))
step_count = abs(difference)
if debug_centering:
tmp_format = 'step_count'
print('Eval: %s %s' % (tmp_format, eval(tmp_format)))
for i in range(int(step_count)):
if difference > 0:
forward(edge_len)
if debug_centering:
print("forward")
else:
backward(edge_len)
if debug_centering:
print("backward")
def move_to_center():
if debug_centering:
down()
color("green")
make_skos_travel()
make_horiz_travel()
def draw_axes():
move_to_center()
color("red")
for i in range(4):
if 1:
horiz_len = edge_len * int(width / 2)
down()
forward(horiz_len)
up()
backward(horiz_len)
left(90)
if 1:
vert_len = edge_len * height
down()
forward(vert_len)
up()
backward(vert_len)
left(90)
def draw_omega():
color("magenta")
down()
left(120)
forward(edge_len)
up()
def main():
onclick(stop_code)
speed(0)
if invisible_turtle:
hideturtle()
up()
back(300)
left(90)
forward(300)
right(90)
down()
for k in range(height):
draw_from_left_to_right()
draw_from_right_to_left()
draw_axes()
draw_omega()
if invisible_turtle:
showturtle()
print("Click on turtle to exit from program.")
mainloop()
main()
|
db72b36df6e99f30537814406f3219f1239f481b | PAPION93/python-playground | /01_python_basic/05-2-loop.py | 1,212 | 3.890625 | 4 | # 반복문 실습
print("while")
v1 = 1
while v1 < 11:
print(v1)
v1 += 1
print()
print("for")
for v2 in range(10):
print(v2)
# 1 ~ 100 sum
sum1 = 0
cnt1 = 1
while cnt1 <= 100:
sum1 += cnt1
cnt1 += 1
print(sum1)
print(sum(range(1, 101)))
print(sum(range(1, 101, 2)))
# list loop
# iterable : ragne, reversed, enumerate, filter, map, zip
names = ["Kim", "Son", "Park"]
for name in names:
print("Your name is", name)
word = "dreams"
for s in word:
print(s)
my_info = {
"name" : "Jun",
"age" : "292",
"city": "NY"
}
for key in my_info:
print(key)
for key in my_info.keys():
print("Key:", key)
for value in my_info.values():
print("value:", value)
for item in my_info.items():
print("item:", item)
for n in name:
if n.isupper():
print(n.lower())
else:
print(n.upper())
# break
# for else
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in nums:
print(num)
if num == 11:
print("found", num)
break
else:
print("Not found 11")
print()
print()
# continue
it = ['1', 2, 5, True, 5.4, complex(4)]
for v in it:
if type(v) is float:
print("found float")
continue
print(type(v))
|
741b721ae7d56eb2fdc2ebe838d0584d3570fa36 | nopeless/perfectionist | /archived/gamev2.py | 3,170 | 3.609375 | 4 | # v7 revision
# this version tried to pair boards with branches
# but i quickly realized a memory waste
# and made path instance lists instead
import numpy as np
import math
VALID_MAX=2048
# max amount of valid returns
# X of the board
X=5
Y=4
# the logic is weird but ill just go with it anyway
class board:# calculated before recursive,
def __init__(self, data: list, lost=0, this_move=None):
# starts with 0 loss
# accumulated loss
self.lost=lost
# only save the last move
self.last_move=this_move
self.board=data
if this_move != None:
# do stuff
pass # edit data
# print(self.board)
# i=0
# for yy in range(y):
# for xx in range(x):
# # if isinstance(data[i], np.byte) == False:
# # raise TypeError(f"TypeError: expected an instance of type 'int' got {repr(type(data[i]).__name__)} instead")
# self.board[yy][xx]=data[i]
# if data[i] != 0:
# self.count+=1
# i+=1
def __repr__(self):
i=0
outstr="-"*(X*3+2)+"\n"
for yy in range(Y):
outstr+="|"
for xx in range(X):
xx
yy
outstr+=str(self.board[i]).rjust(2, " ")+" "
i+=1
outstr+="|\n"
outstr+="-"*(X*3+2)
return outstr
# there are 3 types of moves
# paired moves, unequal moves, and single moves
# the paired and unequal moves are delt by numbers that are NOT 1
# the single moves are ONLY delt by the number 1
# paired moves happen when two blocks disappear together
# when searching for paired moves, only look in the down right diagonal
# so no duplicates can appear
# for unequal moves, search down right diagonal but add a reverse one as well (optimized search time)
# for example, 8->3 works and also 3->8 works as well
# for single moves, only "1" blocks can access this
# "1" blocks move to the other block
# this cannot produce duplicates
# a move is formatted like this
# ((x,y), (x,y))
# use pigeon sort for the move selecting
# max lost is always 14
# 1 loss is index 0
# pigeon sort using 14 slots
# the next move cann
def get_valid_moves_fever(self):
# automatically assumes <=10
# search linearly
moves=[]*14
for cell_index in range(len(self.board)):
if self.board[cell_index] != 0:
for iter_index in range(cell_index, len(self.board)):
if self.board[iter_index] != 0:
moves[abs(self.board[cell_index]-self.board[iter_index])-1].append(tuple(cell_index, iter_index))
return moves
def get_valid_moves_normal(self):
# automatically assumes > 10
moves=[]*14
for row_num_index in range(0, len(self.board), X):
for col in range(row_num_index, row_num_index+Y):
if self.board[col] != 0:
# check for the row cells
for target in range(col, row_num_index+X):
if self.board[col] != self.board[target]:
# add reverse case
moves[abs(self.board[col]-self.board[target])-1].append(tuple(target, col))
moves[abs(self.board[col]-self.board[target])-1].append(tuple(col, target))
return moves
if __name__=="__main__":
game_board=board(5, 4, np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,2,3,4,5], dtype=np.byte))
print(game_board)
|
d3f444921ee3732b33c71f61ddb6af15772e075e | TorinKeenan/Ecs36A | /study_programs/two_compliment.py | 738 | 3.5625 | 4 | #converts binary number to its two's compliment
def twos_compliment(binary_num):
compliment = ""
binary_list = [int(x) for x in list(binary_num)]
for i in range(len(binary_list)):
if binary_list[i] == 1:
binary_list[i] = 0
else:
binary_list[i] = 1
binary_list[len(binary_list)-1] += 1
i = len(binary_list)-1
while binary_list[i] == 2:
if i == 1:
binary_list[1] = 0
break
binary_list[i-1] += 1
binary_list[i] = 0
i -= 1
for binary_num in binary_list:
compliment += str(binary_num)
return compliment
print(twos_compliment("00000001"))
print(twos_compliment("10000001"))
print(twos_compliment("00000100")) |
8405493330548f7b50fb83d061fe5716b6f0f456 | appletreeisyellow/cracking-the-coding-interview | /ch08_recursion_and_dynamic_programming/8.3_magic-index.py | 3,033 | 4.15625 | 4 | import unittest
"""
8.3 Magic Index
A magic index in an array A [1. .. n -1] is defined to be
an index such that A[i] = i. Given a sorted array of distinct
integers, write a method to find a magic index, if one exists,
in array A.
FOLLOW UP
What if the values are not distinct?
"""
# binary search
# O(log2 n)
def find_magic_index(array):
if array is None or len(array) == 0:
return -1
return find_magic_index_helper(array, 0, len(array) - 1)
def find_magic_index_helper(array, start, end):
if start > end:
return -1
mid = (start + end) // 2 # middle index
if array[mid] == mid:
return mid
elif array[mid] < mid:
# search right half
return find_magic_index_helper(array, mid + 1, end)
else:
# search left half
return find_magic_index_helper(array, start, mid - 1)
def find_magic_index_follow_up(array):
# e.g.
# index: 0 1 2 3 4 5 6 7 8 9 10
# value: -10 -5 2 2 2 3 4 7 9 12 13
# A[5] = 3, we know that A[4] cannot be a magic index,
# but A[4] must be <= A[5]
# Instead of search the whole left side, we search
# A[0] to A[3] where 3 is the value of A[5]
# if A[mid] < mid, search left [start, min(mid-1, mid_value)]
# else, search right [max(mid+1, mid_value)]
if array is None or len(array) == 0:
return -1
return find_magic_index_follow_up_helper(array, 0, len(array) - 1)
def find_magic_index_follow_up_helper(array, start, end):
if start > end:
return -1
mid = (start + end) // 2
mid_value = array[mid]
if mid_value == mid:
return mid
# search left [start, min(mid-1, mid_value)]
left = find_magic_index_follow_up_helper(array, start, min(mid - 1, mid_value))
if left >=0:
return left
# search right [max(mid+1, mid_value)]
return find_magic_index_follow_up_helper(array, max(mid + 1, mid_value), end)
class Test(unittest.TestCase):
def test(self):
test_cases = [
# distinct values
([-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13], 7),
([-4, -3, -2], -1),
([], -1),
]
for values, expected in test_cases:
try:
result = find_magic_index(values)
assert (result == expected), "Failed!"
except AssertionError as e:
e.args += ("find_magic_index", values, "should be " + \
str(expected) + ", but got " + str(result))
raise
def test_follow_up(self):
test_cases = [
# distinct values
([-40, -20, -1, 1, 2, 3, 5, 7, 9, 12, 13], 7),
([-4, -3, -2], -1),
([], -1),
# repeated values
([-10, -4, -2, 2, 2, 2, 4, 7, 7, 7], 7),
([-10, -4, 2, 2, 2, 2, 4, 7, 7, 7], 2),
]
for values, expected in test_cases:
try:
result = find_magic_index_follow_up(values)
assert (result == expected), "Failed!"
except AssertionError as e:
e.args += ("find_magic_index_follow_up", values, "should be " + \
str(expected) + ", but got " + str(result))
raise
if __name__ == "__main__":
unittest.main() |
2dfbea8ebfd076d8d7112a3b21ef5d7ebac743ff | mattshakespeare/generation_exercises | /exercise13.py | 2,302 | 4.375 | 4 | '''unit testing'''
#1. Write a unit test for the below function.
def add_two_numbers(a, b):
return a + b
def test_add_two_numbers():
#happy path
#arrange
a = 5
b = 5
expected = 10
#act
actual = add_two_numbers(a,b)
#assert
assert expected == actual
print(f'Test {expected == actual}')
#unhappy path
#arrange
expected = 12
#assert
assert expected != actual
print(f'Test {expected != actual}')
#test_add_two_numbers()
#2. Write a unit test for the function add_number_with_random_number . You will need to update the code to make use of dependency injection and create a
#mock function.
#import random
def get_random_number():
return random.randint(1, 10)
def add_number_with_random_number(a, get_random_number):
return a + get_random_number()
def test_add_number_with_random_number():
#arrange
def mock_get_random_number():
return 10
a = 10
expected = 20
#act
actual = add_number_with_random_number(a,mock_get_random_number)
#assert
assert expected == actual
print(f'Test {expected == actual}')
#test_add_number_with_random_number()
#3. Write a unit test for the below function add_two_random_numbers . You will need to update the code to make use of dependency injection and create a mock
#function.
from random import randint
def get_random_number(randint):
return randint(1, 10)
def add_two_random_numbers(get_random_number):
return get_random_number() + get_random_number()
def test_add_two_random_numbers():
#arrange
def mock_get_random_number():
return 5
expected = 10
#act
actual = add_two_random_numbers(mock_get_random_number)
#assert
assert actual == expected
print(f'Test {actual == expected}')
#test_add_two_random_numbers()
#4. Write a unit test for the get_random_number function seen above. This time it's slightly different as we need to mock a function we haven't written, but the
#same principles apply. Hint: you need to match the number of arguments that the randint function takes for the mock function you will write
def test_get_random_number():
#arrange
def mock_randint(a,b):
return 5
expected = 5
#act
actual =
#assert
|
5a27ba5d6982c232fbdbb3e961c68dc41c75c38a | LucasSGomide/Python | /Códigos/Exercicios_estruturas_controle/ex35_mod7.py | 1,315 | 3.578125 | 4 | A = []
B = []
limite = 2
while len(A) < limite:
a = int(input('Digite um número: '))
if a < 0:
print('Numero inválido')
elif a > 10000:
print('Numero inválido')
else:
A.append(a)
for num in list(str(a)):
B.append(int(num))
print('A =', A)
print("B =", B)
C = []
pos = 0
for num in B: # Para os números em B
if len(C) == 0: # Se o comprimento de C == 0
C.append(num) # Adicionar o 1º numero
elif len(C) == 1: # Se comprimento de C == 1
if num > C[pos]: # Se numero maior que C[pos] == C[0]
C.insert(pos + 1, num) # Iserir numero (pos + 1) == C[1]
else: # Se não for maior
C.insert(pos, num) # Inserir em (pos) == C[0]
else: # Se o comprimento for maior que 1
if C[len(C) - 1] < num: # Se o último número adicionado menor que num
C.insert(len(C), num) # Inserir o num na última posição == len(C)
pos = pos + 1 # Posição aumenta em 1 C[2]
else: # Se for maior
while num > C[pos]: # Enquanto o num for maior que C[2]
pos = pos + 1 # 2 = 2 + 1 (conta posições)
C.insert(pos, num) # inserir numero no índice 3
pos = 0
soma = (A[0] + A[1])
print('C = ', C)
print('Soma = ', soma)
|
1281f05227fa04e5bf3cb0795d5850d54e17da8f | michaelcarlos3/Hangaroo-Problems1-4 | /getAvailableLetters.py | 608 | 4.09375 | 4 | secretWord = str(input("Enter the word to be guessed: "))
lettersGuessed = []
letters = ['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']
def getAvailableLetters():
me=0
while me == 0:
lettersGuessed = input("Type a letter: ").lower()
if lettersGuessed in secretWord:
letters.remove(lettersGuessed)
else:
letters.remove(lettersGuessed)
print ("These are the available words:\n")
print (''.join(letters))
return me
getAvailableLetters() |
5998126d36649bd0fcd1df05e88e66b38d3c51b0 | galayko/euler-python | /problem3.py | 580 | 3.78125 | 4 | #!/usr/bin/env python
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143?
def isprime(num):
tmp = 2
while tmp<num:
if num%tmp==0:
return False
tmp+=1
return True
m = 600851475143
n = 3
while m/n>1:
if n%3==0 or n%5==0 or n%7==0 or n%11==0 or n%13==0 or n%17==0 or n%19==0 or n%23==0:
n+=2
continue
else:
print n,' ',m/n
if m%n==0 and isprime(m/n):
print "Result=%s" % (m/n)
break
n+=2
|
721604259a51061c8236e70ab9d53c50ae19d5de | 3to80/Algorithm | /Base/binarySearch.py | 1,309 | 4.03125 | 4 | def binarySearch(li, start, end, target):
"""
:param li: read only
:param start: start index in step
:param end: end index in step
:param target: read only
:return: int
"""
if end - start < 1: # 더이상 영역이 없음
return -1
mid = start + (int)((end- start) / 2)
if li[mid] == target:
return mid
elif li[mid] < target:
return binarySearch(li, mid + 1, end, target)
else:
return binarySearch(li, start, mid - 1, target)
def binarySearch_nearest(li, start, end, target):
"""
# 이하인 수중 가장 큰 곳의 index를 반환 한다.
:param li: read only
:param start: start index in step
:param end: end index in step
:param target: read only
:return: int
"""
if target > li[-1]:
return len(li)-1
if end - start < 1: # 더이상 영역이 없음
return -1
mid = start + (int)((end- start) / 2)
if li[mid] == target:
return mid
elif li[mid] < target:
if mid+1 < len(li) and li[mid+1] > target:
return mid
return binarySearch_nearest(li, mid + 1, end, target)
else:
if mid - 1 >= 0 and li[mid - 1] <= target:
return mid - 1
return binarySearch_nearest(li, start, mid - 1, target)
|
39d3fedc84585cac995e25bfa39a611c253993ff | PRodenasLechuga/HackerRank | /Python/Tuples.py | 256 | 3.625 | 4 | def convertTupleToHash(tupleElement):
return hash(tupleElement)
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
T = ()
for x in integer_list:
T = T + (x, )
print(convertTupleToHash(T)) |
56ea1fa1d8eacf5286485717b0a570fd4ae31fe1 | kunal12kaushik/calculator | /break and countinue.py | 113 | 3.765625 | 4 | # x = int(input("how much candies you want?"))
# #
# # i = 1
# # while i<=x:
# # print("candy")
# # i+=1
|
479a4c14355483fb27f0bbf979c7323d6ba1c412 | williamqin123/old-python | /Chat.py | 106 | 3.59375 | 4 | print("2013 Python User Chat 0.01pre")
count = 1
while count > 0:
print ">>>"
chat = input("")
|
3f16c0d1f704cc735a9a655dbaa46f95dfaa7869 | chrisxue815/leetcode_python | /problems/test_0233.py | 659 | 3.875 | 4 | import unittest
class Solution:
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
result = 0
m = 1
while m <= n:
m2 = m * 10
result += (n // m + 8) // 10 * m + (n // m % 10 == 1) * (n % m + 1)
m = m2
return result
class Test(unittest.TestCase):
def test(self):
self._test(13, 6)
self._test(1, 1)
self._test(10, 2)
self._test(11, 4)
def _test(self, n, expected):
actual = Solution().countDigitOne(n)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
6a835dd255969413594c861da5798d4178cafee6 | dlemusg/AnalisisNumerico | /metodos/multiplesVariables/LemusCanson/metodoGaussRelajado.py | 3,184 | 3.78125 | 4 | from numpy import *
from sympy import *
import math
def recolectarDatos():
n = int(input("Ingrese el numero de ecuaciones: "))
tolerancia = float(input("Ingrese la tolerancia: "))
niter = int(input("Ingrese el numero maximo de iteraciones: "))
omega = float(input("Ingrese el valor de omega: "))
A = [] #En primera instacia creamos una lista que posteriormente se convertira en una matriz
x0 = [] #Lista de los valores inciales de la variables
b = [] #Vector de terminos independientes
for i in range(n):
A.append([0] * n) #Se le agregan n+1 columnas a la matriz por los terminos independientes
fila = str(input("Ingrese los valores de la fila " + str(i+1) + " separados por espacio y además el termino independiente: ")) #El usuario ingresa los coeficientes de la matriz
valores = fila.split(" ")
for j in range(n+1): #Es n+1 por la columna de terminos independientes
if j==n:
b.append(float(valores[j]))
else:
A [i][j] = float(valores[j]) #Asignamos a la posición correspondiente de la matriz los coeficientes
for i in range(n):
inicial = float(input("Ingrese el valor inicial de x" + str(i+1) + ": "))
x0.append(inicial)
metodoGaussSeidelRelajado(A, b, n, x0, niter,tolerancia, omega)
def metodoGaussSeidelRelajado(A, b, n, x0, niter, tolerancia, omega):
contador = 0
dispersion = tolerancia + 1
x1 = []
mayor = 2
print("\nOrden de los datos: n, x1, x2, x3, ... xn, dispersion " )
print(str(contador) + " " + str(x0) + "\n")
while dispersion > tolerancia and contador < niter:
x1 = calcularNuevoGaussRelajado(x0, n, b, A, omega)
dispersion = norma(x1, x0,n)
if dispersion > tolerancia:
x0 = x1
contador += 1
print(str(contador) + " " + str(x0) + " " + str(float(dispersion)) + "\n")
if dispersion < tolerancia:
print(str(x0) + " es una aproximación con una tolerancia basada en norma maximo/infinito: " + str(tolerancia))
else:
print("Fracaso en " + str(niter) + " iteraciones")
def calcularNuevoGaussRelajado(x0, n, b, A, omega):
x1 = x0[:]
for i in range(n):
suma = 0.0
for j in range(n):
if j != i:
valor = x1[j]
suma += A[i][j] * valor
valor = b[i]
elemento = (valor - suma)/A[i][i]
original = x1.pop(i)
relajado = omega * elemento + (1 - omega) * original
x1.insert(i,relajado)
return x1
def norma(x1, x0, n):
mayorDividiendo = -1
mayorDivisor = -1
norma = 0
for i in range(n):
valor0 = x0[i]
valor1 = x1[i]
if(abs(valor1 - valor0) > mayorDividiendo):
mayorDividiendo = abs(valor1 - valor0)
if(abs(valor1) > mayorDivisor):
mayorDivisor = abs(valor1)
norma = mayorDividiendo / mayorDivisor
return norma
recolectarDatos() |
d490aacc18405dc47c4c2c306147d9acadac5f3f | andrewnnov/tasks_py | /w3/date/dates.py | 187 | 3.578125 | 4 | import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
y = datetime.datetime(2021, 9, 21)
print(y)
print(y.strftime("%B"))
print(y.strftime("%x")) |
35b02a2ee5d4ba2db0dc66621515c0937a106bda | VAB-8350/Read_number-python- | /function.py | 1,440 | 3.75 | 4 | # >>>Victor Andres Barilin<<<
def grouper(n, iterable):
grouped_list = []
i = 0
while i <= len(iterable):
if iterable[i:i+3] != '':
grouped_list.append(iterable[i:i+3])
i += 3
return grouped_list
def clear_number(number):
number = number.strip()
posi = 1
if len(number) > 1:
while posi != -1:
posi = number.find('0')
if posi == 0:
number = number[posi+1:]
else:
posi = -1
number = number.strip()
try:
int(number)
return number
except:
return 'El valor ingresado no es un entero.'
def formulate(text):
text = text[::-1]
answer = ''
for i in text:
answer = answer + i
answer = answer.strip()
return answer
names = {
'simples': ['cero', 'uno ','dos ','tres ','cuatro ','cinco ','seis ','siete ','ocho ','nueve '],
'doble-10': ['diez', 'once', 'doce', 'trece', 'catorce', 'quince', 'dieciseis', 'diecisiete', 'dieciocho', 'diecinueve'],
'doble': ['veinti', 'treinta', 'cuarenta', 'cincuenta', 'secenta', 'setenta', 'ochenta', 'noventa'],
'triple': ['cien', 'doscientos ', 'trescientos ', 'cuatrocientos ', 'quinientos ', 'seiscientos ', 'setecientos ', 'ochocientos ', 'novecientos '],
'quintuples':['millones ', 'billones ', 'trillones ', 'cuatrillones ', 'quintillones ', 'sextillones ']
} |
cccd21d7ca27dbd42bd0daa0052c20f4566296a6 | MrYangShenZhen/pythonstudy | /多线程/多线程队列.py | 638 | 3.625 | 4 | import queue
# # q=queue.Queue(3)#Queue()可传数字,表示该队列可存五组数据
# q=queue.LifoQueue(3)#后进先出模式
'''创建线程队列,默认先进先出'''
# q.put('你好')
# q.put(2)
# q.put({"lesson":"math"})
# q.put('test',False)#会提示满了的报错
# while 1:
# data=q.get()
# print(data)
#put,get在队列满了或者为空时去put,get会导致程序一直在运行中
'''优先级模式'''
# Q=queue.PriorityQueue(3)
# Q.put([2,'你好'])
# Q.put([1,2])
# print(Q.full())
# Q.put([3,{"lesson":"math"}])
# print(Q.full())
# while 1:
# Data=Q.get()
# print(Data[1])
# print(Q.empty()) |
00597ffe70d0e00990e4420d05ceac1d8dcdee3a | GMwang550146647/network | /0.leetcode/3.刷题/1.数据结构系列/1.线性结构/3.栈/1.单调栈/946.mid_验证栈序列(core).py | 783 | 3.59375 | 4 | from fundamentals.test_time import test_time
class Solution():
def __init__(self):
pass
@test_time
def validateStackSequences(self, pushed, popped):
"""
模拟法:一次push一个,一旦该个和pop中的是一样的,同时pop出来!
"""
stack = []
i = 0
for num in pushed:
stack.append(num)
while stack and stack[-1] == popped[i]:
stack.pop()
i += 1
return not stack
def main(self):
pushed = [1, 2, 3, 4, 5]
popped = [4, 5, 3, 2, 1]
# pushed = [1, 2, 3, 4, 5]
# popped = [4, 3, 5, 1, 2]
self.validateStackSequences(pushed, popped)
if __name__ == '__main__':
SL = Solution()
SL.main()
|
ba153dcca867fd84ccbc814d935a77d3d10a3e16 | nikkureev/bioinformatics | /ДЗ 4/Task6_7.py | 233 | 3.515625 | 4 | # функция проверяет тип коллекции и возвращает элемент
def search(collection, a):
if type(collection) == dict:
print(collection.get(a))
else:
print(collection[a])
|
181af1cd954557928354699c98196265ba3ae2fb | gransburyia/Gransbury-MATH361 | /IntroToProgramming/I9_PartialProd2_Gransbury.py | 629 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 08:53:55 2019
@author: grans
"""
import matplotlib.pyplot as plt
#function to change
a_n = lambda n:
#1 + b**n converges: 1 + (7/9)**n
#1 + b**n diverges: 1 + (3/2)**n
#1 + (f(n)/g(n)) converges: 1 + (n/n**4)
#1 + (f(n)/g(n)) diverges: 1 + (n**4/n**2)
def calculateProducts(n):
product = 1
for ii in range(1, n + 1):
product *= a_n(ii)
products.append(product)
n = 100000
products = []
calculateProducts(n)
print("The first 15 values of the product are:", products[:15])
print("The last 15 values of the product are:", products[-15:])
|
1e0f377724916267e50a3f9859ea78d61cbbb421 | yyzz1010/hackerrank | /sWAP_cASE.py | 230 | 3.90625 | 4 | def swap_case(s):
x = ''
word_list = []
for word in s:
if word == word.upper():
word_list.append(word.lower())
else:
word_list.append(word.upper())
return x.join(word_list)
|
0a32f68f8304f61f69f9e7e88b15733f6d405776 | arthurperng/eulerthings | /ehhhhhhhhhhhquickscopehhhhhhh35.py | 880 | 3.734375 | 4 | import math
primelist=[2]
bound = 3
from math import *
def primeornot(number):
global bound
if number < bound:
return number in primelist
for butt in primelist:
if butt<math.sqrt(number)+1:
if number%butt==0:
return False
else:
break
while bound < math.sqrt(number):
if primeornot(bound):
primelist.append(bound)
if number%bound==0:
return False
bound+=1
return True
def circular(gah):
a=str(gah)
if "2" in a or "4" in a or "5" in a or "6" in a or "8" in a or "0" in a:
return False
for green in range(len(a)):
if not primeornot(int(a)):
return False
a=a[1:] + a[0]
return True
count=0
for i in range(2, 1000000):
if circular(i):
print i
count+=1
print count+1
|
94f686780677d8122c26aeb70613f75d2cb69d97 | DonggyuLee92/solving | /2020 Nov/1106/6323/6323.py | 202 | 3.8125 | 4 | num = int(input())
ans = "1, 1"
a = 1
b = 1
if(num==2):
print("[{}]".format(ans))
for i in range(num-2):
c = a + b
a = b
b = c
ans = ans + ', ' + str(c)
print("[{}]".format(ans)) |
e1c80fec4df39dc7dc736a79a8a624860adf3dbb | jacopo-j/advent-of-code-2017 | /day04/code.py | 987 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
def part1(in_data):
valids = 0
for line in in_data.split("\n"):
l_list = line.split(" ")
l_set = set(l_list)
if (len(l_list) == len(l_set)):
valids += 1
return valids
def part2(in_data):
valids = 0
p1_valid = []
for line in in_data.split("\n"):
l_list = line.split(" ")
l_set = set(l_list)
if (len(l_list) == len(l_set)):
p1_valid.append(l_list)
for i in p1_valid:
ok = True
for word in i:
anagrams = ["".join(perm) for perm in itertools.permutations(word)]
present_anagr = [x for x in i if x in anagrams]
if (len(present_anagr) > 1):
ok = False
break
if ok:
valids += 1
return valids
with open("input.txt", "r") as in_file:
in_data = in_file.read().strip()
print(part1(in_data))
print(part2(in_data))
|
2a2c324aff48fd9e24d77248f07ed4a3d24d2451 | PetarSP/SoftUniFundamentals | /Lab5_List_Advanced/7.Group of 10's.py | 542 | 3.625 | 4 | import math
numbers = list(map(int, input().split(", ")))
group = 0
list_of_numbers = []
find_highest_num = max(numbers)
num_of_possible_groups = math.ceil(find_highest_num / 10)
current_group = 0
next_group = 11
while not num_of_possible_groups == 0:
for num in numbers:
if num in range(current_group, next_group):
list_of_numbers.append(num)
num_of_possible_groups -= 1
current_group = next_group
next_group += 10
print(f"Group of {current_group - 1}'s: {list_of_numbers}")
list_of_numbers = [] |
971893dcea7b1b08d677bba9d730053a2e2bb77b | kotlyarovame/python_for_kids | /tasks/tasks_6.py | 2,964 | 4.0625 | 4 | #1. Цикл с приветом
# Как вы считаете, что делает эта программа?
# Сперва придумайте вариант ответа, а потом запустите код и проверьте, угадали ли вы.
for x in range(0, 20): # цикл от 0 до 19
print('привет %s' % x) # номер переменной
if x < 9: # если х меньше 9
break # остановиться
#2. Четные числа
# Создайте цикл, который печатает четные числа до тех пор, пока не выведет ваш возраст.
# Если ваш возраст — нечетное число, создайте цикл, который печатает нечетные числа до
# совпадения с возрастом.
# Программа должна выводить на экран нечто подобное: 2 4 6 8 10 12 14
x = 1
while x < 25:
x = x + 2
print (x)
#3. Пять любимых ингредиентов
# Создайте список с пятью разными ингредиентами для бутерброда:
ingredients = ['bread', 'mayo', 'chren', 'chiken', 'holopenyo']
#Теперь создайте цикл, который печатает список ингредиентов с нумерацией
num = 1 #с чего начать нумерацию
for i in ingredients: #для позиций списка
print (num, i) #вывести номер и позицию
num = num + 1 #увеличить номер на 1
#4. Ваш лунный вес
# Если бы вы сейчас были на Луне, ваш вес составил бы 16,5 процентов от земного.
# Чтобы узнать, сколько это, умножьте свой земной вес на 0,165.
# Если бы каждый год в течение следующих 15 лет вы прибавляли по
# одному килограмму веса, каким бы оказался ваш лунный вес в каждый из
# ежегодных визитов на Луну вплоть до 15-го года? Напишите программу, которая
# с помощью цикла for печатает на экране ваш лунный вес в каждом году.
weight = 65 #вес на земле
year = 1 #год отсчёта
for moon_weight in range (1, 16): #зацикливается на кол-во повторов от 1 до 15
moon_weight = weight * 0.165 #лунный вес = земной вес умноженный на 0,165
print (year, moon_weight) #выводит год и лунный вес
weight = weight + 1 #увеличивает земной вес на 1
year = year + 1 #увеличивает год на 1, возвращаемся на строку 43 |
6eaed8fa7755741ad30a31c0c422b3f7e3abf6ad | npatel37/Tflow_DL | /2_basics.py | 456 | 3.84375 | 4 | import tensorflow as tf
### -- this is called making a "graph" where you don't run anything!
x1 = tf.constant(5)
x2 = tf.constant(6)
result = tf.mul(x1,x2) ## multiplication
print(result)
## --- note: No computation has been done until now!
## -- To actually excecute the multiplication you have to run the session.
#~ sess = tf.Session()
#~ print (sess.run(result))
with tf.Session() as sess:
output = sess.run(result)
print(output)
print(output)
|
47cdf3bad889d8dbeca3fd0a19834edb31caa0dc | tkchris93/ACME | /Backup/test_module.py | 245 | 4.03125 | 4 | students = ["John", "Paul", "George", "Ringo"]
def add_numbers(a,b):
'''
Adds two numbers together
'''
return a+b
def print_students():
'''
Prints the names of each student in the student list
'''
for name in students:
print name
|
51e590a2999c906644f0e9ccbd06d618b4d59785 | khyasir/odoo-10 | /python program/task2.py | 514 | 3.53125 | 4 | import re
url_id=raw_input("enter the url with id")
id=map(int, re.findall(r'\d+', url_id))
abc=len(id)
print abc
or_len=abc-1
print or_len
print id[or_len][2]
print id[or_len][2]
if id[or_len][6]==True:
print id
else:
print "not found"
print url_id[1]
d = defaultdict(list)
for x in url_id:
d[type(x)].append(x)
print d[int]
print d[str]
for x in url_id:
if (a==1):
print x
if (x=="/"):
a=1
len_list=len(url_id)
print len_list
for x in url_id:
if x==str:
print "sring."
else:
print x |
9b981f431a8c7596696b526ab231e07abc9684f9 | jonasht/tkinter-aprendendo | /app25-lista1.py | 476 | 3.546875 | 4 | from tkinter import *
root = Tk()
root.title('listbox')
root.geometry('+600+200')
lista = Listbox(root, selectmode=EXTENDED)#selectmode=EXTENDED - p conseguir selecionr varios itens
lista.pack()
#inserir um item de cada vez
nomes =['jonas', 'lucas', 'carlos', 'pedro']
for nome in nomes:
lista.insert(END, nome)
#lista.delete(1, END)
def Executar():
print(lista.get(ACTIVE))
cmd = Button(root, text=' ok ', width=10, command=Executar).pack()
root.mainloop() |
9b92a41cb933c55e716810d1023c7d7796a3f320 | ComputeCanada/dhsi-coding-fundamentals-2019 | /Programs/mapFlightsCSV.py | 1,151 | 3.796875 | 4 | # Google spreadsheet/map of hometowns and travel routes
# instructions on how to do this with Sheets instead of a CSV: https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html
# note: doing the mapping part with live Google API requires giving a credit card and being charged if go over the rate limit
# import libraries needed for program
import gmplot
import csv
# open csv file of places and read in the latitudes/longitudes; placesReader is a list of lists, that is a list of paired coordinates [lat, long]
placesFile = open("places.csv")
placesReader = csv.reader(placesFile)
# create and center map on the University of Victoria, zoom level 3
gmap = gmplot.GoogleMapPlotter(48.4634, -123.3117, 3)
# create lists of latitudes and longitudes
# we are looping through each list [lat, long] in placesReader
for location in placesReader:
gmap.marker(float(location[0]), float(location[1]))
# create map, save as map.html in the working directory
gmap.draw('map.html')
# close the files so we don't accidentally corrupt them or crash something
placesFile.close() |
088d031815c110a730da508822cb0feac80781eb | armandosrz/DataScience-343 | /KNN/main.py | 2,917 | 3.546875 | 4 | '''
Spirit Animal: generousIbex
Date: 19/10/16
Challenge #: 5
Sources:
- Dr. Jones Lecture
- http://www.cs.olemiss.edu/~jones/doku.php?id=csci343_nearest_neighbors
'''
import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np
import math
import sys
def getKNeighbors(k, reconstruc):
dist = lambda a,b: math.sqrt(math.pow(a[0]-b[0],2)+math.pow(a[1]-b[1],2))
green = [0, 255, 0, 255]
reference = np.float32(Image.open('data.png'))
rc = np.float32(reconstruc)
'''
Get all points from the reference image that are green and
append the coordinates into the rf_coor (reference coordinates) list
'''
rf_coor = []
for row in range(len(reference)):
for col, pixel in enumerate(reference[row]):
if not(pixel == green).all():
rf_coor.append([row, col])
'''
This is where the magic happens.
1.- Iterate through all the points in the reference image
and find the ones that are green
2.- If the pixel is green, then do as follow:
- Find the dist from the pixel coordinates to all the points in
our rf_coor list. Store the value and list coor in a tuple.
- Sort the tuple by the distance value
- Use a list slicing to only keep the k values of the list
3.- Get the average of all the pixels in k_neighbors array by
calling back the reference image to get the actual pixel values.
Numpy average will do it for you.
4.- Set the new value in the corresponding coordinates
'''
for row in range(len(rc)):
for col, pixel in enumerate(rc[row]):
if (pixel == green).all():
k_neighbors = sorted([(dist([row, col], coor), rf_coor[x]) for x, \
coor in enumerate(rf_coor)])[:k]
rc[row][col] = np.average([reference[p[0]][p[1]] for i, p \
in k_neighbors], axis=0)
k_img=np.clip(rc, 0, 255)
k_img=np.uint8(k_img)
mplot.imshow(k_img)
mplot.show(block=True)
mplot.imsave('{}-neigboors.png'.format(k), k_img)
def main():
if len(sys.argv) != 3:
print 'Should have two parameters: <k_neighbors> <file_name>'
exit()
try:
k = int(sys.argv[1])
if k < 1:
print 'K value should be more than one'
sys.exit()
except ValueError:
print "Not a int Value"
sys.exit()
try:
reconstruc = Image.open(sys.argv[2])
except FileNotFoundError:
print "File does not exists"
sys.exit()
getKNeighbors(k, reconstruc)
if __name__ == '__main__':
import timeit
print 'Execution time:'
print('\t' + str(timeit.timeit("main()", setup="from __main__ import main", number=1)))
|
983ddff7e51a990b44b1a9534414d68103d90f3c | mturpin1/CodingProjects | /Python/PiEncryption/listChars.py | 449 | 3.59375 | 4 | import os
array = []
def inputSubroutine():
inputVar = input('Please input the character you want added to the array(type \'end\' to end the program): ')
inputSubroutine()
while (inputVar != 'end'):
array.add(inputVar)
os.system('cls')
inputSubroutine()
print('Here is your array: ',)
arrayCounter = 0
for x in range(array.len() - 1):
print('f{array[arrayCounter]}',)
arrayCounter += 1
print(f' \'{array[arrayCounter]}\'') |
540525bbd4a1f9aeba3c1f177af7f39370c09edb | MTDahmer/Portfolio | /fuckit.py | 2,759 | 3.734375 | 4 | def fillWithAT(grid, theRow, theCol, display):
print('ding')
def printGreeting():
print('Hello user')
print('This program will replace instances of "-" in a given file with the "@" symbol')
def testCharacter(fileData):
print('ding1')
charlist = list()
charList = set('-I')
for i in (fileData):
for char in i:
if not (char in charList):
print('false')
return False
return True
def testRectangle(fileData):
print('ding5')
n = fileData
for i in n:
if len(i) != len(n[0]):
return False
return True
def countRows (fileData):
print('ding6')
sum1 = len(fileData)
print(sum1)
return sum1
def countColumns (fileData):
print('ding7')
sum2 = len(fileData[0])
print(sum2)
return sum2
def createMatrix(fileData , fileName):
print('ding')
def getRow(fileName , fileData):
print('ding9')
flagrow = True
rowcount = countRows(fileData)
while (flagrow == True):
theRow = int(input('Enter the row number: '))
rowtest = testRow(theRow , rowcount)
if (rowtest):
flagrow = False
return theRow
else:
flagrow = True
def testRow(theRow , rowcount):
print('ding10')
if ((theRow <= rowcount) and (theRow >= 0)):
return True
else:
return False
def getCol(fileData):
print('ding11')
flagcolumn = True
columncount = countColumns(fileData)
while (flagcolumn == True):
theCol = int(input('Enter the column number: '))
coltest = testRow(theCol , columncount)
if (coltest):
flagcolumn = False
return theCol
else:
flagcolumn = True
def testCol(theCol , columncount):
print('ding12')
if ((theCol <= columncount) and (theCol >= 0)):
return True
else:
return False
def requestStep():
print('ding13')
displaychoice = input('Print out step by step? Enter yes: ')
displaychoice = displaychoice.lower()
if (displaychoice == 'yes'):
return True
else:
return False
def main():
flagmain = True
printGreeting()
fileData = list()
while (flagmain == True):
fileName = input('Enter the name of your file: ')
with open(fileName) as textFile:
lines = [line.split() for line in textFile]
print(lines)
for i in range (len(lines)):
for j in range (len(lines[0])):
print (lines[i][j], end = ' ')
print()
main() |
e343d54ebee0625b1029f708d25da2ffda3d3b1c | rizalpahlevii/learn-python | /praktikum6/kasus4.py | 179 | 3.703125 | 4 | a = int(input("Masukkan a : "))
sum = 0
i = 0
while i < a:
nilai = float(input("Inputkan nilai "))
sum = sum + nilai
i = i + 1
rata_rata = sum / a
print(rata_rata)
|
d2a1e811f70dcc14ffbed7964ced5d9eea2f8723 | joshf26/Personal-Website | /src/static/rocket-launch/scripts/stars.py | 380 | 3.625 | 4 | from random import randint
NUM_STARS = 100
IMAGE_SIZE = 1000
MIN_SIZE = 1
MAX_SIZE = 3
def main():
for _ in range(NUM_STARS):
radius = randint(MIN_SIZE, MAX_SIZE)
x = randint(0, IMAGE_SIZE - radius)
y = randint(0, IMAGE_SIZE - radius)
print(f'<circle cx="{x}" cy="{y}" r="{radius}" fill="white" />')
if __name__ == '__main__':
main()
|
1a1268d3ab310a5fd2f841493aa3d6a20fee14f2 | Richardjames0289/JavaFiles | /python answers/challenge 2 answers/qa-assessment-example-2/programs/questions.py | 3,516 | 4.15625 | 4 | # <QUESTION 1>
# Given a word and a string of characters, return the word with all of the given characters
# replaced with underscores
# This should be case sensitive
# <EXAMPLES>
# one("hello world", "aeiou") → "h_ll_ w_rld"
# one("didgeridoo", "do") → "_i_geri___"
# one("punctation, or something?", " ,?") → "punctuation__or_something_"
def one(word, chars):
charlist = [char for char in word]
for i in range(len(word)):
if charlist[i] in chars:
charlist[i] = '_'
return ''.join(charlist)
# <QUESTION 2>
# Given an integer - representing total seconds - return a tuple of integers (of length 4) representing
# days, hours, minutes, and seconds
# <EXAMPLES>
# two(270) → (0, 0, 4, 30)
# two(3600) → (0, 1, 0, 0)
# two(86400) → (1, 0, 0, 0)
# <HINT>
# There are 86,400 seconds in a day, and 3600 seconds in an hour
def two(total_seconds):
days = total_seconds // 86400
hours = (total_seconds - (days * 86400)) // 3600
minutes = (total_seconds - (days * 86400) - (hours * 3600)) // 60
seconds = total_seconds - (days * 86400) - (hours * 3600) - (minutes * 60)
return (days, hours, minutes, seconds)
# <QUESTION 3>
# Given a dictionary mapping keys to values, return a new dictionary mapping the values
# to their corresponding keys
# <EXAMPLES>
# three({'hello':'hola', 'thank you':'gracias'}) → {'hola':'hello', 'gracias':'thank you'}
# three({101:'Optimisation', 102:'Partial ODEs'}) → {'Optimisation':101, 'Partial ODEs':102}
# <HINT>
# Dictionaries have methods that can be used to get their keys, values, or items
def three(dictionary):
return {value:key for (key, value) in dictionary.items()}
# <QUESTION 4>
# Given an integer, return the largest of the numbers this integer is divisible by
# excluding itself
# This should also work for negative numbers
# <EXAMPLES>
# four(10) → 5
# four(24) → 12
# four(7) → 1
# four(-10) → 5
def four(number):
mag_num = abs(number)
factors = [i for i in range(1, mag_num) if mag_num % i == 0]
return factors[-1]
# <QUESTION 5>
# Given a string of characters, return the character with the lowest ASCII value
# <EXAMPLES>
# five('abcdef') → 'a'
# four('LoremIpsum') → 'I'
# four('hello world!') → ' '
def five(chars):
list = [ord(char) for char in chars]
return chr(min(list))
# <QUESTION 6>
# Given a paragraph of text and an integer, break the paragraph into "pages" (a list of strings), where the
# length of each page is less than the given integer
# Don't break words up across pages!
# <EXAMPLES>
# six('hello world, how are you?', 12) → ['hello world,', 'how are you?']
# six('hello world, how are you?', 6) → ['hello', 'world,', 'how', 'are', 'you?']
# six('hello world, how are you?', 20) → ['hello world, how are', 'you?']
def six(paragraph, limit):
wordlist = paragraph.split()
pagelist = []
page = ''
while wordlist != []:
if len(page) + len(wordlist[0]) <= limit:
page += (wordlist[0] + ' ')
wordlist.remove(wordlist[0])
else:
pagelist.append(page[0:-1])
page = ''
pagelist.append(page[0:-1])
return pagelist
|
8260c0347e06210ac88d475d033723ee7a3871af | rrwt/daily-coding-challenge | /ctci/ch3/animal_shelter.py | 2,304 | 4.03125 | 4 | """
An animal shelter, which holds only dogs and cats, operates on a strictly
"first in, first out" basis. People must adopt either the "oldest"
(based on arrival time) of all animals at the shelter, or they can select whether
they would prefer a dog or a cat (and will receive the oldest animal of that type).
They cannot select which specific animal they would like. Create the data structures
to maintain this system and implement operations such as enqueue, dequeueAny,
dequeueDog, and dequeueCat. You may use the built-in Linked list data structure.
"""
from typing import Optional
from enum import Enum
from collections import deque
class AnimalKind(Enum):
cat = "cat"
dog = "dog"
class Animal:
def __init__(self, name: str, order: int):
self.name = name
self.order = order
def is_older(self, other: "Animal") -> bool:
return self.order < other.order
class AnimalShelterQueue:
def __init__(self):
self.dog = deque()
self.cat = deque()
self.order: int = 0
def enqueue(self, name: str, kind: AnimalKind):
node = Animal(name, self.order)
self.order += 1
if kind == AnimalKind.cat:
self.cat.append(node)
elif kind == AnimalKind.dog:
self.dog.append(node)
else:
raise ValueError(kind)
def dequeue_any(self) -> Optional[Animal]:
if self.dog and self.cat:
if self.dog[0].is_older(self.cat[0]):
return self.dog.popleft()
else:
return self.cat.popleft()
elif self.dog:
return self.dog.popleft()
elif self.cat:
return self.cat.popleft()
return None
def dequeue_cat(self) -> Optional[Animal]:
return self.cat.popleft() if self.cat else None
def dequeue_dog(self) -> Optional[Animal]:
return self.dog.popleft() if self.dog else None
if __name__ == "__main__":
animals = AnimalShelterQueue()
animals.enqueue("perro", AnimalKind.dog)
animals.enqueue("gato", AnimalKind.cat)
first = animals.dequeue_any()
second = animals.dequeue_cat()
assert first is not None and first.name == "perro"
assert animals.dequeue_dog() is None
assert second is not None and second.name == "gato"
|
83cc1da1f92711e7cef737ac8bb27f9b54de64e1 | ThomasMatlak/tictactoe | /ticTacToe.py | 9,275 | 3.953125 | 4 | #Thomas Matlak
#CSCI100 Final Project
#22 November 2014
#This program runs the game Tic-Tac-Toe for one or two players
#TODO:
#Pretty up the game
#Refactor
from Tkinter import *
import random
import sys
#Draws the tic-tac-toe board
def drawBoard(window):
for i in range(2, 5, 2):
window.create_line(i * 100, 0, i * 100, 600)
window.create_line(0, i * 100, 600, i * 100)
#Global variables for the players to determine who has won and whose turn it is
availablePlaces = [1, 2, 3, 4, 5, 6, 7, 8, 9]
player1Places = []
player2Places = []
#Draws an X beginning at the upper left corner of the given position
def drawX(window, position):
window.create_line(position[0], position[1], position[0] + 200, position[1] + 200, width=2)
window.create_line(position[0] + 200, position[1], position[0], position[1] + 200, width=2)
#Draws an O beginning at the upper left corner of the given position
def drawO(window, position):
window.create_oval(position[0], position[1], position[0] + 200, position[1] + 200, width=2)
#Returns where to place the x or o and which section of the grid that is
def pieceLocation(clickCoordinate):
x = clickCoordinate[0]
y = clickCoordinate[1]
if x < 200 and y < 200:
return ((0, 0), 1)
elif x < 200 and y > 200 and y < 400:
return ((0, 200), 2)
elif x < 200 and y > 400:
return ((0, 400), 3)
elif x > 200 and x < 400 and y < 200:
return ((200, 0), 4)
elif x > 200 and x < 400 and y > 200 and y < 400:
return ((200, 200), 5)
elif x > 200 and x < 400 and y > 400:
return ((200, 400), 6)
elif x > 400 and y < 200:
return ((400, 0), 7)
elif x >400 and y > 200 and y < 400:
return ((400, 200), 8)
elif x >400 and y > 400:
return ((400, 400), 9)
#Determine whether a player has won
def checkHasWon(piecePlaces):
if (1 in piecePlaces and 4 in piecePlaces and 7 in piecePlaces) or \
(2 in piecePlaces and 5 in piecePlaces and 8 in piecePlaces) or \
(3 in piecePlaces and 6 in piecePlaces and 9 in piecePlaces) or \
(1 in piecePlaces and 2 in piecePlaces and 3 in piecePlaces) or \
(4 in piecePlaces and 5 in piecePlaces and 6 in piecePlaces) or \
(7 in piecePlaces and 8 in piecePlaces and 9 in piecePlaces) or \
(1 in piecePlaces and 5 in piecePlaces and 9 in piecePlaces) or \
(3 in piecePlaces and 5 in piecePlaces and 7 in piecePlaces):
return True
else:
return False
#Takes the mouse coordinates when player 1 makes a move
def onClickInGame1(event, numPlayers, first, player):
coordinates = pieceLocation((event.x, event.y))
if coordinates[1] in availablePlaces:
drawX(boardWindow, coordinates[0])
player1Places.append(coordinates[1])
availablePlaces.remove(coordinates[1])
player = 3 - player
else:
player = player
print "That spot is already taken"
ticTacToe(player, numPlayers, first)
#Takes the mouse coordinates when player 2 makes a move
def onClickInGame2(event, numPlayers, first, player):
coordinates = pieceLocation((event.x, event.y))
if coordinates[1] in availablePlaces:
drawO(boardWindow, coordinates[0])
player2Places.append(coordinates[1])
availablePlaces.remove(coordinates[1])
player = 3 - player
else:
player = player
print "That spot is already taken"
ticTacToe(player, numPlayers, first)
#Makes a move for the ai using the random package
def aiMove(aiPlayer, first):
coordinates = pieceLocation((random.randrange(600), random.randrange(600)))
if coordinates[1] in availablePlaces:
if first == "X":
drawO(boardWindow, coordinates[0])
elif first == "O":
drawX(boardWindow, coordinates[0])
if aiPlayer == 1:
player1Places.append(coordinates[1])
elif aiPlayer == 2:
player2Places.append(coordinates[1])
availablePlaces.remove(coordinates[1])
player = 3 - aiPlayer
else:
player = aiPlayer
ticTacToe(player, 1, first)
#Exits the program onclick
def exitClick(event):
sys.exit()
def drawLine(player1Places, player2Places):
if checkHasWon(player1Places):
if (1 in player1Places and 4 in player1Places and 7 in player1Places):
boardWindow.create_line(0, 100, 600, 100, fill="red", width=5)
elif (2 in player1Places and 5 in player1Places and 8 in player1Places):
boardWindow.create_line(0, 300, 600, 300, fill="red", width=5)
elif (3 in player1Places and 6 in player1Places and 9 in player1Places):
boardWindow.create_line(0, 500, 600, 500, fill="red", width=5)
elif (1 in player1Places and 2 in player1Places and 3 in player1Places):
boardWindow.create_line(100, 0, 100, 600, fill="red", width=5)
elif (4 in player1Places and 5 in player1Places and 6 in player1Places):
boardWindow.create_line(300, 0, 300, 600, fill="red", width=5)
elif (7 in player1Places and 8 in player1Places and 9 in player1Places):
boardWindow.create_line(500, 0, 500, 600, fill="red", width=5)
elif (1 in player1Places and 5 in player1Places and 9 in player1Places):
boardWindow.create_line(0, 0, 600, 600, fill="red", width=5)
elif (3 in player1Places and 5 in player1Places and 7 in player1Places):
boardWindow.create_line(0, 600, 600, 0, fill="red", width=5)
if checkHasWon(player2Places):
if (1 in player2Places and 4 in player2Places and 7 in player2Places):
boardWindow.create_line(0, 100, 600, 100, fill="red", width=5)
elif (2 in player2Places and 5 in player2Places and 8 in player2Places):
boardWindow.create_line(0, 300, 600, 300, fill="red", width=5)
elif (3 in player2Places and 6 in player2Places and 9 in player2Places):
boardWindow.create_line(0, 500, 600, 500, fill="red", width=5)
elif (1 in player2Places and 2 in player2Places and 3 in player2Places):
boardWindow.create_line(100, 0, 100, 600, fill="red", width=5)
elif (4 in player2Places and 5 in player2Places and 6 in player2Places):
boardWindow.create_line(300, 0, 300, 600, fill="red", width=5)
elif (7 in player2Places and 8 in player2Places and 9 in player2Places):
boardWindow.create_line(500, 0, 500, 600, fill="red", width=5)
elif (1 in player2Places and 5 in player2Places and 9 in player2Places):
boardWindow.create_line(0, 0, 600, 600, fill="red", width=5)
elif (3 in player2Places and 5 in player2Places and 7 in player2Places):
boardWindow.create_line(0, 600, 600, 0, fill="red", width=5)
#Checks if the game is over. If not, lets the next player make a move
def ticTacToe(player, numPlayers, first):
if checkHasWon(player1Places) or checkHasWon(player2Places):
if numPlayers == 2:
drawLine(player1Places, player2Places)
print "Congratulations Player ", 3 - player, "!"
elif numPlayers == 1 and checkHasWon(player1Places) and first == "X":
drawLine(player1Places, player2Places)
print "Congratulations!"
elif numPlayers == 1 and checkHasWon(player2Places) and first == "O":
drawLine(player1Places, player2Places)
print "Congratulations!"
elif numPlayers == 1 and checkHasWon(player1Places) and first == "O":
drawLine(player1Places, player2Places)
elif numPlayers == 1 and checkHasWon(player2Places) and first == "X":
drawLine(player1Places, player2Places)
boardWindow.bind("<Button-1>", exitClick)
elif availablePlaces == []:
print "Tie Game"
boardWindow.bind("<Button-1>", exitClick)
elif not checkHasWon(player1Places) and not checkHasWon(player2Places):
#Take user input for which location to place their piece or makes the computer's move
if player == 1:
if numPlayers == 1 and first == "X":
boardWindow.bind("<Button-1>", lambda event: onClickInGame1(event, numPlayers, first, player))
elif numPlayers == 1 and first == "O":
aiMove(player, first)
elif numPlayers == 2:
boardWindow.bind("<Button-1>", lambda event: onClickInGame1(event, numPlayers, first, player))
elif player == 2:
if numPlayers == 1 and first == "X":
aiMove(player, first)
elif numPlayers == 1 and first == "O":
boardWindow.bind("<Button-1>", lambda event: onClickInGame2(event, numPlayers, first, player))
elif numPlayers == 2:
boardWindow.bind("<Button-1>", lambda event: onClickInGame2(event, numPlayers, first, player))
mainloop()
#Get number of players
numPlayers = int(raw_input("How many players?: "))
if numPlayers == 1:
symbol = raw_input("Would you like to be X or O?: ")
first = symbol.upper()
elif numPlayers == 2:
first = "X"
#Creates the window for the game
root = Tk()
boardWindow = Canvas(root, width = 600, height = 600)
boardWindow.pack()
drawBoard(boardWindow)
#Run the game
ticTacToe(1, numPlayers, first) |
2d26ec2aece3198533b0c6a4c2fbaee25030190f | DayNKnight/UnnamedCompanyCodeChallenges | /L3/level3.py | 8,208 | 4.1875 | 4 | """
Author: Zack Knight
Date: 5/5/2020
Raytheon Coding Challenges
Level 3
1.Create a command-line based user interface program that:
a.Accepts 3 command line parameters
i. Required: name and age
ii.Optional: phone number
b.Stores the data in a database
c.Supports the following commands:
i.User:
1.Add
2.Remove
3.Edit
ii.Database:
1.Export
2.Clear
iii.Print all users(in table format, sorted by
name, with all attributes) to stdout or a file
"""
import psycopg2
import argparse
import os
from configparser import ConfigParser
from os import system, name
import pandas
from UserCommands import userCommand
# clear function is from https://www.geeksforgeeks.org/clear-screen-python/
def clear():
# for windows
if os.name == 'nt':
os.system('cls')
# for mac and linux(here, os.name is 'posix')
else:
os.system('clear')
def redraw():
clear()
print(
"""
______ _ _ _____ _ _____
| _ \ | | | | / __ \ | |_ _|
| | | |__ _| |_ __ _| |__ __ _ ___ ___ | / \/ | | |
| | | / _` | __/ _` | '_ \ / _` / __|/ _ \ | | | | | |
| |/ / (_| | || (_| | |_) | (_| \__ \ __/ | \__/\ |____| |_
|___/ \__,_|\__\__,_|_.__/ \__,_|___/\___| \____|_____|___/
\n\n""")
# Config and connect gotten from https://www.postgresqltutorial.com/postgresql-python/connect/
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
# This function will either export or clear the database.
# Export just exports all of the data to a file.
# Clear truncates the table
def databaseCommand(cur,conn):
ans = input("Would you like to export or clear the database? [e,c] \n (enter 'back' to go back to the main selection screen) \n >>> ").strip()
if ans == 'e':
print("Exporting database to 'export' file in current directory. This overwrites the file if there is one already there.")
fp = open("export",'w')
cur.copy_to(fp,'people')
fp.close()
elif ans == 'c':
conf = input("Are you sure you want to clear? This will DELETE **ALL** of the data in the table. [y/n]").strip()
if conf == 'y':
cur.execute("TRUNCATE TABLE people;")
conn.commit()
elif ans == 'back':
return
else:
badRedraw(ans)
databaseCommand(cur,conn)
def printDatabase(conn):
# Parse the user input
ans = input("Would you like to print to STDOUT, a text file, or a CSV file? [s,f,c] \n (enter 'back' to go back to the main selection screen) \n >>> ").strip()
# Default answer.
# The dataframe is returned from panda's read_sql function. This is the easy way to print the tables instead of trying to parse the data myself.
# Idea for using pandas came from this: https://stackoverflow.com/questions/43382230/print-a-postgresql-table-to-standard-output-in-python
if ans == None or ans == '':
data_frame = pandas.read_sql('SELECT * FROM people ORDER BY person_name', conn)
print(data_frame.to_string(index=False))
print("\n")
# The file and csv are basically the same, but just have different defaults and different pandas calls
elif ans == 'f' or ans == 'F':
data_frame = pandas.read_sql('SELECT * FROM people ORDER BY person_name', conn)
outF = input("What is the file you would like to output to? (out.txt is default)(This will overwrite an existing file): ").strip()
if outF == None or outF == '':
outF = 'out.txt'
with open(outF,'w') as f:
data_frame.to_string(f,index=False)
redraw()
elif ans == 'c' or ans == 'C':
data_frame = pandas.read_sql('SELECT * FROM people ORDER BY person_name', conn)
outF = input("What is the file you would like to output to? (out.csv is default)(This will overwrite an existing file): ").strip()
if outF == None or outF == '':
outF = 'out.csv'
with open(outF,'w') as f:
data_frame.to_csv(f,index=False)
redraw()
elif ans == 'back':
# This is just here so that the badRedraw is not called for 'back'
return
else:
badRedraw(ans)
printDatabase(conn)
def badRedraw(answer):
redraw()
print(f"\n\n***ERROR*** '{answer}' is not a valid command, please try again \n")
def connect(name,age,phone):
""" Connect to the PostgreSQL database server """
redraw()
conn = None
table_name = "people"
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# check to see if table exists
cur.execute("SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name=%s);", (table_name,))
# if it doesn't exist, create it
if not cur.fetchone()[0]:
print("Table '{s}' not found. Creating it.\n".format(s=table_name))
# For some reason, sql does not like supplied format from psycopg parser, as it puts single quotes around
# the inserted strings
cur.execute(
"""
CREATE TABLE people (
person_id SERIAL PRIMARY KEY,
person_name VARCHAR(255) NOT NULL,
person_age INTEGER NOT NULL,
person_phone VARCHAR(50),
time_created TIMESTAMP WITHOUT TIME ZONE DEFAULT (NOW() at time zone 'utc')
);
""")
conn.commit()
firstUse = True
while True:
answer = input("Would you like to perform user, database, or print commands? [u,d,p] ('q' to quit) \n >>> ")
if answer.strip() == "u":
# In an attmept to keep the code from being too long in one file, the user commands are in UserCommands.py
returned = userCommand(name,age,phone,firstUse,cur,conn)
# If the return was True, it means that the operation was a success, so we can make firstUse = false and
# Continue to run the program to insert more people
#If the return was false, that means that the user exited before running a command, so we can re-use the command
# line values for later in the run.
if returned:
firstUse = False
conn.commit()
redraw()
elif answer.strip() == "d":
databaseCommand(cur,conn)
elif answer.strip() == "p":
printDatabase(conn)
elif answer.strip() == "q":
print("Now exiting program")
exit()
else:
badRedraw(answer)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Reads in ELF files and outputs the strings")
parser.add_argument('-n',"--name",dest='name',help="The name of the person", required=True)
parser.add_argument('-a',"--age",dest='age',help="The age of the person",required=True)
parser.add_argument('-p',"--phone",dest='phone',default=None)
args = parser.parse_args()
connect(args.name,args.age,args.phone)
|
90c1aca70fbce56ebea10f8af9a0a21eddae153f | jjivad/UoP_CS001 | /UoP_CS001/first_step.py | 743 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 15:31:50 2019
@author: VIJ Global
"""
#print 'Hello, World!'___ error message: syntaxError
#1/2
#type(1/2)
##print(01)____Error: SyntaxError: invalid token
#1/(2/3)
import turtle
import math
bob = turtle.Turtle()
#bob.fd(100)
#bob.lt(90)
#bob.fd(100)
#bob.lt(90)
#bob.fd(100)
#bob.lt(90)
#bob.fd(100)
#for i in range(4):
# bob.fd(100)
# bob.lt(90)
#print(bob)
turtle.mainloop()
#
#for i in range(4):
# print('Hello!')
def polygon(t, n, length):
angle = 360 / n
for i in range(n):
t.fd(length)
t.lt(angle)
polygon(bob, 7, 70)
def circle(t, r):
circumference = 2 * math.pi * r
n = 50
length = circumference / n
polygon(t, n, length)
|
37d6f9f429a9160b8848a67d0626a7db7532dc93 | honghyk/algorithm_study | /349. Intersection of Two Arrays.py | 346 | 3.828125 | 4 | from typing import List
# Hash Table, Two Pointers, Binary Search, Sort
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
interSet = set()
nums1Set = set(nums1)
for n in nums2:
if n in nums1Set:
interSet.add(n)
return list(interSet) |
3d71ff9638e3839f884fc0364d7a189a0a631707 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/grgvic001/question1.py | 1,174 | 3.875 | 4 | #program to calculate std andmean of file of marks and check the failures
#victor gueorguiev
#10 may 2014
import math
def calc_mean(marks):
total = 0
for i in marks:
total += i
return total/len(marks)
def calc_std(marks):
totalnum = 0
mean = calc_mean(marks)
for i in marks:
totalnum += (i-mean)**2
return math.sqrt(totalnum/len(marks))
def main():
filename = input("Enter the marks filename:\n")
f = open(filename,"r")
lines = f.readlines()
f.close()
marks = []
names = []
for line in lines:
names.append(line[:line.find(',')])
marks.append(eval(line[line.find(',')+1:]))
mean = calc_mean(marks)
std = calc_std(marks)
print('The average is:','{0:.2f}'.format(mean))
print('The std deviation is:','{0:.2f}'.format(std))
advisor_help = []
for i in range(len(marks)):
if marks[i] < mean - std:
advisor_help.append(names[i])
if advisor_help:
print('List of students who need to see an advisor:')
for i in advisor_help:
print(i)
main()
|
70d4f20ffbce3e5ec812d0b2e342f68c9b9580cc | jerryzhang2019/VScode-git-leetcode | /Leetcode高频考题重中之重/Leetcode链表linkedlist/876. Middle of the Linked List.py | 925 | 3.96875 | 4 | # 求链表的中点:定一个带有头节点的非空单链表head,返回链表的中间节点。
# 如果有两个中间节点,则返回第二个中间节点。
# 范例1:输入:[1,2,3,4,5] 输出:此列表中的节点3(序列化:[3,4,5])
# 返回的节点的值为3。(此节点的法官序列化为[3,4,5])。
# 请注意,我们返回了ListNode对象ans,例如:
# ans.val = 3,ans.next.val = 4,ans.next.next.val = 5,ans.next.next.next = NULL。
# 范例2:输入:[1,2,3,4,5,6] 输出:此列表中的节点4(序列化:[4,5,6])
# 由于列表具有两个中间节点,其值分别为3和4,因此我们返回第二个。
# 注意:给定列表中的节点数将在1 和之间100。
class Solution:
def midNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow |
41e92e13d355ce676ba61069f097d57e85bdd6cc | Macaque2077/DollyTheSheep | /saveBackup.py | 2,001 | 3.703125 | 4 | from shutil import copy2
import os
import sys
import json
#backup a file by passing {original file location} {folder for copied file to be placed in}
#passed files are stored in a dictionary text file
def main(args):
if len(args) > 0:
file_loc = args[0]
folder_name = args[1]
savefile(file_loc, folder_name)
writeJSON(file_loc, folder_name)
else:
saveExistingFiles()
def saveExistingFiles():
try:
with open('/home/machine/Desktop/code/NeekoMySaves/data.txt') as json_file:
data = json.load(json_file)
for p in data['saves']:
savefile(p['location'], p['folder'])
except ValueError:
print("no JSON saves found, you must pass a files location and the name of the folder you want store it in")
def savefile(file_loc, folder_name):
file_name = file_loc.split("/")[-1]
print(file_name)
print(os.path.abspath(os.getcwd()))
# could be improved to only check for the folder name in the location
saveslocation = "/home/machine/Desktop/backups"
if not os.path.isdir("{}/{}".format(saveslocation,folder_name)):
os.makedirs("{}/{}".format(saveslocation,folder_name))
# checking if the file exists
if os.path.isfile(str(file_loc)):
print("found the file")
copy2(file_loc, "{}/{}/{}".format(saveslocation,folder_name,file_name))
else:
print("are you sure {} exists?").format(str(file_loc))
def writeJSON(file_loc, folder_name):
try:
with open('data.txt') as json_file:
data = json.load(json_file)
except ValueError:
print('no backups dictionary found, now creating one')
data = {}
data['saves'] = []
data['saves'].append({
'location' : str(file_loc),
'folder' : str(folder_name)
})
with open('data.txt', 'w') as json_file:
json.dump(data, json_file)
if __name__ == "__main__":
main(sys.argv[1:])
|
7226763ef30f787382dd511cb3f66a18f1bf87ba | jvslinger/Year9Design01PythonJVS | /Sample Project 1/GUI1JVS.py | 1,455 | 3.96875 | 4 | #This opens the tkinter "tool box" containing all support material to make GUI Elements
#By including as tk we are giving a short name to use.
import tkinter as tk
#Main Window
root = tk.Tk() #creates the window
#Three stages to build elements
#1. Construct the Object: Building and Configuring it
#2. Configure the Object: Specify behaviors and settings
#3. Pack the Object: Put it in the window
output = tk.Text(root,height=10,width=30) #Parameters are what we send in.
#ordered parameters: The order we send them matters. (This is the common one, most languages ordered parameters matter)
#named parameters: JavaScript and Python specific.
output.config(state = "disabled",background = "orange")
output.grid(row = 0, column = 0, rowspan = 5)
#******WIDGETS 2,3,4******
labInput1 = tk.Label(root,text = "Input 1",background = "red")
labInput1.grid(row = 5, column = 0)
labInput2 = tk.Label(root,text = "Input 2",background = "white")
labInput2.grid(row = 6, column = 0)
labInput3 = tk.Label(root,text = "Input 3",background = "blue")
labInput3.grid(row = 7, column = 0)
#******WIDGETS 5,6 (Checkboxes)******
var1=tk.IntVar()
var2=tk.IntVar()
cHC = tk.Checkbutton(root, text="Expand", variable=var1)
cHC.grid(row = 0, column = 1)
cLF = tk.Checkbutton(root, text="Expand", variable=var2)
cLF.grid(row = 1, column = 1)
#This is an event drive program
#Build the GUI
#Start it running
#Wait for "event"
root.mainloop() #starts the program
|
47432ab548574ecdbf7759e90c23f5a49f205cd0 | rafaelperazzo/programacao-web | /moodledata/vpl_data/158/usersdata/272/65875/submittedfiles/imc.py | 366 | 3.828125 | 4 | # -*- coding: utf-8 -*-
peso= float(input('Digite o peso:'))
altura= float(input('Digite a altura:'))
IMC=(peso/(altura**2))
if (IMC<20):
print('ABAIXO')
elif (IMC>=20) and (IMC<=25):
print('NORMAL')
elif (IMC>25) and (IMC<=30):
print('SOBREPESO')
elif (IMC>30) and (IMC<=40):
print('OBESIDADE')
elif (IMC>40):
print('OBESIDADE GRAVE') |
0fea85c1fe9190830c71d9104f40429f27e27d14 | RyanMoodGAMING/Python-School | /Flowchart.py | 576 | 4.21875 | 4 | '''
Function Name: flowChart()
Parameters: N/A
Return Value:
What it does:
'''
def flowChart():
age = input("Please input how old you are -> ")
gender = input("Please input your gender -> ")
if int(age) < 20:
dose = float(age) * 0.1
else:
dose = 2
if gender.lower() == "female":
isPregnant = input("Are you pregnant? ")
acceptable = ["True", "Yes", "true", "yes"]
if isPregnant in acceptable:
dose = 1.5
else:
dose = float(dose) * 0.5
#print(dose) # Used for debug
|
ad572777b8f454f725d5a4e2fe66188179049ed8 | ursu1964/Libro2-python | /Cap3/Programa 3_16.py | 460 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Problema 3.16
Quita de la lista aquellos elementos que no forman parte de
las tuplas que son claves de un diccionario.
"""
equipos = {('pat', 'lara'): 85, ('jorge', 'ines'): 80, ('luis', 'leti'): 103}
nombres = ['jose', 'pat', 'lara', 'alicia', 'ines']
solo_nom = list(equipos.keys())
nombres = [ele for tupla in solo_nom for ele in tupla if ele in nombres]
print('\nLista modificada:', nombres) |
d70aba7130700a686ae5e9b4a434a3fb1f27ec9a | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m05_search/merge_sorted_lists.py | 844 | 4.375 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
#
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
# Input:
nums1 = [1,2,3,0,0,0] #m = 3
nums2 = [2,5,6] #n = 3
#
# Output: [1,2,2,3,5,6]
def merge_sorted_lists(nums1, nums2):
nums1_index = 0
nums2_index = 0
while nums2_index < len(nums2):
if nums2[nums2_index] < nums1[nums1_index] or nums1[nums1_index] == 0:
nums1.insert(nums1_index, nums2[nums2_index])
nums1.pop()
nums2_index += 1
nums1_index = nums2_index
else :
nums1_index += 1
return nums1
merge_sorted_lists(nums1, nums2)
|
c85f735ca7b2768ed99b216e82fd8c8c83d1d5ac | saki45/CodingTest | /py/misc/perfectshuffle/permutationdecompose.py | 300 | 3.59375 | 4 | def permutationdecompose(N):
print(N)
seed = 1
while seed < N:
print(seed,end=',')
t = (seed*2)%(N+1)
while t != seed:
print(t,end=',')
t = (t*2)%(N+1)
print()
seed = 3*seed
if __name__ == '__main__':
permutationdecompose(8)
permutationdecompose(6)
permutationdecompose(0)
|
5f51484eb464a79cc1d4b49b8dd8475ee10bd203 | popshia/Algorithm_Homework_1 | /binarySearchTree.py | 1,994 | 3.90625 | 4 | # 演算法分析機測
# 學號: 10624370/10627130/10627131
# 姓名: 鄭淵哲/林冠良/李峻瑋
# 中原大學資訊工程系
# Preorder to Postorder Problem
# Build a binary tree from preorder transversal and output as postorder transversal
class Node():
def __init__(self, data): # initial node
self.data = data
self.left = None
self.right = None
self.isChar = False
def Construction(preorder, low, high, size):
if( Construction.index >= size or low > high): # end case
return None
root = Node(preorder[Construction.index]) # set root node
Construction.index += 1 # increase the visit index
if low == high: # root case
return root
for i in range(low, high+1): # set visit range
if preorder[i] > root.data:
break
root.left = Construction(preorder, Construction.index, i-1 , size) # recursive the left node
root.right = Construction(preorder, i, high, size) # recursive the right node
return root
def ConstructTree(preorder): # constuct the tree
size = len(preorder)
Construction.index = 0
return Construction(preorder, 0, size-1, size)
def PrintPostorder(root, isChar): # print out the postorder transversal of the given root
if root is None:
return
if isChar == False:
PrintPostorder(root.left, False)
PrintPostorder(root.right, False)
print(root.data, end=' ')
if isChar == True:
PrintPostorder(root.left, True)
PrintPostorder(root.right, True)
print(chr(root.data), end=' ')
if __name__ == '__main__':
answers = []
nodeValue = list(input().split())
while len(nodeValue) != 1:
isChar = False
preorder = []
for values in nodeValue:
if values.isnumeric(): # numeric input
preorder.append(int(values))
else: # character input
isChar = True
preorder.append(ord(values))
root = ConstructTree(preorder)
root.isChar = isChar
answers.append(root)
nodeValue = list(input().split())
for roots in answers: # print out the root(s) in the answer array
PrintPostorder(roots, roots.isChar)
print("\r") |
d66f65fb89910c4c51ea2694e7d4db8ae91149d0 | TJJTJJTJJ/leetcode | /105.construct-binary-tree-from-preorder-and-inorder-traversal.py | 2,471 | 3.828125 | 4 | #
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (39.61%)
# Total Accepted: 216.7K
# Total Submissions: 533.2K
# Testcase Example: '[3,9,20,15,7]\n[9,3,15,20,7]'
#
# Given preorder and inorder traversal of a tree, construct the binary tree.
#
# Note:
# You may assume that duplicates do not exist in the tree.
#
# For example, given
#
#
# preorder = [3,9,20,15,7]
# inorder = [9,3,15,20,7]
#
# Return the following binary tree:
#
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# method 1
# class Solution:
# def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
# if len(preorder)!=len(inorder):
# return None
# if not preorder:
# return None
# root = TreeNode(preorder[0])
# # index = inorder.index(preorder[0])
# for index, val in enumerate(inorder):
# if val==root.val:
# break
# root.left = self.buildTree(preorder[1:index+1], inorder[:index])
# root.right = self.buildTree(preorder[index+1:], inorder[index+1:])
# return root
# method 2 相当于对 method 1 的升级版,用了preorder.pop,避免了preorder的偏移量
# 这里对preorder的处理很微妙,因为当处理完左子树后,preorder中是左子树的元素都会被pop掉,不再需要偏移量
# 或者换个思路想,其实是依次弹出preorder的元素,只是不知道弹出的元素是位于上一个结点的左子树还是右子树,
# 需要通过inorder来判断元素位于左子树还是右子树
# 这个思路也还是有问题,只能理解成对mothod1的遍历过程中发现preorder在处理right时,left已经全部处理结束
# 这里 preorder 相当于一个全局变量
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not inorder:
return
ind = inorder.index(preorder.pop(0))
root = TreeNode(inorder[ind])
root.left = self.buildTree(preorder, inorder[:ind])
root.right = self.buildTree(preorder, inorder[ind+1:])
return root
|
81116d7840ce59680d2e39ad7132500b9b561482 | FunkyNoodles/DailyProgrammer | /PythonSolutions/2017-07-05/main.py | 939 | 3.71875 | 4 | import time
def is_palindrome(string):
for idx, char in enumerate(string):
if char != string[-idx-1]:
return False
return True
# n = input('n:\n')
n = 5
max_factor_i = 0
max_factor_j = 0
max_product = 0
found = False
print('n =', n)
start = time.time()
for i in reversed(list(range(1, 10**n))):
if len(str(i)) < n or found:
break
for j in reversed(list(range(1, i+1))):
if len(str(j)) < n:
break
product = i * j
if i < max_factor_i and product < max_product:
found = True
break
if product < max_product:
break
if is_palindrome(str(product)):
if product > max_product:
max_factor_i = i
max_factor_j = j
max_product = product
end = time.time()
print(max_product, 'factors:', max_factor_i, 'and', max_factor_j)
print('Took', end - start, 's')
|
2fbeafbf055879c16aaa94633a8c20cfbdcad5ce | toshhPOP/SoftUniCourses | /Python-Advanced/Multidimentional_Lists/knight.py | 1,364 | 3.75 | 4 | def is_knight_placed(board, r, c):
board_size = len(board)
if r < 0 or c < 0 or r >= board_size or c >= board_size:
return False
return board[r][c] == "K"
def count_affected_knights(board, r, c):
result = 0
board_size = len(board)
if is_knight_placed(board, r - 2, c - 1):
result += 1
if is_knight_placed(board, r - 2, c + 1):
result += 1
if is_knight_placed(board, r + 2, c - 1):
result += 1
if is_knight_placed(board, r + 2, c + 1):
result += 1
if is_knight_placed(board, r - 1, c - 2):
result += 1
if is_knight_placed(board, r - 1, c + 2):
result += 1
if is_knight_placed(board, r + 1, c - 2):
result += 1
if is_knight_placed(board, r + 1, c + 2):
result += 1
return result
size = int(input())
matrix = [[x for x in input()] for i in range(size)]
removed_knights = 0
while True:
max_count = 0
knight_row, knight_col = 0, 0
for r in range(size):
for c in range(size):
if matrix[r][c] == '0':
continue
count = count_affected_knights(matrix, r, c)
if count > max_count:
max_count, knight_row, knight_col = count, r, c
if max_count == 0:
break
matrix[knight_row][knight_col] = '0'
removed_knights += 1
print(removed_knights)
|
9fdcc4daa6fdbca5c906e4baa879ae43a36339d8 | avborup/Kat | /helpers/cli.py | 93 | 3.625 | 4 | def yes():
answer = input("(y/N): ").lower()
return answer == "y" or answer == "yes"
|
217645edebea012bf0f1694f3b277f885a03cf16 | xprime480/projects | /tools/new/python/keys.py | 342 | 3.5 | 4 | #!/usr/bin/python
import string
import random
keys = set([])
while len(keys) < 1000 :
keys.add(''.join([random.choice(string.ascii_lowercase) for x in range(3)]))
keys.add('aaa')
keys.add('aaa')
keys.add('aaa')
lkeys = list(keys);
lkeys.sort()
for k in lkeys :
print 'insert into key_names ( key_name ) value ( \'%s\' );' % k
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.