blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c8d9acb81ae074a09b5bba7f60d7cb919bfd6a0b | bingzhong-project/leetcode | /algorithms/path-sum-iii/src/Solution.py | 1,052 | 3.65625 | 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 pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
def func(node, res):
if node.val == sum:
res[0] += 1
node_sums = [node.val]
left_sums = []
right_sums = []
if node.left:
left_sums = func(node.left, res)
if node.right:
right_sums = func(node.right, res)
for left_sum in left_sums:
temp = left_sum + node.val
if temp == sum:
res[0] += 1
node_sums.append(temp)
for right_sum in right_sums:
temp = right_sum + node.val
if temp == sum:
res[0] += 1
node_sums.append(temp)
return node_sums
res = [0]
if root:
func(root, res)
return res[0]
|
f05c2c875d5ce33ef7c9d706f086bcdee5205e03 | soufuru/Python_textbook_summary | /chapter3/chapter3-1.py | 1,437 | 4.15625 | 4 | # chapter3-1
########################
###---リストについて---###
########################
#あるクラスの平均点を求めるプログラム
points = [88, 76, 52, 90, 62]
sum_v = 0
for i in points:
sum_v += i #
print("平均点は", sum_v / len(points) )
#リストの値を一気に合計するsum()関数
sum_v = sum(points)
print("合計点は", sum_v)
#リストに入るのは数値だけではない
fruits = ["Apple","Banana","Mango","Orange"]
for i in fruits:
print("I like", i ,"!")
# print("「" + i + "」が好き")
# for文でインデックス番号付きの繰り返し enumerate()関数
for i,v in enumerate(fruits):
print(i,v)
# 0 Apple
# 1 Banana
# 2 Mango
# 3 Orange
######################
###---リストの操作---###
######################
# 要素の追加
num = [1,2,3]
num.append(4)
# リストの結合
n1 = [1,2]
n2 = [3,4]
n3 = n1 + n2 # n3 = [1,2,3,4]
n1 += n2 # n1 = [1,2,3,4]
n = [11,22]
n.extend([33,44]) # n = [11, 22, 33, 44]
# スライス
a = [10, 555, 30, 45]
print(a[1:3]) #[555,30]
##### 終了の位置はインデックス番号の+1を指定する必要がある
print(a[:3]) #[10, 555, 30]
print(a[-1]) #45 後ろから
print(a[0:3:2]) #[10,30] 0から2番目まで2個おき
# 要素の削除
del a[0]
print(a) #[555, 30, 45]
#################
###---タプル---###
#################
t = (1,2,3)
#要素を変更できない配列
|
cff15c82fbff49aa47986d3182beea726910fbd6 | chandlersupple/Area-of-a-Triangle | /main.py | 927 | 3.765625 | 4 | import math
class triangle_area():
def __init__(self):
print("Choose the proper method for your given knowns. Enter 'object.help_' for options")
def help_(self):
print("object.method")
print("object.SSA_scalene - two sides and one angle opposite a given side are given")
print("object.SSS_scalene - three sides are given")
print("object.help - lists methods")
def right_triangle(self, a, b):
ans = (0.5)*(a*b)
print("Area: %s units^2" %(ans))
def SSA_scalene(self, a, b, c_angle):
ans = (0.5)*(a*b*(math.sin(c_angle)))
print("Area: %s units^2" %(ans))
def SSS_scalene(self, a, b, c):
s = (0.5)*(a + b + c)
try:
ans = math.sqrt(s*(s - a)*(s - b)*(s - c))
print("Area: %s units^2" %(ans))
except:
print("Encountered Error: No Triangle")
|
cbeed23ff289ab34a5e2919e0b58932c44a1cb5b | ramonvaleriano/python- | /Livros/Introdução à Programação - 500 Algoritmos resolvidos/Capitulo 3/Exemplo 3a/Algoritmo83_InversoAbsoluto.py | 248 | 3.890625 | 4 | # Program: Algoritmo83_InversoAbsoluto.py
# Author: Ramon R. Valeriano
# Description:
# Developed: 23/03/2020 - 16:59
# Updated:
number = float(input("Enter with a number:"))
if number >= 0:
result = 1/number
else:
result = number*(-1)
print(result)
|
4871d9018ffebb749b6745c7d134e617af9ea6fe | team31153/test-repo | /Ryan/RyanChapter5HW/7barChart.py | 2,158 | 4.15625 | 4 | #!/usr/bin/env python3
import turtle
def draw_bar(t, height):
""" Get turtle t to draw one bar, of height. """
if height >= 200:
t.color("blue", "red")
t.begin_fill() # Added this line
t.left(90)
t.forward(height)
t.write(" "+ str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() # Added this line
t.penup()
t.forward(10)
t.down()
elif height >= 100:
t.color("blue", "yellow")
t.begin_fill() # Added this line
t.left(90)
t.forward(height)
t.write(" "+ str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() # Added this line
t.penup()
t.forward(10)
t.down()
elif height >= 0:
t.color("blue", "green")
t.begin_fill() # Added this line
t.left(90)
t.forward(height)
t.write(" "+ str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() # Added this line
t.penup()
t.forward(10)
t.down()
else:
t.color("blue", "green")
t.begin_fill() # Added this line
t.write(" "+ str(height))
t.left(90)
t.forward(height)
#t.write(" "+ str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() # Added this line
t.penup()
t.forward(10)
t.down()
wn = turtle.Screen() # Set up the window and its attributes
wn.bgcolor("lightgreen")
tess = turtle.Turtle() # Create tess and set some attributes
tess.color("blue", "red")
tess.pensize(3)
tess.penup()
tess.right(180)
tess.forward(300)
tess.left(90)
tess.forward(200)
tess.left(90)
tess.down()
xs = [48,117,-45,200,240,160,260,220,-30]
for a in xs:
draw_bar(tess, a)
wn.mainloop()
|
68491fceb645c5d510d75a8fbe23881c96784b6f | muazniwas/leetcodeanswers | /Two Sum/bruteforce.py | 381 | 3.515625 | 4 | class Solution(object):
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0, len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
solution = [i,j]
return solution |
846cffdfa10479491b6f5c8c0f1edcb0fdcee83d | d-ssilva/CursoEmVideo-Python3 | /CursoEmVideo/Mundo 3/1 - Tuplas/DESAFIO 077 - Contador de vogais.py | 380 | 4.03125 | 4 | """ Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar,
para cada palavra, quais são as suas vogais."""
palavra = ('Agatha', 'Graciele', 'Danilo', 'Daniele')
for p in palavra:
print(f'\nNa palavra {p} temos ', end='')
for letra in p:
if letra.lower() in 'aeiou':
print(letra, end='')
|
32571406804517b6b7451ea31392738f698355df | zhangyuejoslin/algorithms | /algorithm_homework/Tim_sort.py | 6,254 | 3.71875 | 4 | import random
import time
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
import numpy as np
def insertion_sort(array, left=0, right=None):
if right is None:
right = len(array) - 1
for i in range(left + 1, right + 1):
key_item = array[i]
j = i - 1
while j >= left and array[j] > key_item:
array[j + 1] = array[j]
j -= 1
array[j + 1] = key_item
return array
def merge_sort(left, right):
values = []
while len(left)>0 and len(right)>0:
if left[0] < right[0]:
values.append(left[0])
left.pop(0)
else:
values.append(right[0])
right.pop(0)
# to apend the rest values
for i in left:
values.append(i)
for j in right:
values.append(j)
return values
def timsort(array, partition_k):
min_run = partition_k
n = len(array)
for i in range(0, n, min_run):
insertion_sort(array, i, min((i + min_run - 1), n - 1))
size = min_run
while size < n:
for start in range(0, n, size * 2):
midpoint = start + size - 1
end = min((start + size * 2 - 1), (n-1))
merged_array = merge_sort(
left=array[start:midpoint + 1],
right=array[midpoint + 1:end + 1])
array[start:start + len(merged_array)] = merged_array
size *= 2
return array
def merge_sort1(values):
if len(values) > 1:
middle = len(values)//2
left = values[:middle]
right = values[middle:]
left = merge_sort1(left)
right = merge_sort1(right)
values = []
while len(left)>0 and len(right)>0:
if left[0] < right[0]:
values.append(left[0])
left.pop(0)
else:
values.append(right[0])
right.pop(0)
# to apend the rest values
for i in left:
values.append(i)
for j in right:
values.append(j)
return values
def insert_sort1(values):
for i in range(1, len(values)):
j = i - 1
while values[i] < values[j]:
if j < 0 :
break
values[i], values[j] = values[j],values[i]
i = j
j = j-1
return values
generated_list = []
start = 0
end = 100
partition_k = 2
partition_end = end
spend_all = []
count = 0
partition_list = []
check_hybrid_K_N = False # The first experiment to check relation between k and n
merge_start_time = 0
merge_end_time = 0
merge_time = 0
insertion_start_time = 0
insertion_end_time = 0
insertion_time = 0
hybrid_start_time = 0
hybrid_end_time = 0
hybrid_time = 0
hybrid_list = []
merge_list = []
insertion_list = []
if check_hybrid_K_N:
while count<30:
spend_time_list = []
generated_list = []
for each_i in range(start, end):
n = random.randint(0, 100)
generated_list.append(n)
while partition_k <= partition_end:
new_list = generated_list.copy()
start_time = time.time()
timsort(new_list, partition_k)
end_time = time.time()
if len(partition_list) < end-1:
partition_list.append(partition_k)
spend_time_list.append((end_time - start_time))
partition_k +=1
spend_all.append(spend_time_list)
count += 1
partition_k = 2
hybrid_array = np.array(spend_all)
hybrid_list = list(np.mean(hybrid_array,axis=0))# hybrid sort
x_list = [x for x in partition_list]
y_list = [y for y in hybrid_list]
x_major_locator=MultipleLocator(30)
ax = plt.gca()
ax.xaxis.set_major_locator(x_major_locator)
ax.set_xlabel('k')
ax.set_ylabel('y')
ax.plot(x_list, y_list, color='r', linewidth=1, alpha=0.6)
plt.savefig('/VL/space/zhan1624/CV_homework/algorithm_homework/output_image/timsort_300.png')
else: # the second experiment to compare hybrid sort with merge and insertion sort. K = 16
while count < 30:
generated_list = []
each_hybrid_list = []
each_merge_list = []
each_insertion_list = []
while len(generated_list) < 100:
n = random.randint(0, 20)
generated_list.append(n)
new_list1 = generated_list.copy()
new_list2 = generated_list.copy()
new_list3 = generated_list.copy()
hybrid_start_time = time.time()
timsort(new_list1,16)
hybrid_end_time = time.time()
hybrid_time = hybrid_start_time -hybrid_end_time
each_hybrid_list.append(hybrid_time)
merge_start_time = time.time()
merge_sort1(new_list2)
merge_end_time = time.time()
merge_time = merge_end_time - merge_start_time
each_merge_list.append(merge_time)
insertion_start_time = time.time()
insert_sort1(new_list3)
insertion_end_time = time.time()
insertion_time = insertion_end_time - insertion_start_time
each_insertion_list.append(insertion_time)
hybrid_list.append(each_hybrid_list)
merge_list.append(each_merge_list)
insertion_list.append(each_insertion_list)
count += 1
hybrid_list = np.mean(np.array(hybrid_list), axis=0)
merge_list = np.mean(np.array(merge_list),axis=0)
insertion_list = np.mean(np.array(insertion_list),axis=0)
y_list_hybrid = [y1 for y1 in hybrid_list]
y_list_merge = [y2 for y2 in merge_list]
y_list_insertion = [y3 for y3 in insertion_list]
x_list = [x for x in range(100)]
x_major_locator=MultipleLocator(10)
ax = plt.gca()
ax.xaxis.set_major_locator(x_major_locator)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.plot(x_list, y_list_hybrid, color='r', linewidth=1, alpha=0.6, label="hybrid")
ax.plot(x_list, y_list_merge, color='b', linewidth=1, alpha=0.6, label="merge")
ax.plot(x_list, y_list_insertion, color='g', linewidth=1, alpha=0.6,label="insertion")
plt.savefig('/VL/space/zhan1624/CV_homework/algorithm_homework/output_image/comparision.png')
|
5f7e2090cd463cd9d62074197aafd3fab15e1c73 | FutureInfinity/Darkness | /darkness-engine/tools/codegen/HistoryIterator.py | 4,304 | 3.546875 | 4 |
class HistoryIterException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class HistoryIter(object):
def __init__(self, *args):
self._it = iter(*args)
self.history = []
self.history_ptr = 0
self.history_length = 0
self.count = 0
def __iter__(self):
return self
def count_reset(self):
self.count = 0
def count_get(self):
return self.count;
def set_history_length(self, len):
self.history_length = len
def prev_data_length(self):
if len(self.history) == 0:
return 0
return self.history_ptr
def current(self):
if len(self.history) == 0:
raise HistoryIterException(0)
if self.history_ptr >= len(self.history):
raise HistoryIterException(0)
return self.history[self.history_ptr]
def next(self):
self.count += 1
# length of 0 will cause immediate return
if self.history_length == 0:
return self._it.next()
# history not full and we're on the last cell
if len(self.history) == 0:
self.history.append(self._it.next())
res = self.history[self.history_ptr]
self.history_ptr = len(self.history)
return res
elif len(self.history) < self.history_length and self.history_ptr == len(self.history):
self.history.append(self._it.next())
res = self.history[self.history_ptr]
self.history_ptr = len(self.history)
return res
elif len(self.history) == self.history_length and self.history_ptr == len(self.history):
self.history.append(self._it.next())
self.history = self.history[1:]
return self.history[self.history_ptr-1]
elif self.history_ptr < len(self.history):
# somewhere in between
res = self.history[self.history_ptr];
self.history_ptr += 1
return res
def prev(self, count = 1):
if self.history_ptr == 0:
raise HistoryIterException(1)
if self.history_ptr - count < 0:
raise HistoryIterException(2)
self.history_ptr = self.history_ptr - count
return self.history[self.history_ptr]
class HistoryIterTestException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def test_setup():
test_data = [0, 1, 2, 3, 4, 5]
hi = HistoryIter(test_data)
return hi
def test_first_value():
hi = test_setup()
print '[TEST HistoryIter]: first value'
val = hi.next()
if val != 0:
raise HistoryIterTestException(3)
print '[TEST HistoryIter]: first value: PASS'
def test_prev_value_failure():
hi = test_setup()
val = hi.next()
val = hi.next()
val = hi.next()
print '[TEST HistoryIter]: prev value fail'
raised = False
try:
val = hi.prev()
except HistoryIterException:
raised = True
if not raised:
raise HistoryIterTestException(3)
print '[TEST HistoryIter]: prev value fail: PASS'
def test_history_length_one():
hi = test_setup()
hi.set_history_length(1)
print '[TEST HistoryIter]: test behaviour of history length 1'
val = hi.next()
if val != 0:
raise HistoryIterTestException(3)
val = hi.prev()
if val != 0:
raise HistoryIterTestException(3)
raised = False
try:
val = hi.prev()
except HistoryIterException:
raised = True
if not raised:
raise HistoryIterTestException(3)
val = hi.next()
if val != 0:
raise HistoryIterTestException(3)
val = hi.next()
if val != 1:
raise HistoryIterTestException(3)
val = hi.prev()
if val != 1:
raise HistoryIterTestException(3)
val = hi.next()
if val != 1:
raise HistoryIterTestException(3)
val = hi.next()
if val != 2:
raise HistoryIterTestException(3)
val = hi.next()
if val != 3:
raise HistoryIterTestException(3)
val = hi.prev()
if val != 3:
raise HistoryIterTestException(3)
raised = False
try:
val = hi.prev()
except HistoryIterException:
raised = True
if not raised:
raise HistoryIterTestException(3)
print '[TEST HistoryIter]: test behaviour of history length 1: PASS'
def test_history_eof():
print '[TEST HistoryIter]: test eof'
hi = test_setup()
val = hi.next()
val = hi.next()
val = hi.next()
val = hi.next()
val = hi.next()
raised = False
try:
val = hi.prev()
except HistoryIterException:
raised = True
if not raised:
raise HistoryIterTestException(3)
print '[TEST HistoryIter]: test eof: PASS'
def perform_history_iter_tests():
test_first_value();
test_prev_value_failure();
test_history_length_one();
test_history_eof();
|
a1ffc8a35a97515b595072931c341f710f43a9bf | Mikhail-QA/IU | /Web_services/Subject_page/Сheck_all_elements_on_the_subject_page/test_пользователь_не_авторизован_проверка_Body.py | 7,738 | 3.546875 | 4 | """
Проверить наличия элементов на странице Алгебра 8 класс в Body
Пользователь не авторизован И проверка наличия инфоблока в Предмете Литература 8класс
URL: https://web-dev01.interneturok.ru/algebra/8-klass"
На странице отображаются: http://joxi.ru/vAWbBDLHkK1YM2
"""
import allure
from selenium.webdriver.common.by import By
from Web_services.SetUp import StartInterneturokClassMethod
from Web_services.URL import SubjectPage
@allure.feature("Страница Предмет-Класс (Алгебра 8 класс и Литература 8 класс)")
@allure.story("Проверка наличия элементов в Body для не авторизованного пользователя")
class ChecksAllElementsInSubjectPageTheBodyUserNotAuth(StartInterneturokClassMethod):
@allure.step("Перейти на страницу урока Литература 8 класс")
def test_000_go_literature(self):
StartInterneturokClassMethod = self.driver
go_page = SubjectPage(StartInterneturokClassMethod)
go_page.go_literature_8_grade()
@allure.step("В предмете Литература на странице Предмет/Класс отображается информационный блок")
def test_001_info_block(self):
self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "div.notification__header"))
with allure.step(
"В инфоблоке отображается текст (На сайте представлены уроки по отдельным произведениям школьной программы, а темы и содержание уроков не всегда строго соответствуют учебникам.)"):
self.assertEqual(
u"На сайте представлены уроки по отдельным произведениям школьной программы, а темы и содержание уроков не всегда строго соответствуют учебникам.",
self.driver.find_element_by_css_selector("div.notification__title").text)
with allure.step("В инфоблоке отображается Ссылка с текстом (В связи с этим хотим заметить)"):
self.assertEqual(u"В связи с этим хотим заметить",
self.driver.find_element_by_css_selector("a.notification__toggle").text)
with allure.step("В инфоблоке отображается кнопка (Закрыть)"):
self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "a.notification__close"))
@allure.step("Перейти на страницу Алгебра 8 класс")
def test_002_open_page(self):
StartInterneturokClassMethod = self.driver
go_page = SubjectPage(StartInterneturokClassMethod)
go_page.go_algebra_8_grade()
@allure.step("Отображается заголовок (Алгебра)")
def test_title_body(self):
self.assertEqual(u"Алгебра", self.driver.find_element_by_css_selector("h1.subject-title").text)
@allure.step("Отображается заголовок (8 класс)")
def test_number_grades(self):
self.assertEqual(u"8 класс", self.driver.find_element_by_css_selector("span.subject-nav__grade").text)
@allure.step("Отображается иконка (Звезда платный урок)")
def test_abonement_widget_displayed(self):
self.assertTrue(self.driver.find_element_by_css_selector("a.lesson-paid"))
@allure.step("Отображается кнопка перехода на 7 класс")
def test_switcher_link_left(self):
self.assertTrue(self.driver.find_element_by_css_selector("a.subject-nav_prev"))
@allure.step("Отображается кнопка перехода на 9 класс")
def test_switcher_link_right(self):
self.assertTrue(self.driver.find_element_by_css_selector("a.subject-nav_next"))
@allure.step("Над учебниками отображается текст (Смотреть уроки как в учебнике:)")
def test_text_name_books(self):
self.assertEqual(u"Смотреть уроки как в учебнике:",
self.driver.find_element_by_class_name("subject-book__title").text)
@allure.step("На странице отображается книга (Алгебра 8 класс (Мордкович А.Г.))")
def test_books_item_one(self):
self.assertTrue(self.driver.find_element_by_css_selector("main a.subject-book:nth-child(1)"))
@allure.step("На странице отображается книга (Алгебра 8 класс (Макарычев Ю.Н.))")
def test_books_item_two(self):
self.assertTrue(self.driver.find_element_by_css_selector("main a.subject-book:nth-child(2)"))
@allure.step(
"Первый блок уроков имеет заголовок (Алгебраические дроби. Арифметические операции над алгебраическими дробями) ")
def test_zagolovok_temi_yroka(self):
self.assertEqual(u"Алгебраические дроби. Арифметические операции над алгебраическими дробями",
self.driver.find_element_by_xpath("//div/ul/li[1]/h4").text)
@allure.step("Отображается список уроков")
def test_list__item(self):
self.assertTrue(self.driver.find_element_by_class_name("subject-theme__sublist"))
@allure.step("Отображается вкладки урока")
def test_icon_tab_grades(self):
self.assertTrue(self.driver.find_element_by_class_name("subject-theme__icons"))
@allure.step("Отображается вкладка урока (Видеоурок)")
def test_mini_icon_video_displayed(self):
self.assertTrue(self.driver.find_element_by_class_name("icon-video"))
@allure.step("Отображается вкладка урока (Текстовый урок)")
def test_mini_icon_text_displayed(self):
self.assertTrue(self.driver.find_element_by_class_name("icon-text"))
@allure.step("Отображается вкладка урока (Тренажеры)")
def test_mini_icon_trainers_displayed(self):
self.assertTrue(self.driver.find_element_by_class_name("icon-trainers"))
@allure.step("Отображается вкладка урока (Тесты)")
def test_mini_icon_test_displayed(self):
self.assertTrue(self.driver.find_element_by_class_name("icon-test"))
@allure.step(
"Урок Основные сведения о рациональных выражениях и их преобразованиях имеет пометку (Свободный доступ) ")
def test_label_free_displayed(self):
self.assertTrue(self.driver.find_element_by_css_selector("span.subject-theme__label_free"))
@allure.step("Отображается список тем урока")
def test_levyai_list_yrokov(self):
self.assertTrue(self.driver.find_element_by_css_selector("ul.nav.menu__list"))
@allure.step("Отображается кнопка (Оставить отзыв)")
def test_button_review_displayed(self):
self.assertTrue(self.is_element_present(By.CSS_SELECTOR, "div.review__close"))
|
47f9c629a106d88dd0ecf2fa1628bd241990ca50 | TY-Jeong/numerical-recipes | /Machine Learning/neural_network.py | 2,848 | 3.609375 | 4 | # Simple fully connected neural network Following the text book "Make Your Own Neural Network" by Tariq Rashid
import numpy as np
def tanh(x):
return np.tanh(x)
def tanh_deriv(x):
return 1.0 - np.tanh(x)**2
class NeuralNetwork:
def __init__(self, structure, learning_rate):
self.layers = len(structure)
self.i_nodes = int(structure[0])
self.h1_nodes = int(structure[1])
self.h2_nodes = int(structure[2])
self.o_nodes = int(structure[3])
self.w_ih1 = np.random.normal(0.0, structure[0]**(-0.5), (self.h1_nodes, self.i_nodes))
self.w_h1h2 = np.random.normal(0.0, structure[1]**(-0.5), (self.h2_nodes, self.h1_nodes))
self.w_h2o = np.random.normal(0.0, structure[2]**(-0.5), (self.o_nodes, self.h2_nodes))
self.act = tanh
self.act_deriv = tanh_deriv
self.lr = learning_rate
def feedforward(self, input_list):
inputs = (np.asfarray(input_list)).reshape([len(input_list),1])
inputs_h1 = np.dot(self.w_ih1, inputs)
outputs_h1 = self.act(inputs_h1)
inputs_h2 = np.dot(self.w_h1h2, outputs_h1)
outputs_h2 = self.act(inputs_h2)
inputs_o = np.dot(self.w_h2o, outputs_h2)
outputs_o = inputs_o
return outputs_o
def backprop(self, input_list, target_list):
inputs = (np.asfarray(input_list)).reshape([len(input_list), 1])
targets = (np.asfarray(target_list)).reshape([len(target_list), 1])
inputs_h1 = np.dot(self.w_ih1, inputs)
outputs_h1 = self.act(inputs_h1)
inputs_h2 = np.dot(self.w_h1h2, outputs_h1)
outputs_h2 = self.act(inputs_h2)
inputs_o = np.dot(self.w_h2o, outputs_h2)
outputs_o = inputs_o
# application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
errors_o = outputs_o - targets
errors_h2 = np.dot(self.w_h2o.transpose(), errors_o)
errors_h1 = np.dot(self.w_h1h2.transpose(), errors_h2)
# update the weights with the derivative (slope) of the loss function
self.w_h2o -= self.lr * np.dot(errors_o, outputs_h2.transpose())
self.w_h1h2 -= self.lr * np.dot(errors_h2 * self.act_deriv(inputs_h2), outputs_h1.transpose())
self.w_ih1 -= self.lr * np.dot(errors_h1 * self.act_deriv(inputs_h1), inputs.transpose())
input_list = range(10)
target_list = [1.1]
NN = NeuralNetwork([10, 30, 30, 1], 0.1)
print("Input= ", input_list, "Output= ", "%4f" % NN.feedforward(input_list)[0, 0], " Target= ", target_list)
epochs = 30
for e in range(epochs):
NN.backprop(input_list, target_list)
print("Epoch= %4d" % (e + 1), "Output= ", "%4f" % NN.feedforward(input_list)[0, 0], " Target= ", target_list[0])
|
edf18a0e46f26d171451e38163c235a39a49818a | nehapokharel/pythonPractice | /question6.py | 178 | 3.6875 | 4 | w = input('enter sentence: ')
if 'not' and 'poor' in w:
a = w.index('poor')
b = w.index('not')
c = w[b:a+len('poor')]
w = w.replace(c,'good')
print(w)
|
ca0c1f2a5e009558b7465ba5a0dc969ea25ece61 | murali-kotakonda/PythonProgs | /PythonBasics1/excel1/Ex2_5.py | 854 | 3.8125 | 4 | # print("A1 TO C1")
#read by ROW WISE
from openpyxl import load_workbook
from openpyxl import Workbook
# create workbook obj
workbook = load_workbook('response1.xlsx')
#get sheet obj
sheet = workbook.active
print("print multiple selected rows")
rows = sheet[1:3] # read rows from 1 to 3
print("**********print entire sheet*****************")
for row in rows:
print("")
for cell in row:
print(cell.value , end= " ")
"""
print("selected read by row and column")
for row in sheet.iter_rows(min_row=1,
max_row=2,
min_col=1,
max_col=3):
print(row)
for row in sheet.iter_rows(min_row=1,
max_row=2,
min_col=1,
max_col=3,values_only=True):
print(row)
"""
|
0361a9f9f33338046d4bf9bd04cdc95fd7cd90d7 | johnvanmeerten/TiCT-VIPROG-15 | /Les02/Perkovic 2.28.py | 169 | 3.609375 | 4 | lst = [1, 4, 6, 3, 2, 4, 7]
index = (int(len(lst)/2))
print(index)
print(lst[index])
lst.sort(reverse=True)
print(lst)
x = lst[0]
lst.pop(0)
lst.append(x)
print(lst) |
1de557866c28cda30ad3a7cb8729a8ebbbb2c47d | Bedoya1123/taller_clase | /Cristian+Bedoya.py | 645 | 3.75 | 4 |
# coding: utf-8
# In[3]:
print "Hola Mundo"
# $\sum_{p}li(x^p)-log(2)$
# In[ ]:
# # Hola mundo
# python
# In[9]:
2+4+5/6.0-3
# In[8]:
3/2
# In[10]:
3.0/2
# In[11]:
3+5j
# In[12]:
(3+5j)-(1-1j)
# In[13]:
abs(3+5j)
# In[14]:
5**3
# In[15]:
int(_13)
# In[16]:
float(_15)
# In[17]:
round(_13)
# In[18]:
complex(_15)
# In[19]:
max(2,8,30)
# In[20]:
min(2,9,32)
# In[21]:
a=5
# In[22]:
print a
# In[23]:
a
# In[24]:
x,y,z,a=1,2,3,4
# In[25]:
x,y=a,z
# In[26]:
x
# In[27]:
y
# In[28]:
x,y=5,8
# In[30]:
if x>y:
print("el mayor es",y)
else:
print("el menor es",x)
# In[ ]:
|
0f332f4f410a2154f1d422dfce4c47afbd74a174 | AchrafONEBourajjai/PythonNetworking | /Json.py | 310 | 3.796875 | 4 | #how to code and decode json
import json
I = ['ali','ahmad','amine','achraf']
print(json.dumps(I))#dumps() converts objects to json string
s = json.dumps(I)
print(type(s)) #to know type of variable
s = '["ali","ahmad","amine","achraf"]'
print(json.loads(s)) #json object to list
print(json.loads(s)[3]) #prouve |
b5568225226eea3488b290601aa419acc6e98dcb | WindboyBase/Who_am_I | /simp_serv.py | 1,140 | 3.765625 | 4 | #此示例为服务器
import socket
address = ('0.0.0.0',9999)
#创建socket
server = socket.socket()
#绑定地址:bind()函数
server.bind(address)
#监听 listen(),10表示:如果服务器没有能力去接收的话,后面可以有多少个队列在此等候
server.listen(10)
print('服务器已启动',address)
#接收请求:accept()函数,接收服务器的请求,这个时候在这儿会形成阻塞,也叫阻塞函数。如果没有客户端连接,它会
#在这一直等,等到有客户端连接时,这个时候才会有返回值,
#sockfd是返回的新的套接字,刚刚我们创建的套接字叫server,它是用来监听的,而返回的这个则是用来进行数据传输的
#addr就是客户端返回的地址
sockfd,addr = server.accept()
#接收完之后,可以打印一下
print('收到客户端连接请求:',addr)
#数据的收发,recv(),1024表示最大接收的1024个字节
data =sockfd.recv(1024)
#网络上的数据是经过编码或是格式转化的,decode是要将它格式转回来
print(data.decode())
#关闭连接
sockfd.close()
server.close()
|
610fbe124aa7ca61ba709f29d4ff69d42a803b94 | SBolsec/SKRJ | /03/zadatak1.py | 2,597 | 3.859375 | 4 | import sys
def load_matrix(file):
matrix = {}
header = file.readline().strip()
if not header: # check if header exists
raise RuntimeError("Header does not exist!")
header = header.split(" ")
if len(header) != 2: # header must contain two values
raise RuntimeError("Header must contain number of rows and columns!")
matrix["size"] = int(header[0]), int(header[1])
while True:
line = file.readline().strip()
if not line: # check if line is empty
break
line = line.split(" ")
if len(line) != 3: # check if line contains enough values
raise RuntimeError("Each matrix entry must contain three values, two indices and the value")
matrix[int(line[0]), int(line[1])] = float(line[2])
return matrix
def print_matrix(matrix):
for i in range(matrix.get('size', (0, 0))[0]):
for j in range(matrix.get('size', (0, 0))[1]):
print("{:6.2f}".format(matrix.get((i, j), 0)), end=" ")
print()
def save_result(path, matrix):
with open(path, "w", encoding='utf8') as file:
size = matrix.get('size', (0, 0))
file.write("{} {}\n".format(size[0], size[1]))
for i in range(size[0]):
for j in range(size[1]):
value = matrix.get((i, j), 0)
if value != 0:
file.write("{} {} {:.2f}\n".format(i, j, matrix.get((i, j))))
def multiply_matrices(a, b):
size_a = a.get('size', (0, 0))
size_b = b.get('size', (0, 0))
if size_a[1] != size_b[0]:
raise RuntimeError("Incompatible matrices!")
matrix = {'size': (size_a[0], size_b[1])}
for i in range(size_a[0]):
for j in range(size_b[1]):
res = 0
for x in range(size_a[1]):
res += a.get((i, x), 0) * b.get((x, j), 0)
matrix[i, j] = res
return matrix
def main():
if len(sys.argv) != 3:
print("Invalid number of command line arguments! Two arguments are required.")
print("First argument is path to file containing matrices.")
print("Second argument is path to save the results to.")
exit(1)
with open(sys.argv[1], "r", encoding='utf8') as file:
matrix_a = load_matrix(file)
matrix_b = load_matrix(file)
print("A:")
print_matrix(matrix_a)
print("\nB:")
print_matrix(matrix_b)
matrix_res = multiply_matrices(matrix_a, matrix_b)
print("\nA*B:")
print_matrix(matrix_res)
save_result(sys.argv[2], matrix_res)
if __name__ == "__main__":
main()
|
74e0dae9cee6d043043dd799fc32c2f59a197147 | arrebole/Ink | /src/algorithm/solved_leetcode/31.next-permutation/solution.py | 1,252 | 3.640625 | 4 | #! /usr/bin/env python
from typing import List
class Solution(object):
def nextPermutation(self, nums):
return self.lexicographicPermute(nums)
def lexicographicPermute(self, array: List):
i = self.findMaxOrdered(array)
if i == -1:
array.sort()
return array
j = self.findMaxBigIndex(array, array[i])
array[i], array[j] = array[j], array[i]
return self.recover(array, i+1, len(array)-1)
# findMaxBigIndex 找到比n大的数的最大索引
def findMaxBigIndex(self, array: List[int], n: int):
result = -1
for i, v in enumerate(array):
if v > n:
result = i
return result
# findMaxOrdered 寻找数组中最大升序
def findMaxOrdered(self, array: List[int]):
result = -1
for i in range(0, len(array)-1):
if array[i+1] > array[i]:
result = i
return result
def recover(self, array: List[int], lo: int, hi: int):
while lo < hi:
array[lo], array[hi] = array[hi], array[lo]
lo += 1
hi -= 1
return array
if __name__ == '__main__':
print(
Solution().nextPermutation([3, 2, 1])
) |
05bb03f4033f9f2749627cedfae766e4df3ec7f5 | CodeForContribute/Algos-DataStructures | /Array/search_element_in_rotated_Array.py | 1,682 | 3.703125 | 4 | def pivotBinarySearch(arr, n, key):
pivot = findPivot(arr,0, n-1)
if pivot == -1:
return binarySearch(arr, 0, n, key)
if arr[pivot] == key:
return pivot
if arr[0] <= key:
return binarySearch(arr, 0, pivot-1, key)
return binarySearch(arr, pivot+1, n-1, key)
def findPivot(arr,low,high):
if high < low:
return -1
if high == low:
return low
mid = int((low+high)//2)
if mid < high and arr[mid] > arr[mid+1]:
return mid
if mid > low and arr[mid] < arr[mid-1]:
return mid-1
if arr[low] >= arr[mid]:
return findPivot(arr, low, mid-1)
return findPivot(arr, mid+1, high)
def binarySearch(arr,low,high, data):
if high < low:
return -1
mid = int((low + high)//2)
if data == arr[mid]:
return mid
if arr[mid] > data:
return binarySearch(arr,low, mid-1, data)
return binarySearch(arr, mid+1, high, data)
################# Improved Solution ##############################
def search(arr, low, high, data):
if low > high:
return -1
mid = (low + high)//2
if arr[mid] == data:
return mid
if arr[low] <= arr[mid]:
if arr[low] <= data <= arr[mid]:
return search(arr,low,mid-1, data)
return search(arr, mid+1, high, data)
if arr[mid] <= data <= arr[high]:
return search(arr, mid+1, high, data)
return search(arr,low, mid-1, data)
if __name__ == '__main__':
arr = [5,6,7,8,9,10,1,2,3]
n = len(arr)
key = 3
print("Index of the element is:",pivotBinarySearch(arr, n, key))
print("\n")
print("Index of the element is:",search(arr, 0, n-1, key))
|
c801216940638daf8dd5028529e864a34bf42150 | esix/competitive-programming | /e-olymp/2xxx/2864/main.py | 196 | 3.9375 | 4 | #!/usr/bin/env python3
from math import sin
a, b, h = map(float, input().split(' '))
def f(x):
return 3 * sin(x)
x = a
while x <= b:
y = f(x)
print("%.3f %.3f" % (x, y))
x += h |
ec11bc66fa29c9951d621abfd87d39468889b578 | Richimetz/introprogramacion | /Practico_1/ejer_10.py | 285 | 3.609375 | 4 | def timeConv (v):
n = int(input("cantidad de tramos realizados: "))
for i in range(0,n):
v = print("duración de tramo: ")
n = v % 60
print(n)
r = (v - m)/60
print(r)
resultado = str(r) + ":" + str(n)
print(timeConv(266)) |
548cedc64e1f8e119e92f7a5d047fb62fe8b4ee1 | keli0215/Coding-Excercise | /stackSort.py | 623 | 4.1875 | 4 | class Solution(object):
def stacksort(self, stack):
if len(stack) != 0:
temp = stack.pop() #First pop all the elements from the stack and store poped element in variable 'temp'.
self.stacksort(stack)
self.stackinsert(stack, temp) #Now stack is empty and 'stackinsert' function is called and it inserts
# element at the bottom of the stack.
def stackinsert(self, stack, x):
if not stack or x > stack[-1]:
stack.append(x)
else:
temp = stack.pop()
self.stackinsert(stack, x)
stack.append(temp)
S = Solution()
stack = [-2, 7, 0, 28, -9, 32]
S.stacksort(stack)
print stack
|
b1da60e212cd02e26276488725534145fcb87042 | hah-ak/algorithm-study | /programmers/biggstNum.py | 245 | 3.671875 | 4 | def solution(numbers):
numbers = list(map(str, numbers))
numbers.sort(key = lambda x: x*3, reverse = True)
if numbers[0] == 0:
return '0'
return ''.join(numbers)
print(solution([0,0,0,0,10,101,1000,111]))
|
adef0e89893e398718ebcfa658405379756a9ab0 | sanshitsharma/pySamples | /leetcode/zigzag_iterators.py | 1,743 | 3.6875 | 4 | #!/usr/bin/python
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.d = {0: v1, 1: v2}
self.currItr = 0
self.itrsIndx = []
if len(self.d[0]) > 0:
self.itrsIndx.append(0)
else:
self.isCurrV1 = False
self.itrsIndx.append(-1)
if len(self.d[1]) > 0:
self.itrsIndx.append(0)
else:
self.itrsIndx.append(-1)
def next(self):
"""
:rtype: int
"""
val = self.d[self.currItr][self.itrsIndx[self.currItr]]
self.itrsIndx[self.currItr] += 1
if self.itrsIndx[self.currItr] > len(self.d[self.currItr])-1:
self.itrsIndx[self.currItr] = -1
if self.currItr == 0 and self.itrsIndx[1] != -1:
self.currItr = 1
elif self.currItr == 1 and self.itrsIndx[0] != -1:
self.currItr = 0
return val
def hasNext(self):
"""
:rtype: bool
"""
if self.itrsIndx[self.currItr] != -1:
return True
i = self.currItr
while i < len(self.itrsIndx) and self.itrsIndx[i] == -1:
i += 1
if i > len(self.itrsIndx) - 1:
return False
self.currItr = i
return True
# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())
if __name__ == "__main__":
v1 = [1,2]
v2 = [3,4,5,6]
i, v, = ZigzagIterator(v1, v2), []
while i.hasNext():
v.append(i.next())
print v |
2dec7acc7b021b7894b7bba11d7b6c8d02b17499 | ShaneNelsonCodes/100Days_Python | /Day11_Blackjack.py | 2,474 | 3.796875 | 4 | from Day11_Blackjack_Art import logo
import random
import os
def clear():
os.system('cls')
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal_card():
rand_card = cards[random.randint(0, len(cards)-1)]
return rand_card
def calculate_score(player_list):
total = sum(player_list)
if 11 in player_list and total > 21:
for i, card in enumerate(player_list):
if card == 11:
player_list[i] == 1
if total == 21:
return 0
else:
return total
def play_game():
user_cards = []
computer_cards = []
for x in range(0, 2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
cont_game = True
while cont_game:
print(logo)
print(f"Your cards: {user_cards}")
print(f"Computer's first card: {computer_cards[0]}")
if calculate_score(computer_cards) == 0:
print("You lose, computer has blackjack!")
cont_game = False
elif calculate_score(user_cards) == 0:
print("You win, you have blackjack!")
cont_game = False
add_card_cont = True
while add_card_cont:
add_card = input("Type 'y' to get another card, type 'n' to pass:")
if add_card == 'y':
user_cards.append(deal_card())
if calculate_score(user_cards) > 21:
add_card_cont = False
if add_card == 'n':
add_card_cont = False
while calculate_score(computer_cards) <= 17:
computer_cards.append(deal_card())
print(f"Your final hand: {user_cards}")
print(f"Computer's final hand: {computer_cards}")
if calculate_score(computer_cards) == 21:
print("You lose!")
elif calculate_score(computer_cards) > 21:
print("You win, computer busts!")
elif calculate_score(user_cards) > 21:
print("You lose, you busted!")
elif calculate_score(user_cards) > calculate_score(computer_cards):
print("You win!")
elif calculate_score(user_cards) < calculate_score(computer_cards):
print("You lose!")
elif calculate_score(user_cards) == calculate_score(computer_cards):
print("push")
else:
print("error")
cont_game = False
while input("Do you want to play a game of Blackjack? Type 'y' or 'n':") == 'y':
clear()
play_game()
|
5def9383de1ab2ea5017caf654679136b11f03a8 | KennaNeitch/KennaNeitch.github.io | /python/Case_Study_Textual_Analysis.py | 3,649 | 3.703125 | 4 | from bs4 import BeautifulSoup
from urllib import request
url = "https://raw.githubusercontent.com/humanitiesprogramming/scraping-corpus/master/full-text.txt"
html = request.urlopen(url).read()
soup = BeautifulSoup(html, "lxml")
raw_text = soup.text
texts = eval(soup.text)
# print(len(raw_text))
# print(len(texts))
import nltk
from nltk import word_tokenize
tokenized_texts = []
for text in texts:
tokenized_texts.append(word_tokenize(text))
for tokenized_text in tokenized_texts:
# print("=====")
# print(len(tokenized_text))
# print(tokenized_text[0:20])
doyle = tokenized_texts[:5]
bronte = tokenized_texts[5:]
# print(len(doyle))
# print(len(bronte))
def normalize(tokens):
"""Takes a list of tokens and returns a list of tokens that has been normalized by lowercasing all tokens and removing Project Gutenberg frontmatter."""
#lowercase all words
normalized = [token.lower() for token in tokens]
#very rough end of front matter.
end_of_front_matter = 90
#very rough beginning of end matter.
start_of_end_matter = -2973
#get only the text between the end matter and front end_of_front_matter
normalized = normalized[end_of_front_matter:start_of_end_matter]
return normalized
# print(normalize(bronte[0])[:200])
# print(normalize(bronte[0])[-200:])
doyle = [normalize(text) for text in doyle]
bronte = [normalize(text) for text in bronte]
# print(doyle[0][:30])
from nltk.corpus import stopwords
# print(stopwords.words("english")[0:30])
def remove_stopwords(tokens):
return [token for token in tokens if token not in stopwords.words("english")]
# print(len(doyle[0]))
# print("start cleaning")
# doyle = [remove_stopwords(text) for text in doyle]
# print("doyle done")
# bronte = [remove_stopwords(text) for text in bronte]
# print("bronte done")
#
# print(len(doyle[0]))
example = nltk.FreqDist(doyle[0])
# print(example.most_common(20))
doyle_freq_dist = [nltk.FreqDist(text) for text in doyle]
bronte_freq_dist = [nltk.FreqDist(text) for text in bronte]
def print_top_words(freq_dist_text):
"""Takes a frequency distribution of a text and prints out the top 10 words in it."""
print("=====")
print(freq_dist_text.most_common(10))
print("=====")
# for text in doyle_freq_dist:
# print_top_words(text)
# for text in bronte_freq_dist:
# print_top_words(text)
# print(doyle_freq_dist[0]["holmes"])
# print(bronte_freq_dist[0]["would"])
def get_counts_in_corpora(token, corpus_one, corpus_two):
"""Take two corpora, represented as lists of frequency distributions, and token query. Return the frequency of that token in all the texts in the corpus. The result should be a list of two lists, one for each text."""
corpus_one_counts = [text_freq_dist[token] for text_freq_dist in corpus_one]
corpus_two_counts = [text_freq_dist[token] for text_freq_dist in corpus_two]
return [corpus_one_counts, corpus_two_counts]
# print(get_counts_in_corpora("evidence", doyle_freq_dist, bronte_freq_dist))
# print(get_counts_in_corpora("reader", doyle_freq_dist, bronte_freq_dist))
# print(get_counts_in_corpora("!", doyle_freq_dist, bronte_freq_dist))
# print(get_counts_in_corpora("?", doyle_freq_dist, bronte_freq_dist))
# results = get_counts_in_corpora("!", doyle_freq_dist, bronte_freq_dist)
# corpus_one_results = results[0]
# corpus_two_results = results[1]
#
# print(corpus_one_results)
# print(corpus_two_results)
# from matplotlib import pylab
# nltk.Text(doyle[0]).dispersion_plot(["evidence", "clue", "science", "love", "say", "said"])
# nltk.Text(bronte[0]).dispersion_plot(["evidence", "clue", "science", "say", "said"])
|
6bc4dbf7f77b486953ee2b4957670ee40a8309a2 | Jagdale-pooja/program | /reverse_arr.py.py | 117 | 3.859375 | 4 | array=[10,11,12,13,14,15]
print("array before reverse",array)
arr2=array[::-1]
print("array after reverse",arr2)
|
f62a6df9e077e6f6c79787a14d332369360fbc98 | kookkig11/Python_Language | /ex5-1.py | 554 | 3.9375 | 4 | i = 0
sum = 0
while True :
x = input()
# check non-input ?
if x == "" :
break
else :
num = float(x)
# loop start and set default value
if i == 0 :
max = num
min = num
# num is positive integer
if num >= 0 :
if num > max :
max = num
if num < min :
min = num
sum += num
# count loop
i = i + 1
# average
avg = sum / i
# output
print("%.2f %.2f" %(max, min))
print("%.2f %.2f" %(sum, avg)) |
7bef991e0b0cc4a0ccbb6365b1ad0fae7bce83cf | KristinCovert/Bootcamp | /PythonProjects/fibonacciCalc.py | 478 | 3.875 | 4 | __author__ = 'Kristin'
def range_top():
top_range = input('Up to what number would you like to calculate the Fibonacci: ')
return top_range
def fibonacci(rt):
i = 0
j = 1
fibonacci_list = []
for number in range(0, rt):
k = i + j
fibonacci_list.append(k)
i = j
j = k
return fibonacci_list
if __name__ == '__main__':
x = range_top()
result = fibonacci(x)
print result
l = len(result)
print l
|
e587cc8e56ab08640d4091836b2d976c9b0af2ea | Tradingstrategie/Test-Projekt | /String-Permutation.py | 1,446 | 3.765625 | 4 | # Permutation:
# Eingabe:
zeichenkette = list(input('Bitte gib eine Zeichenkette ein: '))
# Funktion Fakultät:
def fakultät_r(n):
if n == 0:
return 1
else:
return (n * fakultät_r(n-1))
# Funktion Permutation:
def permutation(zeichenkette):
if len(zeichenkette) == 1:
return zeichenkette
else:
neueliste = []
for i in range(0, len(zeichenkette)):
element = list(zeichenkette[i])
restliste = list(zeichenkette[:i] + zeichenkette[i + 1 : len(zeichenkette) + 1])
längerest = fakultät_r(len(restliste))
xliste = permutation(restliste)
for j in range(0, längerest):
permutation1 = list(element + list(xliste[j]))
neueliste.append(permutation1)
return neueliste
# Permutationen ermitteln:
permutationen = permutation(zeichenkette)
anzahlPermutationen = len(permutationen)
# Permutationen zusammensetzen:
permutationsliste = []
for i in range(0, anzahlPermutationen):
pstring = ''
permutation = permutationen[i]
for j in range(0, len(zeichenkette)):
pstring = pstring + permutation[j]
permutationsliste.append(pstring)
# Ausgabe:
print()
print('Anzahl Permutationen:', anzahlPermutationen)
print('Ermittelte Permutationen:')
for i in range(0, anzahlPermutationen):
print(permutationsliste[i], end=' ')
print()
|
62798aaa0821639e7a3079c946c53c23ec9e32fa | Carolinacapote/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 541 | 3.859375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
from sys import argv
number_arguments = len(argv) - 1
if (number_arguments == 0):
print("{} arguments.".format(number_arguments))
elif (number_arguments == 1):
print("{} argument:".format(number_arguments))
print("{}: {}".format(number_arguments, argv[number_arguments]))
else:
print("{} arguments:".format(number_arguments))
i = 1
while i <= number_arguments:
print("{}: {}".format(i, argv[i]))
i += 1
|
6ccf7faf51030e55ad6304d48adf19eb2f860dc9 | jaeyson/py-scripts | /diff.py | 1,838 | 3.71875 | 4 | #####################################################
# how to use:
# python3 diff.py csv1 csv2 output
# where 1st column from csv1 not found in csv2
# should NOT go inside output file.
# contents from newcsv are the updated rows from csv1
#####################################################
import csv
import os
import sys
first_file = sys.argv[1]
second_file = sys.argv[2]
output_file = sys.argv[3]
data = {} # creating dictionary to store the data
with open(first_file, 'r') as lookuplist:
reader1 = csv.reader(lookuplist)
for col in reader1:
data[col[0]] = col[0] # stores the data from column 0 to column 1 in the data list
with open(second_file, 'r') as csvinput, open(output_file, 'w', newline='') as f_output:
reader2 = csv.reader(csvinput)
csv_output = csv.writer(f_output)
for col in reader2:
# if the column 1 in csv1 does not match with column 0 in csv2 extract
if col[0] in data:
# col = [col[0]] # this only saves the first column
csv_output.writerow(col) # writes all the data that is matched in cmdb wlc extract
#####################################################
# how to use:
# python3 diff.py csv1 csv2 newcsv
# where 1st column from csv1 not found in csv2
# should NOT go inside newcsv file.
# contents from newcsv are the updated rows from csv1
#####################################################
# import sys
# import os
# checklist = []
# os.system('rm ' + sys.argv[3])
# with open(sys.argv[1], 'r') as t1, open(sys.argv[2], 'r') as t2:
# fileOne = t1.readlines()
# fileTwo = t2.readlines()
# with open(sys.argv[3], 'w') as outFile:
# for line in fileOne:
# checkTwo = line.split(",")
# checklist.append(checkTwo[0])
# for line in fileTwo:
# checkOne = line.split(",")
# if checkOne[0] not in checklist:
# outFile.write(line)
|
3813e265f2aef2ac691dc7a28a0211918346d2d0 | msmccue/APCSP-P3 | /hangmanTestingV2.py | 246 | 3.796875 | 4 | theWord = "fair"
#if the user guesses letter "f",
# we would change the variable "theWord" to
# contain "air"
foundLetter = theWord.find("e")
if (foundLetter > -1):
theWord = theWord[:foundLetter] + theWord[foundLetter+1:]
print(theWord)
|
a0efd0079899d45676b286d3fbc5213757bd35a7 | JACKSUYON/TRABAJO5_PROGRAMACION_1_B | /boleta_7.py | 769 | 3.703125 | 4 | #boleta 7: clacular el area lateral del cilindro
#input
pi=3.1416
radio1=float(input("ingrese el radio:"))
generatriz1=int(input("ingrese la generatriz:"))
#processing
area_lateral_cilindro=(2*pi*radio1*generatriz1)
#verificador
verificador=(area_lateral_cilindro>=29)
#output
print("###############################################")
print("# BOLETA DEL AREA DEL CILINDRO #")
print("###############################################")
print("# datos")
print("#pi: ",pi )
print("#radio1: ",radio1)
print("#generatriz1: ",generatriz1)
print("#area latera del cilindro: ",area_lateral_cilindro)
print("#################################################")
print("#area lateral del cilindro>=29",verificador)
|
778d3c819a14048813f420a75ca9d9c27c2fd22b | shamayn/aoc2020 | /day5.py | 1,443 | 3.6875 | 4 | import math
def findSeat(seatcode):
rowcode = seatcode[0:7]
colcode = seatcode[7:10]
row = binarySearch(rowcode, 127)
col = binarySearch(colcode, 7)
print("seat:", row, col)
return (row, col)
def binarySearch(code, max):
start = 0
end = max
for i in range(len(code)):
if code[i] == "F" or code[i] == "L":
end = math.floor((end + start)/ 2)
elif code[i] == "B" or code[i] == "R":
start = math.ceil((end + start)/ 2)
#print(code[i], start, end)
return start
def findMaxSeatId(seatcodes):
maxseat = 0
for sc in seatcodes:
seat = findSeat(sc)
seatid = getSeatId(seat[0], seat[1])
if seatid > maxseat:
maxseat = seatid
return maxseat
def findMissingSeats(seatcodes):
seats = set()
for sc in seatcodes:
seats.add(findSeat(sc))
missingseatids = []
for i in range(128):
for j in range(8):
if (i, j) not in seats:
seatid= getSeatId(i,j)
missingseatids.append(getSeatId(i, j))
print("missing: ", seatid)
def getSeatId(row, col):
return row * 8 + col
def testFindSeat():
input = "FBFBBFFRLR"
result = findSeat(input)
if result == (44, 5):
print("Pass")
else:
print("Fail")
def main():
testFindSeat()
inputList = []
f = open('data/day5_input.txt', 'r')
lines = f.readlines()
for line in lines:
inputList.append(line.strip())
print(len(inputList))
#print("find max seat: ", findMaxSeatId(inputList))
printMissingSeats(inputList)
if __name__ == '__main__':
main() |
61f098ba2c13663b0388db5115849dcbcfb4fdb4 | ToBeTree/cookbookDemo | /4-迭代器和生成器/4-3自定义迭代.py | 367 | 4.125 | 4 | # 实现一个自定义的模式
# 一个生成器的主要特征是只回应next的操作
# 一个函数有yield就可以是生成器了
def frange(star, stop, step):
n = star
while n < stop:
yield n
n += step
for i in frange(1, 3, 0.5):
print(i)
# 原生的range函数不支持浮点型step
# for i in range(1, 10, 0.5):
# print(i)
|
10ca6223125562a474e13280f8c2c4b8f9ca5867 | maryam98hasan/Computer-Graphics | /Draw spiral polygon.py | 385 | 4.28125 | 4 | # Python program to draw spiral polygon in turtle programming
import turtle
screen = turtle.Screen()
screen.bgcolor("black")
t = turtle.Turtle()
t.color("red")
t.speed(0)
numberOfSides = 9
lengthOfSide = 100
exteriorAngle = 360 / numberOfSides
for i in range(200):
t.forward(lengthOfSide)
t.right(exteriorAngle)
lengthOfSide = lengthOfSide - 0.5
turtle.done() |
edcfabc6ef02b8edce79ecc967e2676d412fbab9 | saikrishna1103/first | /twelve.py | 132 | 3.546875 | 4 | b=int(input())
tem=b
re=0
while(b>0):
dig=b%10
re=re*10+dig
b=b//10
if(tem==re):
print("yes")
else:
print("no")
|
4c7009d21c5707bfdd97767a8c4d0339f8bbf8f6 | JeanGrijp/Algorithms | /Estruturas de Dados/arvore.py | 17,687 | 3.953125 | 4 | class No:
def __init__(self, key, value, left=None, right=None):
self.key = key
self.value = value
self.left = left
self.right = right
class Tree:
def __init__(self):
self.root = None
self.size = 0
def insert(self, key, value):
cont = True
noAtual = self.root
noSentinela = None
if type(key) == int and type(value) == str:
while cont:
if noAtual is None:
# arvore ta vazia
self.root = No(key, value)
self.size += 1
cont = False
elif key < noAtual.key:
noSentinela = noAtual #só pra guardar a referência do No before
noAtual = noAtual.left# o No atual avança pra left do no before
if noAtual is None:# se True, é porque o value que eu quero insert é menor que o ultimo nó da arvore(folha)
noSentinela.left = No(key, value) #a importância de guardar a referencia before.
self.size += 1
cont = False
elif key > noAtual.key:# aqui o value que eu quero insert é maior que o no current
noSentinela = noAtual
noAtual = noAtual.right
if noAtual is None: #se True, o value que é maior que a folha da arvore.
noSentinela.right = No(key, value)
self.size += 1
cont = False
elif key == noAtual.key: # aqui é pra caso for igual, apenas substituir, outra opção era não fazer nada.
noAtual = No(key, value)
self.size += 1
cont = False
def search(self, key):
no = self.root
while no is not None:
if no.key == key:
return no.value
elif key > no.key:
no = no.right
else:
no = no.left
raise KeyError(key)
def __len__(self):
return self.size
def remove(self, key):
key = int(key)
noAtual = self.root
noSentinela = None
while noAtual is not None:
if noAtual.key == key:
if noAtual.left is None and noAtual.right is None:
if noSentinela is None:
self.root = None
self.size = 0
else:
if noSentinela.left == noAtual:
noSentinela.left = None
self.size -= 1
elif noSentinela.right == noAtual:
noSentinela.right = None
self.size -= 1
elif (noAtual.left is None and noAtual.right is not None) or (noAtual.left is not None and noAtual.right is None):
if noSentinela is None:
if noAtual.left is not None:
self.root = noAtual.left
self.size -= 1
else:
self.root = noAtual.right
self.size -= 1
else:
if noAtual.left is not None:
if noSentinela.left == noAtual:
noSentinela.left = noAtual.left
else:
noSentinela.right = noAtual.left
else:
if noSentinela.left == noAtual:
noSentinela.left = noAtual.right
else:
noSentinela.right = noAtual.right
elif (noAtual.left is not None) and (noAtual.right is not None):
terceiro = noAtual
segundo = noAtual.right
primeiro = noAtual.right.left
while primeiro is not None:
terceiro = segundo
segundo = primeiro
primeiro = segundo.left
if noSentinela is None:
if self.root.right.key == segundo.key:
segundo.left = self.root.left
else:
if terceiro.left.key == segundo.key:
terceiro.left = None
else:
terceiro.right = None
segundo.left = noAtual.left
segundo.right = noAtual.right
self.root = segundo
else:
if noSentinela.left.key == noAtual.key:
noSentinela.left = segundo
else:
noSentinela.right = segundo
if terceiro.left.key == segundo.key:
terceiro.left = None
else:
terceiro.right = None
segundo.left = noAtual.left
segundo.right = noAtual.right
break
noSentinela = noAtual
if key < noAtual.key:
noAtual = noAtual.left
else:
noAtual = noAtual.right
def remove(self, key):
'''
3 casos:
Caso 1
o nó a ser removido não tem filhos
esse caso é simples, basta setar a ligação
do pai para None
Caso 2
o nó a ser removido tem somente 1 filho
basta colocar o seu filho no lugar dele
Caso 3
o nó a ser removido possui dois filhos
basta pegar o menor elemento da subárvore à right
'''
key = int(key)
noAtual = self.root
noSentinela = None
while noAtual is not None:
# verifica se encontrou o nó a ser removido
if noAtual.key == key:
# caso 1: o nó a ser removido não possui filhos (nó folha)
if noAtual.left is None and noAtual.right is None:
# verifica se é a root
if noSentinela is None:
self.root = None
self.size -= 1
# verifica se é filho à left ou à right
else:
if noSentinela.left == noAtual:
noSentinela.left = None
self.size -= 1
elif noSentinela.right == noAtual:
noSentinela.right = None
self.size -= 1
# caso 2: o nó a ser removido possui somente um filho
elif (noAtual.left is None and noAtual.right is not None) or (noAtual.left is not None and noAtual.right is None):
# verifica se o nó a ser removido é a root
if noSentinela is None:
# verifica se o filho de noAtual é filho à left
if noAtual.left is not None:
self.root = noAtual.left
self.size -= 1
else: # senão o filho de noAtual é filho à right
self.root = noAtual.right
self.size -= 1
else:
# verifica se o filho de noAtual é filho à left
if noAtual.left is not None:
# verifica se noAtual é filho à left
if noSentinela.left and noSentinela.left.key == noAtual.key:
noSentinela.left = noAtual.left
else:# senão noAtual é filho à right
noSentinela.right = noAtual.left
else:# senão o filho de noAtual é filho à right
# verifica se noAtual é filho à left
if noSentinela.left and noSentinela.left.key == noAtual.key:
noSentinela.left = noAtual.right
else:# senão noAtual é filho à right
noSentinela.right = noAtual.right
# caso 3: o nó a ser removido possui dois filhos
# pega-se o menor elemento da subárvore à direita
elif (noAtual.left is not None) and (noAtual.right is not None):
terceiro = noAtual
segundo = noAtual.right
primeiro = noAtual.right.left
while primeiro is not None:
terceiro = segundo
segundo = primeiro
primeiro = segundo.left
# verifica se o nó a ser removido é a root
if noSentinela is None:
# Caso especial: o nó que vai ser a nova root é filho da root
if self.root.right.key == segundo.key:
segundo.left = self.root.left
else:
'''
verifica se o segundo é filho à left ou à right
para setar para None o segundo
'''
if terceiro.left.key == segundo.key:
terceiro.left = None
else:
terceiro.right = None
# seta os filhos à right e left de segundo
segundo.left = noAtual.left
segundo.right = noAtual.right
# faz com que o segundo seja a root
self.root = segundo
else:
'''
verifica se noAtual é filho à left ou à right
para setar o segundo como filho do pai do noAtual (noSentinela)
'''
if noSentinela.left.key == noAtual.key:
noSentinela.left = segundo
else:
noSentinela.right = segundo
'''
verifica se o segundo é filho à left ou à right
para setar para None o segundo
'''
if terceiro.left.key == segundo.key:
terceiro.left = None
else:
terceiro.right = None
# seta os filhos à right e left de segundo
segundo.left = noAtual.left
segundo.right = noAtual.right
break
noSentinela = noAtual
# verifica se vai para left ou right
if key < noAtual.key:
noAtual = noAtual.left
else:
noAtual = noAtual.right
return noAtual.value
def height(self, no):
if no == None or no.left == None and no.right == None:
return 1
else:
if self.height(no.left) > self.height(no.right):
return 1 + self.height(no.left)
else:
return 1 + self.height(no.right)
def nosucessor(self, apaga): # O parametro é a referencia para o No que deseja-se apagar
paidosucessor = apaga
sucessor = apaga
atual = apaga.dir # vai para a subarvore a direita
while atual != None: # enquanto nao chegar no Nó mais a esquerda
paidosucessor = sucessor
sucessor = atual
atual = atual.esq # caminha para a esquerda
# *********************************************************************************
# quando sair do while "sucessor" será o Nó mais a esquerda da subarvore a direita
# "paidosucessor" será o o pai de sucessor e "apaga" o Nó que deverá ser eliminado
# *********************************************************************************
if sucessor != apaga.dir: # se sucessor nao é o filho a direita do Nó que deverá ser eliminado
paidosucessor.esq = sucessor.dir # pai herda os filhos do sucessor que sempre serão a direita
# lembrando que o sucessor nunca poderá ter filhos a esquerda, pois, ele sempre será o
# Nó mais a esquerda da subarvore a direita do Nó apaga.
# lembrando também que sucessor sempre será o filho a esquerda do pai
sucessor.dir = apaga.dir # guardando a referencia a direita do sucessor para
# quando ele assumir a posição correta na arvore
return sucessor
def remover(self, v):
if self.root == None:
return False # se arvore vazia
atual = self.root
pai = self.root
filho_esq = True
# ****** Buscando o valor **********
while atual.item != v: # enquanto nao encontrou
pai = atual
if v < atual.item: # caminha para esquerda
atual = atual.esq
filho_esq = True # é filho a esquerda? sim
else: # caminha para direita
atual = atual.dir
filho_esq = False # é filho a esquerda? NAO
if atual == None:
return False # encontrou uma folha -> sai
# fim laço while de busca do valor
# **************************************************************
# se chegou aqui quer dizer que encontrou o valor (v)
# "atual": contem a referencia ao No a ser eliminado
# "pai": contem a referencia para o pai do No a ser eliminado
# "filho_esq": é verdadeiro se atual é filho a esquerda do pai
# **************************************************************
# Se nao possui nenhum filho (é uma folha), elimine-o
if atual.esq == None and atual.dir == None:
if atual == self.root:
self.root = None # se raiz
else:
if filho_esq:
pai.esq = None # se for filho a esquerda do pai
else:
pai.dir = None # se for filho a direita do pai
# Se é pai e nao possui um filho a direita, substitui pela subarvore a direita
elif atual.dir == None:
if atual == self.root:
self.root = atual.esq # se raiz
else:
if filho_esq:
pai.esq = atual.esq # se for filho a esquerda do pai
else:
pai.dir = atual.esq # se for filho a direita do pai
# Se é pai e nao possui um filho a esquerda, substitui pela subarvore a esquerda
elif atual.esq == None:
if atual == self.root:
self.root = atual.dir # se raiz
else:
if filho_esq:
pai.esq = atual.dir # se for filho a esquerda do pai
else:
pai.dir = atual.dir # se for filho a direita do pai
# Se possui mais de um filho, se for um avô ou outro grau maior de parentesco
else:
sucessor = self.nosucessor(atual)
# Usando sucessor que seria o Nó mais a esquerda da subarvore a direita do No que deseja-se remover
if atual == self.root:
self.root = sucessor # se raiz
else:
if filho_esq:
pai.esq = sucessor # se for filho a esquerda do pai
else:
pai.dir = sucessor # se for filho a direita do pai
sucessor.esq = atual.esq # acertando o ponteiro a esquerda do sucessor agora que ele assumiu
# a posição correta na arvore
return True
def pre_ordem(self, no):
if no is None:
return
a = "{}:'{}'".format(no.key, no.value)
b = self.pre_ordem(no.left)
c = self.pre_ordem(no.right)
final_string = a
if b != None:
final_string += "->" + str(b)
if c != None:
final_string += "->" + str(c)
return final_string
def ordem(self, no):
if no is None:
return
b = self.ordem(no.left)
a = "{}:'{}'".format(no.key, no.value)
c = self.ordem(no.right)
final_string = a
if b != None:
final_string += "->" + str(b)
if c != None:
final_string += "->" + str(c)
return final_string
def pos_ordem(self, no):
if no is None:
return
b = self.ordem(no.left)
c = self.ordem(no.right)
a = "{}:'{}'".format(no.key, no.value)
final_string = a
if b != None:
final_string += "->" + str(b)
if c != None:
final_string += "->" + str(c)
return final_string
|
648b5b0725f2df7bfe71ce059bb22fec6b22b691 | Grug16/CS112-Spring2012 | /hw05/nims.py | 861 | 3.921875 | 4 | #!/usr/bin/env python
"""nims.py
A simple competitive game where players take stones from stone piles.
"""
print "Welcome to Nims. Whoever takes the last stone loses."
stonecount = int(raw_input("Number of stones in the pile: "))
maxtake = int(raw_input("Max number of stones per turn: "))
player = 1
taken = 0
while stonecount>0:
# Ask player for stones taken.
taken = int( raw_input("%i stones left. Player %i [1-%i]: " % (stonecount, player, maxtake)))
if taken >= 1 and taken <= maxtake:
if taken <= stonecount:
# Successful Move
stonecount -= taken
if player == 1: # Switches Players
player = 2
else:
player = 1
else:
print "Not enough stones."
else:
print "Invalid stone selection"
print "Player %i wins!" % (player) |
f04cc9fdae490629df8ee3f3ebd479df3b7c3819 | vip7265/ProgrammingStudy | /leetcode/problems/sjw_remove_the_nth_node_from_end_of_list.py | 1,222 | 3.515625 | 4 | """
Problem URL: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
""" Second version with dummy """
dummy = ListNode()
dummy.next = head
arr = []
curr = dummy
while curr:
arr.append(curr)
curr = curr.next
L = len(arr)
arr[L-n-1].next = arr[L-n].next
return arr[0].next
""" First version wihtout dummy """
# # Collect all nodes
# arr = []
# curr = head
# while curr:
# arr.append(curr)
# curr = curr.next
# # edge case: return empty list
# if len(arr) == 1:
# return None
# # edge case: remove last one
# if n == 1:
# arr[-2].next = None
# return head
# # edge case: remove first one
# if n == len(arr):
# return arr[1]
# # normal case
# arr[-n-1].next = arr[-n+1]
# return arr[0] |
ad8d3c51d4fc20fe4c6f1585a6da27f7e1daf77a | marielymoon/Ejercicios-Python | /conv_funciones.py | 409 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def cambiar(cantidad):
tipo_cambio= 18.81
return cantidad/tipo_cambio
def main():
print('Calculadora de Dolares')
print('')
cantidad = float (input('Ingresa la cantidad de pesos que quieres convertir: '))
result= cambiar(cantidad)
print('${} pesos mx ${}dolares (us)'.format(cantidad, result))
print(' ')
if __name__=='__main__':
main()
|
1fe9c086f48709dfe96a161654e6cf5ebaa41dc9 | bindu0999/py-assignment | /p10.py | 354 | 4.1875 | 4 | #Write a Python program to search a character in a given string using slicing
s = input("Enter string : ")
c = input("Enter a search character : ")
flag = 0
for i in range(0,len(s)-1):
if c == s[i]:
print("Given charcter found at the position index ",i," in String "+s)
flag = 1
if flag == 0:
print("Given charcter not found")
|
705ab23680aba538702f4335d825ec55d2173e6f | Alves-Bruno/Paradigmas_de_Programacao | /extras/HFYT/aux.py | 1,018 | 3.65625 | 4 | import curses
from random import randint
class Screen(object):
def __init__(self, MAX_X, MAX_Y, difficulty):
self.MAX_X = MAX_X
self.MAX_Y = MAX_Y
self.exit = 0
self.vidas = 3
self.difficulty = difficulty
class Lists(object):
def __init__(self, TAM_MAX, colunm):
self.list = [' ' for x in range(TAM_MAX)]
self.colunm = colunm
self.tam = TAM_MAX
self.pontos = 0
def draw(self, win):
[win.addch(X+1, self.colunm, self.list[X]) for X in range(0, self.tam - 1)]
def insert(self, hard):
self.list.pop()
x = randint(0, hard)
if (x == 0):
self.list.insert(0, chr(randint(97, 122)))
else:
self.list.insert(0, ' ')
def detector(self, key):
if key in self.list:
self.list[self.list.index(key)] = '*'
self.pontos += 1
|
9a3a7df8b0cb8bbc6e75870e2483db06e5bd4f23 | mykespb/edu | /tests/summapn.py | 2,173 | 4.09375 | 4 | #!/usr/bin/env python3
# программа ищет суммы положительных и отрицательных чисел в списке
# (C) М.Колодин, 2021-06-25, 2021-08-26 1.2
# -------------------------------------- подготовка
import random
ranger = range(10)
def makerand(size=10, low=-100, upp=100):
""" сделать список из size элементов,
минимальное допустимое значение lower,
максимальное допустимое значение upper
"""
return [random.randint(low, upp) for _ in range(size)]
def head(s):
""" напечатать заголовок
"""
sep = 20 * "-"
print(f"\n{sep}\n{s}\n{sep}\n")
def test(f):
""" запустить функцию на тест
"""
sep = 20 * "-"
print("\n", sep, "function:", f.__name__, sep, "\n")
for i in ranger:
a = makerand()
print("in: ", a)
print("out:", f(a))
# -------------------------------------- функция 1
def sumpn1(a):
"""функция sumpn1
считает суммы + и - чисел
"""
sump = sumn = 0
for e in a:
if e < 0:
sumn += e
else:
sump += e
return sumn, sump
test(sumpn1)
# -------------------------------------- функция 2
def sumpn2(a):
"""функция sumpn2 - тоже про суммы
"""
return (
sum([x for x in a if x<0]),
sum([x for x in a if x>0])
)
test(sumpn2)
# -------------------------------------- конец вызовов
print("\n\nпро функции: классы, имена, описания, вызовы:\n")
print(sumpn1)
print(type(sumpn1))
print(sumpn1.__name__)
print(sumpn1.__doc__)
print([-1, 0, 1], "-->", sumpn1([-1, 0, 1]))
# ~ про функции: классы, имена, описания, вызовы:
# ~ <function sumpn1 at 0x7fa676971790>
# ~ <class 'function'>
# ~ sumpn1
# ~ функция sumpn1
# ~ считает суммы + и - чисел
# ~ [-1, 0, 1] --> (-1, 1)
# -------------------------------------- конец всего
|
24de8c41e123a3983e3471a711e7ce3369a44d01 | alisher13/CitronResearch | /match.py | 3,828 | 3.8125 | 4 | import csv
from datetime import datetime, timedelta
import os.path
def get_stock_prices(file_name):
# date (object, not string) will be the dictionary key, adjusted
# close will be the value something like {"2017-01-01": 200, ...}
data = {}
if not os.path.isfile(file_name):
print("ERROR: %s doesn't exist" % file_name)
return data
with open(file_name) as ticker_csv:
ticker_reader = csv.reader(
ticker_csv, delimiter=',', quotechar='|')
next(ticker_reader, None) # skip the header
for row in ticker_reader:
try:
data[datetime.strptime(row[0], "%Y-%m-%d")] = float(row[5])
except Exception as e:
# print('Skipping row: ', row, e)
# headers appear multiple times in the input data
pass
return data
def get_price_on_or_before_date(date, prices):
"""Given the date, find the price on that date, if the price doesn't
exist on that date, go back one day and return the price, do so
5 days until the price is found. Because, assuming date is on
Monday, if there's no price for Monday, look at Sunday, and of
course no price for Sunday, so do it for Saturday, and lastly for
Friday. For some reason Friday maybe a holiday, so do it 2 more
days.
The return value will look something like (200, 1), where 200 is the
price and 1 is the 1 day before the given date. The values for 1 can
be anything between 0 and 5 inclusive. 0 means the price is for the
given date. If no price is found, an empty tuple is returned.
"""
for i in range(6):
current_date = date - timedelta(days=i)
if current_date in prices:
return float(prices[current_date]), i
return (None, None)
def get_tweets(citron_file):
"""Get tweet date, text, and symbol from the Citron CSV file."""
tweets = []
with open(citron_file) as csvfile:
ticker_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
next(ticker_reader, None) # skip the header
for row in ticker_reader:
if row[3].strip():
tweets.append({
'date': datetime.strptime(row[1], "%y-%m-%d"),
'text': row[2],
'ticker': row[3].strip()
})
return tweets
output = []
tweets = get_tweets('stock data/@CitronResearch222.csv')
for tweet in tweets:
print('processing %s' % tweet['ticker'])
stock_prices = get_stock_prices('stock data/%s.csv' %
tweet['ticker'])
prev_day_price, days_early = get_price_on_or_before_date(
tweet['date'] - timedelta(days=1), stock_prices
)
days = (0, 3, 30, 180, 365)
price_changes = []
for day in days:
price, diff = get_price_on_or_before_date(
tweet['date'] + timedelta(days=day), stock_prices
)
if price is None or prev_day_price is None or\
(day in (0, 3) and diff != 0):
price_changes.append('')
else:
price_changes.append(
(price - prev_day_price) / prev_day_price
)
output.append(
[
tweet['date'].strftime('%Y-%m-%d'),
tweet['text'],
tweet['ticker'],
prev_day_price,
] + price_changes
)
with open('results.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([
'Tweet Date', 'Tweet Text', 'Tweet Ticker',
'Prev day price',
'1 day price change', '3 day price change',
'1 month price change', '6 month price change',
'1 year price change'
])
for row in output:
writer.writerow(row)
print("Done: see results.csv")
|
7c29f58705bc7cba349a7502cc5fc9629d5b59de | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/cuongd/submission.py | 2,200 | 3.890625 | 4 | #!/usr/local/bin/python
import sys
class RevengeOfPancakes(object):
"""
https://code.google.com/codejam/contest/6254486/dashboard#s=p1
"""
def __init__(self, filename):
""" Initialize with the given input file.
:param filename: input file path
:return:
"""
self._filename = filename
pass
def solve(self, output=sys.stdout):
""" Handle input and output before calling an internal method to solve the problem.
:param output: specify output to file or screen.
:return:
"""
try:
with open(self._filename, 'r') as f:
lines = f.readlines()
num = int(lines[0])
for i in xrange(num):
idx = i + 1
out = self._solve_revenge_pancakes(lines[idx].strip())
output.write("Case #%d: %d\n" %(idx, out))
except IOError:
print "Error opening file"
pass
def _solve_revenge_pancakes(self, stack):
""" Find the minimum number of flips to make all pancakes up.
The idea: for a stack of N cakes,
if the last cake is up (+), the problem is equivalent to solving the top N-1 cakes.
if the last case is down (-), the problem is equivalent to solving the top N-1 cakes inverted + 1.
:param stack:
:return:
"""
my_dict = { "+" : True, "-": False}
count = 0
# instead of inverting top (N-1) cakes, keep this flag to invert the top cakes if needed.
flip = True
for char in reversed(stack):
# Check the bottom pancake first
is_up = my_dict[char] if flip else not my_dict[char]
if not is_up:
# if the bottom pancake is "-"
count += 1
flip = not flip
else:
# do nothing
pass
return count
def main():
PROJECT_HOME = "/Users/cdongsi/Hub/python/CodeJam"
solver = RevengeOfPancakes(PROJECT_HOME + "/data/B-large.in")
with open("out.txt", "w") as f:
solver.solve(output=f)
if __name__ == "__main__":
main() |
d0ac1b137bffddcd809fb638ea71302e938f06d2 | young-geng/RatingAnalysis | /preprocess.py | 869 | 3.59375 | 4 | """
Preprocess the raw data to remove month seperation columns and filter out
unused columns.
Usage: python preprocess.py <input filename> <output filename>
"""
from __future__ import division
import numpy as np
import scipy
import pandas as pd
from sys import argv
if __name__ == '__main__':
assert len(argv) == 3
months = (
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
)
data = pd.read_csv(argv[1])
data = data[~data["PTS"].isin(months)].rename(
columns = {
"Visitor/Neutral": "Visitor",
"Home/Neutral": "Home",
"PTS": "VisitorPTS",
"PTS.1": "HomePTS",
"Start (ET)": "Start"
}
)[["Date", "Start", "Visitor", "VisitorPTS", "Home", "HomePTS"]]
data.to_csv(argv[2])
|
e3edf89d753427e43f81d956ecb7635ed4f5b870 | JoaoGabrielDamasceno/Estudo_Python | /coleção/order_dict.py | 357 | 3.796875 | 4 | """
Orderer Dict --> Dicionario em que a ordem de inserção dos elementos importa
"""
from collections import OrderedDict
d1 = {'a': 1, 'b': 5}
d2 = {'b': 5, 'a': 1}
if d1 == d2:
print(True)
else:
print(False)
dic1 = OrderedDict({'a': 1, 'b': 5})
dic2 = OrderedDict({'b': 5, 'a': 1})
if dic1 == dic2:
print(True)
else:
print(False)
|
5b48051a4f37257976f8d22b7ec5feda6cef1cf6 | hnko/uva-judge | /mix/13286.py | 3,297 | 3.609375 | 4 | # AC - topological sort + 01Knapsack
import sys
B = 0
did = {}
dishes = []
prestiges = []
costs = []
recipes_from = {}
opt = []
def topological_sort():
# los platos que tienen in_degree a 0, platos base, en este caso solo hay uno.
in_degree = {}
for x, neighbors in recipes_from.items():
in_degree.setdefault(x, 0)
for n in neighbors:
in_degree[n[0]] = in_degree.get(n[0], 0) + 1
#anadimos los que tienen degree 0 al set
empty = {v for v, count in in_degree.items() if count == 0}
topological = []
#kahn algorithm
while empty:
v = empty.pop() #empty es un set!
topological.append(v)
for neighbor in recipes_from.get(v, []):
in_degree[neighbor[0]] -= 1
if in_degree[neighbor[0]] == 0:
empty.add(neighbor[0])
# nos aseguramos que no hay un ciclo
assert len(topological) == len(dishes)
print(topological)
return topological
# nos quedamos con el menor coste y el mayor prestigio para cada nodo
def compute_costs(toposort):
for dish in toposort:
if dish in recipes_from:
for recipe in recipes_from[dish]:
# buscamos el camino mas corto
new_cost = costs[dish] + recipe[1]
if new_cost < costs[recipe[0]]:
costs[recipe[0]] = new_cost
prestiges[recipe[0]] = prestiges[dish] + recipe[2]
# si se repiten el coste miramos el mejor prestigio
elif new_cost == costs[recipe[0]]:
new_prest = prestiges[dish] + recipe[2]
if new_prest > prestiges[recipe[0]]:
prestiges[recipe[0]] = new_prest
def read_input():
B, N = int(sys.stdin.readline()), int(sys.stdin.readline())
index = 0
for i in range(N):
dish_to, dish_from, _, cost, prestige = [ingredient for ingredient in sys.stdin.readline().strip().split()]
cost, prestige = int(cost), int(prestige)
#ids para cada plato - anadimos los costes y prestigio - anadimos platos
if dish_from not in did:
did[dish_from] = index
costs.append(0)
prestiges.append(0)
dishes.append(dish_from)
index += 1
if dish_to not in did:
did[dish_to] = index
costs.append(int(1e9))
prestiges.append(0)
dishes.append(dish_to)
index += 1
else: #el plato se repite por lo que el coste lo ponemos a INF
dish = did[dish_to]
costs[dish] = int(1e9)
#lista adyacente con los platos origen: (destino, coste, prestigio)
recipes_from.setdefault(did[dish_from], [])
# (to, cost, prestige)
recipes_from[did[dish_from]].append((did[dish_to], cost, prestige))
return B
#01-knapsack clasico
def knapsack(B):
opt.append([])
#primera fila a 0's
for j in range(B+1): opt[0].append(0)
for i in range(1, len(dishes) + 1):
opt.append([])
for w in range(B+1):
if costs[i-1] <= w:
opt[i].append(max(opt[i-1][w-costs[i-1]] + prestiges[i-1], opt[i-1][w]))
else:
opt[i].append(opt[i-1][w])
print (opt[len(dishes)][B])
# la solucion puede estar antes en la matriz, por eso se busca el indice menor
def reconstruct_solution(B):
nitems = len(dishes)
prev = opt[nitems][B]
for i, elem in reversed(list(enumerate(opt[nitems]))):
if prev != elem:
print(i+1)
break
else:
print(0)
while True:
try:
B = read_input()
compute_costs(topological_sort())
knapsack(B)
reconstruct_solution(B)
did.clear(), dishes.clear(), prestiges.clear(), costs.clear(), recipes_from.clear(), opt.clear()
except:
sys.exit(0)
|
aee8b29374b41e5574fd136f75de95e11086243a | themichaelyang/dynsys | /hw-1.5.py | 255 | 3.609375 | 4 | import math
def f(x):
return math.e**x - 2
def g(x):
return math.log(x + 2)
def main():
x = 0
for i in range(10):
x = f(x)
print(x)
print()
x = 0
for i in range(10):
x = g(x)
print(x)
main()
|
c80d8471849bc11eae1b406f9a7881cf80ee380f | Jas-Gomes/2021-software-general-homework | /lesson_3assignment3.py | 510 | 3.859375 | 4 | from typing import cast
x = 1
translation = {}
while x == 1:
ring = input("Please enter a word, or press enter to end: ")
if ring == "" :
print("bye, bye")
break
if " " in ring:
print("You cannot enter spaces")
print("bye, bye")
break
if ring in translation.keys():
print("Key already esists")
print("bye, bye")
break
cat = input("Please enter the word's translation: ")
translation[ring] = cat
print(translation)
|
947d9b0a2389d0bb9b845b525c52ba2ccb67d456 | EvaChitul/python_national | /Own projects/rock_paper_scissors.py | 1,438 | 4.0625 | 4 | '''Make a two-player Rock-Paper-Scissors game.
Rock beats scissors
Scissors beats paper
Paper beats rock'''
def main_menu():
while True:
action = input ('Welcome to Rock Paper Scissors! Please choose an option. Type: \n'
'N for a new game \n'
'Q to quit \n')
if action.lower() == 'n':
new_game()
else:
print('Thanks for playing! See you soon \n')
break
def new_game():
print('Starting New Game!')
player_1 = (input('Player 1: Insert Your Option: Rock/Paper/Scissors: ')).lower()
player_2 = (input('Player 2: Insert Your Option: Rock/Paper/Scissors: ')).lower()
if player_1 == player_2:
print ('It\'s a tie! Play again \n')
new_game()
elif player_1 == 'rock' and player_2 == 'paper':
print('Paper beats rock! Player 2 wins!\n')
elif player_1 == 'paper' and player_2 == 'rock':
print('Paper beats rock! Player 1 wins!\n')
elif player_1 == 'rock' and player_2 == 'scissors':
print('Rock beats scissors! Player 1 wins!\n')
elif player_1 == 'scissors' and player_2 == 'rock':
print('Rock beats scissors! Player 2 wins!\n')
elif player_1 == 'scissors' and player_2 == 'paper':
print('Scissors beats paper! Player 1 wins!\n')
else:
print('Scissors beats paper! Player 2 wins!\n')
main_menu()
main_menu()
|
fa50b1b3acb1a22f531dafb7ef177a3efb7d78da | vunderkind/Intro-Python-II | /src/player.py | 531 | 3.71875 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room=None):
self.name = name
self.current_room = current_room
def __str__(self):
output= ''
output += f'[{self.current_room}]'
if self.current_room == None:
return f'The player is not in a room yet. Consider putting them in a room!'
else:
return f'{self.current_room}.'
# player1 = Player()
# print(player1)
|
e03eda9aaedd7ba9dcbdd1a44270b22771e2d258 | HangZhongZH/LeetCodeAlgorithms | /130. 被围绕的区域.py | 1,223 | 3.515625 | 4 | class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
if not board:
return board
def dfs(i, j):
board[i][j] = 'B'
for x, y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
tempx = i + x
tempy = j + y
if (tempx < len(board) - 1 and tempx >= 1) and (tempy < len(board[0]) - 1 and tempy >= 1) and \
board[tempx][tempy] == 'O':
dfs(tempx, tempy)
for i in range(len(board)):
if board[i][0] == 'O':
dfs(i, 0)
if board[i][len(board[0]) - 1] == 'O':
dfs(i, len(board[0]) - 1)
for i in range(len(board[0])):
if board[0][i] == 'O':
dfs(0, i)
if board[len(board) - 1][i] == 'O':
dfs(len(board) - 1, i)
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == 'B':
board[i][j] = 'O' |
abf8cde53a6fd3a1cebe22413e035639ea1afe90 | gajjarjigar/HackerRank | /Python/Strings/python-string-formatting.py | 329 | 3.890625 | 4 | def print_formatted(number):
width = len(str(bin(number))[2:])
for i in range(1,number+1):
print('{} {} {} {}'.format(str(i).rjust(width), str(oct(i))[2:].rjust(width),str(hex(i))[2:].upper().rjust(width), str(bin(i))[2:].rjust(width)))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
|
463621215260e3d90d02c751bfa5f34b8414f44e | justin-tse/cs50 | /cs50x/pset1/mario/mario.py | 207 | 4.09375 | 4 | while True:
n = int(input("Height: "))
if 0 < n <= 8:
break
print("Input number between 1 and 8.")
for i in range(n):
print(" " * (n - i - 1) + "#" * (i + 1) + " " + "#" * (i + 1)) |
f872cb155bf270d217ea431f53b6053fc22d55fa | ManiNTR/python | /CheckDictionaryEmptyOrNot.py | 383 | 4.5 | 4 | #Python program to check a dictionary is empty or not
num={"one":1,"two":2,"three":3,"four":4,"five":5,"six":6}
print(num)
if not num.items():
print("The dictionary is empty")
else:
print("The dictionary is not empty")
dictionary={}
print(dictionary)
if not dictionary.items():
print("The dictionary is empty")
else:
print("The dictionary is not empty")
|
d7146ac279687399c78b2b33e88f4d00efc151c3 | CarloShadow/CodesByCJ | /Python/guppe/TESTE.py | 60 | 3.65625 | 4 | while True:
num = int(input('Digite um número: '))
|
466b3a60d9c62730129b00cc4b222a0b0f3b8375 | walterwsj/hogwarts_lg | /bicycle/bicycle.py | 583 | 3.75 | 4 | class Bicycle:
def run(self,km):
print(f"Total running {km} miles")
class E_Bicycle(Bicycle):
def __init__(self,valume):
self.valume=valume
def fill_charge(self,vol):
self.valume+=vol
print(f"Charged {vol}. Current volume is {self.valume}")
def run(self,km):
power_km=self.valume*10
if power_km>=km:
print("Charging running {km} miles")
else:
print(f"Battery is out. charging running {power_km}")
super(E_Bicycle, self).run(km-power_km)
ebike=E_Bicycle(10);
ebike.run(200)
|
afc44623763aee68bea5817c5d605835e24940af | Ankitahazra-1906/Rock-Paper-Scissors-Game | /rock paper scissors game.py | 1,075 | 4.1875 | 4 | import random
while True:
user_choice=input("Enter any of the 3 choices between( rock ,paper and scissors): ")
possible_choices=["rock","paper","scissors"]
comp_choice=random.choice(possible_choices)
print("\n You choose", user_choice ,"\n Comp choose", comp_choice,"\n")
if user_choice==comp_choice:
print("Its a tie!Both of you have chose", user_choice)
elif user_choice=="rock":
if comp_choice=="paper":
print("You loose!Paper covers Rock")
else:
print("You win!Rock smashes Scissors")
elif user_choice=="paper":
if comp_choice=="scissors":
print("You loose!Scissors cut the paper")
else:
print("You win!Paper covers Rock")
elif user_choice=="scissors":
if comp_choice=="rock":
print("You loose!Rock smashes scissors")
else:
print("You win!Scissors cut the paper")
continue_game=input("Do you want to continue the game(yes/no): ")
if continue_game!="yes":
break
|
6137dbc5fc51b1b2df71980350d2eceb6847acf7 | SamanehGhafouri/MIT-problems-practice | /ObjectOrientedProgramming/practice1.py | 845 | 4.34375 | 4 | from abc import abstractmethod, ABC
class Animal(ABC): # Abstract class
@abstractmethod
def how_running(self):
pass
class Horse(Animal): # Class Horse is inherited from class Animal
def how_running(self):
print("with 4 legs")
class Human(Animal): # Class Human is inherited from class Animal
def how_running(self):
print("With 2 legs")
animal1 = Horse() # Object of the class Horse
print("how a horse is running: ")
animal1.how_running()
animal2 = Human() # Object of the class Human
print("how a human is running: ")
animal2.how_running()
animalz = Animal() # Object of the class Animal which will give error because
animalz.how_running() # an abstract class cant be instantiated
|
8c215f22adad76c5db50beb6a1b560277e2f0e42 | astrosec/virtualagc-docker | /convert.py | 1,350 | 4.53125 | 5 | # TypeConversions from decimal and binary
# to their respective octal representations
# The choices present to the user
print("a. Hexadecimal to Octal ")
print("b. Decimal to Octal")
print("c. Binary to Octal")
# Function generates octal representation
# from it's binary from
def bin_to_oct():
print("Enter your input in BIN format :-")
# taking user input as binary string and
# then using int() to convert it into it's
# respective decimal format
x = int(input(), 2)
print("Octal form of " + str(x) + " is " + oct(x) )
# Function generates octal representation
# of it's hexadecimal form passed as value.
def hex_to_oct():
print("Enter your input in HEX format :-")
# taking user input as hexadecimal string and
# then using int() to convert it into it's
# respective decimal format
x = int(input(), 16)
print("Octal form of " + str(x) + " is " + oct(x))
# Function converts decimal form to it's
# respective octal representation
def decimal_to_oct():
print("Enter a number with base-10 format :-")
# taking a simple user input and
# converting it to an integer
x = int(input())
print("Octal form of " + str(x) + " is " + oct(x))
# Driver Code
ch = input("Enter your choice :-\n")
if ch is 'a':
hex_to_oct()
elif ch is 'b':
decimal_to_oct()
elif ch is 'c':
bin_to_oct()
|
b64e584569fec77fce64c81e460de556d9e880c5 | jmstudyacc/python_practice | /POP1-Recursion/recursion _sums.py | 910 | 4.125 | 4 | """
Implement a function my_sum(lst) that given a list lst of interger numbers, returns the sum of them.
In this exercise, do not use the standard sum function and no loop of any kind. Implement the function recursively using the following idea:
- If the list contains one element, the sum of the list is equal to this element
- If the list contains more elements, the sum of the list is equal to the first element plus the sum of the remaining list
For example, on input:
print(my_sum([1,2,3]))
Output must be:
6
"""
def my_sum(lst):
if (len(lst)) == 1:
return lst[0]
else:
return lst[0]+ my_sum(lst[1:]) # return index of lst at pos 0 = 3, + value of my_sum(index of lst at pos 1 -->)
a = [3,3,3,4]
print(my_sum(a))
"""
def my_sum(lst):
if len(lst)==1:
return lst[0]
else:
rest_sum = my_sum(lst[1:])
return lst[0]+rest_sum
""" |
baf2a2ff88c0af02af12d36e320065b306f91aa7 | MartinaLima/Python | /exercicios_python_brasil/estrutura_repeticao/24_media_varias_notas.py | 484 | 3.984375 | 4 | print('>>> Informe as notas:')
c = 0
soma = 0
continua = ''
while continua != 'N':
c += 1
nota = float(input(f'- NOTA {c}: '))
soma += nota
continua = str(input('Continuar? [S/N]: ').upper())
while continua not in 'S' and continua not in 'N':
continua = str(input('Continuar? [S/N]: ').upper())
if soma == 0:
media = 0
else:
media = soma / c
print('OPERAÇÃO FINALIZADA!')
print('RESULTADO:')
print(f'MÉDIA GERAL: {media:.2f}')
|
6bae5cc77931e2eed4acbf92795437f913691864 | judywu29/python_pj | /buble_sort.py | 371 | 3.890625 | 4 |
def bubble_sort(seq):
seq_len = len(seq)
for i in range(seq_len):
print(seq_len)
for j in range(seq_len-1, i, -1): # for j in range(i, seq_len-1)[::-1]:
if(seq[j] < seq[j-1]):
temp = seq[j]
seq[j] = seq[j-1]
seq[j-1] = temp
seq = [22,1,33,4,7,6,8,9,11]
bubble_sort(seq)
print(seq) |
047ef617837009070c75a48d1e0b0eb9948a8480 | BarisATAK/Python_Practise | /11_functions_examples.py | 1,092 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 01:24:34 2020
@author: atakb
"""
# Factorial Function.
def Factorial(number):
for i in range(1,number):
number *= i
return number
# Fibonacci Function.
def Fibonacci(number):
f1 = 0
f2 = 1
print(f1+f2)
for i in range(0,number):
fib = f1 + f2
if(fib < number):
print(fib)
f1 = f2
f2 = fib
#a*(x^2)+b*(x)+c
def FindRoots(a,b,c):
discriminant = b*b-4*a*c
if(discriminant<0):
print("Reel kök bulunamadı")
return
else:
x1 = (-b+discriminant**0.5)/(2*a)
x2 = (-b-discriminant**0.5)/(2*a)
return (x1,x2)
#fact
fact_number = int(input("Faktoriyeli hesaplanacak sayı :"))
print(str(fact_number) + "! =", Factorial(fact_number))
#fibon
fibon_number = int(input("Kaça kadar fibonacci sayıları yazılacağını belirt :"))
Fibonacci(fibon_number)
#root
a,b,c = input("Denklemin a,b ve c değerlerini giriniz:").split()
a,b,c = int(a),int(b),int(c)
print("Denklemin kökü =", FindRoots(a,b,c))
|
b6495f5833d953aec86eb570edf283711c691951 | rfsip/learnpython | /DATATYPE.py | 825 | 4.25 | 4 | #coding:utf-8
'''
pyton3有6种数据类型:Number、String、List、Tuple、Sets(集合)、Dictionary
Number: 支持 int、float、bool、complex。只有一种整数类型int,表示长整型。
bool类型只有True False。
String: 长度不可变,用单引号和双引号表示。a="abc",其中a为变量,"abc"才是字符串。a可变。
除法: python3 除法有两种 '/'为精确除,结果为浮点数 10/3=3.33333333 9/3=3.0
'//'为地板除,结果为整型 10/3=3
'''
#练习:打印出下列变量的值
n = 123
f = 456.789
s1 = 'Hello,world'
s2 = 'Hello,\'Adam\''
s3 = r'Hello,"Bart"'
s4 = r'''Hello,
Lisa!'''
print(n)
print(f)
print(s1)
print(s2)
print(s3)
print(s4)
'''
结果如下:
123
456.789
Hello,world
Hello,'Adam'
Hello,"Bart"
Hello,
Lisa!
'''
|
d02d3fdf8c160798a9f6e8933a96fbd24a5e5d22 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/mrpgeo001/question2.py | 2,986 | 4.03125 | 4 | """Vending Machine (Change Calculator)
Geoff Murphy
MRPGEO001
13 April 2014"""
def Vend():
cost = eval(input("Enter the cost (in cents):\n")) #The total amount to be paid
pay = 0 #'pay' is amount of money deposited
dollar = 0 #Initial values for the 'number' of certain denominations. e.g., ?? x 25c etc.
c25 = 0
c10 = 0
c5 = 0
c1 = 0
while pay < cost:
money = eval(input("Deposit a coin or note (in cents):\n")) #continues until full amount is paid or exceeded.
pay += money
else:
change = pay - cost #Calculates the change to be given
change2 = str(change)
if len(change2) > 2: #Starting counting from the right, if the amount has more than 2 digits, everything after is dollars. e.g., 1250 will have 12 dollars total.
dollar += eval(change2[:-2])
twentyfive = eval(change2[-2:]) #Takes the last 2 digits, which will all be cents. e.g., 1250 becomes 50...
floor = twentyfive//25 #Floor divides this value by the current denomination
if floor != 0: #And as long as it is not equal to 0, i.e. paid up, continues...
c25 += floor #Takes this result and adds it to the 'number' of denominations...
twentyfive -= (floor*25) #And then takes this value again, multiplies it by the denomination (i.e. 25 here), and subtracts it from the
#current total (twentyfive).
ten = twentyfive #The current total is renamed 'ten', and the same procedure is followed as before.
floor2 = ten//10
if floor2 != 0:
c10 += floor2
ten -= (floor2*10)
five = ten
floor3 = five//5
if floor3 != 0:
c5 += floor3
five -= (floor3*5)
one = five
floor4 = one//1
if floor4 != 0:
c1 += floor4
one -= (floor4*1)
if change != 0: #So long as the change is not zero, the denominations multiplied by their numbers will be printed out.
print("Your change is:")
if dollar > 0:
print(dollar, "x $1")
if c25 > 0:
print(c25,"x 25c")
if c10 > 0:
print(c10,"x 10c")
if c5 > 0:
print(c5, "x 5c")
if c1 > 0:
print(c1, "x 1c")
Vend() |
82e317794b839558392368c42b5f371668c6617b | RafaelTeixeiraMiguel/PythonUri | /br/com/rafael/teixeira/uri/beginner/uri_1045_triangle_types.py | 636 | 3.84375 | 4 | values = input().split()
a = float(values[0])
b = float(values[1])
c = float(values[2])
if(c > b):
aux = b
b = c
c = aux
if(b > a):
aux = a
a = b
b = aux
if(c > b):
aux = b
b = c
c = aux
if((a >= (b + c))):
print("NAO FORMA TRIANGULO")
else:
if(((a ** 2) == ((b ** 2)+ (c ** 2)))):
print("TRIANGULO RETANGULO")
if( (a ** 2) > ((b ** 2) + (c ** 2)) ):
print("TRIANGULO OBTUSANGULO")
if(((a ** 2) < ((b ** 2) + (c ** 2)))):
print("TRIANGULO ACUTANGULO")
if(a == b == c):
print("TRIANGULO EQUILATERO")
if((a == b != c) | (a == c != b) | (c == b != a)):
print("TRIANGULO ISOSCELES") |
fea37ec9410bce6bdb1357a406b811a3564e24e7 | Introduction-to-Programming-OSOWSKI/2-8-hasl-BrooksOBrien22 | /main.py | 168 | 3.6875 | 4 | #WRITE YOUR CODE IN THIS FILE
def hasL(w):
for x in range(0, len(w)):
if (w[x]) == "l":
return True
return False
print(hasL("word")) |
22c7ebe71b0a58a0dd7531e30580b17c152b451a | ilhamdsofyan/exercism | /python/pangram/pangram.py | 172 | 3.875 | 4 | def is_pangram(sentence):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in sentence:
return False
return True
|
162f26140f4cceaf422c78f11247e5d9a2b02e8b | Computants/StringOperations | /py-23112019-DataTypes.ipynb | 4,942 | 3.9375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
import this
# In[3]:
5 + 8 # Operation
#Operators
# +, - ,/ ,*, %, **
# =, +=, -=, ?=, *=, %=
# ==, >, <, >=, <=
# 5, 8 Oprands
# In[4]:
#complex operation
#PEMDAS
5 + 7 - 8 * (2/2) + 200
# In[9]:
a = 8 #shallow copy
b = 8
print (a)
print (b)
print (id(a))
print (id(b))
# In[10]:
a=True
type(a)
# In[11]:
a = "pakistan"
a*2
# In[13]:
'1'+'7'
# In[16]:
int("1") + int('1')
#type casting
#implicit casting
#explicit casting
# In[26]:
#index 0 1 2 3
names = ["Ali", "Hamza", "Junaid",200 ]
#index -4 -3 -2 -1
print(type(names))
print(names)
print(names[-4])
print(names[0])
# In[36]:
#tuple value cannot be update
#index 0 1 2 3
names = ("Ali", "Hamza", "Junaid",200 )
#index -4 -3 -2 -1
print(type(names))
#print names
print(names[-3])
# In[47]:
#set
#index 0 1 2 3
names = {"Ali", "Hamza", "Junaid",200,"Badar" }
#index -4 -3 -2 -1
names = list(names)
#print(names[-3]) error
print(names[0])
print(type(names))
# In[56]:
data={
#key: value
'name':"Badar Yousaf",
'fname': "M Yousaf",
5 : "Pakistan",
#['a']: True # list cannot be defined in datatype
"a": [True, "Pakistan", 20,3.0]
}
data[5]
data['name']
data["a"]
# In[9]:
a="Badar Yousaf"
dir(a)
# In[11]:
a = "bAdarYouSAF"
a.upper()
# In[66]:
a = "bAdar YouSAF"
a.capitalize()
# In[72]:
a = " bAdar YouSAF "
print(len(a))
print(a.lstrip())
print(len(a.lstrip()))
print(a.rstrip())
print(len(a.rstrip()))
# In[80]:
b = " badar yousaf "
b.split()
# In[ ]:
# In[83]:
b = " badar yousaf "
b.split()
" ".join(b)
# In[85]:
a = "we are pakistan we love our country"
a
# In[101]:
#list[start:end:step]
#tuple[start:end:step]
#string[start:end:step]
#a = "we are pakistan we love our country"
print(a)
print(a[::])
print(a[::-1])
print(a[7:15:1])
# In[108]:
print(a.index("pakistan"))
a[a.index("pakistan"):15:1]
# In[111]:
a="890890asdas98080"
a.join([i for i in a if str.isnumeric(i)])
# In[115]:
#concatenation
card ="""
Bahria University Islamabad
name: Badar Yousaf
FName: M Yousaf
"""
print(card)
# In[150]:
#concatenation
name="badar"
fname="yousaf"
#uni="Bahria"
score=3
card ="""
Bahria University Islamabad
name: %s
FName: %s
score: %d
"""
print(card%(name,fname,score))
# In[125]:
#concatenation
name="badar"
fname="yousaf"
#uni="Bahria"
score=3
card =f"""
Bahria University Islamabad
name: {name}
FName: {fname}
score: {score}
"""
print(card)
# In[128]:
#concatenation
name="badar"
fname="yousaf"
#uni="Bahria"
score=3
card ="""
Bahria University Islamabad
name: {}
FName: {}
score: {}
"""
print(card.format(name,fname,score))
# In[130]:
#concatenation
name="badar"
fname="yousaf"
#uni="Bahria"
score=3
card ="""
Bahria University Islamabad
name: {a}
FName: {b}
score: {c}
"""
print(card.format(a=name,b=fname,c=score))
# In[133]:
#concatenation
name="badar"
fname="yousaf"
#uni="Bahria"
score=3
card ="""
Bahria University Islamabad
name: {2}
FName: {1}
score: {0}
"""
print(card.format(name,fname,score))
# In[135]:
"1" + '1'
# In[5]:
#concatenation
name="badar"
fname="yousaf"
score=3
print("Bahria university Islamabd \nStudent Name:" + name + " " +
"\nFather name: " + fname +
"\nScore: "+ str(score))
# In[8]:
print(a)
# In[15]:
print(a.capitalize())
# In[22]:
s = "Hi This is Badar"
print(s.casefold())
# In[28]:
print(s.center(30))
# In[38]:
s="your name is badar"
print(s.encode())
# In[44]:
s="badaryousaf"
print(s.endswith("dar"))
# In[50]:
s="badar\tyousaf"
print(s.expandtabs(5))
# In[55]:
print(s.find("saf"))
# In[60]:
marks = 40
total=50
line = "My marks are {} out {}"
print(line.format(marks,total))
# In[63]:
print(line.index("marks"))
# In[67]:
s = "sdfas234234"
print(s.isalnum())
a="sdfsdfs"
print(a.isalpha())
# In[72]:
s="asd as# "
print(s.isprintable())
# In[75]:
s=" "
print(s.isspace())
# In[85]:
s="badar yousaf at piaic"
print(s.ljust(40))
print(s.rjust(40))
# In[89]:
print(s.zfill(30))
# In[96]:
x=18
y=5
print(x%y)
# In[101]:
x=2
y=3
print(x**y)
# In[103]:
x=18
y=5
print(x//y)
# In[106]:
x=5
y=5
print(x is not y)
# In[108]:
x=5
y=5
print(x is y)
# In[112]:
x=[5,4,5,6]
y=5
print(y not in x)
print(y in x)
# In[ ]:
|
20317fd4711a7332adada3f46ad876975e1fa51a | hanwenzhang123/python-note | /functional-python/9-currying.py | 845 | 4.71875 | 5 | Currying - technique is used to create alternate versions of a function based on the number of provided arguments
Currying may actually change the behavior of the function, not just its arguments.
you can call a func and that func if does not have enough argument
it will fill in as many argument as it can to itself and sen you back a new version of itself iwth those arguments already filled in, and you can put in new ones after that
def curried_f(x, y=None, z=Zone):
def f(x, y, z):
return x**3 + y**2 + z
if y is not None and z is not None:
return f(x, y, z)
if y is not None:
return lambda z: f(x, y, z)
return lambda y, z=None: (
f(x, y, z) if (y is not None and z is not None)
else (lambda z: f(x, y, z)))
print(curried_f(2, 3, 4)) #21
g = curried_f(2)
print(g)
h = g(3)
print(h)
i = h(4)
print(i)
|
f5ffa705f4016969ea5ca9d5777718f26c8e5d1c | ignifluous777/Exercises | /data_structures/stacks_and_queues/2_stack_insert/Solution/solution.py | 1,219 | 3.890625 | 4 | class Stack:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(f"{temp.value}")
temp = temp.next
def push(self, value):
new_head = Node(value)
new_head.next = self.head
self.head = new_head
def insert_idx(self, val, pos):
if not self.head:
print("Empty Linked List")
return None
temp = self.head
if pos == 0:
self.head = val
self.next = temp
for i in range(pos):
temp = temp.next
if temp is None:
break
if temp is None:
return
val = Node("Earth")
temp_nxt = temp.next
val.next = temp.next
temp.next = val
class Node:
def __init__(self, value, next = None):
self.value = value
self.next = next
stack_planets = Stack()
stack_planets.push("Neptune")
stack_planets.push("Uranus")
stack_planets.push("Saturn")
stack_planets.push("Mars")
stack_planets.push("Venus")
stack_planets.push("Mercury")
stack_planets.insert_idx("Earth", 1)
stack_planets.printList()
|
1537f1f629bc83af582bb930ad83628b13301830 | 17akitsvad/Programming-Portfolio | /madlib.py | 1,292 | 3.953125 | 4 | def main():
adjective1 = raw_input("Please enter an adjective: ")
adjective2 = raw_input("Please enter another adjective: ")
bird = raw_input("Please enter a type of bird: ")
room = raw_input("Please enter a room in a house: ")
verbPast = raw_input("Please enter a past tense verb: ")
verb = raw_input("Please enter a verb: ")
name = raw_input("Please enter a name: ")
noun1 = raw_input("Please enter a noun: ")
liquid = raw_input("Please enter a liquid: ")
verbing = raw_input("Please enter a verb that ends in ing: ")
bodyPart = raw_input("Please enter a plural body part: ")
pluNoun = raw_input("Please enter a plural noun: ")
verbing2 = raw_input("Please enter another verb that ends in -ing: ")
noun2 = raw_input("Please enter another noun: ")
print("It was a " + adjective1 + ", cold November day. I woke up to the " + adjective2 + " smell of " + bird + " roasting in the " + room + " downstairs. I " + verbPast + " down the stairs to see if I could help " + verb + " the dinner. My mom said, 'See if " + name + " needs a fresh " + noun1 + ".' So i carried a tray of glasses full of " + liquid + " into the " + verbing + " room. When I got there, I couldn't believe my " + bodyPart + "! There were " + pluNoun + " " + verbing2 + " on the " + noun2 + "!")
main()
main()
|
4cd018273fc3e3e6622b5fa4235af539e5820a08 | Tmizu0719/csv_convert | /souce/csv_convert.py | 1,913 | 3.84375 | 4 | """
January 4th 2020
Author T.Mizumoto
"""
#! python 3
# ver.01.10
# csv_convert.py - this program converts .csv file to matrix
import numpy as np
import sys
class CsvConvert:
delimiter = ","
def convert_np(self, path):
# header
with open(path, "r") as file:
lines = list(file)
header = lines[0].strip().split(self.delimiter)
# data
data = np.genfromtxt(path, delimiter = self.delimiter, skip_header = 1)
judge = np.isnan(data)
count = 1
for i in judge:
if True in i:
print("There is a missing value on line " + str(count) + ".")
count += 1
return header, data
def delete_nanrow(self, data):
judge = np.isnan(data)
count = 1
del_list = []
for i in judge:
if True in i:
del_list.append(count)
count += 1
del_data = np.delete(data, del_list, 0)
print("Lines" + str(del_list) + "deleted.")
return del_data
def replace_nan(self, data, nan):
replace_data = np.nan_to_num(data, nan = nan)
return replace_data
def D3_connect(self, pathlist):
count = 0
for i in pathlist:
if count == 0:
header, data = self.convert_np(i)
else:
h_tmp, d_tmp = self.convert_np(i)
if not header == h_tmp:
print("ERROR: The header is different.")
print("error file path: " + i)
sys.exit(1)
else:
data = np.dstack([data, d_tmp])
count += 1
return header, data
if __name__ == "__main__":
CC = CsvConvert()
header, data = CC.convert_np("test_data.csv")
print(header)
print(data)
print(CC.delete_nanrow(data))
print(CC.replace_nan(data, 0)) |
36b76d1c304ce7c89614b03abd858502668f0a8a | sakshigupta06/Breakfast_Bot | /breakfast_bot1.py | 2,302 | 4.3125 | 4 | # Before refactoring
# Here's our original code, before we did any refactoring:
import time
print("Hello! I am Bob, the Breakfast Bot.")
time.sleep(2)
print("Abra ka dabra gili gili chu!!🧙♂️")
print("Today we have two breakfasts available.")
time.sleep(2)
print("The first is waffles with strawberries and whipped cream.")
time.sleep(2)
print("The second is sweet potato pancakes with butter and syrup.")
print("Before going further i wanna tell you a story of Two sweet potatos :)")
print("One day two sweet potatos, who were best friends, were walking together down the street./n They stepped off the curb and a speeding car came around the corner and ran one of them over./n The uninjured sweet potato called 911 and helped his injured friend as best he was able. The injured sweet potato was taken to emergency at the hospital and rushed into surgery./n After a long and agonizing wait, the doctor finally appeared. He told the uninjured sweet potato, I have good news, and I have bad news./n The good news is that your friend is going to pull through. The bad news is that he's going to be a vegetable for the rest of his life.")
time.sleep(2)
while True:
while True:
response = input("Please place your order. "
"Would you like waffles or pancakes?\n").lower()
if "waffles" in response:
print("Waffles it is!")
time.sleep(2)
break
elif "pancakes" in response:
print("Pancakes it is!")
time.sleep(2)
break
else:
print("Sorry, I don't understand.")
time.sleep(2)
print("Your order will be ready shortly.")
time.sleep(2)
while True:
order_again = input("Would you like to place another order? "
"Please say 'yes' or 'no'.\n").lower()
if 'no' in order_again:
print("OK, goodbye!")
time.sleep(2)
break
elif 'yes' in order_again:
print("Very good, I'm happy to take another order. :)")
time.sleep(2)
break
else:
print("Sorry, I don't understand. :(")
time.sleep(2)
if 'no' in order_again:
break
|
359e03ad7accf5955f822b39f28c3dbd37e133ac | dkaushik95/learn_python | /42.py | 215 | 4.125 | 4 | def reverse_a_string(given_string):
if len(given_string) <= 1:
return given_string
return reverse_a_string(given_string[1:]) + given_string[0]
print reverse_a_string('Hello')
print reverse_a_string('mississipi') |
c276866c0b6141c295209cc87c6452313e8cbab0 | Sergey0987/firstproject | /Алгоритмы/Решето Эрастофена - ГОТОВО.py | 556 | 3.765625 | 4 | N = int(input())
list_of_numbers = []
list_of_numbers2 = []
for i in range(2, N+1):
list_of_numbers.append(i)
p = list_of_numbers[0]
index = 0
while p**2 <= N:
for i in range(index+p, len(list_of_numbers), p):
list_of_numbers[i] = False
index = index + 1
while list_of_numbers[index] == False:
index = index + 1
p = list_of_numbers[index]
for i in range(len(list_of_numbers)):
if list_of_numbers[i] != False:
list_of_numbers2.append(list_of_numbers[i])
print(list_of_numbers2)
|
171dcb91067aeb212ef365fbd0ca2df94a975087 | janice-cotcher/stick_man | /stick_figure_blank/stick_figure_blank.pyde | 693 | 3.546875 | 4 | # change each of the given functions so they accept parameters
def drawHead():
"""Circle head"""
ellipse(100, 35, 25, 25)
def drawBody():
"""Stick body"""
line(100, 50, 100, 80)
def drawArms():
"""Stick arms"""
line(100, 52, 70, 45)
line(100, 52, 130, 45)
def drawLegs():
"""Stick legs"""
line(100, 80, 85, 125)
line(100, 80, 115, 125)
size(200, 200)
# call the functions that draw the image below with the specified arguements
# draws the head centered at (100, 35)
# draws the body starting at (100, 50) and ending at (100, 80)
# draws the arms starting at (100, 52)
# draws the legs starting at (100, 80)
|
38aec61b8a09893303be94bcab4fb645659efa15 | janlee1020/Python | /Vacation.py | 409 | 3.8125 | 4 | #Vacation.py
#Janet Lee
#Lab 2 MW 2:15
#Plan a vacation
def main():
#Ask what activity you like to do
activity= input("What activity do you like to do?")
#Ask where you would like to visit
visit=input("Where would you like to visit?")
#Print the result
print("You just got to SU and you are already planning a trip to", visit, "so you can", activity)
main()
|
0cd88cef07b0b666eb2bef8cb2620d8ad5539e9f | uwhwan/python_study | /test/dayofyear.py | 742 | 4.4375 | 4 | #计算指定的年月是这一年的第几天
def is_leap_year(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year,month,date):
'''计算传入的日期是这一年的第几天'''
days_of_month = [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
]
#布尔值false和true可以转换成整数0和1
#平年会选中嵌套列表中的第一个列表(2月是28天)
#闰年会选中嵌套列表中的第二个列表(2月是29天)
days = days_of_month[is_leap_year(year)]
total = 0
for index in range(month-1):
total += days[index]
return total + date
print(which_day(1980, 11, 28))
|
89ff82227f6f7e5218eb59e217ba32f7b97aa027 | tianyuchen/project-Euler | /040-Champernowne's_constant.py | 1,164 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
'''
# 1 ~ 9 9 digits
# 10 ~ 99 2 * (99 - 10 + 1) = 180 digits
# 100 ~ 999 3 * 900 = 2700 digits
# 1000 ~ 9999 4 * 9000 = 36000 digits
# 10000 ~ 99999 5 * 90000 = 450000 digits
digits = [(x + 1) * 9 * pow(10, x) for x in range(0, 6)]
# d1 = 1
# d10 = (10 - 9) / 2 = 0.5 --> first digit of (9 + 1)th number = 1
# d100 = (100 - 9) / 2 = 45.5 --> first digit of (9 + 46)th number = 5
# d1000 = (1000 - 9 - 180) / 3 = 270 ... 1 --> first digit of (99 + 271)th number = 3
def d(n):
i = 0
if n < 9:
return n
while n > digits[i]:
n -= digits[i]
i += 1
quotient, remainder = divmod(n , i + 1)
return int(str(pow(10, i) + quotient)[remainder - 1])
produit = 1
for i in range(0, 7):
produit *= d(pow(10, i))
print(produit)
|
3d577367fb9152d1dfc728b5a2d090a39f90411e | LarisaFonareva/Various | /1.5_Caesars_cipher.py | 223 | 3.796875 | 4 | d=int(input())
for c in input():
if c.isalpha():
if c.islower():
print(chr((ord(c)+d-1072)%32+1072),end='')
else: print(chr((ord(c)+d-1040)%32+1040), end='')
else:
print(c,end='') |
82b5788e7f4ea01abdecd1b8a88b91bb079f9f88 | jthiruveedula/PythonProgramming | /OOP/Abstraction.py | 804 | 4.125 | 4 | #Abstraction:- Is the meachanisam of only declaring methods but not instantiated, declared methods are implemented in its child classes
from abc import ABC,abstractclassmethod
#initiating abstract and could be used in other child classes
class abstractClass(ABC):
@abstractclassmethod
def abstractMethod(self):
pass
class childAbstractClass(abstractClass):
def abstractMethod(self):
return "Child Abstract triggered!"
class child2Abstract(abstractClass):
def abstractMethod(self):
return "Another child Abstract Triggered!"
# a= abstractClass() (Can't instantiate abstract class abstractClass with abstract methods abstractMethod)
# print(a.abstractMethod())
a1= childAbstractClass()
a2= child2Abstract()
print(a1.abstractMethod())
print(a2.abstractMethod()) |
2692895ca051c582f0c1485517591f6cc75cff42 | tuxnani/pyrhmn | /Day21/reverse_even_list.py | 1,209 | 3.6875 | 4 | class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data
def newNode(d):
newnode = Node()
newnode.data = d
newnode.next = None
return newnode
def reverse(head, prev):
if (head == None):
return None
temp = None
curr = None
curr = head
while (curr != None and curr.data % 2 == 0) :
temp = curr.next
curr.next = prev
prev = curr
curr = temp
if (curr != head) :
head.next = curr
curr = reverse(curr, None)
return prev
else:
head.next = reverse(head.next, head)
return head
def printLinkedList(head):
while (head != None):
print(head.data ,end= " ")
head = head.next
n = input()
arr = input()
arr = [int(i) for i in arr.split()]
head = None
p = Node()
i = 0
while ( i < int(n) ):
if (head == None):
p = newNode(arr[i])
head = p
else:
p.next = newNode(arr[i])
p = p.next
i = i + 1;
head = reverse(head, None)
printLinkedList(head)
|
f7b549b4bed14ce634509699ea00eb2635db42f3 | Manuel-Python/Python-Maths | /main.py | 735 | 3.984375 | 4 | import math
from tkinter import *
# Based on Angela Yu's work
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
window = Tk()
window.title("Maths")
window.config(padx=200, pady=200, bg=GREEN)
pheta = 1 / (2 * math.sin(math.radians(18)))
print("18 - ", pheta)
pheta1 = 2 * math.cos(math.radians(36))
print("36 - ", pheta1)
pheta2 = 2 * math.sin(math.radians(54))
print("54 - ", pheta2)
pheta3 = 1 / (2 * math.cos(math.radians(72)))
print("72 - ", pheta3)
pheta4 = (1 / (math.sin(math.radians(18))) / 2)
print("18 - ", pheta4)
pheta5 = (1 / (math.cos(math.radians(72))) / 2)
print("72 - ", pheta5)
pheta6 = 2 / (1 / (math.sin(math.radians(54))))
print("54 - ", pheta6)
window.mainloop()
|
7bff1ff2cccdbb4c8f43d5a504bc1d41c7d5545b | crazyyin/algorithm | /search.py | 720 | 3.6875 | 4 | # -*- coding: utf-8 -*-
number_list = [0, 1, 2, 3, 4, 5, 6, 7]
def linear_search(value, iterable):
for index, val in enumerate(iterable):
if val == value:
return index
return -1
assert linear_search(5, number_list) == 5
def linear_search_v2(predicate, iterable):
for index, val in enumerate(iterable):
if predicate(val):
return index
return -1
assert linear_search_v2(lambda x: x == 5, number_list) == 5
def linear_search_recusive(array, value):
if len(array) == 0:
return -1
index = len(array)-1
if array[index] == value:
return index
return linear_search_recusive(array[0:index], value)
|
f6100afa1fc937dca3428adb024e71932837c011 | phantomnat/python-learning | /leetcode/tree/111-minimum-depth-of-binary-tree.py | 1,022 | 3.8125 | 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 minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
depth = 0
if root is None: return depth
current_lv = [root]
next_lv = []
depth = 1
while True:
ptr = current_lv.pop(0)
if ptr.left is None and ptr.right is None:
return depth
# scan for next leafs
if ptr.left is not None:
next_lv.append(ptr.left)
if ptr.right is not None:
next_lv.append(ptr.right)
if len(current_lv) == 0:
if len(next_lv) == 0:
break
# new lv
current_lv = next_lv[:]
next_lv = []
depth += 1
return depth |
307ba4f86661c52f438dda1ccdb1ee78ffdc46a9 | zheryulia/moon_map | /main.py | 681 | 3.625 | 4 | matrix = []
with open("matrix.txt") as file:
for line in file:
matrix.append([int(num) for num in line.strip()])
def calculate(moon_map):
k = 0
row = len(moon_map)
column = len(moon_map[0])
for i in range(row):
for j in range(column):
element = moon_map[i][j]
element_right = 0
element_down = 0
if j < column - 1:
element_right = moon_map[i][j + 1]
if i < row - 1:
element_down = moon_map[i + 1][j]
if element == 1 and element_right == 0 and element_down == 0:
k += 1
return k
count = calculate(matrix)
print(count) |
6274c8a72fc65e2b1c7f44dd4668624f3c52145c | azupero/nlp100knocks | /ch01/nlp04.py | 894 | 3.515625 | 4 | # “Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.”
# という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,
# 取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
text = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'
text2 = text.replace('.', '').split(' ')
one_word_idx = (1, 5, 6, 7, 8, 9, 15, 16, 19)
word_idx = [i+1 for i in range(len(text2))]
words = []
for i, j in enumerate(text2):
if i+1 in one_word_idx:
words.append(j[0]) # j[:1]
else:
words.append(j[:2])
print(dict(zip(words, word_idx))) |
070fccd3ac03fd351de02c7bd0d98a52b4e01d1e | piquesel/coding-math | /ep3.py | 1,476 | 3.75 | 4 | # Coding Math Episode 3
# Boucing ball
__author__ = "piquesel"
import pygame
import math
pygame.init()
RED = pygame.color.THECOLORS['red']
screen = pygame.display.set_mode((800, 600))
screen_rect = screen.get_rect()
centerx = screen_rect.width // 2
centery = screen_rect.height // 2
offset = screen_rect.height * 0.4
speed = 0.01
angle = 0
print(f"Size of the screen ({screen_rect.width}, {screen_rect.height})")
print(f"Center of the screen ({centerx}, {centery})")
screen_fonts = pygame.font.SysFont("monospace", 12)
label = screen_fonts.render("Press key up or down to change the speed...",
1, (255,255,0))
pygame.display.set_caption("Episode 3")
main_loop = True
amplifier = 200
while main_loop:
pygame.time.delay(10)
for event in pygame.event.get():
if (event.type == pygame.QUIT
or event.type == pygame.KEYDOWN
and event.key == pygame.K_ESCAPE):
main_loop = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
speed += 0.01
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
speed -= 0.01
y = round(centery + math.sin(angle) * offset)
screen.fill((0,0,0))
pygame.draw.circle(screen, RED, (centerx,y), 15)
angle += speed;
screen.blit(label, ((screen_rect.width - label.get_rect().width) // 2,
(screen_rect.height - 20)))
pygame.display.update()
pygame.quit()
|
71f15e85a636b858a6e6c7c947c1645bff0586a6 | sushinpv/LabChat | /user.py | 579 | 3.71875 | 4 | name = raw_input("Enter your name: ")
if name != "":
while True:
msg = raw_input("Message : ")
if msg == "<<<":
newmsg = name + " : MultiLine Message \n========================================================================\n"
temp = raw_input("")
while temp != ">>>":
newmsg = newmsg + temp + "\n"
temp = raw_input("")
fd = open("msg","a")
fd.write(newmsg+"========================================================================\n")
fd.close()
if msg != "" and msg!="<<<":
fd = open("msg","a")
fd.write(name+" : "+msg+"\n")
fd.close() |
ddd9018f61be4954247dc5739b26636936c6edfd | HeyIamJames/CodingInterviewPractice | /missing_element.py | 427 | 3.96875 | 4 | """
There is an array of non-negative integers.
A second array is formed by shuffling the elements of the first array and
deleting a random element.
Given these two arrays, find which element is missing in the second array.
http://www.ardendertat.com/2012/01/09/programming-interview-questions/
"""
def findMissingNumber(array1, array2):
result = 0
for num in array1 + array2:
result ^= num
return result
|
2cc7aca22e9af5346b130aee4bd16bee626d757b | guihehans/self_improvement | /code_pattern/subsets/duplicate_subsets.py | 1,356 | 3.5 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: guihehans
@file: duplicate_subsets.py
@time: 2020/12/23 9:53
@function:
"""
def find_subsets(nums):
subsets = [[]]
nums.sort()
last_generated_subsets = subsets
for num_idx in range(len(nums)):
if num_idx > 0 and nums[num_idx] == nums[num_idx - 1]:
traversed_sets = last_generated_subsets
else:
traversed_sets = subsets
n = len(traversed_sets)
output_sets = []
for set_idx in range(n):
subset = list(traversed_sets[set_idx])
subset.append(nums[num_idx])
output_sets.append(subset)
subsets.append(subset)
last_generated_subsets = output_sets
return subsets
def test_null():
sets = []
assert find_subsets(sets) == [[]]
def test():
sets = [1, 3, 3]
result = [[], [1], [3], [1, 3], [3, 3], [1, 3, 3]]
sets_result = list(map(set, result))
for r in find_subsets(sets):
assert set(r) in sets_result
def test_1():
sets = [1, 5, 3, 3]
result = [[], [1], [5], [3], [1, 5], [1, 3], [5, 3], [1, 5, 3], [3, 3], [1, 3, 3],
[3, 3, 5],
[1, 5, 3, 3]]
sets_result = list(map(set, result))
for r in find_subsets(sets):
assert set(r) in sets_result
if __name__ == '__main__':
test()
|
437656422020878aa26cd24a65bc16ccda8a69c6 | smritibhati/Decision-Tree | /q-1-1.py | 5,515 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
import numpy as np
import math
data=pd.read_csv('decision_Tree/train.csv')
# In[3]:
# Divide the data into training and validation. Drop all non categorical columns from the dataframe
# In[4]:
data,testdata= np.split(data,[int(0.80*len(data))])
data= pd.DataFrame(data,columns=['Work_accident', 'promotion_last_5years', 'sales', 'salary', 'left'])
# In[5]:
# Node class is defines a node in the decision tree. Every node has the following properties:
# isleaf : if the node is a leaf
# isnumeric : if the node determines a numerical column
# value : the name of the column on which this node is split
# children : a dictionary of all the children nodes of this node
# In[6]:
class Node:
def __init__(self,split,rows,leaf):
self.isleaf=leaf
self.rows=rows
# print("rows", rows)
yes,no = maxfreq(rows)
if yes==0 or no ==0:
self.isleaf=True
if self.isleaf==True:
if yes>no:
self.value=1
else:
self.value=0
self.children={}
else:
self.value=split #name of the attribute is the value of the node
self.children= partition(rows,split) #all children of this attribute in a dictionar
print (self.value,"Node Value")
return
# In[7]:
# Given a dataframe, counts the number of yes and nos labels
# In[8]:
def maxfreq(rows):
yes=0
no=0
for x in range(len(rows)):
if rows.iloc[x]['left']==1:
yes+=1
else:
no+=1
return yes,no
# In[9]:
# partitions the rows into multiple groups based on the column passed
# In[10]:
def partition(data,col):
countdict={}
uniquevalues = data[col].unique()
for value in uniquevalues:
countdict[value]= data[data[col]==value]
# print (countdict)
return countdict
# In[11]:
#matches the passed rows to count the number of yes and no in the rows
# In[12]:
def matchlabel(data):
stats={}
values, valuecount = np.unique(data['left'],return_counts=True)
for i in range(len(values)):
stats[values[i]]=valuecount[i]
return stats
# In[13]:
#calculate the entropy of the passed column
# In[14]:
def entropy(rows,col):
entro=0
countdict= partition(rows,col)
for key in countdict:
rowgroup=countdict[key]
rowgroupstats=matchlabel(rowgroup)
ans=0
# print(rowgroupstats)
for op in rowgroupstats:
value=rowgroupstats[op]
ans-= float(value)/float(len(rowgroup)) * math.log((float(value)/float(len(rowgroup))),2)
entro+=ans*(len(rowgroup)/len(rows))
return entro
# In[15]:
# calculates the total entropy of the data on the last column
# In[16]:
def totalentropy(data):
countdict=partition(data,'left')
total = 0
for key in countdict:
value=len(countdict[key])
total-= float(value)/float(len(data)) * math.log((float(value)/float(len(data))),2)
return total
# In[17]:
# Runs on all the columns of the data, and returns the max infogain and the column name for that max infogain
# In[18]:
def informationgain(data):
global totalentropy
print("length of data", len(data))
maxinfogain=0
attr=0
infogain=0
for col in data:
if col=='left':
continue
ent=entropy(data,col)
infogain=totalentropy(data)-ent
print (infogain)
if infogain>maxinfogain:
# print(maxinfogain)
maxinfogain=infogain
attr=col
return maxinfogain,attr
# In[19]:
# A recursive funtion to build the tree.
# Initially called with the complete data.
# Recursive calls are made while the data is continuously partitiones and columns are dropped.
# Condition for leaf node: Gain<=0 or if there is only one label in the data
# In[20]:
def buildTree(data):
global level
gain, split = informationgain(data)
print("split", split)
if gain<=0:
return Node(split,data,True)
root = Node(split,data,False)
for child in root.children:
root.children[child]=buildTree(root.children[child].drop(columns=[split]))
return root
# In[21]:
root=buildTree(data)
# print(root.isleaf)
# In[22]:
def findlabel(row):
ptr = root
while ptr.isleaf==False:
value=row[ptr.value]
# print(value)
ptr=ptr.children[value]
return ptr.value
# In[23]:
def calculate(fp,fn,tp,tn,wrong,correct):
accuracy=correct/(wrong+correct)
recall=tp/(tp+fn)
precision=tp/(tp+fp)
f1score=(2/(1/precision)+(1/recall))
return accuracy,recall,precision,f1score
# In[24]:
def predict(data):
correct=0
wrong=0
fp=0
tp=0
fn=0
tn=0
for i in range(0,len(data)):
row=data.iloc[i]
predictlabel=findlabel(row)
if predictlabel==row['left']:
if predictlabel==1:
tp+=1
else:
tn+=1
correct+=1
else:
if predictlabel==0:
fn+=1
else:
fp+=1
wrong+=1
# print(fp,fn,tp,tn,wrong,correct)
return (calculate(fp,fn,tp,tn,wrong,correct))
# In[26]:
accuracy, recall, precision, F1score = predict(testdata)
print(accuracy,recall,precision,F1score)
# In[ ]:
|
38ffeef91b0bd96b2ef593209e0895d514a2ed12 | etporter/Bomb-A-Mole | /bombamole_lib/high_score.py | 3,481 | 3.734375 | 4 | """
This is a program for displaying the user's high scores.
"""
import sys, pygame
pygame.init()
class hs(object):
def __init__(self):
pygame.display.set_caption('High Score')
# set the window size:
dimensions=[1200,650]
font = pygame.font.Font(None, 48)
screen=pygame.display.set_mode(dimensions)
# load the high score storage file:
file = open("High Score.txt", "r")
# read the file:
intext = file.read()
# split the high score storage into useable data
text = str(intext).split('.')
print text
if len(text) > 12 and len(text) < 24:
text1 = text[0:12]
text2 = text[12:]
for i in text1:
# print i
iIndex = text1.index(i)
j = font.render(i, True, [255,255,255])
screen.blit(j, [50, ((iIndex+1)*50)-10])
for i in text2:
# print i
iIndex = text2.index(i)
j = font.render(i, True, [255,255,255])
screen.blit(j, [400, ((iIndex+1)*50)-10])
elif len(text) > 24:
text1 = text[0:12]
text2 = text[12:24]
text3 = text[24:]
for i in text1:
# print i
iIndex = text1.index(i)
j = font.render(i, True, [255,255,255])
screen.blit(j, [50, ((iIndex+1)*50)-10])
for i in text2:
# print i
iIndex = text2.index(i)
j = font.render(i, True, [255,255,255])
screen.blit(j, [400, ((iIndex+1)*50)-10])
for i in text3:
# print i
iIndex = text3.index(i)
j = font.render(i, True, [255,255,255])
screen.blit(j, [800, ((iIndex+1)*50)-10])
else:
# For each item in the list of high scores, blit at a different y coordinate:
for i in text:
# print i
iIndex = text.index(i)
j = font.render(i, True, [255,255,255])
screen.blit(j, [50, ((iIndex+1)*50)-10])
# main loop:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.flip()
if __name__ == "__main__":
begin = hs()
begin.run()
|
546271bd7d5f5ae3f6fdd8030de110dbf75dfbc2 | thanders/light_switch | /lightswitch/displayboard.py | 1,190 | 3.734375 | 4 | class displayboard:
# Initializes instance of the displayboard class
def __init__(self, start_row, finish_row, start_column, finish_column):
self.__grid = []
self.__start_row = start_row
self.__finish_row = finish_row
self.__start_column = start_column
self.__finish_column = finish_column
def size(self):
return print("rows:",self.__start_row, "and columns:", self.__finish_column)
def comprehension(self):
for i in range(self.__start_row, self.__finish_row):
self.__grid.append([])
for j in range(self.__start_column, self.__finish_column):
self.__grid[i].append([j])
def showboard(self):
for i in self.__grid:
print([i])
print()
print(self.__grid)
# L*L matrix (L rows and L lights in each matrix)
# Initalizes the displayboard with row and column inputs
start_row=0
finish_row=2
start_column=2
finish_column=5
x = displayboard(start_row, finish_row, start_row, finish_column)
# Returns the number of rows and columns
x.size()
# Appends items to the array based on the size
x.comprehension()
#prints the array
x.showboard() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.