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 |
|---|---|---|---|---|---|---|
bf62694f4c7a74ce190d4d797e3f47bb48ba35e0 | Rashijb/Assignment3 | /filter.py | 372 | 3.6875 | 4 | my_list = [12, 22, 33, 56, 78, 97]
def even_check(num):
return num%2 == 0
def odd_check(num):
return num%2 != 0
even_numbers=list(filter(even_check, my_list))
print(even_numbers)
filter_list=list(filter(odd_check,my_list))
print(filter_list)
#for lambda functions
square = lambda x : x * x
print(square(55))
sqr=list(map(lambda x : x**2,my_list))
print(sqr) |
0985a9d83268e02ee5693d9ebae60381aee40128 | dodecatheon/UW-Python | /fall2011/week01/grid.py | 1,178 | 3.984375 | 4 | #!/usr/bin/env python
"""
Exercise to hand in for week two:
print_grid(integer) returns a grid like Downey 3.5. Do something reasonable.
"""
def print_grid(n):
"""\
print_grid(n), takes integer n and prints a grid where each of the
four gridlets has n pipes on a side.
Therefore, print(1) looks like
>>> print_grid(1)
+ - + - +
| | |
+ - + - +
| | |
+ - + - +
and print_grid(3) looks like
>>> print_grid(3)
+ - - - + - - - +
| | |
| | |
| | |
+ - - - + - - - +
| | |
| | |
| | |
+ - - - + - - - +
"""
hsect = n*" -" + " +"
plus_line = "+" + 2*hsect
psect = n*" " + " |"
pipe_line = "|" + 2*psect
for j in range(2):
print plus_line
for i in range(n):
print pipe_line
print plus_line
if __name__ == '__main__':
import sys
print "sys.argv =", sys.argv
if len(sys.argv) == 2:
n = int(sys.argv[1])
print "Read first arg as", n, "\n"
else:
n = 5
print "Default size = 5:\n"
print_grid(n)
print "\n",
|
621100ce88779929d2d9f481dc39988e74ce1234 | theodox/Transcrypt | /transcrypt/demos/terminal_demo/terminal_element.py | 160 | 3.625 | 4 | import time
def print_current_time(self):
localtime = time.asctime(time.localtime(time.time()))
print("The current time is {}".format(localtime))
|
9b4993634461fe18231c9ff2069cf87a35c673e4 | bhusalashish/DSA-1 | /Data/Hashing/Subarray with zero-sum/Brute.py | 377 | 3.609375 | 4 | '''
#### Name: Subarray with zero-sum
Link: [link]()
#### Sub_question_name: Brute
Link: [link]()
2 loops
'''
def check_zero(arr):
n = len(arr)
for i in range(1, n):
for j in range(i):
subarray = arr[j:i+1]
if sum(subarray) == 0:
return True
return False
arr = [-3, 2, 3, 1, 6]
print(check_zero(arr)) |
bc6aad76e30d29dd63e0a67e5bc62ec52fe5c71f | mathewsjose90/Python-Learnings | /Examples/Leetcode/solve_the_equation.py | 1,873 | 3.859375 | 4 | '''
https://leetcode.com/problems/solve-the-equation/
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Input: "x=x"
Output: "Infinite solutions"
'''
class Solution:
def solveEquation(self, equation: str) -> str:
equation = equation.replace('"', '')
flip_sign = lambda s: '+' if s == '-' else '-'
lhs, rhs = equation.split('=')
updated_rhs = "".join([c if c not in ('+', '-') else flip_sign(c) for c in rhs])
if updated_rhs[0] not in ['+', '-']:
updated_rhs = '-' + updated_rhs
updated_equation_lhs = lhs + updated_rhs
if not updated_equation_lhs[0] in ['+', '-']:
updated_equation_lhs = '+' + updated_equation_lhs
plus_minus_pos = [i for i, x in enumerate(updated_equation_lhs) if x in ('+', '-')]
x_parts = []
number_parts = []
def add_data(data):
if 'x' in data:
x_parts.append(data)
else:
number_parts.append(data)
previous_pos = 0
for i in plus_minus_pos[1:]:
data = updated_equation_lhs[previous_pos:i]
previous_pos = i
add_data(data)
# Adding the last part of equation that is missing in the above loop
add_data(updated_equation_lhs[plus_minus_pos[-1]:])
get_int_part = lambda x: int(x[:-1]) if len(x) > 2 else int(x[0] + '1')
sum_of_number_parts = sum([int(x) for x in number_parts])
sum_of_x_parts = sum([get_int_part(x) for x in x_parts])
if sum_of_x_parts == 0 and sum_of_number_parts == 0:
return 'Infinite solutions'
elif sum_of_x_parts == 0 and sum_of_number_parts != 0:
return 'No solution'
x_value = int(-sum_of_number_parts / sum_of_x_parts)
return 'x=' + str(x_value)
s = Solution()
print(s.solveEquation(input('Enter the equation :')))
|
665f0043e54ee306dea3b194b3c7a6c7f6e9d6de | pavlovprojects/python_databases | /sqlite/4_delete.py | 308 | 3.640625 | 4 | import sqlite3
connection = sqlite3.connect("data.sqlite")
cursor = connection.cursor()
# cursor.execute("DROP TABLE contacts;")
cursor.execute("DROP TABLE IF EXISTS contacts;")
# sql = "DELETE FROM contacts WHERE name = ?"
#
# cursor.execute(sql, ("HELLOTEST",))
# connection.commit()
connection.close() |
80c272b79fd5aa6c8ff1485aa1dffe7089a1fe9d | phantomnat/python-learning | /leetcode/tree/112-path-sum.py | 1,148 | 3.96875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def dfs(self, node, target, total=0):
if node is None:
return False
# if abs(total) > abs(target) or abs(node.val + total) > abs(target):
# return False
if node.left is None and node.right is None and target == total + node.val:
return True
l = False if node.left is None else self.dfs(node.left, target, total + node.val)
r = False if node.right is None else self.dfs(node.right, target, total + node.val)
return l or r
def hasPathSum(self, root, _sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
return self.dfs(root, _sum, 0)
# s = Solution()
# root = TreeNode(-2)
# root.right = TreeNode(-3)
# print(s.hasPathSum(root, -5))
# root = TreeNode(8)
# root.left = TreeNode(9)
# root.right = TreeNode(-6)
# root.right.left = TreeNode(5)
# root.right.right = TreeNode(9)
# print(s.hasPathSum(root, 7)) |
056012669f405dbac252ae85073c4f0b6a1740cb | Wil10w/Beginner-Library-3 | /More String stuff/inside parentheses.py | 974 | 4.125 | 4 |
def in_parentheses(string):
first_para = string.find('(')
second_para = string.find(')')
if string:
if (first_para == -1 and second_para >= 1):
return "Closed ) only"
if second_para == -1 and first_para >= 1:
return "Open ( only"
if second_para < first_para:
return "Closed ) before ( open"
if first_para == -1 and second_para == -1:
return "No parentheses here!"
if first_para < second_para:
return string.split('(', 1)[1].split(')')[0]
else:
return ''
print(in_parentheses("This is a sentence (words!)."))
print(in_parentheses("No parentheses here!"))
print(in_parentheses("David tends to use parentheses a lot (as he is doing right now). It tends to be quite annoying."))
print(in_parentheses("Open ( only"))
print(in_parentheses("Closed ) only"))
print(in_parentheses("Closed ) before ( open"))
print(in_parentheses(""))
|
8265fc0a51be2495117037905b7b5626d91f86f3 | XingxinHE/PythonCrashCourse_PracticeFile | /Chapter 6 Dictionary/dic_key_value.py | 630 | 3.625 | 4 | dic = {
'Nile' : 'Egypt',
'Yellow River' : 'China',
'Amazon River' : 'Brazil'
}
for river in dic.keys():
print(river)
print('\n')
for country in dic.values():
print(country)
print('\n')
favorite_languages = {
'Jen' : 'Python',
'Sarah' : 'C',
'Edward' : 'Ruby',
'Phil' : 'Python'
}
coders = ['Jen','Steven','Sarah','Morris','Edward']
for coder in coders:
if coder in favorite_languages.keys():
print(coder+' ,you have done the poll.')
else:
print(coder+' ,please finish the poll.')
|
29bbbb3567104f6875312ea40b9357d6cb052f09 | sunyoboy/shell | /python/tup/01_tup.py | 1,001 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
tup1 = (12, 34.56);
tup2 = (1, 2, 3, 4, 5, 6, 7);
print "tup1[0]", tup1[0]
print "tup2[1:5]", tup2[1:5]
# 1、元组运算
# 计算元素个数
print "len((1, 2, 3)) : ", len((1, 2, 3));
# 连接
print "(1, 2, 3) + (4, 5, 6) : ", (1, 2, 3) + (4, 5, 6);
# copy
print "['Hi!'] * 4 : ", ['Hi!'] * 4;
# 存在
print "3 in (1, 2, 3) : ", 3 in (1, 2, 3);
# 迭代
for x in(1, 2, 3):print x,
print "New ";
# 2、索引、截取
L = ('A', 'B', 'C');
print L[2]; # 取索引为2的元素,index start from 0
print L[-2]; # 反向读取,倒数第二个
print L[1:]; # 截取index从1开始的元素
# 3、无关闭分割符
print 'abc', -4.24e93, 18+6.6j, 'xyz'
x, y = 1, 2
print "Value of x, y : ", x, y;
# 4、元组内置函数
# 1. cmp(tuple1, tuple2) : compare two tuple element.
# 2. len(tuple) : count number of elements.
# 3. max(tuple) : return the max element.
# 4. min(tuple) : return the min element.
# 5. tuple(seq) : convert seq to tuple.
|
58212968f548d064adba1c80879a1d8040a097c8 | Garvys/Codingame | /Puzzle/Solo/Moyen/APU_Phase_d'Initialisation/Source.py | 1,008 | 3.75 | 4 | import sys
import math
# Don't let the machines win. You are humanity's last hope...
def findNeighbour(grid, w, h, x, y, dx, dy):
cx = x + dx
cy = y + dy
while cx < w and cy < h:
if grid[cy][cx] == '0':
return [cx, cy]
cx += dx
cy += dy
return [-1,-1]
width = int(input()) # the number of cells on the X axis
height = int(input()) # the number of cells on the Y axis
graph = list()
nodes = list()
for i in range(height):
line = input() # width characters, each either 0 or .
graph.append(str(line.strip()))
for j,x in enumerate(line):
if x == '0':
nodes.append([j,i])
for node in nodes:
x = node[0]
y = node[1]
print(" ".join(map(str,node + findNeighbour(graph,width,height,x,y,1,0) + findNeighbour(graph,width,height,x,y,0,1))))
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
# Three coordinates: a node, its right neighbor, its bottom neighbor
|
3227107bb97c836c68a4d4330c144c6672685f19 | chc1129/python_jisen | /06/isClassMethod.py | 1,400 | 3.6875 | 4 | # クラスメソッド - クラスに紐付くメソッド
# 属性を使ったソートに使える標準ライブラリをインポート
from operator import attrgetter
class Page:
book_title = 'Python Practice Book'
def __init__(self, num, content):
self.num = num
self.content = content
def output(self):
return f'{self.content}'
# クラスメソッドの第1引数はクラスオブジェクト
@classmethod
def print_pages(cls, *pages):
# クラスオブジェクトの利用
print(cls.book_title)
pages = list(pages)
# ページ順に並べ替えて出力
for page in sorted(pages, key=attrgetter('num')):
print(page.output())
first = Page(1, 'first page')
second = Page(2, 'second page')
third = Page(3, 'third page')
# クラスメソッドの呼び出し
Page.print_pages(first, third, second)
# インスタンスからも呼び出せる
first.print_pages(first, third, second)
# スタティックメソッド - 関数のように振る舞うメソッド
class Page:
def __init__(self, num, content):
self.num = num
self.content = content
@staticmethod # スタティックメソッドにする
def check_blank(page):
return bool(page.content)
page = Page(1, '')
Page.check_blank(page)
print( Page.check_blank(page) )
def check_blank(page): # 関数で問題ない
return bool(page.content)
check_blank(page)
print( check_blank(page) )
|
223dfe8a65e1dd4f9a4f4bf7e0c18ae2ce49943d | romperstomper/lpthw | /ex29.py | 420 | 4.125 | 4 | #!/usr/bin/python
people = 20
cats = 30
dogs = 15
if people < cats:
print "too many cats!"
if people > cats:
print "not enough cats"
if people < dogs:
print "not enough dogs"
if people > dogs:
print "defo too many ppl"
dogs += 5
if people >= dogs:
print "ppl are greater or equal to dogs"
if people <= dogs:
print "ppl are less than or equal to dogs"
if people == dogs:
print "people are dogs!"
|
55d9a8a1e8d253f2ed550934a37d913499049f6e | psmilovanov/Python_HW_01 | /homework01_3.py | 331 | 3.765625 | 4 | # Задание 3. Вывести n+nn+nnn.
n = int(input("Введите положительное число n: "))
digit_number = 0
m = n
while (m > 0):
m = m // 10
digit_number += 1
print("Сумма n + nn + nnn = ", n + (n + n * 10 ** digit_number) + (n + n * 10 ** digit_number + n * 10 ** (2 * digit_number)))
|
dafa6962350ae88aa65225c32ea485c500ae0bba | OneHandKlap/Data-Structures | /palindrome_tests.py | 715 | 3.625 | 4 | import unittest
from Recursion_practice import ispalindrome, palin
class palindrometester(unittest.TestCase):
def test1(self):
s="tacocat"
k=0
res=palin(s,k)
self.assertEqual(res,True)
def test2(self):
s="tacoca22t"
k=2
res=palin(s,k)
self.assertEqual(res,True)
def test3(self):
s="asdasd"
k=5
res=palin(s,k)
self.assertEqual(res,True)
def test4(self):
s="ssadd"
k=4
res=palin(s,k)
self.assertEqual(res,True)
def test5(self):
s="alskkdajk"
k=7
res=palin(s,k)
self.assertEqual(res,True)
if __name__ == "__main__":
unittest.main()
|
2b23c2fc1d833eee27c5cc2a2d89b87bdb5b0c60 | feliperojas/mision_tic_G11 | /s11/11.7_condicionales_anidados.py | 426 | 3.96875 | 4 | numero_1 = int(input("Ingrese el numero 1:"))
numero_2 = int(input("Ingrese el numero 2:"))
if numero_1 == numero_2:
resultado = numero_1 * numero_2
print(f"El resultado es: {resultado}")
else:
if numero_1 > numero_2:
resultado = numero_1 - numero_2
print(f"El resultado es: {resultado}")
else:
resultado = numero_1 + numero_2
print(f"El resultado es: {resultado}") |
e8f6c69115084dbbac0ef11f5cd5fe7e964f2b9a | evgranato/Python-Course-Code | /Testing/test_cards.py | 2,422 | 4.03125 | 4 | import unittest
from card_deck import Card, Deck
class CardTests(unittest.TestCase):
def setUp(self):
self.card = Card("A", "Hearts")
def test_init(self):
'''cards should have a suit and value'''
self.assertEqual(self.card.suit, "Hearts")
self.assertEqual(self.card.value, "A")
def test_repr(self):
"""repr should return a string of the form 'VALUE' of 'SUIT'"""
self.assertEqual(repr(self.card), "A of Hearts")
class DeckTests(unittest.TestCase):
def setUp(self):
self.deck = Deck()
def test_init(self):
'''deck should have 52 cards'''
self.assertTrue(isinstance(self.deck.cards, list))
self.assertEqual(len(self.deck.cards), 52)
def test_repr(self):
"""repr should return a string in the form of 'deck of cards'"""
self.assertEqual(repr(self.deck), "Deck of 52 cards")
def test_count(self):
"""count should return a count of the number of cards"""
self.assertEqual(self.deck.count(), 52)
self.deck.cards.pop()
self.assertEqual(self.deck.count(), 51)
def test_deal_sufficient_cards(self):
"""deal should deal the number of cards specified"""
cards = self.deck._deal(10)
self.assertEqual(len(cards), 10)
self.assertEqual(self.deck.count(), 42)
def test_deal_insufficient_cards(self):
cards = self.deck._deal(100)
self.assertEqual(len(cards), 52)
self.assertEqual(self.deck.count(), 0)
def test_deal_no_cards(self):
self.deck._deal(self.deck.count())
with self.assertRaises(ValueError):
self.deck._deal(1)
def test_deal_card(self):
card = self.deck.cards[-1]
dealt_card = self.deck.deal_card()
self.assertEqual(card, dealt_card)
self.assertEqual(self.deck.count(), 51)
def test_deal_hand(self):
cards = self.deck.deal_hand(20)
self.assertEqual(len(cards),20)
self.assertEqual(self.deck.count(),32)
def test_shuffle_full_deck(self):
cards = self.deck.cards[:]
self.deck.shuffle()
self.assertNotEqual(cards, self.deck.cards)
self.assertEqual(self.deck.count(), 52)
def test_shuffle_not_full_deck(self):
self.deck._deal(1)
with self.assertRaises(ValueError):
self.deck.shuffle()
if __name__ == "__main__":
unittest.main() |
33e77a914d3e181146e340b2588e696690a43e43 | JorgeEstrada1/programacion | /Tabla_de_multiplicar.py | 300 | 3.65625 | 4 | #tablas de multiplicar
def tablaM(num):
print("Tabla de multiplicar del", num)
for i in range (1,11):
print(num, " x ", i , " = ", i * num)
num=tablaM(1)
num=tablaM(2)
num=tablaM(3)
num=tablaM(4)
num=tablaM(5)
num=tablaM(6)
num=tablaM(7)
num=tablaM(8)
num=tablaM(9)
num=tablaM(10)
|
614ba0bdf85c8e9c63ca579bc28bd1e611795de8 | terrifyzhao/educative4 | /13/9.py | 924 | 3.75 | 4 | from heapq import *
def find_maximum_distinct_elements(nums, K):
min_heap = []
dic = {}
for num in nums:
dic[num] = dic.get(num, 0) + 1
for k, v in dic.items():
heappush(min_heap, (v, k))
count = 0
while min_heap:
v, k = heappop(min_heap)
if v == 1:
count += 1
else:
K = K - v + 1
if K >= 0:
count += 1
if K > 0:
count -= K
return count
def main():
print("Maximum distinct numbers after removing K numbers: " +
str(find_maximum_distinct_elements([7, 3, 5, 8, 5, 3, 3], 2)))
print("Maximum distinct numbers after removing K numbers: " +
str(find_maximum_distinct_elements([3, 5, 12, 11, 12], 3)))
print("Maximum distinct numbers after removing K numbers: " +
str(find_maximum_distinct_elements([1, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5], 2)))
main()
|
fcda9538ef08650eb5698f7b48b75a8825be5bd3 | RobertRivas/machine_learning_homework1 | /machine_learning_homework1.py | 1,146 | 3.78125 | 4 | import matplotlib.pyplot as plt
x_data = [45, 36, 37, 43, 38, 49, 39, 43, 44, 38, 42, 40]
y_data = [43, 35, 34, 41, 44, 44, 42, 46, 39, 39, 47, 39]
x_average = sum(x_data)/len(x_data)
y_average = sum(y_data)/len(y_data)
xy = []
for i in range(len(x_data)):
xy.append(x_data[i] * y_data[i])
xy_average = sum(xy)/len(x_data)
x_squared = []
for j in range(len(x_data)):
x_squared.append(pow(x_data[j], 2))
x_squared_average = sum(x_squared)/len(x_data)
theta_sub_1 = ((xy_average) - (x_average * y_average))/((x_squared_average)-(pow(x_average, 2)))
theta_sub_0 = y_average - (theta_sub_1 * x_average)
# best linear function
best_linear_function_values = []
for z in range(len(x_data)):
best_linear_function_values.append(theta_sub_0 + (theta_sub_1*x_data[z]))
print(best_linear_function_values[z])
# prediction for x = 27
print()
predicted_value_at_27 = theta_sub_0 + (theta_sub_1 * 27)
print("The predicted value at x = 27 is: ", predicted_value_at_27)
plt.scatter(x_data, y_data)
plt.plot(x_data, best_linear_function_values)
plt.xlabel('Interested in Class')
plt.ylabel('Enrolled in Class')
plt.show() |
b78250b2265566b095b707c9542dfa779e725395 | sgnab/sort_search_algorithms | /selection_reverse_sorting.py | 421 | 3.953125 | 4 | ####BIG O is O(n^2)
import random
def select_sort(num):
if len(num)<=1:
return num
for i in xrange(len(num)):
# print i
for j in xrange(i,len(num)):# here if you use just xrange(len(num)), the list will be ordered in reverse
print j
if num[i]<num[j]:
num[j],num[i]=num[i],num[j]
return num
b = random.sample(range(1,10),9)
print select_sort(b) |
a3548c214b66df72abbdaaf06efae1e0b50f7d12 | AchyuthaBharadwaj/LeetCode | /535-Encode-and-Decode-TinyURL.py | 651 | 3.671875 | 4 | class Codec:
def __init__(self):
self.dic = dict()
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.dic[0] = longUrl
return longUrl
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.dic[0]
#Runtime: 24 ms, faster than 100.00% of Python online submissions for Encode and Decode TinyURL.
url = "https://leetcode.com/problems/design-tinyurl"
codec = Codec()
print(codec.decode(codec.encode(url))) |
8c5439b40cd6f98bd5e3bee396e4957f004c3ee7 | vmohana/UMN-HW | /GibbsRain.py | 3,167 | 4.25 | 4 | '''
NAME: V. MOHANA KRISHNA
ARTIFICIAL INTELLIGENCE II - Homework
Coding assignment
GIBB'S SAMPLER ALGORITHM
-----------------------------------------
1. Start with a random state.
2. Pick a non evidence variable to be sampled ( the non evidence variables must be picked in turn).
3. Sample a value for the picked non evidence variable and change the state as required.
4. Record how many times the sampler takes each value of the desired non evidence random variable.
5. Continue for the required number of iterations.
6. Calculate and print the probabilities.
'''
# Import requried libraries
import random
import sys
import numpy as np
# Read argument from command line
N = sys.argv[1]
ne_variables = ['C', 'R'] # The non evidence variables.
probabilities = {'C':{'R':0.4444, '~R':0.04761}, 'R':{'C':0.8148, '~C':0.2157}, '~C':{'R':0.5555, '~R':0.9524}, '~R':{'C':0.1851, '~C':0.7843}} # The probabilities of non evidence variables given their Markov blankets.
initial_state = ['C','S','R','W'] # An array holding the intial array. It also reflects the current state of random variables.
false_counter = 0 # The number of times a state in which Rain = false is visited.
true_counter = 0 # The number of times a state with Rain = true is visited.
# For loop for the number of iterations
for i in range(int(N)):
variable_to_sample = ne_variables[i%2] # A variable which records which random variable to sample.
current_state_variable = None # This holds the current value of the random variable.
# Check the current value of the sampled random variable and store it in current_state_variable.
# other_variable records the other random variable which is not being sampled.
if variable_to_sample=='C':
current_state_variable = initial_state[0]
other_variable = initial_state[2]
else:
current_state_variable = initial_state[2]
other_variable = initial_state[0]
# Retreive the conditional probability from the dictionary of probabilities.
sampling_probability = probabilities[current_state_variable][other_variable]
# Sample a value according to the probability.
sampled_value = np.random.choice([True, False], p = [sampling_probability, 1-sampling_probability])
# Change the state of the sampled random variable if the sampled value is False. Otherwise, keep it same.
if sampled_value == False:
if current_state_variable=='C':
initial_state[0]='~C'
if current_state_variable=='~C':
initial_state[0]='C'
if current_state_variable=='R':
initial_state[2]='~R'
false_counter+=1 # Record the number of times a state with Rain = False is visited.
if current_state_variable=='~R':
initial_state[2]='R'
true_counter+=1 # Record the number of times a state with Rain = true is visited.
# Don't change the value if the sampled value is True.
else:
if current_state_variable=='R':
true_counter+=1 # Just increment the counter and don't make any changes to the state
if current_state_variable=='~R':
false_counter+=1 # Just increment the counter and don't make any changes to the state
print('True: ', true_counter)
print('False', false_counter)
print('probability of Rain = True: ', (true_counter/int(N)))
|
498aeeabac4d1960a5a9153e14b6cafae22a8e0f | Vaishnavi-Gajinkar/Bridgelabz | /Week1/Permutation.py | 327 | 3.640625 | 4 | def swap(part,s,e):
part=""
char = list(part.split(""))
temp=char[s]
char[s]=char[e]
char[e]=temp
return(part.join(char))
def permute(var,l,r):
if l==r:
print(var)
else:
for i in range(l,r,1):
res=swap(var,l,i)
permute(res,l+1,r)
s="a"
permute(s,0,len(s)) |
29a7199dbf6155e95a5bd880ab48cdc035c0f593 | CodedQuen/Scipy-and-Numpy | /scipy_342_ex1.py | 946 | 3.625 | 4 | import numpy as np
from scipy import stats
# Generating a normal distribution sample
# with 100 elements
sample = np.random.randn(100)
# The harmonic mean: Sample values have to
# be greater than 0.
out = stats.hmean(sample[sample > 0])
print('Harmonic mean = ' + str(out))
# The mean, where values below -1 and above 1 are
# removed for the mean calculation
out = stats.tmean(sample, limits=(-1, 1))
print('\nTrimmed mean = ' + str(out))
# Calculating the skewness of the sample
out = stats.skew(sample)
print('\nSkewness = ' + str(out))
# Additionally, there is a handy summary function called
# describe, which gives a quick look at the data.
out = stats.describe(sample)
print('\nSize = ' + str(out[0]))
print('Min = ' + str(out[1][0]))
print('Max = ' + str(out[1][1]))
print('Mean = ' + str(out[2]))
print('Variance = ' + str(out[3]))
print('Skewness = ' + str(out[4]))
print('Kurtosis = ' + str(out[5]))
|
7f558cec0f059ff4ef7785f69874c3f34a9549aa | SelvorWhim/competitive | /Codewars/TriangleType.py | 430 | 4.28125 | 4 | def triangle_type(a, b, c):
""" return triangle type:
0 : if triangle cannot be made with given sides
1 : acute triangle
2 : right triangle
3 : obtuse triangle
"""
a,b,c = sorted([a,b,c]) # reduce redundancy in conditions
if a + b <= c:
return 0
a2,b2,c2 = (x*x for x in (a,b,c))
if a2 + b2 == c2:
return 2
if a2 + b2 < c2:
return 3
return 1
|
16ef9db1a3947f64e2e8b7f222727bc5ca7bd43e | wuqingze/leetcode | /0106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal/Solution.py | 949 | 3.75 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def tree(self,inorder,postorder,si,ei,sp,ep):
if si > ei or sp>ep:
return None
elif si == ei:
return TreeNode(inorder[si])
root = TreeNode(postorder[ep])
index = si
for i in range(si,ei+1):
if inorder[i] == postorder[ep]:
index = i
break
root.left = self.tree(inorder,postorder,si,index-1,sp,sp+(index-si)-1)
root.right = self.tree(inorder,postorder,index+1,ei,ep-ei+index,ep-1)
return root
def buildTree(self, inorder, postorder):
return self.tree(inorder,postorder,0,len(inorder)-1,0,len(postorder)-1)
s = Solution()
print(s.buildTree( [9,3,15,20,7],[9,15,7,20,3])) |
90444680fbd13f0e7d464336a08b60e17f367c59 | AshishBadgujar/my-python | /python projects/StrongPw.py | 329 | 4.03125 | 4 |
SECURE=(('s','$'),('and','&'),('a','@'),('o','0'),('i','1'))
def securePassword(password):
for a,b in SECURE:
password=password.replace(a,b)
return password
if __name__ == "__main__":
password=input("enter your password:")
password=securePassword(password)
print(f"Your secure password:{password}") |
b4d9d64f46522e916eee83a4acf1a22fa128c1a0 | monreyes/SelWebDriver | /PythonProj1/Sec8-Classes-ObjectOrientedProgramming/847-MethodOverriding/classdemo-inheritance2.py | 1,596 | 4.53125 | 5 | """
Class demo - inheritance 2 (method over riding)
"""
class Car(object): #base class
def __init__(self):
print("You just created the car instance")
def drive(self):
print("Car started...")
def stop(self):
print("Car stopped")
class BMW(Car):
def __init__(self):
Car.__init__(self)
print("You just created the BMW instance")
def drive(self): #overrides the parent method class
super(BMW, self).drive() #calling the base method class
print("You are driving a BMW, Enjoy...")
def headsup_display(self):
print("This is a unique feature")
class Toyota(BMW):
def __init__(self):
Car.__init__(self)
print("You just created the Toyota instance")
def drive(self): #overrides the parent method class
#super(Toyota, self).drive() #calling the parent method class BMW
#The above will print 'You are driving a BMW, Enjoy...'
print("You are driving a reliable car Toyota, go far...")
def headsup_display(self):
print("This is a diff feature - grandchild of Car,and child of BMW")
print("*"*25)
print("Printing parent class 'Car' attributes")
print("-/-"*10)
c = Car() #assigning parent class to a variable
c.drive()
c.stop()
print("*" * 25)
print("*" * 25)
print("Printing child class 'BMW' attributes")
print("-/-" * 10)
b = BMW()
b.drive()
b.stop()
b.headsup_display()
print("*" * 25)
print("*" * 25)
print("Printing child class 'Toyota' (child of BMW) attributes")
print("-/-" * 10)
t = Toyota()
t.drive()
t.stop()
t.headsup_display()
|
f4da1c3da39b36f6f00d018fe9e294770518bd05 | KChen89/Google-foobar | /Level_1/solution.py | 603 | 3.9375 | 4 | import math
def answer(n):
pass
def genPrimeN(n):
if n<5:
raise AssertionError('n cannot be smaller than 5')
primeStrSize=0
primeStr=''
num=1
while primeStrSize<n:
num+=1
if isPrime(num):
primeStr+=str(num)
primeStrSize+=len(str(num))
return primeStr[n-5:n]
def isPrime(n):
if n<2:
return False
for i in range(2, int(math.sqrt(n))+1):
if n%i==0:
return False
return True
def testPrime():
cnt=1
p=0
while p<10:
if isPrime(cnt):
p+=1
print(str(cnt))
cnt+=1
def testPrimeN(n):
print(genPrimeN(n))
if __name__ == '__main__':
# testPrime()
testPrimeN(4+5)
|
b369da4988030543fa993efae1e51cfb410709dd | bgr/project-euler | /p005.py | 148 | 3.5625 | 4 | # What is the smallest number divisible by each of the numbers 1 to 20?
divisors = [11,13,7,4,17,9,19,20]
print reduce(lambda a,b: a*b, divisors)
|
5ac8c80b3d3243eef9643783f72cae5aef0824e8 | sweec/leetcode-python | /src/UniqueBinarySearchTreesII.py | 1,185 | 3.625 | 4 | from Utility import TreeNode
class Solution:
# @return a list of tree node
def generateTrees(self, n):
if n < 1:
return [None]
if n == 1:
node = TreeNode(1)
return [node]
A = self.generateTrees(n-1)
for i in range(len(A)):
cur, j = A[i], 0
while cur:
node = self.copy(A[i])
A.append(node)
k = 0
while k < j:
node = node.right
k += 1
newNode = TreeNode(node.val)
newNode.left = node.left
newNode.right = node.right
node.val = n
node.left = newNode
node.right = None
cur = cur.right
j += 1
node = A[i]
while node.right:
node = node.right
node.right = TreeNode(n)
return A
def copy(self, root):
node = TreeNode(root.val)
if root.left:
node.left = self.copy(root.left)
if root.right:
node.right = self.copy(root.right)
return node |
3dca66bc3d0cd3cf4d8c65603dd4da46b7111cd4 | aakostarev/python-lessons | /lesson-4/task-3.py | 396 | 4.1875 | 4 | # Имя файла : task-3.py
# 3. Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21.
# Необходимо решить задание в одну строку.
# Подсказка: использовать функцию range() и генератор.
my_list = [a for a in range(20, 241) if a % 20 == 0 or a % 21 == 0]
print(my_list) |
c57a3fdc91f707786e87239b3739037a1f6ffd90 | sarmabhamidipati/UCD | /Specialist Certificate in Data Analytics Essentials/DataCamp/13-Machine_Learning_with_Tree-Based_Models_in_Python/e35_Evaluate_the_optimal_forest.py | 2,330 | 3.890625 | 4 | """
Evaluate the optimal forest
In this last exercise of the course, you'll evaluate the test set RMSE of grid_rf's optimal model.
The dataset is already loaded and processed for you and is split into 80% train and 20% test.
In your environment are available X_test, y_test and the function mean_squared_error from sklearn.metrics
under the alias MSE. In addition, we have also loaded the trained GridSearchCV object grid_rf that you
instantiated in the previous exercise. Note that grid_rf was trained as follows:
grid_rf.fit(X_train, y_train)
Instructions
100 XP
Import mean_squared_error as MSE from sklearn.metrics.
Extract the best estimator from grid_rf and assign it to best_model.
Predict best_model's test set labels and assign the result to y_pred.
Compute best_model's test set RMSE.
"""
# Import GridSearchCV
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error as MSE
# Import RandomForestRegressor
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv('bikes.csv')
# print(df.info())
df = df.dropna()
# print(df.info())
X = df.drop('cnt', axis=1)
y = df['cnt']
# print(X.head())
# print(y.head())
# Set seed for reproducibility
SEED = 1
# Split data into 80% train and 20% test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=SEED)
# Instantiate a random forests regressor 'rf'
rf = RandomForestRegressor(random_state=SEED)
# Define the dictionary 'params_rf'
params_rf = {'n_estimators': [100, 350, 500],
'max_features': ['log2', 'auto', 'sqrt'],
'min_samples_leaf': [2, 10, 30]
}
# Instantiate grid_rf
grid_rf = GridSearchCV(estimator=rf,
param_grid=params_rf,
scoring='neg_mean_squared_error',
cv=3,
verbose=1,
n_jobs=-1)
# Fit 'grid_rf' to the training set
grid_rf.fit(X_train, y_train)
# Extract the best estimator
best_model = grid_rf.best_estimator_
# Predict test set labels
y_pred = best_model.predict(X_test)
# Compute rmse_test
rmse_test = MSE(y_test, y_pred)**(1/2)
# Print rmse_test
print('Test RMSE of best model: {:.3f}'.format(rmse_test))
|
5e38dc0b0458fbb6f3678908ec06079da825331b | Hema113/python_puzzles | /timemsg.py | 550 | 3.90625 | 4 | # This program greets based on time
import time, firstname
# Function return current time
def get_time():
return time.strftime('%H')
# Greets the user based on current time
def greet_user(user_name = "Your Name"):
if int(get_time()) < 12:
print(firstname.firstname(user_name, "Good Morning"))
elif int(get_time()) > 12:
print(firstname.firstname(greeting_message = "Good Afternoon",name = user_name))
else:
print("Good Night")
if __name__ == "__main__":
greet_user("Jayanth Nagaraj")
# print(type(get_time()))
|
a84c9f60f1bcf25505f374c8be9659d4a2440e2f | jubileemarie/PYTHON_problem4 | /Problem4.py | 2,251 | 3.796875 | 4 | from math import *
import matplotlib.pyplot as plotting
import numpy as np
#inputs
h= float(input('Initial height of the projectile above the ground in meters: '))
v= float(input('Magnitude of the velocity in m/s: '))
Angled= float(input('The angle in degrees with respect to the +x-axis at which the projectile is fired: '))
ax= float(input('The acceleration in the x-component in m/s^2: '))
ay= float(input('The acceleration in the x-component in m/s^2: '))
#error for input
if h<0:
print('Invalid! Height cannot be less than 0')
elif v<0:
print('Invalid! Magnitude of the velocity cannot be equal to zero')
elif Angled < 0 or Angled > 180:
print('Invalid! Angle cannot be below 0 or above 180 degrees')
elif ay==0:
print('Invalid! Zero vertical acceleration indicates no free-fall')
else:
Angle = (Angled * pi/180)
#velocity with respect to x and y
vx = float(v*cos(Angle))
vy = float(v*sin(Angle))
#non-ideal motion
#using y=voy*t-(0.5*ay*(t^2) formula to get time
#assuming y is negative
#Using quadratic formula
A=-(0.5)*ay
B=vy
C=h
Time=max(np.roots([A,B,C]))
t=np.linspace(0,Time,10000000)
xnon= (vx*t)+(0.5)*(ax)*(t**2)
ynon= (vy*t)-(0.5)*(ay)*(t**2)+h
#ideal
#using y=voy*t-(0.5*ay*(t^2) formula to get time but Ay=9.8 and Ax=0
#assuming y is negative
#Using quadratic formula
a=-(0.5)*9.8
b=vy
c=h
time=max(np.roots([a,b,c]))
T=np.linspace(0,time,10000000)
Xideal = (vx*T) #when in ideal motion, ax=0
Yideal = (vy*T)-(0.5)*(9.8)*(T**2)+h #when in ideal motion, ay=9.8
#Plotting the derived formulas
plotting.subplot(1,2,1)
plotting.axis('equal')
plotting.plot(Xideal,Yideal, 'b') #plots of an ideal motion
plotting.xlabel("Distance in X")
plotting.ylabel("Distance in Y")
plotting.title('Ideal trajectory')
plotting.grid()
plotting.subplot(1,2,2)
plotting.axis('equal')
plotting.plot(xnon,ynon,'r') #plot of a non-ideal motion
plotting.xlabel("Distance in X")
plotting.ylabel("Distance in Y")
plotting.title('Non-ideal trajectory')
plotting.grid()
plotting.show() |
600f5ff805c71e0ea3635ffa8e5ac11b81593c72 | pangfeiyo/PythonLearn | /甲鱼python/课程代码/第40讲/一些相关的BIF.py | 3,035 | 4.28125 | 4 | # BIF 内置函数
# 跟类与对象相关的BIF
'''
issubclass(class, classinfo)
如果 class 是 classinfo 的子类,返回True
'''
# 注意点:
# 1.一个类被认为是其自身的子类
# 2.classinfo可以是类对象组成的元组,只要class与其中任何一个候选类的子类,则返回Ture
class A:
pass
class B(A):
pass
class C:
pass
print(issubclass(B,A))
print(issubclass(B,B))
# object 是所有类的基类,所有类 无论有没有写 class A(object),都是默认继承于object
print(issubclass(B,object))
print(issubclass(B,C))
'''
isinstance(object, classinfo)
检查一个实例对象是否属于一个类
传入一个实例对象,传入一个类
这里同样可以传入元组
'''
# 注意点:
# 1.如果第一个参数不是对象,则永远返回False
# 2.如果第二个参数不是类或由类对象组成的元组,会抛出一个TypeError异常
print("\n-- isinstance(object, classinfo)")
print(isinstance(B,C))
b1 = B()
print(isinstance(b1,B))
# 这里为什么为True,因为B类是继承A类的
print(isinstance(b1,A))
print(isinstance(b1,(A,B,C)))
'''以下是访问对象的属性'''
'''
hasattr(object, name)
测试一个对象里是否有指定的属性
'''
# attr = attribute 属性
# object 对象名, name 属性名
# name 必须要 "" 或 '' 括起
print("\n-- hasattr(object, name)")
class C:
def __init__(self, x = 0):
self.x = x
c1 = C()
print(hasattr(c1,'x'))
'''
getattr(object, name[, default])
返回对象指定的属性的值
'''
# 如果指定的属性不存在,会抛出一个异常AttributeError
# 如果设定了 default , 异常时会打印default的内容
print("\n-- getattr(object, name[, default])")
print(getattr(c1,'x'))
#print(getattr(c1,'y'))
print(getattr(c1,'y','你所搜索的属性不存在'))
'''
setattr(object, name, value)
设定对象中指定属性的值,如果属性不存在,则会新建这个属性并赋值
'''
print("\n-- setattr(object, name, value)")
setattr(c1,'y','FishC')
print(getattr(c1,'y','您搜索的不存在'))
'''
delattr(object, name)
删除对象是指定的属性,如果不存在则抛出异常AttributeError
'''
delattr(c1,'y')
#delattr(c1,'y') # 二次删除就会抛出异常了
print(hasattr(c1,'y')) # 查找是否存在
'''
property(fget=None, fset=None, fdel=None, doc=None)
通过属性来设置属性
'''
# fget 获取属性, fset 设置属性, fdel 删除属性, doc
print("\n-- property(fget=None, fset=None, fdel=None, doc=None)")
class C:
def __init__(self, size = 10):
self.size = size
def getSize(self):
return self.size
def setSize(self, value):
# 让用户设置这个属性
self.size = value
def delSize(self):
del self.size
x = property(getSize, setSize, delSize)
c1 = C()
# 获取c1里的size值,按以前的方法
print(c1.getSize())
# 用propetry之后
print(c1.x)
# 修改值
c1.x = 18
print(c1.x)
# 删除
del c1.x
#print(c1.x) # 被删除了这里会找不到 |
28f6c6de661390821962bb153b03bc4c6900675e | panda-sas/python-basic-coding-exercises | /String operations/main.py | 375 | 4.40625 | 4 | # accepts the user's first and last name and print them in reverse order with a space between them by slicing
f_name = "Jim"
l_name = "Bond"
# print(l_name[::-1] + " " + f_name[::-1])
# using for loop
first_name = ""
last_name = ""
for i in f_name:
first_name = i + first_name
for j in l_name:
last_name = j + last_name
print(first_name + " " + last_name)
|
b262a402c602a4685a991a774c0aebb54955c165 | Boberkraft/Data-Structures-and-Algorithms-in-Python | /chapter4/C-4.20.py | 1,178 | 3.890625 | 4 | """
Given an unsorted sequence, S, of integers and an integer k, describe a
recursive algorithm for rearranging the elements in S so that all elements
less than or equal to k come before any elements larger than k. What is
the running time of your algorithm on a sequence of n values?
i coud sort -> n log n
or create 2 list and append new numbers to them. At the end merging them
ok i have new idea.
Have 2 searchers that search from left and right
if left searcher finds number >= k,
he starts right searcher thats returns to him index of num lesser than k
every my
"""
def _solve(seq, k, left, right):
if left < right:
if seq[left] >= k:
if seq[right] < k:
# swap
seq[left], seq[right] = seq[right], seq[left]
else:
# move right searcher to left and try again
_solve(seq, k, left, right - 1)
return # end live here
# nothing to swap
_solve(seq, k, left + 1, right)
def solve(seq, k):
_solve(seq, k, 0, len(seq)-1)
if __name__ == '__main__':
data = list(range(10,0, -1))
print(data)
solve(data, 5)
print(data)
|
3c57b13151d0e4d5ada7b6d5320b3ead0dad906b | Mo-zj/Leecode | /code2_answer.py | 2,955 | 3.671875 | 4 | # 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
# 请你将两个数相加,并以相同形式返回一个表示和的链表。
# 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class SingleLink(object):
def __init__(self,node=None):
self._head = node
# 头插法
def add(self,item):
listnode = ListNode(item)
listnode.next = self._head
self._head = listnode
# 把列表转换为链的数据结构,尾插法
def append2(self,item):
listnode = ListNode(item)
if self._head == None:
self._head = listnode
else:
cur = self._head
while cur.next != None:
cur = cur.next
cur.next = listnode
# 遍历链表
def tranvel(self):
cur = self._head
while cur != None:
print(cur.val,end=" ")
cur = cur.next
def list_to_link(self, li):
sl = SingleLink()
for i in li:
sl.append2(i)
return sl
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# 先建立一个头节点
head = point = ListNode(0)
carry = 0 # 进位
while l1 or l2:
new_point = ListNode(0)
if not l1:
sum_ = l2.val + carry
new_point.val = sum_%10
carry = sum_ // 10
l2 = l2.next
elif not l2:
sum_ = l1.val + carry
new_point.val = sum_%10
carry = sum_//10
l1 = l1.next
else:
sum_=(l1.val + l2.val + carry)
new_point.val = sum_%10
carry = sum_ // 10
l1 = l1.next
l2 = l2.next
point.next = new_point
point = point.next
"""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = curr = ListNode()
carry = 0
while l1 or l2:
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = x + y + carry
curr.next = ListNode(sum % 10)
## bug 修复:视频中忘了移动 curr 指针了
urr = curr.next
carry = sum // 10
if l1: l1 = l1.next
if l2: l2 = l2.next
if carry: curr.next = ListNode(carry)
return dummy.next
"""
if __name__ == "__main__":
list1 = [1,2,3,4]
list2 = [5,6.7,8]
s1 = SingleLink()
sl1 = s1.list_to_link(list1)
s2 = SingleLink()
sl2 = s2.list_to_link(list2)
so = Solution()
res = so.addTwoNumbers(sl1,sl2)
|
0a23f3dd82ce8a3a2e388fa6f5929da15e938333 | ElaineBalgos/Balgos_E_PhythonHW | /gameFunctions/winlose.py | 1,083 | 3.890625 | 4 | from random import randint
from gameFunctions import gameWars
# define a python function that takes an argument
def winorloose(status):
# status either won or lost - you're passing this is as an argument
print("***********************************")
print("********* R P S G a m e *********")
print("***********************************")
print("You", status,"! Would like to play again?")
choice = input ("Y / N: ")
print(choice)
if (choice is "N") or (choice is "n"):
print("You choose to quit.")
exit()
elif (choice is "Y") or (choice is "y"):
# reset the game so that we can start all over again
# global player_lives
# global computer_lives
# global player
# global computer
# global choices
gameWars.player_lives = 1
gameWars.computer_lives = 1
gameWars.total_lives = 1
gameWars.player = False
gameWars.computer = gameWars.choices[randint(0,2)]
else:
# use recursion to call winotlose again until we get the right input
# recursion is just a fancy way to describe calling a function from within itself
winlose.winorlose(status) |
7f6500f15135f27ddcde1ac4c7f569f83411165a | dmi3s/stepik-512-py | /stings1.py | 625 | 3.625 | 4 | def task(s, a, b):
count_ = 0
while count_ < 1000:
if a not in s:
return count_
s = s.replace(a, b)
count_ += 1
return None
def main():
s, a, b = input(), input(), input()
answer = task(s, a, b)
if answer is not None:
print(answer)
else:
print("Impossible")
main()
def test_task():
tasks = [
("abab", "ab", "ba", 2),
("ababa", "a", "b", 1),
("ababa", "b", "a", 1),
("ababa", "c", "c", 0),
("ababac", "c", "c", None)
]
for s, a, b, answer in tasks:
assert task(s, a, b) == answer
|
f9029dc946bf3a133b2252253f6dd7d1ad1aed27 | 109156247/C109156247 | /44.py | 211 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 7 21:54:45 2021
@author: xl
"""
M=int(input())
D=int(input())
S=(M*2+D)%3
if S==0:
print("普通")
elif S==1:
print("吉")
elif S==2:
print("大吉") |
d8f94285197104b0171469c20b12c0cffa25eb13 | Karenahv/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/6-baum_welch.py | 870 | 3.53125 | 4 | # !/usr/bin/env python
"""The Baum-Welch Algorithm
"""
def baum_welch(Observations, N, M,
Transition=None,
Emission=None, Initial=None):
"""Function that performs the
Baum-Welch algorithm for a hidden markov model
Args:
Observation: is a numpy.ndarray
of shape (T,) that contains the index of
the observation
T: is the number of observations
N: is the number of hidden states
M: is the number of possible observations
Transition: is the initialized
transition probabilities, defaulted to None
Emission: is the initialized
emission probabilities, defaulted to None
Initial: is the initiallized
starting probabilities, defaulted to None
Returns: the converged Transition,
Emission, or None, None on failure
"""
|
f4c718f6c278d7e13bc8ee3bc33c75b538c19554 | linus106/leetcode_python3 | /Q0019.py | 698 | 3.859375 | 4 | from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
pDelete = pTail = head
for i in range(n):
pTail = pTail.next
if pTail is None:
return head.next
while pTail.next is not None:
pTail = pTail.next
pDelete = pDelete.next
pDelete.next = pDelete.next.next
return head
if __name__ == "__main__":
result = Solution().removeNthFromEnd([-5,-4,-3,-2,1,3,3,5],
-11)
print(result)
|
14f4a9b04a5fe3d592f75c70a66984df70989977 | sumati-kulkarni/Teaching-Material-SENG-1000-Software-Engineering-Foundations-and-Practice | /Lecture10 Errors and Exceptions/exceptions/t5.py | 909 | 4.03125 | 4 | #raise SomeExceptionClas("Error message describing cause of the error")
def factorial(n):
try:
if not isinstance(n, int):
raise RuntimeError("Argument must be int")
if n < 0:
raise RuntimeError("Argument must be >= 0")
f = 1
for i in range(n):
f *= n
n -= 1
return f
except RuntimeError:
return "Invalid Input"
print("Factorial of 4 is:", factorial(4))
print("Factorial of 12 is:", factorial("12"))
def factorial(n):
if not isinstance(n, int):
raise RuntimeError("Argument must be int")
if n < 0:
raise RuntimeError("Argument must be >= 0")
f = 1
for i in range(n):
f *= n
n -= 1
return f
try:
print("Factorial of 4 is:", factorial(4))
print("Factorial of 12 is:", factorial("12"))
except RuntimeError as e:
print("Error:", e) |
341e5e6abc27fc11785ab31e2c21dbba7e80856e | matteobolner/python-programming | /exercises/27_11_python_programming_exercises/solutions/sol_002.py | 804 | 4.03125 | 4 | #1
var1 = "fire and ice"
#2
print(var1[2])
#3
print(var1[5])
#4
print(var1[9],var1[-1],var1[-2])
#5 this script prints the even-numbered characters of a given string
odds = var1[1::2]
for elements in odds:
print(elements)
#6 this one prints odd characters
odds = var1[0::2]
for elements in odds:
print(elements)
#7
print(var1[0:len(var1)//2])
#8
var1 = "fire and ice"
print(var1[-1::-1])
#9
print(var1.count("i"))
print(var1.count("e"))
#10
var1 = "fire and ice"
var1.replace("and", "&")
#11
if "fire" in var1:
print("yes,fire")
#12
if "re and" in var1:
print("yes, re and")
#13
if "re &" in var1:
print("yes, re &")
#14
print(var1.index("e"))
#15
print(var1.rindex("e"))
#16
var2 = "234 4329 7654 8923"
var2_fixed = var2.replace(" ","")
for number in var2_fixed :
print(int(number) +3)
|
f14586d7e7625e3e471caa4a2745d97b1b969cd4 | nuydev/my_python | /multiplication.py | 300 | 3.953125 | 4 | #โปรแกรมสูตรคูณ
start1 = int(input("ป้อนแม่สูตรคูณ :"))
start2 = int(input("ป้อนแม่สูตรคูณ :"))
for x in range(start1,start2):
print("แม่ = ",x)
for y in range(1,13):
print(x,"x",y," = ",(x*y)) |
9ca107c537230e65ec61e4af043adde38c977a7e | green-fox-academy/nandormatyas | /week-03/day-02/reversed_order.py | 233 | 4.125 | 4 | def reverse_lines(filename):
fopen = open(filename)
fread = fopen.readlines()
ordered = " "
for i in fread[::-1]:
ordered += i
print(ordered)
filename = input('File? ')
reverse_lines(filename)
|
7c4d987ee1bae29fd3f18a0e2bc0ab3a8a6e9698 | zdyxry/LeetCode | /depth_first_search/0200_number_of_islands/0200_number_of_islands.py | 818 | 3.546875 | 4 |
class Solution(object):
def numIslands(self, grid):
if grid is None or len(grid) is 0:
return 0
numIslands = 0
for y in range(len(grid)):
for x in range(len(grid[y])):
if (grid[y][x] == "1"):
numIslands += self.dfs(grid, y, x)
return numIslands
def dfs(self, grid, y, x):
if ((y < 0) or (y >= len(grid)) or (x < 0) or (x > len(grid[y])) or (grid[y][x] == "0")):
return 0
grid[y][x] = "0"
self.dfs(grid, y - 1, x,)
self.dfs(grid, y + 1, x,)
self.dfs(grid, y, x - 1)
self.dfs(grid, y, x + 1)
return 1
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
res = Solution().numIslands(grid)
print(res)
|
c68f0818eda1b5dcd5bef8ca8fd2120ff8fdfefd | raviMukti/training-python-basic | /src/ElIfStatement.py | 280 | 3.984375 | 4 | # Belajar ElIf
menuPilihan = input("Silakan Pilih Menu 1-3 : ")
if menuPilihan == "1":
print("Anda Memilih Menu 1")
elif menuPilihan == "2":
print("Anda Memilih Menu 2")
elif menuPilihan == "3":
print("Anda Memilih Menu 3")
else:
print("Maaf Menu Tidak Tersedia") |
c53c3411e3716227700b50d536968b80d3b7043a | mwong33/leet-code-practice | /medium/path_sum_2.py | 1,207 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# O(n^2) O(h) space where h is the height of the tree and n is the number of nodes
def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
return self.dfs(root, targetSum, 0)
def dfs(self, root, target_sum, current_sum):
if root == None:
return []
current_sum += root.val
# Base Case
if root.left == None and root.right == None:
if current_sum == target_sum:
return [[root.val]]
else:
return []
left_result = self.dfs(root.left, target_sum, current_sum)
right_result = self.dfs(root.right, target_sum, current_sum)
for index in range(len(left_result)):
left_result[index] = [root.val] + left_result[index]
for index in range(len(right_result)):
right_result[index] = [root.val] + right_result[index]
return left_result + right_result
|
a55614bc4e6679b1beb87a454de54a1e8e78d0ba | Archanaaarya/function | /mirakia_question_5_part_1_code.py | 347 | 3.703125 | 4 | # Question (Part 1)
# check_numbers naam ka ek function likhiye jo do numbers le aur fir print kare "Dono even hain" agar dono numbers even (2 se divide hote hain) nahi toh print kare "Dono numbers even nahi hai"
def check_numbers(num1,num2):
if num1%2==0 and num2%2==0:
print("dono number even hai")
check_numbers(12,34)
|
471e6980fdbf5a66294dc6a111b4594e4fe487ba | chelseashin/TIL | /algorithm/day05/연습1_reverse.py | 426 | 3.75 | 4 | def my_strrev(ary): # ary : 'abcde'
str = list(ary) # str = ['a', 'b', 'c', 'd', 'e']
for i in range(len(str//2)): # 2로 나눈 몫
t = ary[i]
str[i] = str[len(str)-1-i] # 3
str[len(ary) - 1 - i] = t
ary = "".join(str)
return ary
ary = "abcde"
# print(list(ary))
# print(len(str//2))
ary = my_strrev(ary)
print(ary)
s = "Reverse this strings"
s = s[-1:0:-1]
print(s) |
9ad4f1151aeef828d2efbcbb746a14b344301f27 | subreena10/list | /minimumelement.py | 199 | 3.84375 | 4 | numbers = [50,2, 40, 23, 70, 56, 12, 5, 10, 7]
index=0
min=numbers[index]
for n in numbers:
if n<min:
min=n
print(min)
# numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7]
# print(min(numbers))
|
743388f122fd90401a5321946f8c23ae15a184d7 | rhu-script/RH_Exams | /csv_import.py | 5,812 | 3.90625 | 4 | #!/usr/bin/python2.7
## This Script is to read CSV File and process the records to be imported into db.
##
## Author: Ahmed Sammoud
## Date: June, 2016
##
## Company: Red Hat, Red Hat University , Intern_Team_2016
##
## Description :
## - This Script main purpose is to read in ".csv" file and extract the needed information for data analysis.
## - The Script runs in three phases:
## -- 1- It uses the csv package and start reading Rows from the file in the Starter module.
## -- 2- It uses the Extract_Info function to extract the needed info from columns in each row.
## -- 3- The Process_Data function is used to :
## 1- clean up the data from each columns
## 2-populate the needed data structures.
## --
## -- Starter --> Extract_Info --> Process_Data
##
import csv
import re
import logging
import pprint
class CSV_Import:
# A function that selects only the needed Columns and puts it in a new list.
def __init__(self, filename="test_data.csv", perm='rb'):
# Open CSV File
CSV_F = open(filename, perm)
if perm == 'rb':
# Starting the reader, One Row at a time. Puts it into a list.
self.Reader = csv.reader(CSV_F)
self.Reader.next() # skip header rows
self.Reader.next() # skip header rows
else:
# Starting the Writer
self.Writer = csv.writer(CSV_F)
# Setting name for logger information
self.logger = logging.getLogger('___CSV_IMPORT__')
self.logger.debug("CSV_Import intiailized")
def __Extract_Data__(self, Row):
Info = {} # list of values from csv
## Data Format in the Exam .csv file
## Entries in order (Col) :: Info (Notes)
## - Exam Name (A - 0) :: Strings no Exam code.
## - Duration (C - 2) :: In Minutes
## - Examinee name (D - 3) :: Whole String (First M Last)
## - Examinee email (E - 4) :: email (Tag if redhat email)
## - Status of Exam (F - 5) :: Status on how test go (completed,Error,No Show) (Not Scores)
## - Country (G - 6) :: Country Name
## - Site / Office (H - 7) :: Site Name (Include info such as: Employees only, Retired, City Name, On KoaLA )
## - Date of Test (K -10) :: Date (There are 3 Date columns, I choose K since its more consisted: Extract Month,Year)
## Data Dictionary Key : entries
## Exam : Exam Name
## Duration : time In Minutes
## Name : Examinee Name
## Email : Examinee Email
## RedHat : True or False
## Status : Completed, System_Error, No Show
## Country : Conuntry of Test Location
## City : City of Location -- Not Always Available
## Site : Office Name
## Site_Info : Employees Only/Retired
## KoaLa : True/False
## Date : {month,day,year}
Info["Exam"] = str(Row[0].strip())
Info["Duration"] = str(Row[2].strip())
Info["Name"] = str(Row[3].strip())
Info["Email"] = str(Row[4].strip())
# This needs some review, since Only checks for RedHat emails.
Info["RedHat"] = False if re.search('[a-zA-Z0-9_.]*@redhat.com', Info["Email"]) == None else True
Info["Status"] = str(Row[5].strip())
Info["Country"] = str(Row[6].strip())
if "employees only" in str(Row[7].strip().lower()):
Info["Site_Info"] = "Employees Only"
elif "retired" in str(Row[7].strip().lower()):
Info["Site_Info"] = "Retired"
else:
Info["Site_Info"] = "N/A"
## There are a lot of cases with this field
## This is Might start with:
## Employees Only: Red Hat- City -KOALA, Empoyees Only: Red Hat -Office - City - KOALA,or Employees Only: City
Site = str(Row[7].strip())
Info["test"] = Site
if Site.startswith("Employees Only".upper()):
Info["Site"] = "Red Hat"
if "KOALA" in Site:
Info["City"] = re.search('(?<=-)[\s\w-]*(?=-KOALA)', Site).group(0) if re.search(
"(?<=-)[\s\w-]*(?=-KOALA)", Site) is not None else "N/A"
else:
Info["City"] = re.search('(?<=-)[\s\w-]*', Site).group(0)
## Else examples : Office - City or Office - City - KOALA or Office
else:
Info["Site"] = re.search('[\w|\D]*(?=-)*', Site).group(0)
if re.search('(?<=-)[\s\w]*(?=KOALA)*', Site) != None:
Info["City"] = re.search('(?<=-)[\s\w]*(?=KOALA)*', Site).group(0)
else:
Info["City"] = "N/A"
# Is This test on a KOALA ?
Info["KoaLA"] = False if re.search('[a-zA-Z0-9_.-]*KOALA', Site) is None else True
# Extract Date .
datetmp = re.search('\d*/\d*/\d*', Row[10].strip()).group(0).split("/")
month = datetmp[0]
day = datetmp[1]
year = datetmp[2]
Info["Date"] = dict(month=month, day=day, year=year)
return Info
def getlist(self):
list = []
for Row in self.Reader:
if len(Row) > 0:
Info = self.__Extract_Data__(Row)
list.append(Info)
return list
def store_Rows(self, Rows):
for Row in Rows:
self.Writer.writerow(Row)
def store_Row(self, Row):
self.Writer.writerow(Row)
'''
T = CSV_Import("test.csv")
list = T.getlist()
P = pprint.PrettyPrinter()
P.pprint(list)
'''
|
c84c4a139a1628171332258d5b89f7f16d9a41d4 | TheoLiapikos/MSc_projects | /1o Εξάμηνο/Μηχανική Μάθηση/Εργασίες/Εργασία 5 - Neural Networks/Project A/NN_Template.py | 5,210 | 3.96875 | 4 | # =============================================================================
# HOMEWORK 5 - NEURAL NETWORKS
# MULTI-LAYER PERCEPTRON ALGORITHM TEMPLATE
# Complete the missing code by implementing the necessary commands.
# For ANY questions/problems/help, email me: arislaza@csd.auth.gr
# =============================================================================
# From sklearn, we will import:
# 'datasets', for loading data
# 'model_selection' package, which will help validate our results
# 'metrics' package, for measuring scores
# 'neural_network' package, for creating and using a Multi_layer Perceptron classfier
# 'preprocessing' package, for rescaling ('normalizing') our data
from sklearn import
# Load breast cancer dataset.
myData =
# Store features and target variable into 'X' and 'y'.
X =
y =
# The function below will split the dataset that we have into two subsets. We will use
# the first subset for the training (fit) phase, and the second for the evaluation phase.
# By default, the train set is 75% of the whole dataset, while the test set makes up for the rest 25%.
# 'random_state' parameter should be fixed to a constant integer (i.e. 0) so that the same split
# will occur every time this script is run.
x_train, x_test, y_train, y_test = model_selection.train_test_split(X, y, random_state = 0)
# Neural Networks are sensitive to the magnitudes of the features' values. Since we already
# split our dataset into 'train' and 'test' sets, we must rescale them separately (but with the same scaler)
# So, we rescale train data to the [0,1] range using a 'MinMaxScaler()' from the 'preprocessing' package,
# from which we shall then call 'fit_transform' with our data as input.
# Note that, test data should be transformed ONLY (not fit+transformed), since we require the exact
# same scaler used for the train data.
# =============================================================================
minMaxScaler =
x_train =
x_test =
# =============================================================================
# It's time to create our classfier- 'MLPClassifier'. There are several hypermarameters
# that one could adjust in this case, such as:
# hidden_layer_sizes: A tuple, the length of which determines the number of hidden layers
# in the network, and the value at each hidden layers corresponds to
# the number of hidden units (neurons) within that layer.
# (e.g. hidden_layer_sizes = (10,10,8) means 3 hidden layers-
# 1st layer with 10 neurons, 2nd layer with 10 neurons, and 3rd
# layer with 8 neurons).
# activation: This is the activation function used for the neural network. Can be
# 'identity', 'logistic', 'tanh' or 'relu'. Most common activation function
# for deep neural networks is 'relu'.
# solver: This is the solver used for weight optimization. Available solvers in sklearn
# are 'lbfgs' (Limited-memory Broyden–Fletcher–Goldfarb–Shanno (L-BFGS) algorithm),
# 'sgd' (Stochastic gradient descent) and 'adam' (just adam). Default is 'adam', which
# is better for large datasets, whereas 'lbfgs' converges faster and performs better
# on small datasets.
# max_iter: Maximum number of iterations that shall determine that end of the algorithm if
# no convergence (i.e. 'tolerance') has been reached until that point.
# tol: A small number that determines whether the loss function has converged to a
# point at which the iterations can terminate (tolerance).
# Unfortunately, the default and only loss function supported by sklearn is Cross-Entropy, so
# we cannot make this type of adjustment.
# =============================================================================
# ADD COMMAND TO CREAETE MLPCLASSIFIER HERE
model =
# =============================================================================
# Let's train our model.
# =============================================================================
# ADD COMMAND TO TRAIN MODEL HERE
# =============================================================================
# Ok, now let's predict output for the second subset
# =============================================================================
# ADD COMMAND TO MAKE PREDICTION HERE
y_predicted =
# =============================================================================
# Time to measure scores. We will compare predicted output (from input of x_test)
# with the true output (i.e. y_test).
# You can call 'recall_score()', 'precision_score()', 'f1_score()' or any other available metric
# from the 'metrics' library.
# The 'average' parameter is used while measuring metric scores to perform
# a type of averaging on the data. Use 'macro' for final results.
# =============================================================================
# ADD COMMANDS TO COMPUTE METRICS HERE
print()
print()
print()
# ============================================================================= |
57714e8fce003d9d0e4d91c7b36a17dc84b90eb4 | Pranjal-Lotankar/Python-Assignment-Submission | /ticTacToe.py | 6,223 | 3.59375 | 4 | # A simple graphical Calculator Application in Python
from itertools import permutations
from itertools import combinations
from graphics import *
def getRes():
# generate all the winning combinations and store in an array
resArr = []
seq = permutations(['7', '8', '9'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['6', '5', '4'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['3', '2', '1'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['1', '4', '7'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['2', '5', '8'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['3', '6', '9'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['1', '5', '9'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
seq = permutations(['3', '5', '7'])
for p in list(seq):
tt = ''.join(p)
resArr.append(tt)
return resArr
def check(clkvals, rescombs):
playArr = []
combi = permutations(clkvals, 3)
# generate all the combinations of boxes clicked by a player
for c in list(combi):
tt = ''.join(c)
playArr.append(tt)
# compare the player's combinations with all the winning combinations
for p in playArr:
if (p in rescombs):
# return true if a combination matches a winning combination
return True
def main():
# generate all the winning combinations and store in an array
rescombs = getRes()
# define window for the game board
workArea = GraphWin('TicTacToe', 300, 350) # give title and dimensions
workArea.setBackground('yellow')
# horizontal lines
ln = Line(Point(10, 100), Point(280, 100))
ln.setWidth(3)
ln.draw(workArea)
ln = Line(Point(10, 190), Point(280, 190))
ln.setWidth(3)
ln.draw(workArea)
# vertical lines
ln = Line(Point(100, 10), Point(100, 280))
ln.setWidth(3)
ln.draw(workArea)
ln = Line(Point(190, 10), Point(190, 280))
ln.setWidth(3)
ln.draw(workArea)
# variables
arrf = []
arrt = []
cnt1 = 0
cnt2 = 0
x = 10
y = 10
i = 0
j = 8
p1 = [' ']
p2 = [' ']
pl = "X"
# loop to store boundaries
while j >= 0:
arrf.append(Point(x, y))
arrt.append(Point(x + 90, y + 90))
x = x + 90
j = j - 1
i = i + 1
if (i == 3):
x = 10
y = y + 90
i = 0
clk = True
numv = ""
t1 = Text(Point(1, 1), p1)
t2 = Text(Point(1, 1), p1)
finres = False
cnt = 1
inBox = False
mid = Point(0, 0)
# loop to check the range of coordinates where user clicked
while cnt <= 9:
ch = workArea.getMouse()
if (ch.x > arrf[0].x and ch.x < arrt[0].x and ch.y > arrf[0].y and ch.y < arrt[0].y):
numv = "9"
mid = Point(arrf[0].x + 45, arrf[0].y + 45)
inBox = True
if (ch.x > arrf[1].x and ch.x < arrt[1].x and ch.y > arrf[1].y and ch.y < arrt[1].y):
numv = "8"
mid = Point(arrf[1].x + 45, arrf[1].y + 45)
inBox = True
if (ch.x > arrf[2].x and ch.x < arrt[2].x and ch.y > arrf[2].y and ch.y < arrt[2].y):
numv = "7"
mid = Point(arrf[2].x + 45, arrf[2].y + 45)
inBox = True
if (ch.x > arrf[3].x and ch.x < arrt[3].x and ch.y > arrf[3].y and ch.y < arrt[3].y):
numv = "6"
mid = Point(arrf[3].x + 45, arrf[3].y + 45)
inBox = True
if (ch.x > arrf[4].x and ch.x < arrt[4].x and ch.y > arrf[4].y and ch.y < arrt[4].y):
numv = "5"
mid = Point(arrf[4].x + 45, arrf[4].y + 45)
inBox = True
if (ch.x > arrf[5].x and ch.x < arrt[5].x and ch.y > arrf[5].y and ch.y < arrt[5].y):
numv = "4"
mid = Point(arrf[5].x + 45, arrf[5].y + 45)
inBox = True
if (ch.x > arrf[6].x and ch.x < arrt[6].x and ch.y > arrf[6].y and ch.y < arrt[6].y):
numv = "3"
mid = Point(arrf[6].x + 45, arrf[6].y + 45)
inBox = True
if (ch.x > arrf[7].x and ch.x < arrt[7].x and ch.y > arrf[7].y and ch.y < arrt[7].y):
numv = "2"
mid = Point(arrf[7].x + 45, arrf[7].y + 45)
inBox = True
if (ch.x > arrf[8].x and ch.x < arrt[8].x and ch.y > arrf[8].y and ch.y < arrt[8].y):
numv = "1"
mid = Point(arrf[8].x + 45, arrf[8].y + 45)
inBox = True
# put point
if inBox:
txt = Text(mid, pl)
txt.setSize(36)
txt.draw(workArea)
inBox = False
cnt = cnt + 1
# change symbol of the current player and check result
if pl == "X":
p1.append(numv)
if len(p1) >= 3:
finres = check(p1, rescombs)
if finres:
t1 = Text(Point(workArea.getWidth() / 2, 320), "Player " + pl + " wins")
t1.setSize(20)
t1.setTextColor("red")
t1.draw(workArea)
clk = False
break
pl = "O"
else:
cnt2 += 1
p2.append(numv)
if len(p2) >= 3:
finres = check(p2, rescombs)
if finres:
t1 = Text(Point(workArea.getWidth() / 2, 320), "Player " + pl + " wins")
t1.setSize(20)
t1.setTextColor("red")
t1.draw(workArea)
clk = False
break
pl = "X"
# If game is draw
if clk:
t1 = Text(Point(workArea.getWidth() / 2, 320), "Game Draw")
t1.setSize(20)
t1.setTextColor("red")
t1.draw(workArea)
main() |
93f60c9bd5dd4b130dba2cbc431abd55c5691bef | greatertomi/problem-solving | /hackerrank-challenges/easy2/anagram.py | 669 | 3.71875 | 4 | # Problem Link: https://www.hackerrank.com/challenges/anagram/problem
def anagram(string):
length = len(string)
if length % 2 == 1:
return -1
part1 = list(string[:length//2])
part2 = list(string[length//2:])
count = 0
for val in part1:
if val in part2:
index = part2.index(val)
del part2[index]
else:
count += 1
return count
string1 = 'aaabbb'
string2 = 'ab'
string3 = 'abc'
string4 = 'mnop'
string5 = 'xyyx'
string6 = 'xaxbbbxx'
print(anagram(string1))
print(anagram(string2))
print(anagram(string3))
print(anagram(string4))
print(anagram(string5))
print(anagram(string6))
|
c774e93fc0dd15fbaa62ea23722fcdc97d449fe5 | NickG-NZ/PyQubed-GNC | /TRIAD/py_funcs/deterministic_ad.py | 943 | 3.5 | 4 | import numpy as np
def triad_ad(M, V):
"""
Computes rotation matrix from inertial to body frame using measurement vectors and modelled measurement vectors
Inputs:
M - Matrix where each column is a measurement vector in the body frame - Note, most accurate measurement should be in the first column
V - Matrix where each column is a modeled vector of the corresponding measurement vector from M, in the inertial frame
Outputs:
R - rotation matrix from inertial to body frame
"""
assert M.shape[0] == V.shape[0] == 3, "Either M or V vectors aren't length 3"
if M.shape[1] == 2 and V.shape[1] == 2:
m2 = np.cross(M[:, 0], M[:, 1])
m3 = np.cross(M[:, 0], m2)
v2 = np.cross(V[:, 0], V[:, 1])
v3 = np.cross(V[:, 0], v2)
R = np.column_stack((M[:, 0], m2, m3)) @ np.linalg.inv(np.column_stack((V[:, 0], v2, v3)))
else:
R = M @ np.linalg.inv(V)
return R |
09491268d4f8bf7657a78f643c403626e2bd0e8a | txjzwzz/leetCodeJuly | /Majority_Element_II.py | 1,762 | 3.8125 | 4 | #-*- coding=utf-8 -*-
__author__ = 'zz'
"""
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
思路仍然是Majority Element的思路,进行削减。但是要在之后进行一次搜索,看看是否满足出现次数的限制
有时候有些事情不是要一次全部搞定的
"""
class Solution:
# @param {integer[]} nums
# @return {integer[]}
def majorityElement(self, nums):
if not nums:
return []
res = []
a, b, countA, countB = 0, 0, 0, 0
for i in nums:
if i == a:
countA += 1
elif i == b:
countB += 1
elif countA == 0 :
countA += 1
a = i
elif countB == 0:
countB += 1
b = i
else:
countA -= 1
countB -= 1
countA, countB = 0, 0
for i in nums:
if i == a:
countA += 1
elif i == b:
countB += 1
if countA > len(nums) / 3:
res.append(a)
if countB > len(nums) / 3:
res.append(b)
return res
if __name__ == '__main__':
nums1 = [1]
nums2 = [1, 2]
nums3 = [1, 1, 2, 2, 3, 3]
nums4 = [1, 1, 1, 1, 2, 2, 3, 3, 3, 3]
nums5 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
nums6 = [1, 2, 3, 4, 3, 2, 1, 3, 2, 3, 2]
solution = Solution()
print solution.majorityElement(nums1)
print solution.majorityElement(nums2)
print solution.majorityElement(nums3)
print solution.majorityElement(nums4)
print solution.majorityElement(nums5)
print solution.majorityElement(nums6)
|
e934bbe990db9e6c233f6a83d891bcec8019c4d1 | AmigaTi/Python3Learning | /functional/map-reduce.py | 2,571 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from functools import reduce
# map
# map函数接收两个参数,一个是函数,一个是Iterable,
# map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5])
print(list(r)) # [1, 4, 9, 16, 25]
# reduce
# reduce函数:把一个函数作用在一个序列[x1, x2, x3, ...]上,
# reduce把结果继续和序列的下一个元素做累计计算,其效果就是:
# reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
def add(x, y):
return x + y
r = reduce(add, [1, 2, 3, 4, 5])
print(r) # 15
# -------------------------------------------------------
# str2int
def str2int(s):
def fn(x, y):
return x * 10 + y
# return lambda x, y: x * 10 + y
def char2num2(ch):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[ch]
return reduce(fn, map(char2num2, s))
r = str2int('12345')
print(r)
# -------------------------------------------------------
# 1.
# 利用map()函数,把用户输入的不规范的英文名字,
# 变为首字母大写,其他小写的规范名字。
def normalize(name):
return name.lower().capitalize()
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2) # ['Adam', 'Lisa', 'Bart']
# 2.
# 编写一个prod()函数,可以接受一个list并利用reduce()求积
def prod(lst):
return reduce(lambda x, y: x * y, lst)
print('3 * 5 * 7 * 9 = ', prod([3, 5, 7, 9]))
# 3 * 5 * 7 * 9 = 945
# 3.
# 利用map和reduce编写一个str2float函数,
# 把字符串'123.456'转换成浮点数123.456
def str2float(s):
def fn(x, y):
return x * 10 + y
def char2num(ch):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[ch]
def split2(cstr):
lst = []
i = 0
for ch in cstr:
if ch == '.':
break
i += 1
lst.append(cstr[:i])
lst.append(cstr[i+1:])
return lst
def construct(a, b):
return a + b/10**len(str(b))
return reduce(construct, [reduce(fn, map(char2num, l)) for l in split2(s)])
print('str2float(\'123.456\') = ', str2float('123.456'))
# str2float('123.456') = 123.456
'''
# for test customized split function
f = '123.456'
i = 0
for ch in f:
if ch == '.':
print(i) # 3
break
i += 1
print(f)
print(f[:i])
print(f[i+1:])
''' |
63905f054c18575bbb17feead3b79066677529eb | koonerts/algo | /py-algo/leetcode/linked-list.py | 5,609 | 3.671875 | 4 | from heapq import *
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# def __lt__(self, other):
# other_val = other.val if other else float('inf')
# return self.val < other_val
def print_list(self):
vals = ''
node = self
while node:
if node:
vals += str(node.val)
if node.next:
vals += '->'
node = node.next
print(vals)
class Solution:
def subtract(self, head: ListNode) -> ListNode:
lo, hi = 0, 0
last = head
while last and last.next:
last = last.next
hi += 1
n = hi-lo+1
# 1->2->3->4->5
node = head
lo, mid = 0, n//2
while lo <= mid:
node = node.next
lo += 1
prev = None
while node:
temp = node.next
node.next = prev
prev = node
node = temp
left, right = head, prev
while node:
left.val = right.val - left.val
if left.next:
left = left.next
right = right.next
node = prev
prev = None
while node:
temp = node.next
node.next = prev
prev = node
node = temp
left.next = prev
return head
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""https://leetcode.com/problems/add-two-numbers/"""
carry_over = 0
head, prev_digit_node = None, None
while l1 or l2:
l1_val = 0 if not l1 else l1.val
l2_val = 0 if not l2 else l2.val
digit_sum = l1_val + l2_val + carry_over
digit_node = ListNode(digit_sum % 10)
if prev_digit_node:
prev_digit_node.next = digit_node
else:
head = digit_node
prev_digit_node = digit_node
carry_over = digit_sum // 10
if l1: l1 = l1.next
if l2: l2 = l2.next
if not l1 and not l2 and carry_over == 1:
digit_node = ListNode(1)
prev_digit_node.next = digit_node
return head
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
prev = node
curr = node.next
while curr:
prev.val = curr.val
if not curr.next:
prev.next = None
break
prev = curr
curr = curr.next
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
prev, node, ahead_node = None, head, head
for _ in range(n):
ahead_node = ahead_node.next
while ahead_node:
ahead_node = ahead_node.next
prev = node
node = node.next
if prev and node:
prev.next = node.next
if head == node:
head = head.next
return head
def reverseList(self, head: ListNode) -> ListNode:
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev
def reverseListRecursive(self, head: ListNode) -> ListNode:
def reverse(curr: ListNode, prev: ListNode = None) -> ListNode:
if not curr:
return prev
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return reverse(curr, prev)
return reverse(head)
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2
elif not l2: return l1
head: ListNode
if l1.val <= l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
node = head
while l1 or l2:
if not l1:
node.next = l2
l2 = None
elif not l2:
node.next = l1
l1 = None
else:
if l1.val <= l2.val:
node.next = l1
l1 = l1.next
node = node.next
else:
node.next = l2
l2 = l2.next
node = node.next
return head
def isPalindrome(self, head: ListNode) -> bool:
head_copy = head
reversed_head = self.reverseList(head_copy)
while head or reversed_head:
if (head and not reversed_head) or (reversed_head and not head):
return False
if head.val != reversed_head.val:
return False
head = head.next
reversed_head = reversed_head.next
return True
def mergeKLists(self, lists: list[ListNode]) -> ListNode:
if not lists: return None
min_heap = []
for i in range(len(lists)):
head = lists[i]
if head: heappush(min_heap, (head.val, head))
head, prev = None, None
while min_heap:
val, node = heappop(min_heap)
if node.next:
heappush(min_heap, (node.val, node.next))
if not head:
head = node
else:
prev.next = node
prev = node
return head
node1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
val = Solution().subtract(node1)
val.print_list()
|
4bcfbac61fd25b31536295303a99d217330b89f9 | tisnik/python-programming-courses | /Python2/examples/serialization/employee_class_pickle_read.py | 1,016 | 3.5 | 4 | #!/usr/bin/env python3
# vim: set fileencoding=utf-8
"""Serializace objektů do souboru."""
import pickle
class Employee:
"""Třída reprezentující zaměstnance."""
def __init__(self, first_name, surname, salary):
"""Konstruktor objektu."""
self._first_name = first_name
self._surname = surname
self._salary = salary
self._poznamka = 124
def __str__(self):
"""Speciální metoda pro převod objektu na řetězec."""
return "name: {name} {surname} Salary: {salary}".format(
name=self._first_name, surname=self._surname, salary=self._salary
)
def __eq__(self, other):
if other is None:
return False
return (
self._first_name == other._first_name
and self._surname == other._surname
and self._salary == other._salary
)
with open("test", "rb") as fin:
employees = pickle.load(fin)
for employee in employees:
print(employee)
|
4b28ab762b70112a3ad1875ab9ddad0e0e4f28ec | adqz/interview_practice | /algo_expert/p38_reverse_every_k_elements_linked_list.py | 1,847 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def generate_linked_list_from_iterable(iterable, visualize = False):
if not iterable:
return None
for i, val in enumerate(iterable):
if i == 0:
head = Node(val)
curr = head
else:
curr.next = Node(val)
curr = curr.next
if visualize:
print_linked_list(head)
return head
def print_linked_list(head):
curr = head
while curr:
print(curr.data, '-> ', end='')
curr = curr.next
print('None')
def reverse_k_nodes(head, k):
if not head: return head
if k <= 1: return head
slow = head
fast = slow
counter = 1
while fast.next and counter < k:
fast = fast.next
counter += 1
head1 = slow
head2 = fast.next
fast.next = None
while head1.next is not None:
head1 = head1.next
head1.next = reverse_k_nodes(head2, k)
return head
def reverse(head):
node = head
if node.next == None:
return head
prev_node = None
# 1. Reverse links until last element
while node.next != None and node.next.next != None:
next_node = node.next
next_next_node = node.next.next
# Reverse
next_node.next = node
node.next = prev_node
node = next_next_node
prev_node = next_node
# 2. Reverse last link
if node.next != None:
next_node = node.next
node.next = prev_node
next_node.next = node
else:
node.next = prev_node
next_node = node
return next_node
if __name__ == "__main__":
head = generate_linked_list_from_iterable([1,2,3,4,5], True)
ans = reverse_k_nodes(head, 3)
# print_linked_list(ans)
# print() |
fe52e4d315ef80dfed09c5689b8b69c3c279df14 | wansang93/Algorithm | /Programmers/Python/Code/더 맵게.py | 1,187 | 3.734375 | 4 | # 풀이1
# 이 방법은 효율성에서 에러가 발생함으로 heapq를 이용해야된다.
def solution(scoville, K):
answer = 0
mylist = sorted(scoville)
least = min(mylist)
while True:
if len(mylist) <= 1:
if mylist[0] < K:
return -1
else:
return answer
if least >= K:
break
else:
a = mylist.pop(0)
b = mylist.pop(0)
mylist.append(a + (b * 2))
mylist.sort()
least = min(mylist)
answer += 1
return answer
# 풀이2
import heapq as hq
def solution2(scoville, K):
hq.heapify(scoville)
answer = 0
while True:
first = hq.heappop(scoville)
if first >= K:
break
if len(scoville) == 0:
return -1
second = hq.heappop(scoville)
hq.heappush(scoville, first + second*2)
answer += 1
return answer
print(solution2([1, 2, 3, 9, 10, 12], 7))
# heapq library documents in english
# https://docs.python.org/3/library/heapq.html
# 힙큐 관련 라이브러리 설명서
# https://python.flowdas.com/library/heapq.html |
de98bc16563148397308bb58764caf2acfb4204f | bonfiglio/introPython | /E Esercizi Ricorsione/totocalcio.py | 2,381 | 3.828125 | 4 | class Risultato():
UNO = '1'
DUE = '2'
ICS = 'X'
class Previsione(object): # 1 2 x
def __init__(self, r1=None, r2=None, r3=None):
self.risultati = set()
if r1 is not None:
self.risultati.add(r1)
if r2 is not None:
self.risultati.add(r2)
if r3 is not None:
self.risultati.add(r3)
def __str__(self):
str = 'Risultati -'
# + str(self.risultati)
for risultato in self.risultati:
str += risultato + "-"
return str
class Pronostico(object):
def __init__(self, n):
self.N = n
self.previsioni = []
self.colonne = []
def add(self, p):
if len(self.previsioni) < self.N:
self.previsioni.append(p)
# } else {
# throw new IllegalStateException("Too many elements in Proonostico") ;
def __str__(self):
str = 'Pronostico: \n'
for previsione in self.previsioni:
str += previsione.__str__() + "\n"
return str
def sviluppoColonna(self):
# PROBLEMA RICORSIVO
self.sviluppoRiga('', 0)
print(self.colonne)
return
# Idee per sviluppare un problema che si ripete: immagino di essere a metà soluzione
# soluzione parziale passo-1 + un passo -> passo +1 etc fino alla FINE
# colonna fino a riga i-1 + riga i --> svilupporighe successive
def sviluppoRiga(self, colonna, i):
if i == self.N:
self.colonne.append(colonna)
else:
# step 1 riga i = una delle previsioni fatte + previsioni successive
for risultato in self.previsioni[i].risultati:
self.sviluppoRiga(colonna + risultato, i + 1)
return
p = Pronostico(4)
p.add(Previsione(Risultato.DUE, Risultato.ICS))
p.add(Previsione(Risultato.UNO))
p.add(Previsione(Risultato.UNO, Risultato.ICS, Risultato.DUE))
p.add(Previsione(Risultato.ICS))
p.add(Previsione(Risultato.UNO, Risultato.DUE))
p.add(Previsione(Risultato.UNO))
p.add(Previsione(Risultato.DUE, Risultato.ICS))
p.add(Previsione(Risultato.UNO))
p.add(Previsione(Risultato.UNO, Risultato.ICS, Risultato.DUE))
p.add(Previsione(Risultato.ICS))
p.add(Previsione(Risultato.UNO, Risultato.DUE))
p.add(Previsione(Risultato.UNO))
p.add(Previsione(Risultato.DUE, Risultato.ICS))
print(p)
p.sviluppoColonna()
|
19daf8c297c57c6af1feaab94a36044c619c3a9b | ubarredo/Microsoft-DAT210x | /m5a09_regression.py | 2,754 | 3.5625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from mpl_toolkits.mplot3d import Axes3D
def draw_line(model, data, label, title, r2):
# Plot the observations and display the R2 coefficient:
fig, ax = plt.subplots()
ax.scatter(data, label, c='g', marker='o')
ax.plot(data, model.predict(data), color='orange', linewidth=1, alpha=.7)
ax.set_title(title + ' R2: ' + str(r2))
print(title + ' R2: ' + str(r2))
print(f"Intercept(s): {model.intercept_}")
def draw_plane(model, data, label, title, r2):
# Plot the observations and display the R2 coefficient:
fig = plt.figure()
ax = Axes3D(fig)
# Set up a grid:
x_max, y_max = np.max(data, axis=0)
x_min, y_min = np.min(data, axis=0)
x, y = np.meshgrid(np.arange(x_min, x_max, (x_max - x_min) / 10),
np.arange(y_min, y_max, (y_max - y_min) / 10))
# Predict based on possible input values:
z = model.predict(np.c_[x.ravel(), y.ravel()]).reshape(x.shape)
ax.scatter(data.iloc[:, 0], data.iloc[:, 1], label, c='g', marker='o')
ax.plot_wireframe(x, y, z, color='orange', alpha=.7)
ax.set_zlabel('prediction')
ax.set_title(title + ' R2: ' + str(r2))
print(title + ' R2: ' + str(r2))
print(f"Intercept(s): {model.intercept_}")
plt.style.use('ggplot')
# Load up the dataset:
df = pd.read_csv('datasets/college.csv', index_col=0)
# Encode features directly:
df['Private'] = df['Private'].map({'Yes': 1, 'No': 0})
print(df.head())
# Create the linear regression model:
lreg = LinearRegression()
Y = df['Accept'].copy()
for i in ['Room.Board', 'Enroll', 'F.Undergrad']:
# Index the slice:
X = df[[i]].copy()
# Use train_test_split to cut data:
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=.3,
random_state=7)
# Fit and score the model:
lreg.fit(X_train, Y_train)
score = lreg.score(X_test, Y_test)
# Pass it into draw_line with your test data:
draw_line(lreg, X_test, Y_test, f'Accept({i})', score)
plt.savefig('plots/regression.png')
# Do multivariate linear regression:
X = df[['Room.Board', 'Enroll']].copy()
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=.3,
random_state=7)
lreg.fit(X_train, Y_train)
score = lreg.score(X_test, Y_test)
# Pass it into draw_plane with your test data:
draw_plane(lreg, X_test, Y_test, "Accept(Room.Board,Enroll)", score)
# Show graphs:
plt.show()
|
72c7d6790ae47155e2b3f0b66fcb87ba920241ee | rajbin/DistanceCalculator | /Tour.py | 1,940 | 3.703125 | 4 | import urllib2
from xml.etree import ElementTree
class Tour(object):
"""An instance of this class is to be instantiated with an arbitrary
number of US cities, and is used to fetch information from the web."""
__googleAPI = "http://maps.googleapis.com/maps/api/distancematrix/xml"
def __init__(self, *cities, **kwarg):
self._lstCity = []
for city in cities:
self._lstCity.append(city)
# Get the total distance between the cities, default mode is driving.
def getDistance(self, mode="driving"):
totalDistance = 0
counter, nextCounter = 0,0
#loop through all the city list to get the total distance
for counter in range(0, len(self._lstCity) - 1):
nextCounter = counter + 1
url = self.__googleAPI
url = url + "?origins={0}&destinations={1}&mode={2}&sensor=false".format(self._lstCity[counter].replace(" ","+").replace(",",""), self._lstCity[nextCounter].replace(" ","+").replace(",",""), mode)
try:
response = urllib2.urlopen(url).read()
xmlResponse = ElementTree.fromstring(response)
#from xml read the distance value
distance = xmlResponse.find("row").find("element").find("distance").findtext("value")
if distance != "":
totalDistance += float(distance)
except urllib2.HTTPError, err:
if err.code == 404:
print "Page not found!"
elif err.code == 403:
print "Access denied!"
else:
print "An error has occured. Please try after sometime."
except urllib2.URLError, err:
print "An error has occured. Please try after sometime."
return totalDistance
def __str__(self):
return str(self._lstCity) |
444811508c95d89d31f2e3837341389f922999ba | TGITS/programming-workouts | /python/misc/learning_python/reduce_examples.py | 3,153 | 3.953125 | 4 | import functools
import operator
import math
import decimal
# Exemple classique d'utilisation de reduce pour réaliser la somme d'une liste de nombres
numbers_1_to_10 = range(1, 11)
sum_numbers_1_to_10 = functools.reduce(operator.add, numbers_1_to_10)
print("Somme des nombres de 1 à 10 avec reduce :", sum_numbers_1_to_10)
print()
# Néanmoins Python propose directement la fonction native sum() pour ce cas d'utilisation
print("Somme des nombres de 1 à 10 avec sum :", sum(numbers_1_to_10))
print()
print("Pareil mais avec une valeur de départ de 5 ajoutée à la somme")
# Utilisation de operator.add plutôt que de la lambda `lambda a, b: a + b`
sum_numbers_1_to_10_plus_5 = functools.reduce(
operator.add, numbers_1_to_10, 5)
print("Somme des nombres de 1 à 10 avec une valeur initiale de 5 avec reduce :",
sum_numbers_1_to_10_plus_5)
print("Somme des nombres de 1 à 10 avec une valeur initiale de 5 avec sum :",
sum(numbers_1_to_10, 5))
# Pour les nombres flottants mieux vaut utiliser math.fsum que sum
print("Somme de nombres flottants avec sum : ",
decimal.Decimal.from_float(sum([1.234556e-20, 1.2e-10, math.pi, math.e, math.sqrt(2)])))
print("Somme de nombres flottants avec fsum : ",
decimal.Decimal.from_float(math.fsum([1.234556e-20, 1.2e-10, math.pi, math.e, math.sqrt(2)])))
print('\n##############\n')
# Autre exemple classique d'utilisation de reduce pour retourner le maximum ou le minimum
print("Le plus grand nombre pour l'intervalle de 1 à 10 avec reduce :",
functools.reduce(lambda a, b: a if a > b else b, numbers_1_to_10))
print("Le plus petit nombre pour l'intervalle de 1 à 10 avec reduce :",
functools.reduce(lambda a, b: a if a < b else b, numbers_1_to_10))
print()
# Néanmoins Python propose directement les fonctions native max() et min() pour ce cas d'utilisation
print("Le plus grand nombre pour l'intervalle de 1 à 10 avec max :",
max(numbers_1_to_10))
print("Le plus petit nombre pour l'intervalle de 1 à 10 avec min :",
min(numbers_1_to_10))
print('\n##############\n')
print("On n'est pas obligé de réduire à une valeur scalaire ! On peur réduire à n'importe quelle valeur !")
# Ensemble de maisons de Westeros
houses = {"tyrell", "stark", "lannister", "tarly", "baratheon", "targaryen"}
print('Houses :', houses)
def aggregate(accumulator, current_item):
accumulator.update({current_item: len(current_item)})
return accumulator
length_by_house = functools.reduce(aggregate, houses, {})
print("Longueur du nom par nom de maison avec reduce:", length_by_house)
print("Longueur du nom par nom de maison avec compréhension:",
{house: len(house) for house in houses})
class HousesOfWesteros:
def __init__(self):
self.nameLengthByName = {}
def update(self, dictionary):
self.nameLengthByName.update(dictionary)
def __str__(self):
return str(self.nameLengthByName)
print("Longueur du nom par nom de maison avec reduce sur un objet :", functools.reduce(aggregate, houses, HousesOfWesteros())) |
60478ff7f9a83979ef0fa8afa9e7dd55a9cc5c05 | ChJL/LeetCode | /medium/394. Decode String.py | 941 | 3.546875 | 4 | #Tag: Stack, DFS
"""
Example 1:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
Example 2:
Input: s = "3[a2[c]]"
Output: "accaccacc"
SOL: from discussion: https://leetcode.com/problems/decode-string/discuss/87662/Python-solution-using-stack
using stack, store number than string.
note that cur_n = cur_n*10 + int(ele), since the number may be larger than 10 100.
"""
class Solution:
def decodeString(self, s: str) -> str:
stack = []
cur = ""
cur_n = 0
for ele in s:
if ele == "[":
stack.append(cur_n)
stack.append(cur)
cur_n = 0
cur = ""
elif ele == "]":
pre_s = stack.pop()
num = stack.pop()
cur = pre_s + cur * num
elif ele.isdigit():
cur_n = cur_n*10 + int(ele)
else:
cur += ele
return cur |
64d3f5135fb3d0364ae51f12ecd1754da66c6f54 | mpwesthuizen/eng57_files_and_error_handling | /run_file.py | 555 | 4.0625 | 4 | # example of error handling with try and except
def int_convert(var):
try:
return int(var)
except ValueError:
print("ValueError: The value doesn't contain numbers")
# print(int_convert(13))
#
# print(int_convert("string"))
#
# print(int_convert(13.00))
def int_convert2(var):
if type(var) == int:
try:
return type(var)
except ValueError:
return 'ValueError: ' + type(var) + ' is not an \'int\''
print(int_convert2(13))
print(int_convert2("string"))
print(int_convert2(13.00))
|
3ebcd377f22edc0d2716d8069c51e3dec8f07d22 | hessio/pythonExamples | /Oddities.py | 204 | 3.796875 | 4 | N = int(input())
q = [0] * N
for i in range(0, N):
q[i] = int(input())
for j in range(0, N):
if q[j] % 2 == 0:
print(q[j], "is even")
elif q[j] % 2 != 0:
print(q[j], "is odd")
|
396df24ec9de4603bddd0fbba287ff59cbfd7fac | dolapobj/interviews | /Data Structures/Trees/MaximumDepthOfBinaryTree.py | 732 | 3.984375 | 4 | ##Maximum Depth of Binary Tree
##Leetcode Problem 104
""" Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. """
"""
3
/ \
9 20
/ \
15 7
return depth of 3
"""
def maxDepth(root):
if root == None:
return 0
left = 1 + maxDepth(root.left)
right = 1 + maxDepth(root.right)
return max(left,right)
#RT analysis: O(n) --> we traverse through all nodes in the tree once in the worst case.
#SC analysis: O(n) --> in the longest path, we store the left and right children to come back to
# because we backtrack when we finish traversing the left side.
|
355153fec689426e01b1ce23a6ab1c8046d756ad | jdchristesen/projectEuler | /largest_prime_factor.py | 432 | 3.578125 | 4 | from math import sqrt
number_to_factor = 600851475143
largest_prime = 1
prime = False
for i in range(2, int(sqrt(number_to_factor))):
if number_to_factor % i == 0:
for j in range(2, int(sqrt(i))):
if i % j == 0:
prime = False
break
else:
prime = True
if prime:
largest_prime = i
prime = False
print(largest_prime) |
13601beb27279804f4140ea6edd2ea3d515bd0b3 | Spico197/GPU-Scheduler-Demo | /send_email.py | 1,115 | 3.609375 | 4 | import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# 邮箱发信地址(SMTP服务器) - SMTP server host/domain name of sender
EMAIL_HOST = 'smtp.163.com'
# 邮箱发信端口(SMTP服务器端口) - SMTP server port of sender
EMAIL_PORT = 25
# 邮箱账号 - email of sender
EMAIL_USER = '***@163.com'
# 邮箱密码或授权码(作为第三方登录) - email password or authentication code
EMAIL_PASSWORD = '***'
# 收信人地址 - email of receiver
EMAIL_RECEIVER = "***@qq.com"
def send_email(html_message):
# set up the SMTP server
s = smtplib.SMTP(host=EMAIL_HOST, port=EMAIL_PORT)
s.starttls()
s.login(EMAIL_USER, EMAIL_PASSWORD)
msg = MIMEMultipart() # create a message
msg['From'] = EMAIL_USER
msg['To'] = EMAIL_RECEIVER
msg['Subject']="Notice"
msg.attach(MIMEText(html_message, 'html'))
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
if __name__ == "__main__":
send_email('<strong>Hey,</strong><br> Your program has started!')
|
0373ad9669ad7507587fce88d275181df31620a5 | MarcPartensky/Python-Games | /Game Structure/geometry/version4/mycase.py | 7,661 | 3.546875 | 4 | from myabstract import Form,Point
from mypixel import Pixel
from pygame.locals import *
import time
import mycolors
class TrueCase(Form):
def __init__(self,*position,size=[1,1],color=mycolors.WHITE,fill=True):
"""Create a case using the position and optional size, color and fill."""
if len(position)==1: position=position[0]
self.position=list(position)
self.size=size
self.color=color
self.fill=fill
def getPoints(self):
"""Return the points of the case."""
xmin,ymin,xmax,ymax=self.getCorners()
p1=Point(xmin,ymin)
p2=Point(xmax,ymin)
p3=Point(xmax,ymax)
p4=Point(xmin,ymax)
return [p1,p2,p3,p4]
def setPoints(self,points):
"""Set the points of the case by changing the position and the size.
Because all the sets of points cannot match a pure rectangle, some
approximations will be made. Technically only two points are necessary
to create a rectangle."""
xmin=min([p.x for p in pointss])
xmax=max([p.x for p in points])
ymin=min([p.y for p in points])
ymax=max([p.y for p in points])
corners=[xmin,ymin,xmax,ymax]
coordonnates=self.getCoordonnatesFromCorners(corners)
self.position=coordonnates[:2]
self.size=coordonnates[2:]
def __eq__(self,other):
"""Determine if two cases are the same by comparing its x and y components."""
return self.position==other.position and self.size==other.size
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the position through an iteration."""
if self.iterator<2:
value=self.position[self.iterator]
self.iterator+=1
return value
else:
raise StopIteration
def getCenter(self):
"""Return the center of the case."""
xmin,ymin,xmax,ymax=self.getCorners()
x=(xmin+xmax)/2
y=(ymin+ymax)/2
return Point(x,y)
def setCenter(self,point):
"""Set the center of the case."""
sx,sy=self.size
px,py=self.point
self.position=[px+sx/2,py+sy/2]
def show(self,surface,**kwargs):
"""Show the case. By default it only show the associated form."""
self.showForm(surface,**kwargs)
def showText(self,surface,text):
"""Show the text on the surface."""
point=self.center()
point.showText(surface,text)
def showForm(self,surface,fill=None,area_color=None,side_color=None):
"""Show the pixel on screen."""
f=self.getForm(fill,area_color,side_color)
f.show(surface)
def __str__(self):
"""Return the string representation of the object."""
return "case("+str(self.position[0])+","+str(self.position[1])+")"
def getCorners(self):
"""Return the corners of the case."""
px,py=self.position
sx,sy=self.size
return (px,py,px+sx,py+sy)
def setCorners(self):
"""Set the corners of the case."""
coordonnates=self.getCoordonnatesFromCorners(corners)
self.position=coordonnates[:2]
self.size=coordonnates[2:]
def __contains__(self,position):
"""Determine if the point is in the paint."""
x,y=position
xmin,ymin,xmax,ymax=self.getCorners()
return (xmin<=x<=xmax) and (ymin<=y<=ymax)
center=property(getCenter,setCenter,"Allow the user to manipulate the center of the case easily.")
points=property(getPoints,setPoints,"allow the user to manipulate the points of the case easily")
class Case(Pixel):
def __init__(self,*position,size=[1,1],color=mycolors.WHITE,fill=True):
"""Create a pixel."""
if len(position)==1: position=position[0]
self.position=position
print(position)
self.size=size
self.color=color
self.fill=fill
def __eq__(self,other):
"""Determine if two cases are the same by comparing its x and y components."""
return self.position==other.position
def __iter__(self):
"""Iterate the points of the form."""
self.iterator=0
return self
def __next__(self):
"""Return the next point threw an iteration."""
if self.iterator<2:
value=self.position[self.iterator]
self.iterator+=1
return value
else:
raise StopIteration
def getForm(self,fill=None,area_color=None,side_color=None):
"""Return the abstract form associated with the case."""
if not fill: fill=self.fill
if not area_color: area_color=self.color
if not side_color: side_color=mycolors.WHITE
xmin,ymin,xmax,ymax=self.getCorners()
p1=Point(xmin,ymin)
p2=Point(xmax,ymin)
p3=Point(xmax,ymax)
p4=Point(xmin,ymax)
points=[p1,p2,p3,p4]
return Form(points,fill=fill,side_color=side_color,area_color=area_color,point_show=False)
def getCenter(self):
"""Return the center of the case."""
xmin,ymin,xmax,ymax=self.getCorners()
x=(xmin+xmax)/2
y=(ymin+ymax)/2
return Point(x,y)
def setCenter(self,point):
"""Set the center of the case."""
sx,sy=self.size
px,py=self.point
self.position=[px+sx/2,py+sy/2]
def show(self,surface,**kwargs):
"""Show the case. By default it only show the associated form."""
self.showForm(surface,**kwargs)
def showText(self,surface,text):
"""Show the text on the surface."""
point=self.center()
point.showText(surface,text)
def showForm(self,surface,fill=None,area_color=None,side_color=None):
"""Show the pixel on screen."""
f=self.getForm(fill=fill,area_color=area_color,side_color=side_color)
f.show(surface)
__getitem__=lambda self,i:self.position[i]
#def __getitem__(self,index):
def __str__(self):
"""Return the string representation of the object."""
return "case("+str(self.position[0])+","+str(self.position[1])+")"
def getCorners(self):
"""Return the corners of the case."""
px,py=self.position
sx,sy=self.size
return (px,py,px+sx,py+sy)
def __contains__(self,position):
"""Determine if the point is in the paint."""
x,y=position
xmin,ymin,xmax,ymax=self.getCorners()
return (xmin<=x<=xmax) and (ymin<=y<=ymax)
center=property(getCenter,setCenter,"Allow the user to manipulate the center of the case easily.")
if __name__=="__main__":
from mysurface import Surface
from myzone import Zone
#surface=Surface(plane=Zone(size=[20,20]))
surface=Surface()
cases=[Case([x,y],color=mycolors.random(),fill=True) for x in range(-20,20) for y in range(0,20)]
cases=[Case([x,y],color=mycolors.GREEN,fill=True) for x in range(8) for y in range(8)]
#cases=[]
matrix=[[None for i in range(8)] for y in range(8)]
for x in range(8):
for y in range(8):
matrix[x][y]=Case([x,y],color=mycolors.GREEN,fill=True)
#case=Case([x,y],color=mycolors.GREEN,fill=True)
#if x%8==0 or y%8==0:
# case.color=mycolors.BLUE
#cases.append(case)
#matrix[1][1].color=mycolors.BLUE
#matrix[1][0].color=mycolors.BLUE
while surface.open:
surface.check()
surface.control()
surface.clear()
surface.show()
for case in cases:
case.show(surface)
surface.flip()
|
902d60cec7b400d14bea87d29319c99a45a6c178 | Aasthaengg/IBMdataset | /Python_codes/p02860/s336324881.py | 147 | 3.515625 | 4 | N = int(input())
S = list(input())
ans = 'No'
if N%2 == 0:
num = int(N/2)
pre = S[:num]
suf = S[num:]
if pre == suf: ans = "Yes"
print(ans) |
6fab7328785293bbf9789108a5e2de7b8be233ac | bayek0fsiwa/Practice-Programs | /python/find_keywords.py | 470 | 4.21875 | 4 | keywords = {"break",
"case",
"continue",
"default",
"defer",
"else",
"for",
"func",
"goto",
"if",
"map",
"range",
"return",
"struct",
"type",
"elif",
"else",
"var",
"super",
"self",
"private",
"public",
"let",
"const"
}
getkeyword = input('Enter the word: ')
if getkeyword in keywords:
print(f"{getkeyword} is a keyword")
else:
print(f"{getkeyword} is not a keyword") |
94e3fa813e71d0ffc3736d422e955d7d9aa433a5 | softsys4ai/unicorn | /causallearn/graph/GraphNode.py | 2,650 | 3.78125 | 4 | #!/usr/bin/env python3
# Implements a basic node in a graph--that is, a node that is not itself a variable.
from causallearn.graph.Node import Node
from causallearn.graph.NodeType import NodeType
class GraphNode(Node):
def __init__(self, name):
self.name = name
self.node_type = NodeType.MEASURED
self.center_x = -1
self.center_y = -1
self.attributes = {}
# @return the name of the variable.
def get_name(self):
return self.name
# @return the node type
def get_node_type(self):
return self.node_type
# @return the x coordinate of the center of the node
def get_center_x(self):
return self.center_x
# @return the y coordinate of the center of the node
def get_center_y(self):
return self.center_y
# sets the name of the node
def set_name(self, name):
if name == None:
raise TypeError('Name cannot be of NoneType')
self.name = name
# sets the node type
def set_node_type(self, type):
if type == None:
raise TypeError('Node cannot be of NoneType')
self.node_type = type
# sets the x coordinate of the center of the node
def set_center_x(self, center_x):
self.center_x = center_x
# sets the y coordinate of the center of the node
def set_center_y(self, center_y):
self.center_y = center_y
# sets the (x, y) coordinates of the center of the node
def set_center(self, center_x, center_y):
self.center_x = center_x
self.center_y = center_y
# @return the name of the node as its string representation
def __str__(self):
return self.name
# Two continuous variables are equal if they have the same name and the same
# missing value marker.
def __eq__(self, other):
return isinstance(other, GraphNode) and self.name == other.get_name()
def __lt__(self, other):
return self.name < other.name
def __hash__(self):
return hash(self.name)
def like(self, name):
node = GraphNode(name)
node.set_node_type(self.get_node_type())
def get_all_attributes(self):
return self.attributes
def get_attribute(self, key):
return self.attributes[key]
def __getitem__(self, key):
return self.get_attribute(key)
def remove_attribute(self, key):
self.attributes.pop(key)
def __delitem__(self, key):
self.remove_attribute(key)
def add_attribute(self, key, value):
self.attributes[key] = value
def __setitem__(self, key, value):
self.add_attribute(key, value)
|
e729e4a7857872b3cf1acca146ab694db7cacee7 | gladguy/PyKids | /Star.py | 496 | 3.953125 | 4 | import turtle
star=turtle.Turtle()
star.shape("turtle")
screen=turtle.Screen() # Take control of the Turtle Screen
screen.bgcolor("grey")
star.pencolor("red") # Standards color
for i in range(5): # Star have five sides
star.forward(100)
star.right(144)
childstar = star.clone()
print ("New Star is ready")
screen=turtle.Screen()
screen.bgcolor("yellow")
childstar.pencolor("green")
childstar.forward(-100)
for i in range(5):
childstar.forward(100)
childstar.right(144)
|
df70648378c761aa86d3d11d575a4a0a66144dd8 | vdpir/Deep-Python | /solution_magic.py | 1,494 | 3.6875 | 4 | import tempfile
import os
import random
class File:
"""Класс FileReader помогает читать из файла"""
def __init__(self, file_path):
self.file_path = file_path
if not os.path.exists(file_path):
f = open(self.file_path, 'w')
f.close()
self.f = open(self.file_path, 'r')
def read(self):
try:
with open(self.file_path) as f:
return f.read()
except IOError:
return ""
def write(self, string_to_write):
try:
with open(self.file_path, 'w') as f:
return f.write(string_to_write)
except IOError:
return ""
def __add__(self, obj):
string_from_file_obj = obj.read()
string_from_this_file = self.read()
target_path = os.path.join(tempfile.gettempdir(), str(random.randint(10000,100000)))
new_file = File(target_path)
new_file.write(string_from_file_obj+string_from_this_file)
return new_file
def __str__(self):
return '{}'.format(self.file_path)
def __iter__(self):
self.ff = open(self.file_path, 'r')
return self
def __next__(self):
returned_string = self.ff.readline()
if returned_string == '':
self.ff.close()
raise StopIteration
return returned_string
def __enter__(self):
return self.f
def __exit__(self, *args):
self.f.close()
|
836a749557f86215f5bbd6acac83f75b79417f46 | TianyaoHua/LeetCodeSolutions | /Count of Smaller Numbers After Self.py | 1,593 | 3.703125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.size = 1
self.p = None
self.left = None
self.right = None
class Solution(object):
def insert(self, root, node):
y = None
x = root
r = 0
while x:
y = x
if node.val <= x.val:
x.size += 1
x = x.left
else:
if x.left:
r += x.left.size + 1
else:
r += 1
x.size += 1
x = x.right
node.p = y
if not y:
root = node
elif node.val <= y.val:
y.left = node
else:
y.right = node
return root, r
# def rank(self, root, node):
# r = 1
# y = node
# while y != root:
# if y == y.p.right:
# r = r + y.p.left.size+1
# y = y.p
# return r
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
if not n:
return []
else:
counter = [0 for i in range(n)]
counter[-1] = 0
root = TreeNode(nums[-1])
for i in range(n-2, -1, -1):
node = TreeNode(nums[i])
root, r = self.insert(root, node)
counter[i] = r
root = root
return counter
solution = Solution()
nums = [1,2,1,2,1,2,1]
counter = solution.countSmaller(nums)
print(counter)
|
b049bdb2faa520f2c8a5bd3ee4b6b154a5e3421d | daniel-reich/ubiquitous-fiesta | /6LAgr6EGHKoZWGhjd_9.py | 460 | 3.671875 | 4 |
def final_direction(initial, turns):
com = ["N", "E", "S", "W"] # The directions on a compass in order
overall_turn = 0
initial_pos = com.index(initial) # The position of the initial position
for l in turns: # Counting the tunrs
if l == "R":
overall_turn += 1
else:
overall_turn -= 1
index = ((overall_turn + initial_pos) % 4) # Using modulo to keep it in range and get the total displacement
return com[index]
|
8f3150726832ebda175a8ee24be32f5a450a78dd | Anjali-M-A/Code | /Code_5datatype.py | 5,746 | 4.28125 | 4 | #Script to demonstrate Python Datatypes
"""
Different datatypes in python:
*Numeric - int, float, complex
*Sequence - list, tuple, range
*Boolean - True and False
*Binary - bytes, bytearray, memoryview(buffer protocol)
*Mapping -dictionary
*Set - set, frozen-set
*String - literal, characters, strings
"""
"""
**Methods used here
*** type -to know the object type of the variable (data type)
*** isinstance - to check whether two variables are of same datatype or not
"""
"""Numeric Datatype"""
#integer - syntax int()
sample_Integer = 2
print("Type of num is:", type(sample_Integer))
sample_Integer_Long = 265376387498478937498274938
print(sample_Integer_Long)
print(isinstance(sample_Integer,int))
#float
"""
float - syntax float()
"""
sample_Float = 3.0
print("Type of num_1 is:", type(sample_Float))
sample_Float_Truncated = 12.213243243464874668376764873487
print(type(sample_Float_Truncated))
print(sample_Float_Truncated)
#complex
"""
complex - syntax complex()
"""
num_2 = 3+5j
print("Type of num_2 is:", type(num_2))
print("The number ", num_2, " is complex number?", isinstance(3+5j, complex))
"""Sequential DataType"""
#list
"""
***syntax - [] (explicit)
or we can use list()
***list is mutable and ordered collection of values
***operations related to list:
#search
#update
#remove
#delete
#slice
"""
"""
Additional information:
list([]) or list(())
"""
list_1 = [1,2,3,4]
list_2 = [1, 1.1, 1+2j, 'Learn']
list_3 = list([1,2,3])
print(list_1)
print(list_2)
print(list_3)
#mutable
list_1[2]=5 #mutable bcz in list we can change the value
ordered_Sample_List = "abcdefghijklmnopqrstuvwxyz"
ordered_List = list(ordered_Sample_List)
print(list_1)
#tuple
"""
Syntax - tuple()
We can create tuple -
*Creating a Tuple with the use of Strings
*Creating a Tuple with the use of list
*Creating a Tuple with the use of built-in function
*Creating a Tuple with nested tuples
"""
"""
*Tuple is immutable
*once we define the value we cant change it
"""
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with the use of Strings
Tuple1 = ('Anjali', 'Annappa')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the use of built-in function
Tuple1 = tuple('Apple')
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'Sir')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
#range
"""
Syntax-range()
"""
for i in range(5, 10):
print(i, end =" ")
print("\r")
"""Boolean Datatype"""
#Data type with one of the two built-in values True or False.
print(type(True))
print(type(False))
"""Strings"""
"""
# Creating a String with single Quotes
# Creating a String with double Quotes
# Creating a String with triple Quotes
# Creating String with triple quotes allows multiple lines
"""
# Creating a String with single Quotes
String1 = 'Hello World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String with double Quotes
String1 = "I'm a very happy"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String with triple Quotes
String1 = '''I'm Anjali and I'm from shimogha'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple quotes allows multiple lines
String1 = ''' Python
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
"""Binary DataTypes"""
#bytes
x =(b'abc')
print(x[2])
#bytearray
b=bytearray(b'''Anj''')
print(b)
print(memoryview(x))
"""Mapping DataTypes"""
#dictionary
"""
Syntax - dict()
*Creating a Dictionary
**with Integer Keys
**with Mixed keys
**with dict() method
**with key-values
"""
# Creating a Dictionary with Integer Keys
Dict = {1: 'Hai', 2: 'Hello', 3: 'People'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary with Mixed keys
Dict = {'Name': 'Anjali', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary with dict() method
Dict = dict({1: 'Hai', 2: 'Hello', 3:'People'})
print("\nDictionary with the use of dict(): ")
print(Dict)
#Creating a dictionary with key-values
dict = {1:'Anjali', 2:'Annappa'};
print (dict.keys());
print (dict.values());
"""Set DataType"""
"""
# Syntax -set()
#Two type:*set is mutable
*frozen-set is immutable
# we can create set with
*the use of a string
*the use of a List
*a mixed type of values(Having numbers and strings)
"""
sample_set = {"red", "green", "black"} #mutable
print(sample_set)
frozen_set = ({"sagar", "shimogha", "karnataka"}) #immutable
print(frozen_set)
# Creating a Set with the use of a String
set1 = set("HakunaMatata")
print("\nSet with the use of String: ")
print(set1)
# Creating a Set with the use of a List
set1 = set(["Hai", "Hello", "People"])
print("\nSet with the use of List: ")
print(set1)
# Creating a Set with a mixed type of values
set1 = set([1, 2, 'Hai', 4, 'Hello', 6, 'People'])
print("\nSet with the use of Mixed Values")
print(set1)
|
779b458973fe31f493fd6a82cf4107703651ec8f | ryan-semmler/game-of-sticks | /AIsticks.py | 2,803 | 3.875 | 4 | import random
def start():
while True:
try:
stick_count = int(input("How many sticks would you like to play with? "))
if stick_count > 0:
return stick_count
except ValueError:
print("Pick a number.")
def pick_up(stick_count, dic):
while True:
if stick_count > 2:
try:
picked_up = int(input("Pick up some sticks: (1-3) "))
if picked_up <= stick_count and picked_up <= 3 and picked_up > 0:
return picked_up
elif picked_up == 0:
print(dic)
except ValueError:
pass
elif stick_count == 2:
try:
picked_up = int(input("Pick up some sticks: (1-2) "))
if picked_up == 1 or picked_up == 2:
return picked_up
else:
print("Please pick a valid number")
except ValueError:
pass
else:
return 1
def show_board(stick_count):
print('There are {} sticks on the board'.format(stick_count))
def switch_player(is_player_turn):
return not is_player_turn
def main():
dic = {}
while True: #game loop
turns_made = []
stick_count = start()
is_player_turn = True
while stick_count > 0: #turn loop
show_board(stick_count)
stick_count -= pick_up(stick_count, dic)
is_player_turn = switch_player(is_player_turn)
if stick_count == 0:
break
turns_made = AI_turn(turns_made, stick_count, dic)
stick_count -= turns_made[-1][1]
is_player_turn = switch_player(is_player_turn)
if is_player_turn:
print("Player wins!")
for item in turns_made:
sub_from_entry(item[0], dic, item[1])
else:
print("AI wins!")
for item in turns_made:
add_to_entry(item[0], dic, item[1])
def create_entry(stick_count, dic):
if stick_count >= 3:
dic[stick_count] = [1, 2, 3]
return dic
if stick_count == 2:
dic[stick_count] = [1, 2]
return dic
dic[stick_count] = [1]
return dic
def add_to_entry(stick_count, dic, new_ball):
dic[stick_count].append(new_ball)
def sub_from_entry(stick_count, dic, ball):
if dic[stick_count].count(ball) > 1:
dic[stick_count].remove(ball)
def AI_turn(turns_made, stick_count, dic):
if stick_count not in dic:
dic = create_entry(stick_count, dic)
choice = random.choice(dic[stick_count])
turns_made.append((stick_count, choice))
print("AI picks up", choice)
return turns_made
if __name__ == '__main__':
main()
|
b7fbb75797c8cad89e27599cb5618f2265e31b62 | Shulamith/csci127-assignments | /Classcode/madlibs.py | 2,149 | 3.640625 | 4 | #lab --make sure to write correct file name!! and folder
##madlib= "<exclamation> he said <Adverb> as he jumped into his <noun> and drove off with his <adjective> wife."
##NOUNS = ["car", "dog", "hammer"]
##def func_that_uses_NOUNS():
## global NOUNS
import random
#could make it more complex that adj and verbs would change but lets say a persons name wouldn't change
sentence = "<firstname> Reeves, whose first name means <adj> <noun> over the <noun> in Hawaiian, <verb> for a living."
sentenceTwo = "<hero> <verb> in the <noun> and then <hero> <verb> <noun> later."
##madliblist = split.sentence()
firstnames = ["Kasandra", "Ying", "Sam", "Michael"]
adjectives = ["swift", "fast", "fiery", "many", "blue", "sad", "joyous"]
nouns = ["car", "mountain", "sky", "star", "wolf", "dog", "shoe", "watch"]
verbs = ["meditates", "works", "runs", "plays", "sings", "spits", "explodes"]
heros=["Spiderman", "Wonderwoman", "Thor", "Batman"]
##def madlibs(s):
###function that finds all the missing words
###function that randomly chooses the items
###function that replaces all the <> with the item
###
## madliblist = s.split()
## for item in madliblist:
## s = s.replace("<firstname>", random.choice(firstnames))
## s = s.replace("<adj>", random.choice(adjectives))
## s = s.replace("<noun>", random.choice(nouns))
## s = s.replace("<verb>", random.choice(verbs))
## return s
##print(madlibs(sentence))
def madlibs(s):
newS=[]
heroN=random.choice(heros)
#make a list that holds all the bracketed stuff
for item in s.split():
if item == "<firstname>":
newS.append(random.choice(firstnames))
elif item == "<adj>":
newS.append(random.choice(adjectives))
elif item == "<noun>":
newS.append(random.choice(nouns))
elif item == "<verb>":
newS.append(random.choice(verbs))
elif item == "<hero>":
newS.append(heroN)
else:
newS.append(item)
sentenceString = " ".join(newS)
return sentenceString.capitalize()
print(madlibs(sentence))
print(madlibs(sentenceTwo))
|
f36ab0361ed057a891462fcea32ffe82384643ac | kapeed54/python-exercises | /Data Types/21. sort_list.py | 280 | 4.46875 | 4 | # python program to get a list, sorted in increasing order by the last element
# in each tuple from a given list of non-empty tuples.
def list(n):
return n[-1]
def list_sort(tuples):
return sorted(tuples, key=list)
print (list_sort([(2,5),(1,2),(4,4),(2,3),(2,1)]))
|
73837de06e0d6a4ba7a7166862c2ee9c37d2fb5d | Yury-Tret/Python | /homework_7/homework_0.py | 2,156 | 3.953125 | 4 | # Currencies courses
currencies = {'EUR': 0.85, 'UAH': 26.26, 'RUR': 62.13, 'GBP': 0.75, 'USD': 1}
class Converter:
def __init__(self, currencies_to_usd):
self.exit_flag = False
self.currencies_to_usd = currencies_to_usd
def summ_in_usd(self, summ, currency):
return float(summ) / self.currencies_to_usd[currency]
def sum_in_target_currency(self, summ_in_usd, target_currency):
return float(summ_in_usd) * self.currencies_to_usd[target_currency]
def calculate(self):
target_summ = self.sum_in_target_currency(self.summ_in_usd(self.summ, self.currency), self.target_currency)
print(self.summ, self.currency, '=', '{0:.2f}'.format(target_summ), self.target_currency)
print('-' * 20)
while True:
exit_flag = input('Do you want exit?: [Y/n]')
if exit_flag == 'Y'.lower():
self.exit_flag = True
return
elif exit_flag == 'n':
self.exit_flag = False
return
else:
print('Non existent choice, try again')
def input(self):
print('-' * 20)
while True:
self.currency = input('Enter currency (EUR, UAH, RUR, GBP, USD):\n').upper()
if self.currency not in self.currencies_to_usd:
print('Invalid currency, try again')
else:
break
while True:
try:
self.summ = float(input('Enter summ:\n'))
except ValueError:
print('Invalid summ, try again')
else:
if self.summ <= 0:
print('Invalid summ, try again')
else:
break
while True:
self.target_currency = input('Enter target currency (EUR, UAH, RUR, GBP, USD):\n').upper()
if self.target_currency not in self.currencies_to_usd:
print('Invalid currency, try again')
else:
break
conv1 = Converter(currencies)
while True:
if conv1.exit_flag:
break
conv1.input()
conv1.calculate()
|
5284a896780322c7295ed54a99aeebbdcfbc58ac | manuelmhtr/algortithms-course | /k-clustering/unionfind.py | 937 | 3.59375 | 4 | class Subset:
def __init__(self, tag):
self.tag = tag
self.parent = tag
self.rank = 0
def increase_rank(self):
self.rank += 1
def join(self, parent):
self.parent = parent
def is_root(self):
return self.parent == self.tag
class Union:
def __init__(self, collection):
self.collection = collection
self.size = len(collection)
def get_group(self, tag):
node = self.collection[tag]
while not node.is_root():
node = self.collection[node.parent]
return node.parent
def join(self, tag1, tag2):
group1 = self.get_group(tag1)
group2 = self.get_group(tag2)
if group1 == group2: return
node1 = self.collection[group1]
node2 = self.collection[group2]
self.size -= 1
if node1.rank > node2.rank:
node2.join(node1.tag)
elif node1.rank < node2.rank:
node1.join(node2.tag)
else:
node2.join(node1.tag)
node1.increase_rank()
|
6f834ba31b09a86c32e68fedfef6adac35858e52 | gingij4/Forritun | /grading.py | 482 | 4.34375 | 4 | grade = float(input("Input a grade: ")) # Do not change this line
if grade < 0.0 or grade > 10.0:
print("Invalid grade!") # Do not change this line
elif 5.0 <= grade <= 10.0:
print("Passing grade!") # Do not change this line
elif 0.0 <= grade < 5.0:
print("Failing grade!") # Do not change this line
#A passing grade is between 5.0 and 10.0 (both inclusive).
# The program pints out "Invalid grade!", "Passing grade!", or "Failing grade!", depending on the input. |
6154e01a3a34157eb1eeeb5db9d524e9f5bce1a3 | soo-youngJun/pyworks | /ch04/split.py | 340 | 3.953125 | 4 | # 두 수를 동시에 입력받아 계산하기
'''
n1 = input("첫째수 입력 : ")
x = int(n1)
n2 = input("둘째수 입력 : ")
y = int(n2)
print(n1, n2)
print(n1 + n2)
'''
n1, n2= input("두 개의 수 입력 : ").split() # 괄호 기호가 없으면 공백문자
print(n1 + n2)
x = int(n1)
y = int(n2)
#print(x, y)
print(x + y)
|
90b137e2bf472d784ef34354814f0e5c08471a48 | AYamaui/Practice | /exercises/word_concatenation.py | 4,324 | 4.21875 | 4 | """
An array of N words is given. Each word consists of small letters ('a' − 'z'). Our goal is to concatenate the words in such a way as to obtain a single word with the longest possible substring composed of one particular letter. Find the length of such a substring.
Write a function:
def solution(words)
that, given an array words containing N strings, returns the length of the longest substring of a word created as described above.
Examples:
1. Given N=3 and words=["aabb", "aaaa", "bbab"], your function should return 6. One of the best concatenations is words[1] + words[0] + words[2] = "aaaaaabbbbab". The longest substring is composed of letter 'a' and its length is 6.
2. Given N=3 and words=["xxbxx", "xbx", "x"], your function should return 4. One of the best concatenations is words[0] + words[2] + words[1] = "xxbxxxxbx". The longest substring is composed of letter 'x' and its length is 4.
3. Given N=4 and words=["dd", "bb", "cc", "dd"], your function should return 4. One of the best concatenations is words[0] + words[3] + words[1] + words[2] = "ddddbbcc". The longest substring is composed of letter 'd' and its length is 4.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
all the words are non−empty and consist only of lowercase letters (a−z);
S denotes the sum of the lengths of words; S is an integer within the range [1..100,000].
"""
def categorize_words(words):
same_letter_words = {}
first_letter_words = {}
last_letter_words = {}
letters = set()
for idx, word in enumerate(words):
first_letter = word[0]
last_letter = word[-1]
letters.add(first_letter)
letters.add(last_letter)
first_letter_count = 0
last_letter_count = 0
for letter in word:
if letter == first_letter:
first_letter_count += 1
else:
break
for i in range(len(word) - 1, -1, -1):
if word[i] == last_letter:
last_letter_count += 1
else:
break
if first_letter_count == len(word):
same_letter_words.setdefault(word[0], [])
same_letter_words[word[0]].append((idx, len(word)))
else:
first_letter_words.setdefault(word[0], [])
last_letter_words.setdefault(word[-1], [])
first_letter_words[word[0]].append((idx, first_letter_count))
last_letter_words[word[-1]].append((idx, last_letter_count))
return letters, first_letter_words, same_letter_words, last_letter_words
def solution(words):
max_substring_length = 0
max_substring_letter = None
letters, first_letter_words, same_letter_words, last_letter_words = categorize_words(words)
for letter in letters:
idx, length = max(last_letter_words.get(letter, []), key=lambda x: x[1], default=(None, 0))
substring_length = (length +
sum(length for _, length in same_letter_words.get(letter, [])) +
max(first_letter_words.get(letter, []),
key=lambda x: x[1] if x[0] != idx else 0, default=(None, 0))[1])
if substring_length > max_substring_length:
max_substring_length = substring_length
max_substring_letter = letter
for letter in letters:
idx, length = max(first_letter_words.get(letter, []), key=lambda x: x[1], default=(None, 0))
substring_length = (max(last_letter_words.get(letter, []),
key=lambda x: x[1] if x[0] != idx else 0, default=(None, 0))[1] +
sum(length for _, length in same_letter_words.get(letter, [])) +
length)
if substring_length > max_substring_length:
max_substring_length = substring_length
max_substring_letter = letter
return max_substring_letter, max_substring_length
if __name__ == '__main__':
# words = ["aabb", "aaaa", "bbab"]
# words = ["xxbxx", "xbx", "x"]
# words = ["dd", "bb", "cc", "dd"]
# words = ['a', 'b', 'c']
# words = ["aabb", "ccccc", "bbaa"]
# words = ["aabb", "ab", "bbaaccccc"]
words = ["aaaaabb", "ab", "bbaacc"]
print(solution(words))
|
3d5aa32e778a0a5b63d25c5d3bdf044d0ad705fd | VVivid/python-programs | /list/7.py | 126 | 3.703125 | 4 | """Write a Python program to remove duplicates from a list."""
a = [10, 20, 30, 20, 10, 50, 60, 40, 80, 50, 40]
print(set(a))
|
4de6b0f766938229ba5af415db8a160cc8147db2 | opastushkov/codewars-solutions | /CodeWars/Python/4 kyu/Sudoku Solution Validator/main.py | 574 | 3.546875 | 4 | def validSolution(board):
num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
for i in board:
if set(i) != num: return False
for x in range(9):
line = []
for y in range(9):
line.append(board[y][x])
if set(line) != num: return False
for step_x in range(3):
for step_y in range(3):
square = []
for x in range(3):
for y in range(3):
square.append(board[x + step_x * 3][y + step_y * 3])
if set(square) != num: return False
return True
|
596551f62a39052e1ed181e483282713f657c548 | Aayush789/C100-Project | /atm.py | 350 | 3.703125 | 4 | class Atm(object):
atm = input("enter your card number: ")
atm = input("enter your pin number: ")
def __init__(self,color):
self.color= color
def start(self):
print("CashWithdrawl")
def stop(self):
print("BalanceEnquiry")
atm = Atm("Blue")
print(atm.start())
print(atm.stop()) |
b83e0f00c7105f9b358c2af4d94cfd957cd88d00 | e-mohammadzadeh/Pattern-Finder-For-Binary-Numbers | /pattern_finder.py | 1,538 | 3.71875 | 4 | ######################################################################
############# Erfan Mohammadzadeh #################
############# Pattern Finder in Binary Num #################
######################################################################
import re
def get_binary_string():
binary_string = input("Enter a binary number (contain only 1s and 0s) to find pattern in it : ")
flag = True
while flag:
for index in binary_string:
flag = False
if index != "1" and index != "0":
binary_string = input("Must be a binary number, Enter again : ")
flag = True
break
return binary_string
def find_pattern_in_binary_string(binary_string):
pattern = system_forecast(binary_string)
if not checker(binary_string, pattern):
print("{} 's pattern is equal to {}.".format(binary_string, pattern))
else:
print("Number {} has NOT any pattern!!!".format(binary_string))
def system_forecast(binary_string):
regex = re.compile(r'(.+ .+)( \1)+')
try:
match = regex.search(number_separator(binary_string)).group(1)
except AttributeError:
print("Number {} has NOT any pattern!!!".format(binary_string))
exit()
return concatenation(match)
def number_separator(binary_string):
new_string = ""
for index in binary_string:
new_string += index + " "
return new_string
def concatenation(string):
return string.replace(" ", "")
def checker(string, sub_string):
return string.replace(sub_string, "")
if __name__ == "__main__":
find_pattern_in_binary_string(get_binary_string())
|
43de7a682c35fb9e36b13dc5d5db4710d29f1710 | kingtheoden/wills-life | /src/animal.py | 5,721 | 3.625 | 4 | from abc import ABCMeta, abstractmethod
from random import choice, randint
from emptyspace import EmptySpace
from life import Life
class Animal(Life, metaclass=ABCMeta):
def __init__(self, x, y):
self.sees_prey = False # Must come before self.get() methods to properly define thresholds
self.sees_lots_of_prey = False
self.age = 0
self.hunger = 0
self.ready_to_breed = False
self.is_hungry = False
self.could_eat = False
self.meals_since_procreation = 0
self.death_age = self.get_death_age()
self.hunger_death = self.get_hunger_death()
self.move_counter = randint(0, self.get_ticks_per_move() - 1)
Life.__init__(self, x, y)
@abstractmethod
def get_dead_animal(self):
raise NotImplementedError
@abstractmethod
def get_death_age(self):
raise NotImplementedError
@abstractmethod
def get_hunger_death(self):
raise NotImplementedError
@abstractmethod
def get_hunger_thresh(self):
raise NotImplementedError
@abstractmethod
def get_eat_thresh(self):
raise NotImplementedError
@abstractmethod
def get_meals_until_procreation(self):
raise NotImplementedError
@abstractmethod
def get_animal(self, x, y):
raise NotImplementedError
@abstractmethod
def get_prey(self):
raise NotImplementedError
@abstractmethod
def can_trample(self, thing):
raise NotImplementedError
@abstractmethod
def sees_lots_of_prey_check(self, num_of_prey):
raise NotImplementedError
def eat(self):
self.meals_since_procreation = Life.increase(self.meals_since_procreation, self.get_meals_until_procreation())
self.hunger = 0
self.is_hungry = False
self.could_eat = False
if self.meals_since_procreation >= self.get_meals_until_procreation():
self.ready_to_breed = True
def die(self):
self.age = Life.increase(self.age, self.death_age)
self.hunger = Life.increase(self.hunger, self.hunger_death)
if self.hunger > self.get_eat_thresh():
self.could_eat = True
if self.hunger > self.get_hunger_thresh():
self.is_hungry = True
if self.age >= self.death_age:
return self.get_dead_animal()
elif self.hunger >= self.hunger_death:
return self.get_dead_animal()
else:
return None
def propagate(self):
self.get_immediate_awareness(self.land)
if self.ready_to_breed:
other_animal = self.awareness.inner_get(type(self))
if other_animal is not None and other_animal.ready_to_breed:
empty = self.awareness.inner_get(EmptySpace)
if empty is not None:
self.meals_since_procreation = 0
self.ready_to_breed = False
other_animal.meals_since_procreation = 0
other_animal.ready_to_breed = False
return self.get_animal(empty.pos_x, empty.pos_y)
def move(self):
if not self.can_move():
return None
self.get_awareness(self.land)
self.sees_prey = False
num_of_prey = self.awareness.count_in_awareness(self.get_prey())
self.sees_lots_of_prey = self.sees_lots_of_prey_check(num_of_prey)
if self.is_hungry:
move = self.hungry_move()
elif self.ready_to_breed:
move = self.move_toward_thing(type(self))
elif self.could_eat:
move = self.hungry_move()
else:
move = self.laze_about()
return move
def hungry_move(self):
nearest_thing = self.awareness.get_nearest(self.get_prey())
self.sees_prey = type(nearest_thing) is self.get_prey()
move = self.move_toward_thing(self.get_prey())
if type(move) is self.get_prey():
self.eat()
elif type(move) is type(self):
move = self.laze_about()
return move
def can_move(self):
if self.move_counter >= self.get_ticks_per_move():
self.move_counter = 0
return True
else:
self.move_counter += 1
return False
def move_toward(self, thing):
dir_x = self.find_dir(self.pos_x, thing.pos_x)
dir_y = self.find_dir(self.pos_y, thing.pos_y)
thing_x = self.awareness.get_in_front(dir_x, 0)
thing_y = self.awareness.get_in_front(0, dir_y)
thing_opposite_x = self.awareness.get_in_front(-dir_x, 0)
thing_opposite_y = self.awareness.get_in_front(0, -dir_y)
if self.can_trample(type(thing_x)) and self.can_trample(type(thing_y)):
li = [thing_x, thing_y]
return choice(li)
elif self.can_trample(type(thing_x)):
return thing_x
elif self.can_trample(type(thing_y)):
return thing_y
elif dir_x is not 0 and self.can_trample(type(thing_opposite_x)):
return thing_opposite_x
elif dir_y is not 0 and self.can_trample(type(thing_opposite_y)):
return thing_opposite_y
else:
return None
def move_toward_thing(self, type_of_thing):
immediate_thing = self.awareness.inner_get(type_of_thing)
if immediate_thing is not None:
return immediate_thing
nearest_thing = self.awareness.get_nearest(type_of_thing)
if nearest_thing is not None:
return self.move_toward(nearest_thing)
return self.laze_about()
def laze_about(self):
empty = self.awareness.inner_get(EmptySpace)
return empty
|
494aaf8466bd096cc8ddee7ce20443db375322f0 | youssefarizk/ExercismPython | /meetup/meetup.py | 1,107 | 3.59375 | 4 | import calendar
import datetime
MeetupDayException = Exception
def meetup_day(year, month, day_, mode):
dayToString = {
'Monday': 0,
'Tuesday': 1,
'Wednesday': 2,
'Thursday': 3,
'Friday': 4,
'Saturday': 5,
'Sunday': 6
}
modeDic = {
'1st': [datetime.date(year,month,day) for day in range(8)[1:]],
'2nd': [datetime.date(year,month,day) for day in range(15)[8:]],
'3rd': [datetime.date(year,month,day) for day in range(22)[15:]],
'4th': [datetime.date(year,month,day) for day in range(29)[22:]],
'5th': [datetime.date(year,month,day) for day in range(29)[29:] if day in range(calendar.monthrange(year,month)[1]+1)],
'teenth': [datetime.date(year,month,day) for day in range(21)[10:]],
'last': [datetime.date(year,month,day) for day in range(calendar.monthrange(year,month)[1]+1)[calendar.monthrange(year,month)[1]-6:]]
}
findDay = dayToString[day_]
for i in modeDic[mode]:
if i.weekday() == findDay:
return i
raise MeetupDayException
|
f6eff11c4fdc0185274c474c60862b5ee11d3aa7 | wangweijun123/python_all | /workspace3/file.py | 1,003 | 3.515625 | 4 | # 路劲注意是正斜线
f = None
try:
f = open('E:/study/udacity/python/workspace3/my_file.txt', 'r')
# 读取文件
file_data = f.read()
# f.write('adbc') # exception
print(file_data)
except:
print("error")
finally:
print(f)
if f != None: # 等价于 f is not None
print('close')
f.close()
# 删除行 ctrl+shift+k
# 写文件(之前文件中内容被覆盖)
ff = open('E:/study/udacity/python/workspace3/my_file.txt', 'w')
ff.write('wangweijun')
ff.close()
# 向文件中追加添文本
fff = open('E:/study/udacity/python/workspace3/my_file.txt', 'a')
fff.write('aaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
fff.close()
# with : 使用完文件后自动关闭文件句柄
print('with : 使用完文件后自动关闭stream')
with open('E:/study/udacity/python/workspace3/my_file.txt', 'r') as ffff:
file_Data = ffff.read()
print(file_Data)
with open('E:/study/udacity/python/workspace3/my_file.txt', 'a') as file1:
file1.write('bbbbbbbbb')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.