blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
a8376b5a8d0951e42672b102382ddb3273d78be2 | grapefruit623/leetcode | /easy/1005_MaximizeSumOfArrayAfterKNegations.py | 2,010 | 3.796875 | 4 | # -*- coding:utf-8 -*-
#! /usr/bin/python3
import unittest
from typing import List
'''
leetcode tag: Greedy
'''
class Solution:
'''
AC
'''
def largestSumAfterKNegations(self, A:List[int], K:int)->int:
a = sorted(A)
i = 0
'''
Inverse negivation numbers.
'''
while K > 0:
if a[i] < 0:
a[i] *= -1
K -= 1
else:
break
i += 1
'''
Eventhough there are still negative number,
but the smallers are inversed to positive.
'''
if K == 0:
return sum(a)
'''
All remaining negation used on zero,
all negative number are inversed to positive.
'''
a = sorted(a)
if a[0] == 0:
return sum(a)
'''
All numbers are positive now, we need to chose smaller to be
negation.
Because sign of number will not be modified by twice nagivation.
Just care about K mod 2 and inversed the smallest number.
'''
K %= 2
a[0] *= -1 if K == 1 else 1
return sum(a)
class Unittest(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_sample1(self):
A = [4,2,3]
K = 1
expected = 5
self.assertEqual(expected, self.sol.largestSumAfterKNegations(A,K))
def test_sample2(self):
A = [3,-1,0,2]
K = 3
expected = 6
self.assertEqual(expected, self.sol.largestSumAfterKNegations(A,K))
def test_sample3(self):
A = [2,-3,-1,5,-4]
K = 2
expected = 13
self.assertEqual(expected, self.sol.largestSumAfterKNegations(A,K))
def test_sample4(self):
A = [-2,9,9,8,4]
K = 5
expected = 32
self.assertEqual(expected, self.sol.largestSumAfterKNegations(A,K))
if __name__ == "__main__":
unittest.main()
|
0c9c140591ac7c25cc625512b8823a3d5a190343 | amit928/important-python-codes | /binary_search_using_recursive_function.py | 502 | 3.90625 | 4 | def binary_search(l1,element):
if len(l1)==0:
return False
else:
mid=len(l1)//2
if(element<l1[mid]):
return binary_search(l1[:mid], element)
elif(element>l1[mid]):
return binary_search(l1[mid+1:], element)
else:
return True
l1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,19,34,46,78,123,345,456,7891345,12349,123401] # The list should be in sorted form for binary searching .
element=34
print(binary_search(l1,element))
|
2b6112a9dec754c85b0bba0e17ce880f63ff4730 | MengyingGIRL/python-100-days-learning | /Day05/palindrome.py | 263 | 3.78125 | 4 | '''
正整数的反转
@Time : 2020/1/9 10:06
@Author : wangmengying
@File : palindrome.py
'''
num = int(input('请输入一个正整数:'))
reversed_num = 0
while num > 0:
reversed_num = num % 10 + reversed_num * 10
num = num // 10
print(reversed_num) |
b8db14461229cda8dfe9e6e5bad239f41bc6516a | archits14/datavisualisation | /jsonproj.py | 1,528 | 4.0625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
#importing the crime data from json file
crimedata = pd.read_json('crimedata.json', orient='columns')
#user prompt for asking what data needs to be plotted
option = input("Pls let us know what data you would be interested in seeing in the plot: Enter 1 for No. of Crimes against Year and 2 for No. of Settled Cases against Year:")
#condition to plot data which is for number of crimes against years
if (option == '1'):
plt.plot((crimedata.loc[:,'year']), (crimedata.loc[:,'crimes']), label='line 1', linewidth=2)
plt.xlabel('Year')
plt.ylabel('Number of Crimes')
plt.title('Crimes against Years - Line Plot')
plt.show()
plt.bar((crimedata.loc[:,'year']), (crimedata.loc[:,'crimes']), label='line 1', linewidth=2)
plt.xlabel('Year')
plt.ylabel('Number of Crimes')
plt.title('Crimes against Years - Bar Graph')
plt.show()
#condition to plot data which is for number of settled cases against years
elif(option == '2'):
plt.plot((crimedata.loc[:,'year']), (crimedata.loc[:,'settledCases']), label='line 1', linewidth=2)
plt.xlabel('Year')
plt.ylabel('Number of Settled Cases')
plt.title('Settled Cases against Years - Line Plot')
plt.show()
plt.bar((crimedata.loc[:,'year']), (crimedata.loc[:,'settledCases']), label='line 1', linewidth=2)
plt.xlabel('Year')
plt.ylabel('Number of Settled Cases')
plt.title('Settled Cases against Years - Bar Graph')
plt.show()
else:
print("Wrong Input") |
d262b429509a00cabe7871b71d7e1b3d1b36760d | puneetb97/Python_course | /day2/circle.py | 324 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 17:22:11 2019
@author: Puneet
"""
# taking radius from user
radius = float(input("enter radius:"))
# calculating area and parameter
import math
area = math.pi*radius**2
parameter = 2*math.pi*radius
print("area of circle is:",area)
print("parameter of circle is:",parameter) |
aaa4ea745e2e40ed8173352fbc30a6eaed7f1c0d | nkgarcia/string_manipulations | /makeAnagram.py | 1,486 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 12:08:42 2020
@author: ngarcia
"""
import pandas as pd
def makeAnagram(a,b):
"""Returns the minimum total characters that must be deleted to make a and b anagrams of each other"""
excluded = [i for i in set(a) if i not in set(b)]
excluded1 = [i for i in set(b) if i not in set(a)]
lst = excluded+excluded1
cnt_rem_a = 0
cnt_add_a = 0
new_str = ''
cnt_rem_b = 0
cnt_add_b = 0
new_str1 = ''
for i in a:
if i not in lst:
new_str = new_str + i
cnt_add_a += 1
else:
cnt_rem_a += 1
n = list(new_str)
n.sort()
r_str = ''.join(n)
for i in b:
if i not in lst:
new_str1 = new_str1 + i
cnt_add_b += 1
else:
cnt_rem_b += 1
n1 = list(new_str1)
n1.sort()
r_str1 = ''.join(n1)
zipped = zip(list(r_str),list(r_str1))
tups = list(zipped)
df1 = pd.DataFrame(tups,columns=['l1','l2']).groupby('l1').count()
df2 = pd.DataFrame(tups,columns=['l1','l2']).groupby('l2').count()
mdf = pd.merge(df1,df2,left_on='l1',right_on='l2',how='left',right_index=True)
mdf.index.name = 'index'
mdf.fillna(0,inplace=True)
mdf['l3']=abs(mdf['l2'] - mdf['l1'])
final_exclude = sum(mdf['l3'])
min_char_del = final_exclude +cnt_rem_b+cnt_rem_a
return min_char_del
|
8e6aadc8e034c1b24a1fdda6b6a055abf374f5c8 | mapatelian/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/3-common_elements.py | 368 | 4.25 | 4 | #!/usr/bin/python3
def common_elements(set_1, set_2):
"""Function that looks for common elements in two sets
Args:
set_1 (set)
set_2 (set)
Return:
New list with common elements
"""
new = []
for i in set_1:
for k in set_2:
if i is k:
new.append(i)
return new
|
75dfc5922a9bac61aff7b23d74914f6f5e9c5520 | EvanJamesMG/Leetcode | /python/Array/169. Majority Element.py | 633 | 4 | 4 | # coding=utf-8
__author__ = 'EvanJames'
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
'''
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==1:
return nums[0]
nums.sort()
return nums[len(nums)/2]
# if __name__ == '__main__':
# res = Solution().containsNearbyDuplicate([1, 2, 3, 4, 1], 10)
# print(res)
|
c1b930e25863c4a0351b1601b505e790f981db49 | Iliya-Yeriskin/Learning-Path | /Python/Class_work/L9_While/L9.4.py | 294 | 3.921875 | 4 | while True:
name = input("Enter a name: ")
if name == "iliya":
print("Hello Iliya")
break
elif name == "dan":
continue
else:
print("Where is Iliya?")
number = int(input("Enter a number: "))
print(number*4)
print("Bye Bye...")
|
c455557d8ca7fb60ad564bcd279f3df6b5b823be | aitorlomu/SistemasGestores | /Python/Python/Ejercicios/10.py | 156 | 3.71875 | 4 | ini=int(input('Introduce el número inicial '))
fin=int(input('Introduce el número final '))
for i in range(ini,fin+1):
if (i%7)==0:
print(i)
|
94981b8608b3d9d6e3602e3b323a0aa0823cdad9 | amrithajayadev/misc | /connect-nodes-of-same-level.py | 3,895 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 20:05:11 2019
@author: jayada1
"""
{
#Initial Template for Python 3
import atexit
import io
import sys
from collections import defaultdict # default dict used as a map, to store node-value mapping.
#Contributed by : Nagendra Jha
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
# Node Class:
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
self.nextRight = None
# Tree Class
class Tree:
def __init__(self):
self.root = None
self.map_nodes = defaultdict(Node)
def Insert(self,parent, child,dir):
if self.root is None:
root_node = Node(parent)
child_node = Node(child)
if dir == 'L':
root_node.left = child_node
else:
root_node.right = child_node
self.root = root_node
self.map_nodes[parent] = root_node
self.map_nodes[child] = child_node
return
parent_node = self.map_nodes[parent]
child_node = Node(child)
self.map_nodes[child] = child_node
if dir == 'L':
parent_node.left = child_node
else:
parent_node.right = child_node
return
def InOrder(root):
'''
:param root: root of the given tree.
:return: None, print the space separated in order Traversal of the given tree.
'''
if root is None: # check if the root is none
return
InOrder(root.left) # do in order of left child
print(root.data, end=" ") # print root of the given tree
InOrder(root.right) # do in order of right child
def printSpecial(root):
leftmost_node = root
while leftmost_node :
curr_node = leftmost_node
leftmost_node = None
if curr_node.left :
leftmost_node = curr_node.left
elif curr_node.right :
leftmost_node = curr_node.right
print(curr_node.data,end=" ")
while curr_node.nextRight :
print(curr_node.nextRight.data,end=" ")
curr_node = curr_node.nextRight
print()
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases):
n = int(input()) # number of nodes in tree
a = list(map(str, input().strip().split())) # parent child info in list
# construct the tree according to given list
tree = Tree()
i = 0
while (i < len(a)):
parent = int(a[i])
child = int(a[i + 1])
dir = a[i + 2]
i += 3
tree.Insert(parent, child, dir) # Insert the nodes in tree.
connect(tree.root)
printSpecial(tree.root)
InOrder(tree.root)
print()
}
''' This is a function problem.You only need to complete the function given below '''
#User function Template for python3
def connect(root):
'''
:param root: root of the given tree
:return: none, just connect accordingly.
{
# Node Class:
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
self.nextRight = None
}
'''
#h = height(root)
if root is None:
return
q = list()
q.append(root)
while len(q)>0:
node = q.pop(0)
node.nextRight = q[0] if len(q)>0 else None
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
|
6bc8cf71d53be657ad62ed831af79ac6d2526230 | victorfengming/python_projects | /history_pro/python_ydma/Python基础/day02/99乘法表.py | 914 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by xiaoming
# 本模块的功能:<99乘法表>
# # 如何打印一行 10个#
# print(help(print))
# print(1,end="")
#
# i = 0
# while i<10:
# j = 0
# while j<10:
# print("#",end = "")
# j += 1
# print()
# i += 1
# 乘法表
i = 1#行数
while i <= 9 :
j = 1
while j <= i :
print( str(j)+"*"+str(i)+"="+str((i)*j)+" ",end = "")
if i*j<10 :
print("\t",end ="")
j+=1
print()
i+=1
# 隔行变色
# i = 0
# while i<10:
# j = 0
# while j<10:
# if j%2 :
# if i%2:
# print("*",end = "")
# else :
# print("#", end="")
# else:
# if i%2:
# # print("#",end = "")
# # else :
# # print("*", end="")
#
# j += 1
#
# print()
# i += 1
|
3533485fb4af0a43e75df55601e3dc68072fa085 | aline20santos/lab6_seguran-a | /teste.py | 82 | 3.78125 | 4 | #!/usr/bin/python3
var = input("Digite um texto: ") print("Voce digitou: " + var)
|
f759f66d0e4b31365bdf7d284fe93c2b3801bfc6 | csJd/oj-codes | /archive/xhs_190818_1.py | 866 | 3.859375 | 4 | """
字符串倒序
时间限制:C/C++语言 1000MS;其他语言 3000MS
内存限制:C/C++语言 65536KB;其他语言 589824KB
题目描述:
薯队长带着小红薯参加密室逃脱团建游戏,首先遇到了反转游戏,小红薯们根据游戏提示收集了多个单词线索,并将单词按要求加一个空格组成了句子,最终要求把句子按单词反转解密。
说明:收集的时候单词前后可能会有多个空格,反转后单词不能有多个空格,具体见输入输出样例。
输入
输入一个字符串。包含空格和可见字符。长度<=10000。
输出
输出一个字符串,表示反转后结果。
样例输入
the sky is blue!
样例输出
blue! is sky the
"""
def main():
str_list = input().split()[::-1]
print(" ".join(str_list))
if __name__ == "__main__":
main()
|
890cb4c5bda8013a8f83b64140fa004ac914b03f | Yegor9151/Algorithms_and_data_structures_in_Python. | /losson 5 - Collections. Collections module/lesson5_task1.py | 1,672 | 3.78125 | 4 | """
1. Пользователь вводит данные о количестве предприятий, их наименования и прибыль за четыре квартала для каждого
предприятия. Программа должна определить среднюю прибыль (за год для всех предприятий) и отдельно вывести наименования
предприятий, чья прибыль выше среднего и ниже среднего.
"""
from collections import defaultdict
ent_count = int(input("Введите число предприятий:"))
enterprises = defaultdict(int)
all_profit = 0
for i in range(ent_count):
ent_name = input(f"Введите название {i + 1} предприятия:")
for j in range(4):
profit = int(input(f"Введите прибыль от {ent_name} за {j + 1} квартал"))
all_profit += profit
enterprises[ent_name] += profit
mean_profit = all_profit / (ent_count * 4)
more_mean = defaultdict(int)
less_mean = defaultdict(int)
for i, v in enterprises.items():
v /= 4
if v > mean_profit:
more_mean[i] = v
elif v < mean_profit:
less_mean[i] = v
print(f'Средняя прибыль за год для всех предприятий = {mean_profit}')
print(f'\nПредприятия чья прибыль выше средней')
for k, v in more_mean.items():
print(f'{k} = {v}')
print(f'\nПредприятия чья прибыль ниже средней')
for k, v in less_mean.items():
print(f'{k} = {v}')
|
9b4c096df5fce2c0413d0b95236f0fdc4120e008 | TheAlgorithms/Python | /machine_learning/scoring_functions.py | 3,398 | 3.546875 | 4 | import numpy as np
""" Here I implemented the scoring functions.
MAE, MSE, RMSE, RMSLE are included.
Those are used for calculating differences between
predicted values and actual values.
Metrics are slightly differentiated. Sometimes squared, rooted,
even log is used.
Using log and roots can be perceived as tools for penalizing big
errors. However, using appropriate metrics depends on the situations,
and types of data
"""
# Mean Absolute Error
def mae(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mae(predict,actual),decimals = 2)
0.67
>>> actual = [1,1,1];predict = [1,1,1]
>>> mae(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = abs(predict - actual)
score = difference.mean()
return score
# Mean Squared Error
def mse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mse(predict,actual),decimals = 2)
1.33
>>> actual = [1,1,1];predict = [1,1,1]
>>> mse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
square_diff = np.square(difference)
score = square_diff.mean()
return score
# Root Mean Squared Error
def rmse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(rmse(predict,actual),decimals = 2)
1.15
>>> actual = [1,1,1];predict = [1,1,1]
>>> rmse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
square_diff = np.square(difference)
mean_square_diff = square_diff.mean()
score = np.sqrt(mean_square_diff)
return score
# Root Mean Square Logarithmic Error
def rmsle(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [10,10,30];predict = [10,2,30]
>>> np.around(rmsle(predict,actual),decimals = 2)
0.75
>>> actual = [1,1,1];predict = [1,1,1]
>>> rmsle(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
log_predict = np.log(predict + 1)
log_actual = np.log(actual + 1)
difference = log_predict - log_actual
square_diff = np.square(difference)
mean_square_diff = square_diff.mean()
score = np.sqrt(mean_square_diff)
return score
# Mean Bias Deviation
def mbd(predict, actual):
"""
This value is Negative, if the model underpredicts,
positive, if it overpredicts.
Example(rounded for precision):
Here the model overpredicts
>>> actual = [1,2,3];predict = [2,3,4]
>>> np.around(mbd(predict,actual),decimals = 2)
50.0
Here the model underpredicts
>>> actual = [1,2,3];predict = [0,1,1]
>>> np.around(mbd(predict,actual),decimals = 2)
-66.67
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
numerator = np.sum(difference) / len(predict)
denumerator = np.sum(actual) / len(predict)
# print(numerator, denumerator)
score = float(numerator) / denumerator * 100
return score
def manual_accuracy(predict, actual):
return np.mean(np.array(actual) == np.array(predict))
|
d4dfcea0cf6fad315a63cd10ddc4d4d4bac572ec | RobDWaller/requirements-rules-examples | /form/src/validator.py | 2,358 | 3.578125 | 4 | '''
Wrapper for the FormValidation class
'''
from .form_validation import FormValidation
# pylint: disable=too-few-public-methods
class Validator:
'''
Simple class which validates a forms input. Contains one method validate.
'''
# pylint: disable=too-many-arguments
def __init__(self, first_name, last_name, email, date_of_birth, terms_conditions):
'''
Accepts and sets first name string, last name string, email string,
date of birth string, and terms and conditions string.
'''
self.first_name = first_name
self.last_name = last_name
self.email = email
self.date_of_birth = date_of_birth
self.terms_conditions = terms_conditions
def validate(self):
'''
Method that validates all the inputted fields using the form validation
class. Returns a dictionary containing boolean result and list of
validation error messages.
'''
form_validation = FormValidation()
result = {'result': True, 'messages': []}
if form_validation.name(self.first_name) is False:
result['result'] = False
result['messages'].append((
'Please fill in a valid first name only alpha numeric characters, '
'spaces and dashes allowed.'
))
if form_validation.name(self.last_name) is False:
result['result'] = False
result['messages'].append((
'Please fill in a valid last name only alpha numeric characters, '
'spaces and dashes allowed.'
))
if form_validation.email(self.email) is False:
result['result'] = False
result['messages'].append('Please fill in a valid email.')
if form_validation.date_of_birth(self.date_of_birth) is False:
result['result'] = False
result['messages'].append((
'Please fill in a valid date of birth, format day/month/year, '
'after 1900 and before or equal to today.'
))
if form_validation.terms_conditions(self.terms_conditions) is False:
result['result'] = False
result['messages'].append((
'Please agree to our terms and conditions and privacy policy.'
))
return result
|
7ea176a96323e5904d2facb45deefb0d465df71e | basdijkstra/abgt-unit-testing-frameworks-python | /examples/adding_assertions_to_a_test.py | 2,392 | 3.625 | 4 | import pytest
def test_add_2_and_2_should_equal_4():
""" This test checks that 2 and 2 equals 4.
As that is true, the test will pass
"""
our_result = 2 + 2
assert our_result == 4
def test_add_2_and_2_should_equal_5():
""" This test checks that 2 and 2 equals 5.
As that is true, the test will fail
"""
our_result = 2 + 2
assert our_result == 5
def test_add_2_and_2_should_equal_5_fails_with_supplied_message():
""" This test, too, checks that 2 and 2 equals 5.
As that is not true, the test will fail again,
but this time with the specified message
"""
our_result = 2 + 2
assert our_result == 5, "2 and 2 should equal 5"
def test_create_boolean_with_value_true_check_that_value_is_true():
""" This test uses an assertTrue to check that the value of
a specified boolean variable is equal to 'True'.
"""
our_boolean = True
assert our_boolean is True
def test_create_variable_with_value_none_it_check_that_value_is_none():
""" This test asserts that a variable has not been initialized
(it has never been assigned a value, or it has explicitly
been assigned the 'None' value).
"""
our_variable = None
assert our_variable is None
def test_check_dividing_by_zero_raises_zerodivisionerror():
""" This test uses a 'with pytest.raises' construct
to check that a code statement raises a specific type of error,
in this case a ZeroDivisionError.
As that is the case, the test will pass.
"""
with pytest.raises(ZeroDivisionError):
our_result = 2 / 0
def test_check_dividing_by_zero_raises_valueerror():
""" This test uses a 'with pytest.raises' construct
to check that a code statement raises a specific type of error,
in this case a ValueError. As that is not the case,
(it raises a ZeroDivisionError) the test will fail.
"""
with pytest.raises(ValueError):
our_result = 2 / 0
def test_check_dividing_by_zero_raises_zerodivisionerror_but_doesnt():
""" This test uses a 'with pytest.raises' construct
to check that a code statement raises a specific type of error,
in this case a ZeroDivisionError.
Since no error is raised at all, the test will fail.
"""
with pytest.raises(ZeroDivisionError):
our_result = 2 / 1
|
fdb9e3bf826f384d1d51fd167fc9703a12674012 | KarlaDiass/AulaEntra21_Karla | /atividadesPY/Variáveis/Operação_Matemática/opmatematica.py | 2,067 | 4.3125 | 4 | ###############################
#
# Operações Matemáticas Básicas
#
###############################
# O python possui 7 operadores matemáticos. Vamos ver os 5 primeiros.
#
# SOMA
# O operado usado para soma é o sinal de mais +
# 2 + 2 = 4
# Subtração
# O operador para subtração é o sinal de menos -
# 5 - 3 = 2
# Divizão
# O operador para divizão é a barra /
# 10 / 2 = 10
# Multiplicação
# O operador para multiplicação é o asterisco *
# 2 * 5 = 10
# Quando aparecer a seguinte situação: 2x isso é a mesma coisa que: 2*x
# Expoente
# Você se lemba o que é um expoente?
# O expoente é uma conta matemática em que o primeiro número multiplica por ele mesmo uma quantidade de vezes.
# Exempo é o 4² (lea-se 4 elevado a 2 ou 4 ao quadrado)
# 4² -> 4 * 4 = 16
# 4³ -> 4 * 4 * 4 = 64
# O operador para o expoente são dois asteriscos **
# 4² -> 4 ** 2 = 16
# 4³ -> 4 ** 3 = 64
# exemplo de soma:
numero1 = int(input("Digite o primeiro número: "))
numero2 = int(input("Digite o segundo número: "))
soma = numero1 + numero2
print("A soma dos números é: ", soma)
print("\n")
# exemplo de multiplicação:
valor = float(input("Digite o preço do produto: "))
quantidade = int(input("Digite a quantidade de produto que você deseja: "))
preco_total = valor * quantidade
print("O valor total a ser pago é: ", preco_total)
print('\n')
# exemplo de divisão
quantidade = int(input("Digite a quantidade de laranjas que você tem: "))
pessoas = int(input("Digite a quantidade de pessoas: "))
divisao = quantidade / pessoas
print("Cada pessoa deve ficar com ", divisao, " laranjas")
# exemplo de subtração
predio_alto = float(input("Digite o tamanho do prédio alto: "))
predio_baixo = float(input("Digite o tamanho do prédio baixo: "))
diferenca = predio_alto - predio_baixo
print("O prédio mais alto ", diferenca, " metros mais alto que o prédio baixo")
# exemplo de expoente
numero = int(input("Digite o número para ser elevado ao quadrado: "))
quadrado = numero ** 2
print("O quadrado de ", numero, " é: ",quadrado)
|
95ff4aac0663bbc2430804ff9081fb529dca812f | Davv7d/UnitTestPythonQuadraticFunction | /Quadf.py | 824 | 3.609375 | 4 | import math
class Quadratic_function:
@staticmethod
def delta(a, b, c):
if not (isinstance(a, (int, float)) and
isinstance(b, (int, float)) and
isinstance(c, (int, float))):
return None
delta = b*b - 4*(a*c)
if delta < 0:
return None
return delta
@staticmethod
def zero_place(a, b, c):
delta = Quadratic_function.delta(a, b, c)
if(delta is None or a == 0):
# print("delta < 0")
return None
elif(delta == 0):
# print("delta == 0")
return -b/(2*a)
pdelta = math.sqrt(delta)
return ((-b - pdelta)/(2*a)), ((-b + pdelta)/(2*a))
if __name__ == "__main__":
f1_result = Quadratic_function.miejsca_zerowe(1, 6, 8)
print(f1_result) |
c8f7d90e9b494eba3ffaf8b0092e43c745428783 | Bluette1/PythonTutorial | /print_name.py | 846 | 4.5625 | 5 | # Statement
#
# Write a program that greets the user by printing the word "Hello", a comma, the name of the user and an exclamation mark after it. See the examples below.
#
# Warning. Your program's output should strictly match the desired one, character by character. There shouldn't be any space between the name and the exclamation mark. You can use + operator to concatenate two strings. See the lesson for details.
#
#
# Example input
#
# Harry
#
#
# Example output
#
# Hello, Harry!
#
#
# Theory
#
# If you don't know how to start solving this assignment, please, review a theory for this lesson:
# https://snakify.org/lessons/print_input_numbers/
#
# You may also try step-by-step theory chunks:
# https://snakify.org/lessons/print_input_numbers/steps/1/
# Read a string:
name = input()
# Print a string:
print("Hello, " + name + "!")
|
a9b1aef0ef36dbe48e5cb56fd4d082ddd13731c9 | atm1992/algorithm_interview | /a46_trap.py | 1,585 | 4.125 | 4 | # -*- coding: UTF-8 -*-
"""
接雨水。
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
例如:输入数组 [0,1,0,2,1,0,1,3,2,1,2,1],输出 6
解题思路:
双指针法
使用left,right两个指针逐步向中间移动,使用maxleft、maxright这两个变量来存储当前的左右两侧最大值
若maxleft小于maxright,则left移动一步;否则right移动一步,直到left小于right
时间复杂度O(N),空间复杂度为O(1)
"""
from typing import List
class Solution:
"""双指针法"""
def trap(self, height: List[int]) -> int:
if not height or len(height) < 3:
return 0
n = len(height)
maxleft, maxright = height[0], height[n - 1]
left, right = 1, n - 2
res = 0
while left <= right:
# 更新maxleft, maxright
# 确保此时的maxleft一定大于等于height[left],从而确保maxleft-height[left]大于等于0
maxleft = max(height[left], maxleft)
maxright = max(height[right], maxright)
# 能否盛水,盛多少水,取决于短板(矮的那个)
if maxleft < maxright:
# res每次累加的都是当前柱子上能接多少雨水,所以当left = right时,累加的是left和right最后共同指向的那根柱子
res += maxleft - height[left]
left += 1
else:
res += maxright - height[right]
right -= 1
return res
|
323f622300e23d6a89c71e340235993822743693 | furgerf/advent-of-code-2018 | /day-02/part-1/main.py | 473 | 3.90625 | 4 | #!/usr/bin/env python
if __name__ == "__main__":
with open("input") as fh:
data = fh.readlines()
two_letters = 0
three_letters = 0
for d in data:
counts = {}
for char in d:
if char not in counts:
counts[char] = 0
counts[char] += 1
if 2 in counts.values():
two_letters += 1
if 3 in counts.values():
three_letters += 1
print("Two", two_letters, "Three", three_letters, "Product", two_letters*three_letters)
|
9aa7bcaf459b04578d534a86596b2e5960f669d3 | michaeld97/shoot-your-shot | /Model.py | 12,181 | 4.125 | 4 | import math
# Set of Joint Angles
# User Input
print("---Creating Player Profile---")
player_name = input('Name: ')
dominant_hand = input("Are you left (L) or right (R) handed? ")
if dominant_hand in ('R', 'r', 'right', 'Right'):
shooting_arm = 'right'
else:
shooting_arm = 'left'
print('What is your height?')
height_feet = int(float(input("Feet: ")))
total_height = int(12 * height_feet)
height_inches = int(float(input("Inches: ")))
total_height = int(total_height + height_inches)
print(f"{player_name} is {height_feet} feet {height_inches} inches tall")
print(f"Height in Inches: {total_height}")
print("\nPlease enter the following measurements in inches.")
upper_arm = float(input(f"Length of {shooting_arm} upper arm: "))
forearm = float(input(f"Length of {shooting_arm} forearm: "))
hand = float(input(f"Length of {shooting_arm} hand: "))
print(f"\n{player_name} has a {shooting_arm} upper shooting arm of {upper_arm} inches, forearm of {forearm} inches, "
f"and hand length of {hand} inches.\n")
# Recommended Shooting Angle
if total_height < 60:
recommended_angle = "56 (and up)"
elif 60 <= total_height <= 64:
recommended_angle = "53 - 56"
elif 64 < total_height <= 68:
recommended_angle = "52 - 55"
elif 68 < total_height <= 72:
recommended_angle = "51 - 54"
elif 72 < total_height <= 76:
recommended_angle = "50 - 53"
elif 76 < total_height <= 80:
recommended_angle = "49 - 52"
elif 80 < total_height <= 84:
recommended_angle = "48 - 51"
else:
recommended_angle = "47 (and lower)"
print(f"For {player_name}, who is {int(height_feet)}'{int(height_inches)}\", a recommended range of 3PT line release "
f"angles is {recommended_angle} degrees\n")
# Customize Settings
shooting_angle = float(input("Desired Shooting Angle: "))
print("Plotting your optimal shooting form release...")
# record the user data
with open('user_data.txt', 'w') as filehandle:
filehandle.write('%s\n' % shooting_angle)
filehandle.write('%s\n' % player_name)
filehandle.write('%s' % dominant_hand)
# upper_arm = 9
# forearm = 8
# hand = 7
# Examples:
# 11, 9.5, 7.25
# Joint Angles Optimization
# Lists for X Coordinates
x_elbow = []
x_wrist = []
x_fingertip = []
# Lists for Y Coordinates
y_elbow = []
y_wrist = []
y_fingertip = []
# Release & Joint Angles
# shooting_angle = 48
# shoulder_angle = 20
# elbow_angle = 20
# wrist_angle = 20
# Angle Ranges
# Literature Range for Shoulder:
shoulder_min = 15
shoulder_max = 50
# Literature Range for Elbow:
elbow_min = shoulder_min + 1
elbow_max = 60
# Literature Range for Wrist:
wrist_min = 40
wrist_max = 89
shoulder_angle = shoulder_min
# Margin Sensitivity
margin_error = 0.01
# Change in angles
wrist_increment = 1
elbow_increment = 1
shoulder_increment = 1
while shoulder_angle <= shoulder_max:
x_elbow_coord = upper_arm * math.cos(math.radians(shoulder_angle))
y_elbow_coord = upper_arm * math.sin(math.radians(shoulder_angle))
elbow_angle = elbow_min
# print("changing angle")
# loop for elbow_angle (0 - 85)
while elbow_angle <= elbow_max:
x_wrist_coord = x_elbow_coord + forearm * math.cos(math.radians(elbow_angle))
y_wrist_coord = y_elbow_coord + forearm * math.sin(math.radians(elbow_angle))
wrist_angle = wrist_min
# loop for wrist_angle (0 - 130)
while wrist_angle <= wrist_max:
x_fingertip_coord = x_wrist_coord + hand * math.cos(math.radians(wrist_angle))
y_fingertip_coord = y_wrist_coord + hand * math.sin(math.radians(wrist_angle))
margin = math.degrees(math.atan(y_fingertip_coord/x_fingertip_coord))
if (margin - margin_error <= shooting_angle) and (shooting_angle <= margin + margin_error):
# Append X Coordinates
x_elbow.append(x_elbow_coord)
x_wrist.append(x_wrist_coord)
x_fingertip.append(x_fingertip_coord)
# Append Y Coordinates
y_elbow.append(y_elbow_coord)
y_wrist.append(y_wrist_coord)
y_fingertip.append(y_fingertip_coord)
# print("let's get this bread")
# print(x_wrist_coord)
# print(math.cos(math.radians(wrist_angle)))
# print(x_fingertip_coord)
# print(margin)
# Figure out how to correctly iterate each angle joint by 0.5 degrees
# Check if the shooting angle works for this set of joint angles
wrist_angle += wrist_increment
elbow_angle += elbow_increment
shoulder_angle += shoulder_increment
# compute average of x and y coordinates of fingertip
x_sum = 0
for i in x_fingertip:
x_sum += i
x_release = x_sum / len(x_fingertip)
y_sum = 0
for i in y_fingertip:
y_sum += i
y_release = y_sum / len(y_fingertip)
print(f'The x release coord is: {x_release} and the y release coord is {y_release}')
with open('basketball_data.txt', 'w') as filehandle0:
index = 0
while index < len(x_elbow):
filehandle0.write('%s ' % x_elbow[index])
filehandle0.write('%s ' % y_elbow[index])
filehandle0.write('%s ' % x_wrist[index])
filehandle0.write('%s ' % y_wrist[index])
filehandle0.write('%s ' % x_fingertip[index])
filehandle0.write('%s' % y_fingertip[index])
filehandle0.write('\n')
index = index + 1
with open('y_elbow.txt', 'w') as filehandle1:
for listitem in y_elbow:
filehandle1.write('%s\n' % listitem)
with open('x_wrist.txt', 'w') as filehandle2:
for listitem in x_wrist:
filehandle2.write('%s\n' % listitem)
with open('y_wrist.txt', 'w') as filehandle3:
for listitem in y_wrist:
filehandle3.write('%s\n' % listitem)
with open('x_fingertip.txt', 'w') as filehandle4:
for listitem in x_fingertip:
filehandle4.write('%s\n' % listitem)
with open('y_fingertip.txt', 'w') as filehandle5:
for listitem in y_fingertip:
filehandle5.write('%s\n' % listitem)
# //Ball Release Properties
# Optimal Backspin is said to be 3Hz or about 3 full rotations during ball trajectory
# User Input
print("---Calculating Ball Radius and Distance of 3-Point Shot---")
print('Basketball Sizes: Size 7 (29.5"), Size 6 (28.5"), Size 5 (27.5"), Size 4 (26.5")')
ball_type = input("Please input basketball size---Size 7 (1), Size 6 (2), Size 5 (3), Size (4): ")
if ball_type == 1:
ball_radius = 0.119 # roughly 4.695 inches
elif ball_type == 2:
ball_radius = 0.1152 # roughly 4.536 inches
elif ball_type == 3:
ball_radius = 0.1111 # roughly 4.377 inches
else:
ball_radius = 0.1071 # roughly 4.218 inches
three_type = input('Corner 3? (Y/N): ')
if three_type in ('Y', 'y'):
location = 'corner'
else:
location = 'above-the-break'
competition_level = input("Please enter competition level---Professional (P), Collegiate (C), High School "
"or Lower (H): ")
if competition_level in ('P', 'p', 'Professional', 'professional'):
classify = input("Please input the association---NBA (N), FIBA (F), or WNBA (W): ")
if classify in ('N', 'n', 'NBA', 'nba'):
classify = 'NBA'
if three_type in ('Y', 'y', 'Yes', 'yes'):
shot_distance = 6.7056
else:
shot_distance = 7.239
else:
if three_type in ('Y', 'y', 'Yes', 'yes'):
shot_distance = 6.60
else:
shot_distance = 6.75
if classify in ('F', 'f', 'FIBA', 'fiba'):
classify = 'FIBA'
else:
classify = 'WNBA'
elif competition_level in ('C', 'c', 'Collegiate', 'collegiate'):
division = input("Please input the division---I (1), II (2), III (3): ")
classify = input("Please input the program---Men's (M), Women's (W): ")
if classify in ('M', 'm'):
classify = "NCAA Men's"
if division in ('1', 'I', 'i'):
if three_type in ('Y', 'y', 'Yes', 'yes'):
shot_distance = 6.60
else:
shot_distance = 6.75
division = ' Division I'
classify = classify + division
else:
shot_distance = 6.3246
if division in ('2', 'II', 'ii'):
division = ' Division II'
classify = classify + division
else:
division = ' Division III'
classify = classify + division
else:
classify = "NCAA Women's"
shot_distance = 6.3246
if division in ('1', 'I', 'i'):
division = ' Division I'
classify = classify + division
elif division in ('2', 'II', 'ii'):
division = ' Division II'
classify = classify + division
else:
division = ' Division III'
classify = classify + division
else:
shot_distance = 6.0198
classify = 'High School or lower'
#
# # //Ball Properties
#
# # Backspin
backspin_rad = 2 * math.pi * (shot_distance + 2)/3
backspin_hz = backspin_rad * (1/(math.pi * 2))
shot_info = ("\n{a}'s {b} 3-point shot is {c:2.2f} feet from the hoop. An ideal backspin for this shot is {d:1.2} "
"Hz.".format(a=classify, b=location, c=3.28084 * shot_distance, d=backspin_hz))
print(shot_info)
# Calculate the d_hypotenuse
d_hypotenuse = math.sqrt(x_release**2 + y_release**2)
d_hypotenuse = (d_hypotenuse/12)/3.2808
print(f'The hypotenuse is: {d_hypotenuse}')
# Calculating ltb and htb
jump_height = 0.1524 # roughly 6 inches
# Convert Height to Height in m
total_height = (total_height / 12) / 3.2808
shoulder_height = (21/25) * total_height
print(f'Shoulder height: {shoulder_height}')
htb = 3.048 - (shoulder_height + jump_height + d_hypotenuse*math.sin(math.radians(shooting_angle)) +
ball_radius*math.sin(math.radians(shooting_angle)))
ltb = shot_distance - (d_hypotenuse*math.cos(math.radians(shooting_angle)) +
ball_radius*math.cos(math.radians(shooting_angle)))
print(f"The length to basket is l: {ltb} and the height to basket is h: {htb}")
gravity = 9.81
holder0 = math.tan(math.radians(shooting_angle)) - htb/ltb
holder1 = ((math.cos(math.radians(shooting_angle)))**2)*holder0
ball_velocity = math.sqrt((gravity*ltb)/(2*holder1))
print('\nThe ball velocity is: {a:2.2f} m/s'.format(a=ball_velocity))
# //Fingertip Components
# Acceleration
fingertip_acc_hor = ball_radius*(backspin_hz**2)*math.cos(math.radians(shooting_angle))
fingertip_acc_ver = ball_radius*(backspin_hz**2)
fingertip_acc = math.sqrt((fingertip_acc_hor**2) + (fingertip_acc_ver**2))
print('The x-direction fingertip acceleration is {a:2.2f} m/s^2\nThe y-direction fingertip acceleration is'
' {b:2.2f} m/s^2\nThe overall fingertip acceleration is {c:2.2f} m/s^2.\n'.format(a=fingertip_acc_hor,
b=fingertip_acc_ver,
c=fingertip_acc))
# Velocity
fingertip_vel_hor = ball_velocity*math.cos(math.radians(shooting_angle)) + \
ball_radius*backspin_hz*math.sin(math.radians(shooting_angle))
fingertip_vel_ver = ball_velocity*math.sin(math.radians(shooting_angle)) - \
ball_radius*math.cos(math.radians(shooting_angle))
fingertip_vel = math.sqrt((fingertip_vel_hor**2) + (fingertip_vel_ver**2))
angle = math.degrees(math.atan(fingertip_vel_ver/fingertip_vel_hor))
print('\nThe x-direction fingertip velocity is {a:2.2f} m/s\nThe y-direction fingertip velocity is '
'{b:2.2f} m/s\nThe overall fingertip velocity is {c:2.2f} m/s.\n'.format(a=fingertip_vel_hor, b=fingertip_vel_ver,
c=fingertip_vel)) |
fe64dbd52fc3579b8cf7bfbc00cb0a410cf666ae | kengru/pcrash-course | /chapter_002/exercises/personal_message.py | 113 | 3.96875 | 4 | # Exercise 2-3. Printing a hello with a custom name.
name = 'Carlos'
print('Hello, ' + name + '. How are you?')
|
3b95c14f03bd60820a47e579706aa5da9b7cea61 | ErosMLima/last-classes-js-py-node-php | /exercicios-aula-8-module.py | 1,157 | 4.03125 | 4 | exercicios-aula-8-module.py
import math
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
print('A raiz de {} é iqual a {}'.format(num, raiz))
output
C:\Users\Deltah\PycharmProjects\pythonteste.py\venv\Scripts\python.exe C:/Users/Deltah/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/exercicios-aula-8-math-module.py
Digite um número: 81
A raiz de 81 é iqual a 9.0
Process finished with exit code 0
from math import sqrt,floor
num = int(input('Digite um número: '))
raiz = sqrt(num)
print('A raiz de {} é iqu'
// outuput
C:\Users\Deltah\PycharmProjects\pythonteste.py\venv\Scripts\python.exe C:/Users/Deltah/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/exercicios-aula-8-math-module.py
Digite um número: 29
A raiz de 29 é iqual a 5
Process finished with exit code 0
import random
num = random.randint(0, 100)
print(num)
num1 = random.randint(101, 999)
print(num1)
// outuput
C:\Users\Deltah\PycharmProjects\pythonteste.py\venv\Scripts\python.exe C:/Users/Deltah/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_1.py
95
247
Process finished with exit code 0 |
791d73d1c35b80fe60f667f90535636f2c4e2746 | MMR1998-DEV/python-excersise-workbook | /76.py | 126 | 3.921875 | 4 | #print today's date
from datetime import datetime
today = datetime.now()
print(today.strftime("Today is %A, %B %d, %Y")) |
b69c7ea76844c8500252bb9fcdaf8bb6450f5b31 | PaulVirally/Abstract-Genetic-Algorithm | /GA/Selection.py | 609 | 4.03125 | 4 | import random
def roulette_wheel(population, k):
"""Performs roulette wheel selection.
The chosen individual is chosen with a probability proportional to its fitness. The higher the fitness, the greater chance the chromosome has at being chosen.
Arguments:
population {[Chromosome]} -- The population to choose from.
k {int} -- The number of Chromosomes to choose.
Returns:
[Chromosome] -- A list of Chromosomes that were chosen.
"""
fitnesses = [chromo.fitness for chromo in population]
return random.choices(population, weights=fitnesses, k=k) |
049a5fa27ef0d6b0f4b780a8442c4a7f10f64838 | huzbasicamila/graph-theory-with-python | /part_04/solutions.py | 3,124 | 4.3125 | 4 | from graph import Graph, degrees, out_degrees
# Solution for calculating the total degrees in a directed graph
def total_degrees(graph):
"""
Return a dictionary of total degrees for each node in a
directed graph.
"""
if not graph.is_directed:
raise ValueError("Cannot call total_degrees() on an undirected graph")
# The total degree of a node is the same as the total number of
# edges connected to that node. So you can get the total degree
# by calling `degrees()` on an undirected graph with the same
# nodes and edges as `graph`.
undirected_graph = Graph(graph.nodes, graph.edges, is_directed=False)
return degrees(undirected_graph)
# Solution #1 for calculating the in degrees of a directed graph
# This solution uses the `total_degrees()` function degined above.
# Although it works, it is not ideal because it calls both
# `total_degrees()` and `out_degrees()`, both of which end up calling
# `_degrees()`. In other words, it builds the adjacency list twice.
def in_degrees1(graph):
"""
Return a dictionary of in degrees for each node in a
directed graph
"""
# Since total degree = in degree + out degree, you can calculate
# the in degrees by subtracting the out degrees from the total
# degrees for each node
graph_total_degrees = total_degrees(graph)
graph_out_degrees = out_degrees(graph)
return {
node: graph_total_degrees[node] - graph_out_degrees[node]
for node in graph.nodes
}
# Solution #2 for calculating the in degrees of a directed graph
def in_degrees2(graph):
"""
Return a dictionary of in degrees for each node in a
directed graph
"""
# If you reverse the edges of a directed graph then out neighbors
# in the reversed graph are in neighbors in the original graph.
reversed_edges = [(node2, node1) for node1, node2 in graph.edges]
reversed_graph = Graph(graph.nodes, reversed_edges, is_directed=True)
return out_degrees(reversed_graph)
# ~~~~~~~~~~~~~~~~~ BONUS ~~~~~~~~~~~~~~~~~
def min_degree(graph):
"""Return the minimum degree of an undirected graph."""
return min(degrees(graph).values())
def max_degree(graph):
"""Return the maximum degree of an undirected graph."""
return max(degrees(graph).values())
def min_in_degree(graph):
"""Return the minimum in degree of a directed graph."""
return min(in_degrees2(graph).values())
def max_in_degree(graph):
"""Return the maximum in degree of a directed graph."""
return max(in_degrees2(graph).values())
def min_out_degree(graph):
"""Return the minimum out degree of a directed graph."""
return min(out_degrees(graph).values())
def max_out_degree(graph):
"""Return the maximum out degree of a directed graph."""
return max(out_degrees(graph).values())
def min_total_degree(graph):
"""Return the minimum total degree of a directed graph."""
return min(total_degrees(graph).values())
def max_total_degree(graph):
"""Return the maximum total degree of a directed graph."""
return max(total_degrees(graph).values())
|
ed8a3f1169482b8b245dd8e58253cf47436ebd58 | Vutov/SideProjects | /Coursera/Python3/Code/class_book.py | 1,936 | 4.03125 | 4 | class Book:
''' Information about a book'''
def __init__(self, title, authors, publisher, isnb, price):
''' (book, str, list of str, str, str, int) -> NoneType
Create a new book entitled title, writen by the people in authors,
published by publisher, with ISBN isbn and costing price in dollars.
>>> python_book = Book( \
'Practical Programming', \
['Campbell', 'Gries', 'Montojo'], \
'Pragmatic Bookshelf', \
'978-1-93778-545-1', \
25.0)
>>> python_book.title
'Practical Programming'
>>> python_book.authors
['Campbell', 'Gries', 'Montojo']
>>> python_book.publisher
'Pragmatic Bookshelf'
>>> python_book.ISBN
'978-1-93778-545-1'
>>> python_book.price
25.0
'''
self.title = title
self.authors = authors[:]
self.publisher = publisher
self.ISBN = isnb
self.price = price
def __str__(self):
''' (Book) -> str
Return a human readable string representation of this book
'''
return """Title: {0}\nAuthors: {1}\nPublisher: {2}\nISBN: {3}\nPrice: ${4}""".format(
self.title, ', '.join(self.authors), self.publisher, self.ISBN, self.price)
def __eq__(self, other):
''' (Book, Book) -> bool
Return True iff this book and the other hava the same ISBN
'''
return self.ISBN == other.ISBN
def num_authors(self):
''' (Book) -> int
Return the number of authors of this book
>>> python_book = Book( \
'Practical Programming', \
['Campbell', 'Gries', 'Montojo'], \
'Pragmatic Bookshelf', \
'978-1-93778-545-1', \
25.0)
>>> python_book.num_authors()
3
'''
return len(self.authors)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
521733f8bfb6ea70a2584b8c1a1a68d0052ec456 | lpfan0307/leetcode | /top_interview_questions/surrounded_regions.py | 943 | 3.640625 | 4 | class Solution:
# @param board, a 9x9 2D array
# Capture all regions by modifying the input board in-place.
# Do not return any value.
def solve(self, board):
def fill(x, y):
if x<0 or x>m-1 or y<0 or y>n-1 or board[x][y] != 'O': return
queue.append((x,y))
board[x][y]='D'
def bfs(x, y):
if board[x][y]=='O':queue.append((x,y)); fill(x,y)
while queue:
curr=queue.pop(0); i=curr[0]; j=curr[1]
fill(i+1,j);fill(i-1,j);fill(i,j+1);fill(i,j-1)
if len(board)==0: return
m=len(board); n=len(board[0]); queue=[]
for i in range(n):
bfs(0,i); bfs(m-1,i)
for j in range(1, m-1):
bfs(j,0); bfs(j,n-1)
for i in range(m):
for j in range(n):
if board[i][j] == 'D': board[i][j] = 'O'
elif board[i][j] == 'O': board[i][j] = 'X' |
342ef3232d8e962e1562c3081e5ba94388755dd0 | alexandervin/Python | /tuple.py | 97 | 3.65625 | 4 | t1 = tuple('Это кортеж')
print(t1[::-1])
x = 1
y = 2
print(x, y)
x, y = y, x
print(x,y) |
749e556ea110b707bce98ca91f4dc14117ffd373 | Sisyphus235/tech_lab | /algorithm/sort/shell_sort.py | 1,021 | 4.34375 | 4 | # -*- coding: utf8 -*-
"""
advanced insertion sort
apply to small scale
best scenario: O(n)
worst scenario: < O(n^2), approach to O(nlogn)
"""
import time
import random
def shell_sort(array: list):
# group gap
gap = len(array) // 2
# loop until gap equals to 1, all array will be sorted
while gap > 0:
# sort all groups in one loop, increase 1 each time, perhaps operating insertion sort to different groups
for i in range(gap, len(array)):
j = i
# operating insertion sort based on groups
while j > 0 and array[j] < array[j - gap]:
array[j], array[j - gap] = array[j - gap], array[j]
j -= gap
gap //= 2
def test_shell_sort():
array = [random.randint(0, 100) for _ in range(100)]
print(f'before: {array}')
before = time.time()
shell_sort(array)
after = time.time()
print(f'after: {array}')
print(f'time cost: {after - before}')
if __name__ == '__main__':
test_shell_sort()
|
1e1012c8089031805ae8ed05c2d924813adf9649 | ImSo3K/numerical-analysis-SCE | /FinalProject/Q17_B.py | 2,866 | 4.25 | 4 | from math import exp
import numpy as np
def simpsons_one_third(f, a, b, N) -> float:
"""Calculates and prints the process of Simpson's one-third method for calculating an integral.
Args:
f (function): the function that is going to be integraled.
a (int): lower boundry of the integral.
b (int): upper boundry of the integral.
N (int): number of subintervals of [a,b].
Raises:
ValueError: incase a non-even N was given.
Returns:
float: approximation of the integral of f(x).
"""
if N % 2 == 1:
raise ValueError('N must be an even integer.')
integral = f(a)
deltaX = (b - a) / N
print(f'deltaX={deltaX}')
print(f'h/3 * ({integral})', end='')
multiplier = 2
for i in range(1, N-1):
fxi = multiplier*f(a+i*deltaX)
print(f' + {multiplier}*f({a+i*deltaX:.5f}) ', end='')
integral += fxi
multiplier = 4 if multiplier == 2 else 2
print(f'+ {f(b):.5f})')
return (deltaX/3)*(integral + f(b))
def romberg(f, a, b, p) -> nd.array:
"""Calculates and prints the process of Romberg's method for calculating an integral.
Args:
f (function): the function that is going to be integraled.
a (int): lower boundry of the integral.
b (int): upper boundry of the integral.
p (int): number of rows in the Romberg table.
Returns:
ndarray: 'L' shape table of approximation.
"""
def trapezcomp(f, a, b, N) -> float:
"""composite trapezoidal function integration.
Args:
f (function): the function that is going to be integraled.
a (int): lower boundry of the integral.
b (int): upper boundry of the integral.
N (int): number of panels in range [a,b].
Returns:
float: approximation of the integral of f(x).
"""
# Initialization
deltaX = (b - a) / N
x = a
# Composite rule
In = f(a)
for k in range(1, N):
x = x + deltaX
In += 2*f(x)
return (In + f(b))*deltaX*0.5
approx_table = np.zeros((p, p))
for k in range(0, p):
# Composite trapezoidal rule for 2^k panels
approx_table[k, 0] = trapezcomp(f, a, b, 2**k)
# Romberg recursive formula
for j in range(0, k):
approx_table[k, j+1] = (4**(j+1) * approx_table[k, j] - approx_table[k-1, j]) / (4**(j+1) - 1)
print(approx_table[k, 0:k+1]) # display intermediate results
return approx_table
def func(x): return x**2*exp(-x**2-5*x-3)*(3*x-1)
if __name__ == '__main__':
print(f'Simpsons Solution: {simpsons_one_third(func, 0.5, 1, 20)}')
print()
p_rows = 2
final_I = romberg(func, 0.5, 1, p_rows)
solution = final_I[p_rows-1, p_rows-1]
print(f'Romberg Solution: {solution}')
|
3d12bd814f439cea61b2a5d088df46b7956dbe13 | Thomas-Neill/CardRoguelike | /arrow.py | 922 | 3.921875 | 4 | import pygame
class Arrow:
def __init__(self,start):
self.start = start
def set_destination(self,what):
self.destination = what
def draw(self,surface):
#Draw a circle trail: Maybe animate???
delta = self.destination - self.start
distance = delta.magnitude()
if distance == 0:
return
offset = (pygame.time.get_ticks()//15) % 10
step = delta / distance * 10
stepper = self.start
for i in range(int(distance//10)):
pygame.draw.circle(surface,(255,255,255),stepper.toInt() + (step*offset/10).toInt(),3)
stepper += step
#Now draw a little triangle for the head of the arrow
pygame.draw.polygon(surface,(255,255,255), [
self.destination,
self.destination - step + step.perpendicular(),
self.destination - step - step.perpendicular()])
|
59df32eadb83aea6bd565139d1c7f5fca3dd2e1d | mng990/AI-Programing-HW | /HW07_201724461/TSP.py | 3,129 | 3.8125 | 4 | import random
import math
NumEval = 0 # Total number of evaluations
def createProblem():
## Read in a TSP (# of cities, locatioins) from a file.
## Then, create a problem instance and return it.
fileName = input("Enter the file name of a TSP: ")
infile = open(fileName, 'r')
# First line is number of cities
numCities = int(infile.readline())
locations = []
line = infile.readline() # The rest of the lines are locations
while line != '':
locations.append(eval(line)) # Make a tuple and append
line = infile.readline()
infile.close()
table = calcDistanceTable(numCities, locations)
return numCities, locations, table
def calcDistanceTable(numCities, locations): ###
start = list(range(numCities))
assignment = start[:]
table = []
for sp in start:
row = []
for ap in assignment:
dis = 0
for dim in range(2):
dis += (locations[sp][dim] - locations[ap][dim])**2
row.append(math.sqrt(dis))
table.append(row)
return table # A symmetric matrix of pairwise distances
def randomInit(p): # Return a random initial tour
n = p[0]
init = list(range(n))
random.shuffle(init)
return init
def evaluate(current, p): ###
## Calculate the tour cost of 'current'
## 'p' is a Problem instance
## 'current' is a list of city ids
global NumEval
NumEval += 1
cost = 0
for index in range(len(current)):
if index == (len(current)-1):
break
cost += p[2][current[index]][current[index+1]]
return cost
def randomInit(p): # Return a random initial tour
n = p[0]
init = list(range(n))
random.shuffle(init)
return init
def evaluate(current, p): ###
## Calculate the tour cost of 'current'
## 'p' is a Problem instance
## 'current' is a list of city ids
global NumEval
NumEval += 1
cost = 0
for index in range(len(current)):
if index == (len(current)-1):
break
cost += p[2][current[index]][current[index+1]]
return cost
def inversion(current, i, j): # Perform inversion
curCopy = current[:]
while i < j:
curCopy[i], curCopy[j] = curCopy[j], curCopy[i]
i += 1
j -= 1
return curCopy
def describeProblem(p):
print()
n = p[0]
print("Number of cities:", n)
print("City locations:")
locations = p[1]
for i in range(n):
print("{0:>12}".format(str(locations[i])), end = '')
if i % 5 == 4:
print()
def displaySetting(algorithm):
print()
print("Search algorithm: {} Hill Climbing".format(algorithm))
def displayResult(solution, minimum):
print()
print("Best order of visits:")
tenPerRow(solution) # Print 10 cities per row
print("Minimum tour cost: {0:,}".format(round(minimum)))
print()
print("Total number of evaluations: {0:,}".format(NumEval))
def tenPerRow(solution):
for i in range(len(solution)):
print("{0:>5}".format(solution[i]), end='')
if i % 10 == 9:
print() |
399bbccc6024b34429fe6bd601ccff58d2615e3a | vj-reddy/PythonBatch1 | /Aug20/inheritancedemo/vehicles/car.py | 555 | 3.828125 | 4 | from vehicles import vehicle
class Car(vehicle.Vehicle,):
"""
This class represents a car
"""
def __init__(self, name):
super().__init__(name)
def start(self):
print("Car started")
def stop(self):
print("Car Stopped")
class HatchBack(Car):
def __init__(self, name):
super().__init__(name)
def start(self):
print("This is hatch back")
super().start()
pass
class SUV(Car):
def __init__(self, name):
super(SUV, self).__init__(name)
pass
|
be5632bc7dfac82949bc6876a1d1d836afe3c485 | Languomao/PythonProject | /python_learn_01/demo_01.py | 475 | 3.8125 | 4 | from random import randint
print("开始游戏,你只有三次机会。。。")
i = 0
num = randint(1, 10)
while i < 3:
input_num = input("随机输入一个数字:")
guess = int(input_num)
if guess == num:
print("恭喜你猜对了!")
break
else:
if guess > num:
print("大了。。。")
i += 1
if guess < num:
print("小了。。。")
i += 1
print("不玩了。。。")
|
1251adf5ecc7b7b1d17576a6e7e27bf6db112789 | liuya2360/H2-Computing | /Python/Worksheets/Worksheet4/4.py | 583 | 3.5 | 4 | fileHandle = open("WORDS.TXT")
data = fileHandle.read().split("\n")
cnt_row = 0
word = ""
number = None
max_word = []
max_number = -1
#print(data)
for row in data:
#print(row)
if cnt_row % 2 == 0:
try:
word = str(row.strip())
#print(word)
cnt_row += 1
except:
continue
else:
try:
number = int(row.strip())
#print(number)
cnt_row += 1
if number > max_number:
max_number = number
max_word = []
max_word.append(word)
elif number == max_number:
max_word.append(word)
except:
continue
for each_word in max_word:
print(each_word) |
f8dbebdbfac641282e9ef15b6d279cb6caf0c5f0 | HongyuS/Vegetable-Market | /CSC1001/Assignment_2/q1.py | 650 | 4.09375 | 4 | def sqrt(n): # function to calculate square root
lastGuess = 1
while True:
nextGuess = (lastGuess + (n/lastGuess)) / 2
if nextGuess - lastGuess <= 0.0001\
and lastGuess - nextGuess <= 0.0001:
return nextGuess
else:
lastGuess = nextGuess
while True: # an example of using the function
try:
n = float(input('Enter a positive number >'))
except:
print('Invalid input.\nPlease try again!')
else:
if n > 0:
break
else:
print('Please input a positive number.')
print('The square root of', n, 'is:', sqrt(n))
|
b0973d71f99956d851aa857744db6cde71febe59 | YJuwailes/Power | /Turbojet_Engine/ALTITUDE22.py | 5,166 | 3.59375 | 4 | from tkinter import *
import TurboJet
import math
#Setting up the window
root = Tk()
root.title('Jet Engine Claculator')
root.resizable(width=False, height=False)
#Setting up the checkbox
var1 = IntVar()
diameterCheckBox = Checkbutton(root, text='Diameter', variable=var1).grid(row=0, column=4)
#Positioning the cells
thrust_str = StringVar()
power_str = StringVar()
eff_str = StringVar()
thrust_str.set('Thrust =')
power_str.set('Propulsion power =')
eff_str.set('Propulsive efficiency =')
label_1 = Label(root, text="Velocity of the Plane: ")
label_2 = Label(root, text="Mass flowrate/Diameter: ")
label_5 = Label(root, text="Pressure ratio of the compressor: ")
label_6 = Label(root, text="Isentropic efficiency of the compressor: ")
label_7 = Label(root, text="Isentropic efficiency of the turbine: ")
label_8 = Label(root, text="Temperature of the turbine Inlet: ")
label_9 = Label(root, text='Altitude: ')
label_10 = Label(root, textvariable=thrust_str, fg='red')
label_11 = Label(root, textvariable=power_str, fg='blue')
label_12 = Label(root, textvariable=eff_str, fg='black')
entry_1 = Entry(root)
entry_2 = Entry(root)
entry_5 = Entry(root)
entry_6 = Entry(root)
entry_7 = Entry(root)
entry_8 = Entry(root)
entry_9 = Entry(root)
label_1.grid(row=0, sticky=W)
entry_1.grid(row=0, column=1)
label_2.grid(row=0, column=2, sticky=W)
entry_2.grid(row=0, column=3)
label_5.grid(row=1, sticky=W)
entry_5.grid(row=1, column=1)
label_6.grid(row=1, column=2, sticky=W)
entry_6.grid(row=1, column=3)
label_7.grid(row=2, sticky=W)
entry_7.grid(row=2, column=1)
label_8.grid(row=2, column=2, sticky=W)
entry_8.grid(row=2, column=3)
label_9.grid(row=3, sticky=W)
entry_9.grid(row=3, column=1)
label_10.grid(row=5, sticky=W)
label_11.grid(row=6, sticky=W)
label_12.grid(row=7, sticky=W)
def turboCalculate():
tj = TurboJet.TurboJet()
#Taking the inputs and assigning them to variables
tj.plane_velocity = float(entry_1.get())
tj.rp = float(entry_5.get())
tj.comp_eff = float(entry_6.get()) / 100
tj.tur_eff = float(entry_7.get()) / 100
tj.t_turbine = float(entry_8.get())
tj.altitude = float(entry_9.get())
#An array of different heights with densities, pressure and temperature
altitude_2 = [
[0, 1.225, 101.3, 288.15],
[250, 1.19587, 98.357, 286.525],
[500, 1.16727, 95.460, 284.900],
[750, 1.13920, 92.633, 283.275],
[1000, 1.11164, 89.874, 281.65],
[1250, 1.08460, 87.182, 280.02],
[1500, 1.05807, 84.556, 278.40],
[1750, 1.03202, 81.994, 276.77],
[2000, 1.00649, 79.495, 275.15],
[2250, 0.981435, 77.058, 273.525],
[2500, 0.956859, 74.682, 271.900],
[2750, 0.932757, 72.366, 270.275],
[3000, 0.909122, 70.108, 268.65],
[3250, 0.885948, 67.908, 267.025],
[3500, 0.863229, 65.764, 265.400],
[3750, 0.840958, 63.675, 263.775],
[4000, 0.819129, 61.6402, 262.15],
[4250, 0.797737, 59.658, 260.525],
[4500, 0.776775, 57.728, 258.900],
[4750, 0.756236, 55.849, 257.275],
[5000, 0.736116, 54.0199, 255.65],
[5250, 0.716408, 52.239, 254.025],
[5500, 0.697106, 50.506, 252.400],
[5750, 0.678204, 48.821, 250.775],
[6000, 0.659697, 47.181, 249.15],
[6250, 0.641579, 45.586, 247.525],
[6500, 0.623844, 44.034, 245.900],
[6750, 0.606487, 42.526, 244.275],
[7000, 0.589501, 41.060, 242.65],
[7250, 0.572882, 39.635, 241.025],
[7500, 0.556624, 38.251, 239.400],
[7750, 0.540721, 36.906, 237.775],
[8000, 0.525168, 35.5998, 236.15],
[8250, 0.509959, 34.331, 234.525],
[8500, 0.495090, 33.099, 232.90],
[8750, 0.480555, 31.903, 231.27],
[9000, 0.466348, 30.742, 229.65],
[9250, 0.452465, 29.616, 226.40],
[9500, 0.438901, 28.523, 226.40],
[9750, 0.425649, 27.463, 224.77],
[10000, 0.412707, 26.436, 223.15]
]
for x in altitude_2:
for y in x:
if y == tj.altitude:
tj.density = x[1]
tj.pressure = x[2]
tj.temperature = x[3]
# Diameter or Mass flowrate
if var1.get() == 1:
tj.jet_diameter = float(entry_2.get())
tj.m_flowrate = 0
else:
tj.m_flowrate = float(entry_2.get())
tj.jet_diameter = 0
# mass flowrate calculation:
if tj.jet_diameter == 0:
mass_flowrate = tj.m_flowrate
else:
mass_flowrate = (0.25 * math.pi * tj.plane_velocity * tj.density * tj.jet_diameter ** 2)
x = mass_flowrate - math.floor(mass_flowrate)
if x > 0.5:
mass_flowrate = math.ceil(mass_flowrate)
else:
mass_flowrate = math.floor(mass_flowrate)
tj.mass_flowrate = mass_flowrate
res = tj.calculate()
#Showing the results on the active window
thrust_str.set('Thurst = ' + str(res[0]) + ' kN')
power_str.set('Propulsive power = ' + str(res[1]) + ' kW')
eff_str.set('Propulsive efficiency = ' + str(res[2]) + ' %')
button1 = Button(root, text='Calculate', fg='black', command=turboCalculate)
button1.grid(row=3, column=2)
root.mainloop()
|
b42a25e587ae57e02d106ad23940ffa2bdb129ec | larsthorup/python-sandbox | /make_positive.py | 137 | 3.765625 | 4 | def make_positive(a):
for i in range(len(a)):
if a[i] < 0:
a[i] = -a[i]
return a
print(make_positive( [-3, 1, -2, 5, -3])) |
c2806ce31496a1338878d841c8ce9b67d08e60d8 | wingerlang/Eulerproject | /Python/Euler30.py | 659 | 3.984375 | 4 | """
Digit fifth powers
Problem 30
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 44^ + 7^4 + 4^4
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
def makeList(n):
return sum([int(i)**5 for i in list(str(n)) ])
def theLoop(stop = 10):
total = 0
for i in range(2,stop+1):
if i == makeList(i):
total += i
return total
print(theLoop(354294)) |
a0a6df1cd48f556d8e4ee12a58f4cadbeb34e881 | wahahab/mit-6.0001 | /ps1/ps1.py | 582 | 4.15625 | 4 | # -*- coding: utf-8 -*-
import math
from util import number_of_month
if __name__ == '__main__':
month_passed = 0
current_savings = 0
portion_down_payment = .25
r = .04
annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(input('Enter the percent of your salary to save, as a decimal: '))
total_cost = float(input('Enter the cost of your dream home: '))
print 'Number of months:', int(number_of_month(portion_down_payment,
total_cost, current_savings, annual_salary, portion_saved, r))
|
acae1a2e918d8dacc69b5041e255509d6c6a292d | Mohi294/classesAndInheritanceB | /classesAndInstances.py | 1,109 | 3.921875 | 4 | class bodyParts:
def __init__(self):
self.hand = "hand"
self.foot = "foot"
def display(self):
print( self.hand )
class creatures:
def _init_(self, name):
self.bP = self.bodyPart()
self.name = name
class bodyPart(bodyParts):
def __init__(self):
super().__init__()
def display(self):
print("bitch")
super().display()
x = creatures().bodyPart().display()
# y = x.bodyPart()
x
# class A:
# def __init__(self):
# self.db = self.Inner()
# def display(self):
# print('In Parent Class')
# # this is inner class
# class Inner:
# def display1(self):
# print('Inner Of Parent Class')
# class B(A):
# def __init__(self):
# print('In Child Class')
# super().__init__()
# class Inner(A.Inner):
# def display2(self):
# print('Inner Of Child Class')
# # creating child class object
# p = B()
# p.display()
# # create inner class object
# x = p.db
# x.display1()
# x.display2()
|
705607b47655f2429bc82f91063a6c31c72383ed | yash94749/myrepos | /traverse_string.py | 169 | 4.09375 | 4 | str=input("please enter string. ")
def traverse_string(str):
x = len(str)
for i in range(x):
print(str[x-1-i])
return ''
print(traverse_string(str))
|
e71326924c91ca0329a3b4f4a2b280b11730fe80 | Elkleaf/Python-Chess-Game | /chessBoard.py | 1,067 | 3.90625 | 4 | # The chess board is an 8x8 grid
# We'll number the vertical rows
# and alphabetize the horizontal
# Some of the following code was inspired by http://norvig.com/sudoku.html
# Notation in chess is column then row
# Sample Output:
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
#__|__|__|__|__|__|__|__
import gamePiece as gP
class ChessBoard:
"""docstring for chessBoard"""
def __init__(self):
super(ChessBoard, self).__init__()
self.rows = '12345678'
self.cols = 'ABCDEFGH'
self.squares = [col+row for col in self.cols for row in self.rows]
def printBoard(self, wPlayer, bPlayer):
units = [['__' for row in self.rows] for col in self.cols]
for unit in wPlayer:
units[unit.row-1][unit.col-1] = unit.tag
for unit in bPlayer:
units[unit.row-1][unit.col-1] = unit.tag
for r in range(0,8):
print('|'.join(str(item) for item in units[r]))
print('')
# Just testing here
# l = chessBoard()
# l.printBoard()
|
1c8a68fd19d8f3a0469686665b0654843bd72aed | PacktPublishing/Hands-On-Artificial-Intelligence-for-Search | /Chapter01/Do it yourself Code/RecursiveDFS.py | 1,405 | 3.59375 | 4 | '''
@author: Devangini Patel
'''
from State import State
from Node import Node
class RecursiveDFS():
"""
This performs DFS search
"""
def __init__(self):
self.found = False
def search(self):
"""
This method performs the search
"""
#get the initial state
initialState = State()
#create root node
rootNode = Node(initialState)
#perform search from root node
self.DFS(rootNode)
rootNode.printTree()
def DFS(self, node):
"""
This creates the search tree
"""
if not self.found:
print "-- proc --", node.state.path
#check if we have reached goal state
if node.state.checkGoalState():
print "reached goal state"
self.found = True
else:
#find the successor states from current state
childStates = node.state.successorFunction()
#add these states as children nodes of current node
for childState in childStates:
childNode = Node(State(childState))
node.addChild(childNode)
self.DFS(childNode)
dfs = RecursiveDFS()
dfs.search() |
c2af09a3372d309a5c0e2a0349ea2a9ea3d1acba | L200184092/Praktikum-AlgoStruk | /Praktikum 8/5.py | 957 | 3.78125 | 4 | class PriorityQueue(object):
def __init__(self):
self.qlist = []
def isEmpty(self):
return len(self) == 0
def __len__(self):
return len(self.qlist)
def enqueue(self, data, priority):
entry = PriorityQEntry(data, priority)
self.qlist.append(entry)
def dequeue(self):
assert not self.isEmpty(), "Antrian sedang kosong"
max = 0
for i in range(len(self.qlist)):
if self.qlist[i].priority < self.qlist[max].priority:
max = i
hasil = self.qlist[max]
del self.qlist[max]
print(hasil.item)
class PriorityQEntry(object):
def __init__(self, data, priority):
self.item = data
self.priority = priority
S = PriorityQueue()
S.enqueue("Jeruk", 4)
S.enqueue("Tomat", 2)
S.enqueue("Mangga", 0)
S.enqueue("Duku", 5)
S.enqueue("Pepaya", 2)
S.dequeue()
S.dequeue()
S.dequeue()
|
45108af83fbb13a64009dd988f878bbd60386c0c | welmervdwel/03-how-many-times-did-you-spin | /spin.py | 807 | 4.0625 | 4 | spins = input("How many times did you spin? (Enter a negative number for counter-clockwise spins) ")
#TODO - Edit the degrees calculation here!
degrees = (float(spins) * 360) % 360 # see WB notes below
print("You are facing", degrees, "degrees relative to north")
# when I input 0.25, I should get "90.0 degrees relative to north". WB: 90 / 360 = 0.25, which leaves a remainder of .25 of 360 = 90
# when I input 1, I should get "0.0 degrees relative to north" (back where I started). WB: 360 / 360 = 1, which leaves 0 remainder.
# when I input -2, I should get "0.0 degrees relative to north" (again, back where I started). WB: -720 / 360 = -2, which leaves 0 remainder.
# when I input 1.5, I should get "180.0 degrees relative to north". WB: 540 / 360 = 1.5, which leaves a remainder of 0.5 of 360 = 180
|
b60eb75845cf423d1474b8bf1c19c3fd953767df | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/260/51370/submittedfiles/testes.py | 189 | 3.5 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
#!/usr/bin/python
n=int(input("n"))
a=n
z=n
c=0
s=0
cont=0
while n>0:
resto=n%10
s=s+resto*2**(cont)
n=n//10
cont=cont+1
print(s) |
95874924ec9c5032a0121373b67dc13b77b73291 | pizisuan/Learn-Python | /Python简明教程/expression.py | 114 | 3.703125 | 4 | length = 5
breath = 2
area = length * breath
print('Area is', area)
print('Perimeter is', 2 * (length + breath))
|
ab5931c88b089116d4887caf487017965d2de3f5 | romulorm/cev-python | /ex.101.funcoesParaVotacaor.py | 1,040 | 4.125 | 4 | '''Exercício Python 101: Crie um programa que tenha uma função chamada voto() que vai receber como parâmetro o ano de
nascimento de uma pessoa, retornando um valor literal indicando se uma pessoa tem voto NEGADO, OPCIONAL e OBRIGATÓRIO
nas eleições.'''
def verificaEleitor(nasc):
from datetime import datetime
anoatual = datetime.now().year
idade = anoatual - nasc
if idade < 16:
return f'Com {idade} anos: \33[31mNÃO VOTA\33[m'
elif 18 <= idade <= 64:
return f'Com {idade} anos o voto é \33[32mOBRIGATÓRIO\33[m'
else:
return f'Com {idade} anos o voto é \33[33mOPCIONAL\33[m'
# PROGRAMA PRINCIAL
while True:
anonasc = int(input('Informe o seu ano de nascimento: '))
print(verificaEleitor(anonasc))
opcao = str(input('Deseja continuar? (S/N): ').strip().upper()[0])
while opcao not in 'SN':
print('\33[31mInforme uma opção válida!\33[m')
opcao = str(input('Deseja continuar? (S/N): ').strip().upper()[0])
if opcao == 'N':
break
|
8eef4983c1df9b475dc4852d371f71162e73c050 | pauleclifton/GP_Python210B_Winter_2019 | /students/jesse_miller/session02/print_grid2.py | 1,698 | 4.21875 | 4 | #!/usr/local/bin/python3
import sys
"""Above I'm importing sys for arguments"""
#from argparse import ArgumentParser
#parser = ArgumentParser(description='print_grid3.py X')
#parser.add_argument(' ', choices=['x'], default='h',
# help="X is size of square.")
#parser.parse_args()
"""This is a bit disappointing. I wanted to add a help argument for clarity, but I wasn't able to get it to work"""
n = int(sys.argv[1])
"""This is the input variable. This number determines the length and width of each square in the grid"""
def do_one(f):
f()
"""This is me not being sure how to just pull a function once in a function"""
def do_two(f):
f()
f()
"""This runs the given function twice"""
def do_row(f):
for _ in range(n):
do_one(f)
"""This function is to print a row for every iteration of variable 'n'"""
minus = (' -' * n)
plus = '+'
"""Here, I'm defining the variables for printing. Made the math easier this way"""
def print_line():
print(plus + minus + plus + minus + plus)
"""This defines the tops and bottoms of the squares"""
def print_post():
print('|' + (' ' * (2*n) ) + '|' + (' ' * (2*n) ) + '|'),
"""This defines the column markers. The 2*n is to coensate for the length of the column being double the length of a row in print"""
def print_row():
print_line()
do_row(print_post)
"""And here's the magic. In this function I'm calling on print_line as well as parsing print_post through do_row"""
def print_grid():
do_two(print_row)
print_line()
"""This defines the grid function. It executes print_row twice through do_two, and the print_line to close the square."""
print_grid()
"""Here we execute the whole mess above"""
|
97143a26d0fd23d8a88c9ca2041cd08b9177165b | bishnoimukesh/ML | /python/gui.py | 610 | 3.640625 | 4 | from Tkinter import *
root= Tk()
root.title('deep.tech')
root.configure(background='black')
root.geometry('360x480')
name = Label(root, text='entervalue:', width=20, bg = "green")
name.grid(row=0,column=0)
num1=Entry(root, width=20, bg='pink')
num1.grid(row=1,column=0)
num2=Entry(root, width=20, bg='pink')
num2.grid(row=2,column=0)
def changename():
value_a=num1.get()
value_b=num2.get()
sum=int(value_a)+int(value_b)
name.configure(text='your sum is:' + str(sum) )
btn=Button(root, width=10,bg='red', fg='red', command=changename)
btn.grid(row=2,column=1)
root.mainloop()
|
08164dcd2ad2d04451ffd9a8d87d40b60a373fdf | gervanna/100daysofcode | /Days/Day2_Tip_Calculator.py | 697 | 4.1875 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: You might need to do some research in Google to figure out how to do this.
print("Welcome to the Tip Calculator.")
total_bill = float(input("What was the total of the bill? $"))
tip_options = int(input("What % tip would you like to give? 10, 12 or 15? "))
num_ppl = int(input("How many people are splitting the bill? "))
bill_and_tip = (total_bill * tip_options/100) + total_bill
per_person = round(bill_and_tip / num_ppl, 2)
print(f"Each person should pay ${per_person:.2f}.")
# {:.2f} string formatting will research further |
3888ed4417b9e3cea77e2026b92ee505adbef2b2 | JaneNjeri/Think_Python | /ex_03_3.py | 705 | 4.5 | 4 | #!/usr/bin/python
#AUTHOR: alexxa
#DATE: 24.12.2013
#SOURCE: Think Python: How to Think Like a Computer Scientist by Allen B. Downey
# http://www.greenteapress.com/thinkpython/html/index.html
#PURPOSE: Chapter 3. Functions
# Exercise 3.3
# Write a function named right_justify that takes a string named s
# as a parameter and prints the string with enough leading spaces
# so that the last letter of the string is in column 70 of the display.
# >>> right_justify('allen')
# allen
def right_justify(s):
length = len(s)
num_of_spaces = 70 - length
print(' '*num_of_spaces, s)
right_justify('allen'*14)
right_justify('allen')
#END |
fa16f14bb45fcc4e4504fa8156acbbd2607c2faa | Hyuancheng/Python | /OOA/OOA-01.py | 1,218 | 3.875 | 4 | '''
关于类与对象,需要明确四个元素,即:
一.类
二.类的成员
三.对象.
四.对象的成员
类与对象的关系,有以下几个特点:
1.当类被赋值给对象的时候,会为对象创建一个空的类,对象的成员实际上仍指向对它赋值的类,即对象成员地址与类成员的地址相同;
2.当对象中某一成员被重新赋值时,对象的空壳中会添加一个新成员,因此该新成员与类中相同成员拥有不同的地址;
3.无论是修改类还是对象中的成员,都无法改变类和对象的地址.
'''
class B():
name = "shuaige"
age = 23
a = B()
print(id(a))
#验证1 新创建一个空的类
print(B.__dict__)
print(a.__dict__)
print("*" * 20)
#验证1 对象成员与类成员地址相同
print(B.name)
print(id(B.name))
print(a.name)
print(id(a.name))
print("*" * 20)
#验证2 对象成员被重新赋值,对象中新增成员,成员地址发生改变
a.name = "meinv"
print(a.name)
print(a.__dict__)
print(id(a.name))
print("*" * 20)
#验证3 修改类和对象中的成员,仅改变成员地址,不改变类和对象的地址
print("a的id为",":",id(a))
print(id(B))
print(id(B.name))
B.name = "goudan"
print(id(B))
print(id(B.name))
|
ebc60df0990a1b63db43d880396d918d301f4639 | GeorgianBadita/LeetCode | /medium/CountNumberOfTeams.py | 1,138 | 3.65625 | 4 | # https://leetcode.com/problems/count-number-of-teams/
from typing import List
class Solution:
def get_comp_lists(self, rating):
larger = [0]*len(rating)
smaller = [0]*len(rating)
for i in range(len(rating) - 1):
for j in range(i + 1, len(rating)):
if rating[j] > rating[i]:
larger[i] += 1
if rating[j] < rating[i]:
smaller[i] += 1
return larger, smaller
def get_teams(self, rating, comp_list, comp_type):
num_teams = 0
for i in range(len(rating) - 1):
for j in range(i + 1, len(rating)):
if comp_type == 'G':
if rating[j] > rating[i]:
num_teams += comp_list[j]
elif comp_type == 'S':
if rating[j] < rating[i]:
num_teams += comp_list[j]
return num_teams
def numTeams(self, rating: List[int]) -> int:
larger, smaller = self.get_comp_lists(rating)
return self.get_teams(rating, larger, 'G') + self.get_teams(rating, smaller, 'S')
|
415cfeb5e76c61eabb67a1a692fb8ce14826e8e6 | dionysus/coding_challenge | /leetcode/002_AddTwoNumbers.py | 1,151 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def addTwoNumbers(l1, l2):
"""
>>> node01A = ListNode(9)
>>> node01B = ListNode(9)
>>> node01A.next = node01B
>>> node02A = ListNode(9)
>>> new_list = addTwoNumbers(node02A, node01A)
>>> node01A.val
8
>>> node01A.next.val
0
>>> node01A.next.next.val
1
"""
if not l1 and not l2:
return None
else:
if l1 and not l2:
v = l1.val
elif l2 and not l1:
v = l2.val
l1, l2 = l2, None
else:
v = l1.val + l2.val
if v >= 10:
v -= 10
if l1.next is None:
if l2 is None or l2.next is None:
l1.next = ListNode(1)
else:
l2.next.val += 1
else:
l1.next.val += 1
l1.val = v
if not l2:
l1.next = self.addTwoNumbers(l1.next, None)
else:
l1.next = self.addTwoNumbers(l1.next, l2.next)
return l1
|
219612e633fa8e393937f52942093f862453a92f | Dendinrdiansyh/Pembelajaran_python | /input-output/menggunakan-fungsi-input.py | 164 | 3.609375 | 4 | nama_mu = input("inputkan nama kamu: ")
nama_dia = input("inputkan nama dia: ")
print("{} dengan {} sepertinya pasangan yang serasi:". format(nama_mu, nama_dia))
|
83f223f1b3f52e11e8da9419baf5f4ed1873b8f5 | VictoriaGomez7/SistemasOperativos | /SO.py | 345 | 3.71875 | 4 | class SistemasOperativos:
def PedirNumeros(self):
self.num1=int(input('Ingrese primer numero: '))
self.num2 = int(input('Ingrese segundo numero: '))
def Suma(self):
suma=self.num1+self.num2
print "La suma es:",suma
S=SistemasOperativos()
S.PedirNumeros()
S.Suma()
|
bad80871fa2d0901f75b3a8d6f07996aac2aecf6 | ttkchang/real-python-test | /sql/sqlk.py | 1,047 | 3.78125 | 4 | import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
# c.execute("""CREATE TABLE orders
# (make TEXT, model TEXT, order_date TEXT)
# """)
orderstuple =[
('Ford','F190','1995-04-01'),
('Ford','F190','1996-04-02'),
('Ford','F190','1997-04-03'),
('Honda','Civic','1997-04-03'),
('Honda','Civic','1997-04-04'),
('Honda','Civic','1997-04-05'),
('Honda','Civic','1997-04-06'),
('Honda','Accord','2000-04-03'),
('Honda','Accord','2000-04-04'),
('Honda','Accord','2000-04-06'),
('Honda','Accord','2000-04-06')
]
#c.executemany("INSERT INTO orders VALUES(?,?,?)", orderstuple)
# c.execute("SELECT * from orders")
# rows = c.fetchall()
# for r in rows:
# print r[0],r[1],r[2]
c.execute("""SELECT DISTINCT inventory.make, inventory.model, orders.order_date FROM inventory, orders
WHERE inventory.make = orders.make ORDER by inventory.make ASC
""")
rows = c.fetchall()
for r in rows:
print "Make: " + r[0]
print "Model: " + r[1]
print "Order_date: " + r[2] |
dc06ace2c8402503c93ad2a5901cd2b5c5a8ea8a | MartyMcFlyHasNoFarmHiaHiaHo/asractivelearning | /datastructures/interval.py | 726 | 3.5625 | 4 | import intervaltree
__author__ = 'martin'
class IntervalBookKeeper(intervaltree.IntervalTree):
@staticmethod
def compute_overlap(interval1, interval2):
if interval1.begin < interval1.begin:
low_interval = interval1
high_interval = interval2
else:
low_interval = interval2
high_interval = interval1
return low_interval.end - high_interval.begin
def get_interval_overlap(self, interval):
overlapping_intervals = self.search(interval.begin, interval.end)
overlap = sum(IntervalBookKeeper.compute_overlap(interval, overlap_interval)
for overlap_interval in overlapping_intervals)
return overlap
|
8b31735dfdfe18af6b023d22b67ae2eac1d21fbe | msahani10294/Python_Code | /args_kwgs/sum.py | 187 | 3.671875 | 4 | import math
n = int(input("how many no you want to add : "))
l = []
j = 1
for i in range(n):
number = int(input("enter {} no :".format(j)))
l.append(number)
j+=1
print(sum(l)) |
17884ea7f762ea7901873d1256e1d54244ebda35 | Yaachaka/pyPractice1 | /bhch04/bhch04exrc05.py | 296 | 3.984375 | 4 | from random import randint
guess = eval(input('Guess a number between 1 and 10: '))
if 0 < guess < 11:
rand = randint(1, 10)
if rand == guess:
print('Woww.. you guessed it right.')
else:
print('Alas... The random number generated is', rand)
else:
print('Out of bound guess.') |
b080167851463c969f462dc189f9b5e3ee6bdb5e | mjyuen/Misc-Python | /practice/checkprime.py | 608 | 4.1875 | 4 | # http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
# by Michelle Yuen, for Python 2.7
# Program takes user submitted number and checks if it is or isn't prime.
# If the number is not prime, a list of divisors is returned.
num = int(raw_input("Enter a number: "))
possible = range(2, num) # generate a list of possible divisors
divisors = []
for div in possible:
if num % div == 0:
divisors.append(div)
if len(divisors) == 0:
print "The number is prime."
else:
print "The number is not prime. Here is a list of divisors: \n"
print divisors
|
aee6ac5f51b33513e295a484da2624a300b73d9a | Oleg-Kistanov/python-project-lvl1 | /brain_games/games/prime.py | 466 | 3.9375 | 4 | #!/usr/bin/env python3
import random
def check_prime():
"""
Generates a random integer and checks if it is a prime number.
:return: correct answer and integer
"""
expression = random.randint(1, 100)
composite_dividers = list(range(2, expression))
if expression == 1:
return ("no", expression)
for i in composite_dividers:
if expression % i == 0:
return ("no", expression)
return ("yes", expression)
|
a54b462a7baf4ee4382c954c0ed5d36360b90e3c | Alsten-Tauro/ML_Programs | /ML_LAB(03-08-2020)/ml_prgm1.py | 99 | 3.5625 | 4 | s=input("enter a sentence :").split()
a=list(set(s))
for i in a:
print(i,"-",s.count(i)) |
f2fba2a1ae5f8f6afb7effe1af6050bbaaaec44f | uralbash/Python-lectures | /lec3/LPTHW/ex10.py | 486 | 3.78125 | 4 | # coding: utf-8
# Escape символы
print "I am not 6'2\" tall"
print 'I am not 6\'2" tall'
tabby_cat = "\t I'm tabbed in"
persian_cat = "I'm split\non a line"
backslash_cat = "I'm \\ a \\ cat"
fat_cat = """
i'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
# Упражения:
#
# 1. Выясните, какие ещё escape-последовательности существуют
#
|
d4b295d08289abd16a3843f57917699e0317dcee | shivapk/Programming-Leetcode | /Python/sorting/insertion_sort[n2,1].py | 307 | 3.875 | 4 | #Insertion sort
#Time==O(n2)
#space=O(1)
def insertionSort(a):
for i in range(1,len(a)):
for j in range(i,0,-1):
if a[j]<a[j-1]:
a[j],a[j-1]=a[j-1],a[j]
else:
break
return a
l=[4,3,2,1]
print insertionSort(l) |
b4de28b4b550c3540943d362f1a7d4d580be53bb | amanagarwal2189/DAWithPython | /pyScript-2/2_employment.py | 962 | 3.59375 | 4 | import numpy as np
countries = np.array([
'Algeria', 'Argentina', 'Armenia', 'Aruba', 'Austria','Azerbaijan',
'Bahamas', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Bolivia',
'Botswana', 'Brunei', 'Bulgaria', 'Burkina Faso', 'Burundi',
'Cambodia', 'Cameroon', 'Cape Verde'
])
# Employment data in 2007 for those 20 countries
employment = np.array([
55.70000076, 51.40000153, 50.5 , 75.69999695,
58.40000153, 40.09999847, 61.5 , 57.09999847,
60.90000153, 66.59999847, 60.40000153, 68.09999847,
66.90000153, 53.40000153, 48.59999847, 56.79999924,
71.59999847, 58.40000153, 70.40000153, 41.20000076
])
def standadize_data(employment):
#ind = np.where(countries==country_name)
return (employment - np.mean(employment))/np.std(employment)
for i in range(len(countries)):
print('Country {} has {} completion rate'.format(countries[i],standadize_data(employment)[i])) |
0281d9135b1c8d3682b3c0f02505c026ae8a7807 | LeaRain/IVcal | /ivcal/database/database_master.py | 765 | 4.09375 | 4 | """
In this file, an abstract database class is defined, so other classes can inherit from this class for a connection to
the database file. There can be different purposes for a database connection.
"""
import sqlite3
class MasterDatabaseClass:
"""
Create an abstract/master database class with access to the database file.
"""
def __init__(self):
# Initialize a connection and if this file does not exist, it is created in this step. The isolation level is
# set to None, so autocommit is possible.
database_connection = sqlite3.connect("pokemon.db", isolation_level=None)
# Use a cursor as class object, so every function has access to the database.
self.database_cursor = database_connection.cursor()
|
17555db37762a4590a39e21030ff008b02c49457 | hinewin/The-Modern-Python-3-Bootcamp | /ch.10 Functions Part 2/1. args Intro.py | 935 | 4.25 | 4 | # *args - a special operator we can pass to functions as a parameter
# gather arguments as a tuple
# JUST a parameter, can call whatever you want(has to start with *)
def sum_all_nums(num1,num2,num3): # INSTEAD of adding more parameters
#to hold num4, num5, we can use *args
return num1+num2+num3
print (sum_all_nums(4,6,9))
def sum_nums(*args):
print(args)
print (sum_nums(4,7,8,9,6))
# output: (4,7,8,9,6) its a tuple (cant be changed)
def iterate(num1,*args):
total = 0
print (num1) # print first variable, then the rest
for num in args:
total += num
return total
print (iterate(1,1,5))
def ensure_correct_info(*args):
print(f"input: {args}")
if "Hai".lower() in args and "Nguyen".lower() in args:
return "Welcome back Hai"
else:
return "Not sure who you are..."
print (ensure_correct_info("he",1,3,"nguye"))
print (ensure_correct_info("hai",1,3,"nguyen")) |
e6be380b41442caf392b84161b7e660456e130ae | JerryHu1994/LeetCode-Practice | /Solutions/244-Shortest-Word-Distance-II/python.py | 935 | 3.6875 | 4 | class WordDistance(object):
def __init__(self, words):
"""
:type words: List[str]
"""
self.dic = {}
for i,w in enumerate(words):
if w in self.dic:
self.dic[w].append(i)
else:
self.dic[w] = [i]
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
list1 = self.dic[word1]
list2 = self.dic[word2]
curr1, curr2 = 0, 0
ret = float("inf")
while curr1 < len(list1) and curr2 < len(list2):
ret = min(abs(list1[curr1]-list2[curr2]), ret)
if list1[curr1] > list2[curr2]:
curr2+=1
else:
curr1+=1
return ret
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2) |
0af5555045a68cbdfb217fbecfbda76fd53dc171 | mauriziokovacic/ACME | /ACME/model/num_parameters.py | 368 | 3.875 | 4 | def num_parameters(model):
"""
Returns the number of parameters in the given model
Parameters
----------
model : torch.nn.Module
the model to count the parameters of
Returns
-------
int
the number of parameters in the given model
"""
n = 0
for p in model.parameters():
n += p.numel()
return n
|
b97c4d98bea49911c166211b2bd012d32ebcdaf2 | CapnFlint/TwitchBot101 | /05 - Basic Syntax/3 - Iteration and Loops/examples.py | 637 | 3.984375 | 4 | '''
Iteration and Loops
'''
# If-Else
a = 2
if a == 1:
print "a is 1"
elif a == 2:
print "a is 2"
else:
print "a isn't 1 or 2"
# for
myList = [1,2,3,4,5]
for element in myList:
print element
# while
count = 10
while count > 0:
print count
count = count - 1
print "Blastoff!"
# Break
haystack = [1,4,6,8,9]
needle = 6
pos = 0
while pos < len(haystack):
if haystack[pos] == needle:
break
pos += 1
print "Needle found at position: " + str(pos)
# Continue
myList = [1,1,0,1,0,0,0,1,0,1]
count = 0
for item in myList:
if item == 0:
continue
count += 1
print "Found: " + str(count)
|
0fb05211c6a188b91cb823d7fc92382dbd75b3cc | megamayoy/Coursera-Algorithmic-toolbox | /week4_divide_and_conquer/2_majority_element/majority_element.py | 1,303 | 4.03125 | 4 | # Uses python3
from math import floor
def get_majority_element(a, left, right):
# if there's only one element in the array
# then this element is the majority element
if left == right:
return a[left]
middle = floor(left + (right - left) / 2)
left_result = get_majority_element(a, left, middle)
right_result = get_majority_element(a, middle+1, right)
# if majority element in both sides are the same
# then Horraaay this is majority element at the entire array level
if left_result == right_result:
return left_result
array_size = right - left + 1
counter_dict = dict.fromkeys([left_result, right_result], 0)
# count occurrences
for i in range(left, right+1):
if a[i] == left_result:
counter_dict[left_result] += 1
if a[i] == right_result:
counter_dict[right_result] += 1
majority_element = -1
if counter_dict[left_result] > array_size / 2:
majority_element = left_result
elif counter_dict[right_result] > array_size / 2:
majority_element = right_result
return majority_element
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
if get_majority_element(a, 0, n-1) != -1:
print(1)
else:
print(0)
|
762e8fceca41d0031dced0680344fcd643bbf89f | OlyaS94/Homework_1 | /homework.py | 5,923 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[313]:
class Student:
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
def lect_rate(self, lecturer, course, grade):
if isinstance(lecturer,Lecturer) and course in lecturer.courses_attached and course in self.courses_in_progress and grade <= 10:
if course in lecturer.grades:
lecturer.grades[course] += [grade]
else:
lecturer.grades[course] = [grade]
else:
return 'Ошибка'
def avg_grade(self):
sum_1 = 0
count_1 = 0
for grades in self.grades.values():
sum_1 += sum(grades)
count_1 += len(grades)
return round(sum_1/count_1)
def __str__(self):
result = f'Имя: {self.name}\n' f'Фамилия: {self.surname}\n' f'Средняя оценка за домашние задания: {self.avg_grade()}\n' f'Курсы в процессе изучения: {self.courses_in_progress}\n' f'Завершенные курсы: {self.finished_courses}'
return print(result)
def __lt__(self, stud_2):
if not isinstance(stud_2,Student):
print('Такого студентa нет!')
else:
compare = self.avg_grade() < stud_2.avg_grade()
if compare:
print(f'У студента {stud_2.name} {stud_2.surname} средняя оценка выше, чем у {self.name} {self.surname}.')
else:
print(f'У студента {self.name} {self.surname} средняя оценка выше, чем у {stud_2.name} {stud_2.surname}.')
# In[314]:
class Mentor:
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.courses_attached = []
# In[315]:
class Lecturer(Mentor):
def __init__(self ,name, surname):
super().__init__(name, surname)
self.grades = {}
def avg_grade_l(self):
sum_1 = 0
count_1 = 0
for grades in self.grades.values():
sum_1 += sum(grades)
count_1 += len(grades)
return round(sum_1/count_1)
def __str__(self):
resul = f'Имя: {self.name}\n' f'Фамилия: {self.surname}\n' f'Средняя оценка за лекции: {self.avg_grade_l()}\n'
return print(resul)
def __lt__(self, lect_2):
if not isinstance(lect_2, Lecturer):
print('Такого лектора нет!')
return
else:
comp = self.avg_grade_l() < lect_2.avg_grade_l()
if comp:
print(f'У лектора {lect_2.name} {lect_2.surname} средняя оценка выше, чем у {self.name} {self.surname}.')
else:
print(f'У лектора {self.name} {self.surname} средняя оценка выше, чем у {lect_2.name} {lect_2.surname}.')
# In[316]:
class Reviewer(Mentor):
def rate_hw(self, student, course, grade):
if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:
if course in student.grades:
student.grades[course] += [grade]
else:
student.grades[course] = [grade]
else:
return 'Ошибка'
def __str__(self):
res = f'Имя: {self.name}\n' f'Фамилия: {self.surname}'
return print(res)
# In[317]:
best_student = Student('Thomas', 'Miller', 'm')
best_student.courses_in_progress += ['Java', 'Git']
best_student.finished_courses += ['Python']
good_student = Student('Anna','Frank', 'f')
good_student.courses_in_progress += ['Git', 'Java']
good_student.finished_courses += ['C++']
# In[318]:
lecturer_1 = Lecturer('Paul','Geiger')
lecturer_1.courses_attached += ['Java','Git']
lecturer_2 = Lecturer('Maja','Kunzt')
lecturer_2.courses_attached += ['Python','C++','Java', 'Git']
# In[319]:
reviewer_1 = Reviewer('Richard', 'Friedrich')
reviewer_1.courses_attached += ['Python', 'Git', 'Java','C++']
reviewer_2 = Reviewer ('Betta', 'Golz')
reviewer_2.courses_attached += ['Python', 'Git', 'Java','C++']
# In[320]:
reviewer_1.rate_hw(best_student, 'Java', 10)
reviewer_1.rate_hw(best_student, 'Git',8)
reviewer_2.rate_hw(good_student, 'Git', 8)
reviewer_2.rate_hw(good_student,'Java', 6)
# In[321]:
best_student.lect_rate(lecturer_1, 'Java', 10)
best_student.lect_rate(lecturer_1, 'Git', 8)
good_student.lect_rate(lecturer_2, 'Java', 9)
good_student.lect_rate(lecturer_2,'Git', 7)
# In[322]:
best_student.avg_grade()
# In[323]:
best_student.__str__()
# In[324]:
best_student.__lt__(good_student)
# In[325]:
lecturer_1.avg_grade_l()
# In[326]:
lecturer_1.__str__()
# In[327]:
lecturer_1.__lt__(lecturer_2)
# In[328]:
reviewer_1.__str__()
# In[333]:
def avg_all_stud(stud_list,course):
total = 0
for student in stud_list:
for course_name,grade in student.grades.items():
if course_name == course:
total += sum(grade)/len(grade)
return round(total/len(stud_list),2)
# In[334]:
def avg_all_lect(lect_list,course):
total = 0
for lect in lect_list:
for course_name,grade in lect.grades.items():
if course_name == course:
total += sum(grade)/len(grade)
return round(total/len(lect_list),2)
# In[335]:
print(avg_all_stud([best_student,good_student],'Java'))
# In[336]:
print(avg_all_lect([lecturer_1,lecturer_2],'Java'))
# In[ ]:
|
a52be80d89d6c57c2702df543dec0ddde1f61058 | wcgs-programming/wcgs-programming.github.io | /files/showcase/Killian/cipher.py | 1,373 | 3.796875 | 4 | while 1:
def e():
string = raw_input("What do you want to encode? ")
alphabet = "abcdefghijklmnopqrstuvwxyz "
calphabet = "qwertyuiopasdfghjklzxcvbnm/"
ualphabet = alphabet.upper()
ucalphabet = calphabet.upper()
estring = ""
for i in string:
k = ""
j = 0
while j<27:
if i == alphabet[j]:
k = calphabet[j]
if i == ualphabet[j]:
k = ucalphabet[j]
j = j+1
estring = estring + k
print estring
def d():
string = raw_input("What do you want to decode? ")
alphabet = "qwertyuiopasdfghjklzxcvbnm/"
calphabet = "abcdefghijklmnopqrstuvwxys "
ualphabet = alphabet.upper()
ucalphabet = calphabet.upper()
estring = ""
for i in string:
k = ""
j = 0
while j<27:
if i == alphabet[j]:
k = calphabet[j]
if i == ualphabet[j]:
k = ucalphabet[j]
j = j+1
estring = estring + k
print estring
selection = raw_input("Encode or Decode. e/d ")
if selection == "e":
e()
else:
d()
|
a38f2c82844ab2eaff572f98b6ea410e58f252a9 | SanthoshKR93/Python_Anandology_Solutions | /Working_with_Data/problem_32_mutate.py | 2,004 | 3.859375 | 4 | # Write a function mutate to compute all words generated by a single mutation on a given word.
# A mutation is defined as inserting a character, deleting a character, replacing a character,
# or swapping 2 consecutive characters in a string. For simplicity consider only letters from a to z.
ret = []
w = []
b = []
a = []
s = []
ml = []
l = []
t = ''
clen = 0
def mutate(d):
clen = len(d)
# creating a list of alphabets from a to z
alp=map(chr,range(97,123))
for i in alp:
a.append(i)
s=[]
for i in range(clen):
s.append(d[i])
# inserting values
for i in a:
for j in range(clen):
if j < (clen):
s.insert(j,i)
ml.append(s)
#print(s)
s = []
for x in range(clen):
s.append(d[x])
if j == (clen -1):
s.append(i)
ml.append(s)
s = []
for x in range(clen):
s.append(d[x])
#removing any one value at a time
for p in range(clen):
s = []
w = []
for r in range(clen):
s.append(d[r])
w.append(d[r])
s.remove(w[p])
ml.append(s)
# replacing a value with any value in a to z
s= []
for q in range(clen):
s.append(d[q])
for e in a:
for f in range(clen):
s[f] = e
#print(s)
ml.append(s)
s = []
for o in range(clen):
s.append(d[o])
# swapping any two concecutive characters.
for t in range(clen):
if(t < (clen -1)):
temp = s[t]
s[t] = s[t+1]
s[t+1] = temp
ml.append(s)
#print(s)
s = []
for t1 in range(clen):
s.append(d[t1])
# converting list into string.
for val in ml:
ret.append(("").join(val))
return ret
print ('hlelo' in mutate('hello'))
print ('helo' in mutate('hello'))
print ('helldo' in mutate('hello'))
print ('hllo' in mutate('hello'))
print ('hlo' in mutate('hello'))
|
6e2ca1087430a82309c373bc2f8e44744c318b5a | alkaran4/python | /3.py | 465 | 3.9375 | 4 | declination = {1 : 'процент', 2 : 'процента', 3 : 'процентов'}
percent = int(input('Введите число от 0 до 20 - '))
if percent < 0 or percent > 20 :
print('Введите положительное число от 0 до 20')
elif percent == 1:
print(f'{percent} {declination[1]}')
elif percent <= 4 and percent != 0:
print(f'{percent} {declination[2]}')
else:
print(f'{percent} {declination[3]}')
|
d525e3aeeeea5284a3ffbfcdb71efeef07f9ecb8 | ankit039/Competitive_Programming_Solutions | /HackerRank/Apple_and_Orange.py | 719 | 3.703125 | 4 |
import math
import os
import random
import re
import sys
def countApplesAndOranges(s, t, a, b, apples, oranges):
app = 0
ora = 0
for ap in apples:
if a+ap >=s and a+ap <=t:
app +=1
for org in oranges:
if b+org <= t and b+org>=s:
ora +=1
print(app)
print(ora)
if __name__ == '__main__':
st = input().split()
s = int(st[0])
t = int(st[1])
ab = input().split()
a = int(ab[0])
b = int(ab[1])
mn = input().split()
m = int(mn[0])
n = int(mn[1])
apples = list(map(int, input().rstrip().split()))
oranges = list(map(int, input().rstrip().split()))
countApplesAndOranges(s, t, a, b, apples, oranges)
|
38747283821c724cce5b099a119975d034f55160 | Moscdota2/Archivos | /python1/listas y tuplas/ejercicio10.py | 233 | 3.875 | 4 | prices = [50, 75, 46, 22, 80, 65, 8]
min = max = prices[0]
for price in prices:
if price < min:
min = price
elif price > max:
max = price
print("El mínimo es " + str(min))
print("El máximo es " + str(max)) |
6cf7197950b732ccd882d6fc9298281999a32bd7 | sachsom95/my_leets | /algoExpert/SmallestDifference.py | 652 | 3.8125 | 4 | def smallestDifference(arrayOne, arrayTwo):
arrayOne.sort()
arrayTwo.sort()
data = []
i, j = 0, 0
smallest_val = float("inf")
while (i < len(arrayOne) and j < len(arrayTwo)):
arr1 = arrayOne[i]
arr2 = arrayTwo[j]
diff = abs(arr1-arr2)
if diff < smallest_val:
smallest_val = diff
data = [arrayOne[i], arrayTwo[j]]
if (arr1 > arr2):
j += 1
elif (arr1 < arr2):
i += 1
else:
return [arr1, arr2]
return data
arr1 = [-1, 3, 5, 10, 20, 28]
arr2 = [15, 17, 26, 134, 135]
print(smallestDifference(arr1, arr2))
|
59e233a69aeeb9517484d1ad65ca29c4b8c56a0a | chipmuenk/python_snippets | /dsp_fpga/00_py_examples/fibonacci.py | 179 | 3.65625 | 4 | # Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
c = d = e = a+1
print c, d, e
while b < 10:
print a, b
a, b = b, a+b
print "Ende!"
|
f1f7830bf90b0f8e29b213d82a15046be8170606 | Wolfhan99/LeetCode-Javascript-Solution | /常考代码/sort-python/bubble.py | 619 | 3.9375 | 4 | """ 冒泡排序
相邻的两个元素进行比较,然后把较大的元素放到后面(正向排序),
在一轮比较完后最大的元素就放在了最后一个位置,
因为这一点像鱼儿在水中吐的气泡在上升的过程中不断变大,所以得名冒泡排序。 """
def bubble_sort(alist):
size = len(alist)
for i in range(size-1):
for j in range(size - i - 1):
if alist[j] > alist[j+1]:
alist[j] , alist[j+1] = alist[j+1], alist[j]
import random
data = [random.randint(-100, 100) for _ in range(10)]
bubble_sort(data)
print(data) |
66163425f72971fd46e665432a98083971b009f2 | github/codeql | /python/ql/src/Expressions/Regex/MissingPartSpecialGroup.py | 252 | 3.65625 | 4 | import re
matcher = re.compile(r'(P<name>[\w]+)')
def only_letters(text):
m = matcher.match(text)
if m:
print("Letters are: " + m.group('name'))
#Fix the pattern by adding the missing '?'
fixed_matcher = re.compile(r'(?P<name>[\w]+)') |
0ecc0acef2ef11d9164cbb2a12b13d055530a1e1 | yorkypy/selise-intervie | /string/vowelCount.py | 245 | 3.90625 | 4 | '''Python | Count and display vowels in a string'''
def solve(s,v):
return [i for i in s if i in v]
#Driver
if __name__ == "__main__":
v=['A','a','E', 'e','I','i','O','o','U','u']
print(solve('Nima isnnsdn ds aeio',v))
|
70fc9e074bf709abec9155d5c885a8d61ac8d163 | dotran/bibtex-for-zotero | /bibutils/check_duplicate_citekeys.py | 645 | 3.5 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def check_duplicate_citekeys(list_of_dicts):
list_of_citekeys = [item['id'] for item in list_of_dicts]
if len(set(list_of_citekeys)) == len(list_of_citekeys):
print(" No duplicate citation key detected.")
else:
print(" There are duplicate citation keys:")
for citekey in set(list_of_citekeys):
if list_of_citekeys.count(citekey) > 1:
print(" '%s'" % citekey, "occurs", list_of_citekeys.count(citekey), "times")
|
afea459e0ba5590c1bc49daa582c10fcdb6a9b18 | erjan/coding_exercises | /bold_words_in_string.py | 1,092 | 3.859375 | 4 | '''
Given an array of keywords words and a string s, make all appearances of all keywords words[i] in s bold. Any letters between <b> and </b> tags become bold.
Return s after adding the bold tags. The returned string should use the least number of tags possible, and the tags should form a valid combination.
'''
class Solution:
def boldWords(self, words: List[str], S: str) -> str:
bold = [0] * len(S)
for word in words:
start = 0
while start < len(S):
idx = S.find(word, start)
if idx >= 0 :
bold[idx:idx+len(word)] = [1] * len(word)
start = idx + 1
else:
break
result = []
for i, c in enumerate(S):
if bold[i] and (i == 0 or not bold[i - 1]):
result.append('<b>')
result.append(c)
if bold[i] and (i == len(S) - 1 or not bold[i + 1]):
result.append('</b>')
return "".join(result)
|
e55ba4323446e7c014c3131cea0eabbeac76b2ea | hafdhisofien/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 2,374 | 4.46875 | 4 | #!/usr/bin/python3
class Square:
"""" A simple Square"""
def __init__(self, size=0, position=(0, 0)):
"""Example function with PEP 484 type annotations.
Args:
self: self.
size: size of my_square.
postion: position of my_square
"""
self.__size = size
self.__position = position
@property
def size(self):
"""Getter of size.
Args:
slef: self.
Returns: size of my_square.
"""
return self.__size
@size.setter
def size(self, value):
""" setter of my size.
Args:
self: self.
value: value of my size.
Returns:none.
"""
if type(value) != int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
self.__size = value
@property
def position(self):
""" Get position.
Args:
self:self.
Returns:
None.
"""
return self.__position
@position.setter
def position(self, value):
""" set postion
Args
self:self.
value:position .
Returns:
None.
"""
if type(value) is not tuple or len(value) != 2:
raise TypeError('position must be a tuple of 2 positive integers')
elif type(value[0]) is not int or type(value[1]) is not int:
raise TypeError('position must be a tuple of 2 positive integers')
elif value[0] < 0 or value[1] < 0:
raise ValueError('position must be a tuple of 2 positive integers')
else:
self.__position = value
def area(self):
""" area of my_square.
Args:
self: self.
Returns:
returns the area of my_square.
"""
area = self.__size * self.__size
return(area)
def my_print(self):
""" prints a sqaure
Args:
self:self
Return:
None.
"""
if self.size == 0:
print()
return
for r in range(self.position[1]):
print()
for i in range(self.size):
for spc in range(self.position[0]):
print(" ", end="")
for j in range(self.size):
print("#", end="")
print()
|
478eab0f31bed2976f631f6c72ab25961f493d38 | nehasrichandra/PSP-LAB | /demo 1.py | 480 | 4.125 | 4 | import matplotlib.pyplot as plt
X = range(1, 50)
Y = [value * 2 for value in X]
print("Values of X:")
print(*range(1,50))
print("Values of Y (twice of X):")
print(Y)
# Plot lines and/or markers to the Axes.
plt.plot(X, Y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Plot of (X,Y).')
# Display the figure.
plt.show() |
cbc047e075024f7e17890cdece87f5458c82ecff | stathopoan/bd4h-cse-6250 | /code/plots.py | 6,294 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
# TODO: You can use other packages if you want, e.g., Numpy, Scikit-learn, etc.
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import roc_curve, auc
from scipy import interp
from itertools import cycle
def plot_learning_curves(train_losses, valid_losses, train_accuracies, valid_accuracies):
# TODO: Make plots for loss curves and accuracy curves.
# TODO: You do not have to return the plots.
# TODO: You can save plots as files by codes here or an interactive way according to your preference.
plt.figure()
plt.plot(np.arange(len(train_losses)), np.array(train_losses) * 0.53, label='Train')
plt.plot(np.arange(len(valid_losses)), np.array(valid_losses) * 0.53, label='Validation')
plt.ylabel('Loss')
plt.xlabel('epoch')
plt.legend(loc="best")
plt.savefig('plot_losses')
plt.show()
plt.figure()
plt.plot(np.arange(len(train_accuracies)), train_accuracies, label='Train')
plt.plot(np.arange(len(valid_accuracies)), valid_accuracies, label='Validation')
plt.ylabel('Accuracy')
plt.xlabel('epoch')
plt.legend(loc="best")
plt.savefig('plot_accuracies')
plt.show()
def plot_confusion_matrix_sklearn_example(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
This function used from: https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html#sphx-glr-auto-examples-model-selection-plot-confusion-matrix-py
"""
if not title:
if normalize:
title = 'Normalized confusion matrix'
else:
title = 'Confusion matrix, without normalization'
# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)
# Only use the labels that appear in the data
# classes = classes[unique_labels(y_true, y_pred)]
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
fig, ax = plt.subplots()
im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
ax.figure.colorbar(im, ax=ax)
# We want to show all ticks...
ax.set(xticks=np.arange(cm.shape[1]),
yticks=np.arange(cm.shape[0]),
# ... and label them with the respective list entries
xticklabels=classes, yticklabels=classes,
title=title,
ylabel='True label',
xlabel='Predicted label')
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Loop over data dimensions and create text annotations.
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i in range(cm.shape[0]):
for j in range(cm.shape[1]):
ax.text(j, i, format(cm[i, j], fmt),
ha="center", va="center",
color="white" if cm[i, j] > thresh else "black")
fig.tight_layout()
return ax
def plot_confusion_matrix(results, class_names):
# TODO: Make a confusion matrix plot.
# TODO: You do not have to return the plots.
# TODO: You can save plots as files by codes here or an interactive way according to your preference.
y_true = [i[0] for i in results]
y_pred = [i[1] for i in results]
plot_confusion_matrix_sklearn_example(y_true, y_pred, classes=class_names)
plt.savefig('plot_cm.png')
plt.show()
# Reference: https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html
def plot_roc_curve(yhat_raw, y):
if yhat_raw.shape[0] <= 1:
return
fpr = {}
tpr = {}
roc_auc = {}
# get AUC for each label individually
relevant_labels = []
auc_labels = {}
for i in range(y.shape[1]):
# only if there are true positives for this label
if y[:, i].sum() > 0:
fpr[i], tpr[i], _ = roc_curve(y[:, i], yhat_raw[:, i])
if len(fpr[i]) > 1 and len(tpr[i]) > 1:
auc_score = auc(fpr[i], tpr[i])
if not np.isnan(auc_score):
auc_labels["auc_%d" % i] = auc_score
relevant_labels.append(i)
n_classes = y.shape[1]
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y.ravel(), yhat_raw.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))
# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
# Finally average it and compute AUC
mean_tpr /= n_classes
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
lw = 2
# Plot all ROC curves
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
# for i, color in zip(range(n_classes), colors):
# plt.plot(fpr[i], tpr[i], color=color, lw=lw,
# label='ROC curve of class {0} (area = {1:0.2f})'
# ''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC multi-class')
plt.legend(loc="lower right")
plt.savefig('plot_roc')
plt.show()
|
10fef4ff01f63e216a77c3488f1ff2761876e44e | KindoIssouf/DataWareHousingScripts | /main-nn.py | 5,735 | 4.1875 | 4 | # CS4412 : Data Mining
# Fall 2021
# Kennesaw State University
"""In this script, we use TensorFlow to manually model a feedforward
neural network, neuron-by-neuron and layer-by-layer. We do this to be
more familiar with how neural networks work; it is much easier and
efficient to use TensorFlow abstractions to define a neural network.
We train this neural network on the mnist dataset, a dataset of
handwritten images of digits.
Things to try:
1) try using the sigmoid activation function instead of relu (training
will probably fail)
2) try increasing the size of the hidden layer, until the neural
network starts to overfit.
3) try to use the SlowLayer's instead of the Layer's in the
initializer of the NeuralNetwork class, and see how much slower it
becomes. Using a matrix-multiply to evaluate all neurons at once,
rather than one-by-one is much faster. If you have an nvidia GPU, it
might be MUCH faster to use Layer instead of SlowLayer (since GPUs are
really good at doing matrix multiply's really fast).
4) if you want to try a different dataset, try Fashion-MNIST, which
are 28x28 images of different types of clothes. (the same dimension
as MNIST)
"""
import tensorflow as tf
import pickle
with open("mnist/mnist-train-images",'rb') as f: train_images = pickle.load(f)
with open("mnist/mnist-train-labels",'rb') as f: train_labels = pickle.load(f)
with open("mnist/mnist-test-images",'rb') as f: test_images = pickle.load(f)
with open("mnist/mnist-test-labels",'rb') as f: test_labels = pickle.load(f)
# do one-hot-encoding of the labels
train_labels = tf.keras.utils.to_categorical(train_labels,num_classes=10)
test_labels = tf.keras.utils.to_categorical(test_labels,num_classes=10)
"""A neuron is of the form:
f( sum_i w_i x_i + b )
where x_i are our inputs
w_i is a weight, one per input
b is a bias term
and f is an activation function.
"""
class Neuron(tf.keras.models.Model):
def __init__(self,input_dim,activation):
super(Neuron,self).__init__()
self.w = tf.random.uniform([input_dim,1]) # random weights
self.b = tf.zeros([1,1]) # a zero bias
self.w = tf.Variable(self.w)
self.b = tf.Variable(self.b)
self.activation = activation # activation function
# returns the output of the neuron
def call(self,x):
return self.activation(x@self.w + self.b)
"""A layer is a row of multiple neurons. In this class, we represent
a layer as an explicit list of neurons. It is faster to not represent
the neurons explicitly, and just treat each layer as a
matrix-multiply, which we do in the Layer class.
"""
class SlowLayer(tf.keras.models.Model):
def __init__(self,input_dim,output_dim,activation):
super(SlowLayer,self).__init__()
self.units = [ Neuron(input_dim,activation) \
for _ in range(output_dim) ]
# returns the output of the layer
def call(self,x):
output = [ neuron(x) for neuron in self.units ]
return tf.concat(output,axis=1)
"""We represent a layer of neurons as a matrix multiply. A matrix
multiply is equal to doing a dot product of n weight vectors (each
representing a neuron), with the same input. The bias term is now a
vector of biases.
"""
class Layer(tf.keras.models.Model):
def __init__(self,input_dim,output_dim,activation):
super(Layer,self).__init__()
self.A = tf.random.uniform([input_dim,output_dim]) # random weights
self.b = tf.zeros([1,output_dim]) # zero biases
self.A = tf.Variable(self.A)
self.b = tf.Variable(self.b)
self.activation = activation # activation function
# returns the output of the layer
def call(self,x):
return self.activation( x@self.A + self.b )
"""A feedforward neural network is a sequence of layers.
"""
class NeuralNetwork(tf.keras.models.Model):
def __init__(self,dimensions,activation):
super(NeuralNetwork,self).__init__()
self._layers = []
# the input of a layer is the output of the previous layer
last_dim = dimensions[0] # the dimension of the last layer
for dim in dimensions[1:]: # the dimension of the cur layer
layer = Layer(last_dim,dim,activation)
self._layers.append(layer)
last_dim = dim # output of cur is input of next layer
# returns the output of the layer
def call(self,x):
for layer in self._layers:
x = layer(x)
return x
# specify the function to use to test accuracy
accuracy_function = tf.keras.metrics.CategoricalAccuracy()
# dimensions of the neural network. first dimension is the size of
# the input layer (28*28) and the last dimension is the size of the
# output layer (10, one for each digit)
dimensions = [ 28*28, 40, 10 ]
# construct the neural network and set it up for training
model = NeuralNetwork(dimensions,tf.nn.relu)
model.compile(optimizer="adam",
loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=[accuracy_function])
# train the model
model.fit(train_images,train_labels,epochs=10)
# evaluate the model on the training data
train_predictions = model.predict(train_images)
train_acc = accuracy_function(train_predictions,train_labels)
print("train accuracy: %.2f%%" % (100*train_acc))
# evaluate the model on the testing data
test_predictions = model.predict(test_images)
test_acc = accuracy_function(test_predictions,test_labels)
print("test accuracy: %.2f%%" % (100*test_acc))
# To repeat: this is a really inefficient way of implementing a neural
# network in tensorflow. We are just doing it like this to know what
# a neural network actually looks like.
|
f66ec07124f5ca0fee489bd08dd597efac8d962a | romulovieira777/Programacao_em_Python | /Exercícios e Soluções/exercicio_09.py | 762 | 4.15625 | 4 | """
Crie uma estrutura de repetição para fazer a leitura de 5 números inteiros e os armazene dentro de uma lista.
Após a leitura, crie outra estrutura de repetição para somar todos os valores digitados.
"""
# Criando uma Lista e Declarando uma Variável
list_01 = []
# Percorrendo toda a Lista
for lista in range(1, 6):
# Insere os Valores Percorridos no for na Lista Criada
list_01.append(lista)
# Apresenta os Valores na Tela
print(list_01)
# Percorrendo a Lista e Criando uma Variável para fazer a Soma
soma = 0
# Criando uma Estrutura de Repetição Utilizando o for
for i in range(len(list_01)):
# Somando os Valores na Variável Soma
soma += list_01[0]
soma += list_01[1]
# Apresenta os Valores na Tela
print('Sum', soma)
|
51fe81ac25642de38098f513578df596240e5287 | LucasOJacintho/Curso_em_video_python | /Exercícios/ex16.py | 553 | 4.25 | 4 | # Devolução de numero inteiro por biblioteca ou de forma simples
from math import floor
num = float(input('Digite um numero: '))
inteiro = floor(num)
print('O número {} tem a parte inteira {}. '. format(num, inteiro))
#Outro metodo
import math
num = float(input('Digite um numero: '))
print('O número {} tem a parte inteira {}. '. format(num,math.trunc(num))) # trunc corta a parte real, deixando só a inteira
#Outra formar mais simples
num = float(input('Digite um numero: '))
print('O número {} tem a parte inteira {}. '. format(num,int(num))) |
358ad3edc6ac021952f8c2768cac4e68d1919606 | te14017/ML_RL_proj | /runner.py | 2,176 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# copyright (C) Team Kingslayer, University of Zurich, 2017.
"""
@author: Te Tan, Yves Steiner, Victoria Barth, Lihua Cao
"""
from robot import *
from environment import Environment
import random
import math
import plotter
def main():
# algo: 1 is Q-learning, 2 is TD
# multi-step: when algo=2, if multi-step=1, then it's SARSA
robot = Robot(algo=2, multi_step=5)
# dealer's initial card value for plotting
# pick a value in the range 1 to 10
dealers_init_val = 10
i = 1
n = 3000 # trials we want to run
wins = 0
random.seed(2016)
while i <= n:
t = 0
T = math.inf # record how many steps until terminate
action = robot.doAction()
while True:
if t < T:
newState, reward, terminate, dealer_final = Environment.doStep(robot, action)
robot.update(new_state=newState, action=action, reward=reward) # update robot state immediately
if terminate:
T = t + 1
if reward == 1:
wins += 1
else:
action = robot.doAction() # update action for next step
updated_step = t - robot.multi_step + 1 # this is the step whose Q-value will be updated in TD algorithm
# update Q value of the robot
robot.updateQ(target_step=updated_step, T=T, new_action=action)
if updated_step == T - 1:
break
t += 1
# pretty output that helps
if n-i < 50:
print("Trial %s: # steps: %d - %s. dealer's final: %d, Reward is: %d" % (i, T, robot, dealer_final, reward))
robot.reset()
i += 1
print("size of robot's Q value dictionary: " + str(len(robot.q)))
print("random exploration times: " + str(robot.explorations) + ", " + str(robot.epsilon))
print("Winning rate: " + str(wins/n))
print(robot.q)
"""Next evaluate robot's performance"""
robot.evaluate_robot()
#plotter.createplot(robot)
plotter.create2dplot(robot, dealers_init_val)
if __name__ == '__main__':
main()
|
68f4042e8952a49f1283a8910f1b138d597592f7 | sLevasseur/Simple-Banking-System | /banking.py | 8,000 | 3.609375 | 4 | import random
import _sqlite3
import re
conn = _sqlite3.connect("card.s3db")
cur = conn.cursor()
cur.execute("DROP TABLE card;")
conn.commit()
# Write your code here
exit_value = True
login_success = False
user_s_choice = 0
id_calc = 1
SELECT_DATA_card_number = "SELECT * FROM card WHERE number = ?;"
SELECT_DATA_pin = "SELECT * FROM card WHERE pin = ?;"
SELECT_DATA_BAlANCE = "SELECT balance from card WHERE number = ?"
INSERT_DATA = "INSERT INTO card (number, pin) VALUES ( ?, ?);"
UPDATE_DATA = "UPDATE card SET pin = ? WHERE pin = ?"
UPDATE_BALANCE = "UPDATE card SET balance = ? WHERE balance = ? AND number = ?"
SELECT_DATA_ACCOUNT = "SELECT number FROM card WHERE number = ?"
DELETE_ACCOUNT = "DELETE FROM card WHERE number = ? AND PIN = ?"
def checking_database_exists():
cur.execute(
"CREATE TABLE IF NOT EXISTS card (id INTEGER PRIMARY KEY AUTOINCREMENT , number TEXT, pin TEXT, balance INTEGER DEFAULT 0 );")
conn.commit()
class CardNumber:
def __init__(self):
self.start_number = str(400000)
self.account_id = ""
self.luhn_number = ""
self.pin = ""
self.checksum = ""
def making_card_number(self):
# making account id
self.account_id += self.start_number
for i in range(0, 9, 1): # generate the id
self.account_id += str(random.randint(0, 9))
list_car_number = [int(i) for i in self.account_id] # put the id in an integer list for processions
for index, _ in enumerate(list_car_number):
if index % 2 == 0:
list_car_number[index] *= 2
if list_car_number[index] > 9:
list_car_number[index] -= 9
check_sum = str((10 - sum(list_car_number) % 10) % 10)
self.account_id += check_sum
conn.commit()
cur.execute(INSERT_DATA, (self.account_id, 0))
conn.commit()
return str(self.account_id)
def making_pin(self):
self.pin = str(random.randint(1000, 9999))
cur.execute(UPDATE_DATA, (self.pin, 0))
conn.commit()
return str(self.pin)
class Action:
def __init__(self, account, current_balance):
self.account = account,
self.current_balance = current_balance
def display_value(self, base_value):
display = "Balance : {}".format(base_value)
return display
def add_income(self, base_value, money_in, money_in_account):
new_value = int(base_value) + money_in
cur.execute(UPDATE_BALANCE, (new_value, base_value, money_in_account))
conn.commit()
return "Income was added !"
def check_transfer(self, account_to_transfer, account_number):
temp_card_number = cur.execute(SELECT_DATA_card_number, (account_to_transfer,)).fetchone()
conn.commit()
final_string = ""
if account_to_transfer == account_number:
final_string = "You can't transfer money to the same account!"
elif Action.luhn_checksum(self, account_to_transfer) is False:
if Action.luhn_checksum(self, account_to_transfer) is False:
final_string = "Probably you made a mistake in the card number. Please try again!"
else:
final_string = "Such a card does not exist."
elif temp_card_number is None:
final_string = "Such a card does not exist."
else:
final_string = "True"
return final_string
def luhn_checksum(self, card_number):
list_car_number = [int(i) for i in card_number] # put the id in an integer list for processions
for index, _ in enumerate(list_car_number):
if index % 2 == 0:
list_car_number[index] *= 2
if list_car_number[index] > 9:
list_car_number[index] -= 9
checksum = sum(list_car_number)
return checksum % 10 == 0
def make_transfer(self, account_to_transfer, money_to_transfer, cash_in_account, account_number):
if money_to_transfer > cash_in_account:
return "Not enough money!"
else:
# get the money in the account to transfer
money_in_account_to_transfer = cur.execute(SELECT_DATA_BAlANCE, (account_to_transfer,)).fetchall()
conn.commit()
money_in_account_to_transfer = int(''.join(map(str, money_in_account_to_transfer[0])))
# update balance in the account to transfer
cur.execute(UPDATE_BALANCE, (money_in_account_to_transfer + money_to_transfer, money_in_account_to_transfer, account_to_transfer))
conn.commit()
# update balance in the source account
cur.execute(UPDATE_BALANCE, (cash_in_account - money_to_transfer, cash_in_account, account_number ))
conn.commit()
print(money_to_transfer)
print(cash_in_account)
print(money_in_account_to_transfer)
return "Success!"
def closing_account(self, number, pin):
cur.execute(DELETE_ACCOUNT, (number, pin))
conn.commit()
return "The account has been closed!"
while exit_value is True:
print("____________________")
print("1. Create an account")
print("2. Log into account")
print("0. Exit")
checking_database_exists()
user_s_choice = int(input())
if user_s_choice == 1:
new_card = CardNumber()
temp_card = str(new_card.making_card_number())
temp_PIN = int(new_card.making_pin())
print("Your card has been created")
print("Your card number:")
print(temp_card)
print("You card PIN:")
print(temp_PIN)
elif user_s_choice == 2:
temp_card = str(input("Enter your card number:"))
temp_PIN = int(input("Enter your PIN:"))
data_card = cur.execute(SELECT_DATA_card_number, (temp_card,)).fetchone()
conn.commit()
pin_from_data_card = int(''.join(map(str, data_card[2])))
if pin_from_data_card != temp_PIN:
print("Wrong card number or PIN!")
else:
print("You have successfully logged in!")
login_success = True
while login_success:
user_balance = cur.execute(SELECT_DATA_BAlANCE, (temp_card,)).fetchall()
conn.commit()
user_balance_int = int(''.join(map(str, user_balance[0])))
print("____________________")
print("1. Balance")
print("2. Add income")
print("3. Do transfer")
print("4. Close account")
print("5. Log out")
print("0. Exit")
user_s_choice = int(input())
new_account = Action(temp_card, user_balance_int)
if user_s_choice == 1:
print(new_account.display_value(user_balance_int))
elif user_s_choice == 5:
print("You have successfully logged out!")
login_success = False
elif user_s_choice == 2:
income_to_add = int(input("Enter income :"))
print(new_account.add_income(user_balance_int, income_to_add, temp_card))
elif user_s_choice == 3:
card_to_transfer = input("Enter card number:")
checking = new_account.check_transfer(card_to_transfer, temp_card) # !!! doesn't work properly !!!
if checking == "True":
money_flow = int(input("Enter how much money you want to transfer:"))
print(new_account.make_transfer(card_to_transfer, money_flow, user_balance_int, temp_card))
else:
print(checking)
elif user_s_choice == 4:
print(new_account.closing_account(temp_card, temp_PIN))
login_success = False
else:
login_success = False
exit_value = False
elif user_s_choice == 0:
exit_value = False
print("Bye!")
conn.close()
|
7a9193eebfd755899628706ccb31b1e233217898 | alecabiz97/AI_Project | /Node.py | 1,777 | 3.921875 | 4 | from copy import copy
class Node:
id = -1
def __init__(self, puzzle=None, parent=None, children=[], depth=0) -> None:
self.puzzle = copy(puzzle) # the state of that node
self.parent = parent # the parent node
self.parent_move = '' # the move has been done from the parent node
self.children = copy(children) # list of all the children nodes
self.path_cost = 0 # cost of the path from the root to this node
self.total_cost = 0 # path cost + heuristic value
self.depth = depth # depth of this node
Node.id += 1
self.id = copy(Node.id) # node id, the first node (root) has id=0
def expand(self):
"""Expand the node, so it fills the list self.children"""
p_children = self.puzzle.calculate_next_configurations() # ex p_children -> [('U',new_puzzle),...]
for move, p in p_children:
n = Node(puzzle=p, parent=self, depth=self.depth + 1)
n.parent_move = move
n.path_cost += self.path_cost + n.puzzle.get_path_cost() # in this case getpath_cost() is always 1
self.children.append(n)
def calculate_path(self):
"""Return the moves from the root node to the target"""
path = []
# if self.parent==None it means that I am the root node because
# I don't have a parent
while self.parent is not None:
path.append(self.parent_move)
self = self.parent
# Reverse the order of the moves from target -> root to root -> target
return path[::-1]
def __str__(self):
return str(self.puzzle)
def __eq__(self, node2):
"""Return true if the state in the two nodes are the same"""
return self.puzzle == node2.puzzle
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.