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 |
|---|---|---|---|---|---|---|
acec3a907ca1975fbc11cd0c7215de858d0f49af | Aasthaengg/IBMdataset | /Python_codes/p02380/s385132831.py | 298 | 3.546875 | 4 | import math
a,b,deg = map(float,input().split(" "))
sindeg = math.sin(math.radians(deg))
S = (a*b*sindeg)/2
cosdeg = math.cos(math.radians(deg))
z = a*a + b*b - 2*a*b*cosdeg
L = a + b + math.sqrt(z)
h = b*sindeg
print("{:.5f}".format(S))
print("{:.5f}".format(L))
print("{:.5f}".format(h))
|
d2ca8acfcba325631de2448dd7611835801cf8d0 | sergeymalinkin/praktikum.yandex.ru | /backend-developer/Основы Python/2. Циклы и ветвления/Множественные ветвления.py | 2,777 | 3.625 | 4 | # Научите Анфису склонять слово «сообщения» в зависимости от их количества:
for messages_count in range(0, 21):
if messages_count > 4:
print('У вас ' + str(messages_count) + ' новых сообщений')
elif messages_count == 0:
print('У вас нет новых сообщений')
elif messages_count == 1:
print('У вас ' + str(messages_count) + ' новое сообщение')
elif messages_count == 2:
print('У вас ' + str(messages_count) + ' новых сообщения')
elif messages_count == 3:
print('У вас ' + str(messages_count) + ' новых сообщения')
elif messages_count == 4:
print('У вас ' + str(messages_count) + ' новых сообщения')
else:
print('У вас нет новых сообщений')
# Анфиса умеет здороваться утром и днём, но ей нужно добавить приветствия для ночи и вечера.
# Напишите условную конструкцию, которая выводит уместные сообщения:
# ВРЕМЯ ТЕКСТ ПРИВЕТСТВИЯ
# до 6 Доброй ночи!
# до 12 Доброе утро!
# до 18 Добрый день!
# до 23 Добрый вечер!
# в остальных случаях - Доброй ночи!
for current_hour in range(0, 24):
print("На часах " + str(current_hour) + ":00.")
if current_hour == 6:
print("Доброе утро!")
elif current_hour == 7:
print("Доброе утро!")
elif current_hour == 8:
print("Доброе утро!")
elif current_hour == 9:
print("Доброе утро!")
elif current_hour == 10:
print("Доброе утро!")
elif current_hour == 11:
print("Доброе утро!")
elif current_hour == 12:
print("Добрый день!")
elif current_hour == 13:
print("Добрый день!")
elif current_hour == 14:
print("Добрый день!")
elif current_hour == 15:
print("Добрый день!")
elif current_hour == 16:
print("Добрый день!")
elif current_hour == 17:
print("Добрый день!")
elif current_hour == 18:
print("Добрый вечер!")
elif current_hour == 19:
print("Добрый вечер!")
elif current_hour == 20:
print("Добрый вечер!")
elif current_hour == 21:
print("Добрый вечер!")
elif current_hour == 22:
print("Добрый вечер!")
else:
print("Доброй ночи!")
|
5a5558b3e02fa45f3db312046d38ea7fb97e2561 | tayadehritik/ChromeExtension | /ICS_Code/is5.py | 800 | 3.734375 | 4 |
# coding: utf-8
# In[23]:
import numpy as np
print("Enter a")
a=int(input())
print("Enter b")
b=int(input())
print("Enter G in x and y")
G=np.array([int(input()),int(input())])
# In[24]:
A=a*G
print("The value of A is ",A)
B=b*G
print("The value of B is ",B)
# In[25]:
key1=B*a
key2=A*b
print("The value of key1 is ",key1)
print("The value of key2 is ",key2)
# In[26]:
key=key1=key2
# In[27]:
print("Enter message in x and y format")
m=np.array([int(input()),int(input())])
# In[28]:
c1=key*G
print("The value of c1 is ",c1)
c2=m+key*B
print("The value of c2 is ",c2)
# In[29]:
decrypt1=c1*b ##c1 and c2 are sent to receiver .He has b
finaldecrypt=c2-decrypt1
print("The value of decrypted message is ",finaldecrypt)
print("The value of original message is ",m)
|
a1c0402c58018d9bc220af7401ce69b9cd4b02b7 | bopopescu/Python-13 | /Cursos Python/Python 3 Básico ao avançado - Geek University/tipo_none.py | 315 | 4.0625 | 4 | """
Tipo none
O tipo de dado none em python representa o tipo sem tipo, ou como tipo vazio, porém
Quando utilizamos?
- Podemos utilizar none quando queremos criar uma variavel e inicializa-la com um tipo sem tipo, antes
de recebermos qualquer valor final.
"""
numeros = None
print(numeros)
print(type(numeros))
|
8d53cd089c94bb75edcaed5fa4707a00222b2f7c | SheepSnail/PythonTest | /Q1.py | 494 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def valid_password(pwd):
if pwd[0].isalpha():
if pwd[-1].isalpha() or pwd[-1].isdigit():
if len(pwd) >= 2 and len(pwd) <= 10:
for x in pwd:
if x.isalpha() or x.isdigit() or x == '_':
pass
else:
return False
return True
return False
pwd = input('password:')
print(valid_password(pwd))
|
fc330841149195728e8a80a7f7a636b3f699371f | FiratCeylan32/BUS232-Test-2-submission | /BUS232 Test 2 submission FIRAT CEYLAN v1.py | 2,483 | 4.1875 | 4 | #function for reading input, and returns a list of shares
def read():
#list for shares
shares = []
#runs until share is 0, to exit
share = None
while share != 0:
#prompting and reading shares
share = int(input("Please enter the number of shares: "))
#if input is invalid
if share < 0:
print("Invalid input!")
#adding share to shares list
elif share != 0:
shares.append(share)
return shares
#sort function, returns sorted list of shares, in descending order
def sort(shares):
#sorting shares list using built-in sorted function
return sorted(shares, reverse=True)
#totalShares function, returns total shares in shares list
def totalShares(shares):
#calculating sum of shares in shares list using built-in sum
return sum(shares)
#shareHolders functions, number of top shareholder needed
def shareHolders(shares, requiredShares):
#sorting shares list using sort function
shares = sort(shares)
#variable for storing count of shareholders
count = 0
total = 0
#iterating over shares list
for share in shares:
#incrementing total by adding share to it
total += share
#increment count by 1
count += 1
#if total reached requiredShare, returns count
if total >= requiredShares:
return count
#main program
#calling read() function
shares = read()
#calculating and printing total shares
total = totalShares(shares)
print(f"Thank you, there is a total of {total} shares represented here.")
#calculating requried shares to win
requiredShares = total//2 + 1
print(f"Shares needed for majority vote is {requiredShares}.")
#calling shareHolders function, to count top required shareholders
topShareHolders = shareHolders(shares, requiredShares)
print(f"You need the support of top {topShareHolders} shareholders for this number of votes.")
#bonus
#creating and opening text file named "Apple" in write mode
with open("Apple.txt", 'w') as file:
#writing data to text file using wite method of file object(file)
file.write(f"Thank you, there is a total of {total} shares represented here." + "\n")
file.write(f"Shares needed for majority vote is {requiredShares}." + "\n")
file.write(f"You need the support of top {topShareHolders} shareholders for " +
"this number of votes.")
|
b1761c86bebe6e6fd0891270da82d7906be8dca0 | ekohilas/google-kickstart-2017 | /round_f/a/io.py | 539 | 3.578125 | 4 | def worst_case(n, l):
s_l = sorted(l)
mid = l.pop((n-1)//2)
while l:
if mid == s_l[0]:
s_l.pop(0)
elif mid == s_l[-1]:
s_l.pop()
else:
return "NO"
mid = l.pop((len(l)-1)//2)
return "YES"
def print_cases(func):
for i in range(1, int(input())+1):
n = int(input())
l = list(map(int, input().split()))
output = func(n, l)
print("Case #{}: {}".format(i, output))
if __name__ == "__main__":
print_cases(worst_case)
|
e9edfe9c5584644d102fd303bd7609bdae8b6d92 | SocialFinanceDigitalLabs/AdventOfCode | /solutions/2020/pughmds/day06/Day 6 - Part 2.py | 1,443 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
testData = """
abc
a
b
c
ab
ac
a
a
a
a
b
"""
def parseData(textInput):
# Each group is split by two newlines
groups = textInput.split("\n\n")
for num, g in enumerate(groups):
groups[num] = g.split("\n") # Split group's answers into a list
groups[num] = list(filter(None, groups[num])) # Get rid of any stray empty elements
if len(groups[num]) > 1:
# If there's more than one person in the group, we find the intersection of the sets of characters
for idx, item in enumerate(groups[num]):
groups[num][idx] = set(item)
groups[num] = set(''.join(sorted(set.intersection(*groups[num]))))
else:
# Otherwise, we just turn the one answer into a set of characters
groups[num] = set (''.join (groups[num]).replace (',', '') )
return groups
def openFile(filename):
with open (filename, "r") as dataFile:
data = parseData(dataFile.read())
return data
def countSets(groupData):
count = 0
for g in groupData:
count += len(g)
return count
#Test Run
groupData = parseData(testData)
groupCount = countSets(groupData)
print("Test Data: whole-group 'yes' answers: %d " % (groupCount))
#Real Run
groupData = openFile("day6.txt")
groupCount = countSets(groupData)
print("Live Data: whole-group 'yes' answers: %d " % (groupCount))
|
3f240cb21b812f57feab58f271d9d189cdd26b06 | vrushtipateUSA/AutomationRepo | /Drivers/string/string(4.1).py | 323 | 4.28125 | 4 | str = "vrushti and jigar are celebrating a party"
word = str.split()
largest = small = word[0]
for i in range (len(word)):
if len(largest) < len(word[i]):
largest = word[i]
if len(small) > len(word[i]):
small = word[i]
print("largest word in string", largest)
print("small word in string", small)
|
0290790cac70736e8ba3cd77a628c0269e5f6a65 | omriz/coding_questions | /390.py | 582 | 3.75 | 4 | #!/usr/bin/env python3
import typing
def find_missing(num_list: typing.List[int]) -> typing.List[int]:
# O(nlog(n)) - in place, but we can sacrafice space for not in place
num_list.sort()
missing = []
if num_list[0] != 1:
i = 1
while i < num_list[0]:
missing.append(i)
i += 1
# O(n)
for i in range(1, len(num_list)):
if num_list[i] - num_list[i - 1] == 1:
continue
x = num_list[i - 1] + 1
while x < num_list[i]:
missing.append(x)
x += 1
return missing
|
3628fe7db6fba7cdaa1117434cf5c24378ed4584 | navyifanr/LeetCode-Source | /LeetCode-Py/Array/[88]合并两个有序数组.py | 2,452 | 3.5 | 4 | # 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
#
# 请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
#
# 注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m 个元素表示应合并
# 的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
#
#
#
# 示例 1:
#
#
# 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
# 输出:[1,2,2,3,5,6]
# 解释:需要合并 [1,2,3] 和 [2,5,6] 。
# 合并结果是 [1,2,2,3,5,6] ,其中斜体加粗标注的为 nums1 中的元素。
#
#
# 示例 2:
#
#
# 输入:nums1 = [1], m = 1, nums2 = [], n = 0
# 输出:[1]
# 解释:需要合并 [1] 和 [] 。
# 合并结果是 [1] 。
#
#
# 示例 3:
#
#
# 输入:nums1 = [0], m = 0, nums2 = [1], n = 1
# 输出:[1]
# 解释:需要合并的数组是 [] 和 [1] 。
# 合并结果是 [1] 。
# 注意,因为 m = 0 ,所以 nums1 中没有元素。nums1 中仅存的 0 仅仅是为了确保合并结果可以顺利存放到 nums1 中。
#
#
#
#
# 提示:
#
#
# nums1.length == m + n
# nums2.length == n
# 0 <= m, n <= 200
# 1 <= m + n <= 200
# -10⁹ <= nums1[i], nums2[j] <= 10⁹
#
#
#
#
# 进阶:你可以设计实现一个时间复杂度为 O(m + n) 的算法解决此问题吗?
# Related Topics 数组 双指针 排序 👍 1235 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
idx1 = m - 1
idx2 = n - 1
idx = m + n - 1
while idx1 >= 0 and idx2 >= 0:
if nums1[idx1] >= nums2[idx2]:
nums1[idx] = nums1[idx1]
idx1 -= 1
else:
nums1[idx] = nums2[idx2]
idx2 -= 1
idx -= 1
while idx2 >= 0:
nums1[idx] = nums2[idx2]
idx -= 1
idx2 -= 1
return nums1
# leetcode submit region end(Prohibit modification and deletion)
|
c76730d51f314d0a9a3590551c4911bdb1735246 | cnphuyen0601/pythonProject1 | /compute.py | 730 | 3.53125 | 4 | listt = [
{"type": "Square", "area": 150.5},
{"type": "Rectangle", "area": 80},
{"type": "Rectangle", "area": 660},
{"type": "Circle", "area": 68.2},
{"type": "Triangle", "area": 20}
]
class Geometry:
x = 5
def __init__(self, type, area):
self.type = type
self.area = area
def get_type(self):
return self.type #return type of geometry
def get_area(self):
return self.area #return the area of geometry
g1 = Geometry("Square", 150.5)
g2 = Geometry("Rectangle", 80)
g3 = Geometry("Rectangle", 660)
g4 = Geometry("Circle", 68.2)
g4 = Geometry("Triangle", 20)
for i in range(len(listt)):
print(f'{i+1}- {listt[i]["type"]} with area size {listt[i]["area"]}') |
346c650be79d39d4fe6f2709a9aa6e4bfed30590 | KanwalSaeed/Logical_Operational_Python | /19. LOGICAL OPERATOR IN PYTHON.py | 1,149 | 4.25 | 4 | # and Logical AND "if both the operands are true then condition become true" (a and b) is true
# "lOGIN CREDENTIAL"
user_name = input("Enter User Nmae: ")
pass_word = input("Enter password: ")
if user_name == "Admin" and pass_word == "Admin":
print("Login sucessfully")
else:
print("You have entered wrong User Name or Password")
# or Logical OR "if any two of operand are non zero then condition become true" (a or b) is true
degree = input("Enter your BS Degree: ")
if degree == "cs" or "CSE":
print("You are eligible.")
else:
print("Yu are n't eligible.")
percentage = int(input("Enter your percentage: "))
city = input("Enter your city: ")
if percentage > 70 and city == "Karachi" or city == "Lahore":
print("Congrates, you are selected for Job.")
else:
print("Sorry, You are n't selected.")
# not Logical NOT "used to reverse the logical state of its operand" NOT (a and b ) is false
is_valid = True
city = input("Enter your city name: ")
if city == "Lahore":
is_valid = False
if not is_valid:
print("You are not eligible to apply here")
else:
print("You are eligible and yoou can apply. ") |
ca4bff50c2d20c491e3e76ee4af6bd4d32bcacb0 | jackfrostwillbeking/atcoder_sample | /ABC/python/109/B.py | 277 | 3.53125 | 4 | import sys
N = int(input())
array_word = [ input() for word in range(N) ]
before = array_word[0]
for I in array_word[1:]:
if before[-1] == I[0] and array_word.count(I) == 1:
before = I
continue
else:
print('No')
sys.exit()
print('Yes') |
631e45ad1ef27dc8aec5b3a062fa431f9bc946a3 | adamwmeek/python-sand-pile | /ToppleRules/BasicToppleRule.py | 1,707 | 3.9375 | 4 | """ Defines how columns end up in topple condition and how this effects the state """
import copy
class BasicToppleRule:
def will_topple(self, cols, x_pos, y_pos):
""" In this example, a column will topple if height > 4 """
height = cols[x_pos][y_pos]
return height >= 4
def has_topples(self, cols, size):
for i in range(size):
for j in range(size):
if self.will_topple(cols, i, j):
return True
return False
def num_topples(self, cols, size):
num = 0
for i in range(size):
for j in range(size):
if self.will_topple(cols, i, j):
num = num + 1
return num
def topple_cols(self, cols, size):
new_cols = copy.deepcopy(cols)
for i in range(size):
for j in range(size):
if self.will_topple(cols, i, j):
new_cols[i][j] = 0
for k in range(-1, 2):
neighbor_x = i + k
list_range = [0]
if k == 0:
list_range = [-1, 1]
for l in list_range:
neighbor_y = j + l
if neighbor_x >= size or neighbor_x < 0:
# Don't move this grain OOB or back onto the start
continue
if neighbor_y >= size or neighbor_y < 0:
continue
new_cols[neighbor_x][neighbor_y] = new_cols[neighbor_x][neighbor_y] + 1
return new_cols
|
ebdbd87b771c4581f083366f6a626a07d459936f | AmitAps/advance-python | /instance_class_and_static_method/second_class.py | 305 | 3.578125 | 4 | class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
# def __repr__(self):
# return f'Pizza({self.ingredients!r})'
def __repr__(self):
return 'Pizza(%r)' % self.ingredients
"""
>>> Pizza(['cheese','tomotoes'])
Pizza(['cheese', 'tomotoes'])
"""
|
a975cc5f2f278f089ea98165e26cc39b043ddea8 | arjungirish/hello-world | /first1.py | 378 | 4.21875 | 4 | # hello-world
user_temp = input("Please enter the temperature in Celsius that you want to convert to Farenheit: ")
def converter(number_in_c):
return number_in_c * 9 / 5 + 32
if user_temp is float:
number_in_f = converter(user_temp)
print("Here is your temperature in Farenheit: ")
print(number_in_f)
else:
print("Sorry, your temperature is not valid")
|
22d7fa76f904a0ac5061338e9f90bb3b9afd5d41 | Pasquale-Silv/Improving_Python | /Python Programming language/DataCampPractice/Corso_CISCO_netacad/Lists/list4.py | 288 | 3.734375 | 4 | # A four-column/four-row table - a two dimensional array (4x4)
table = [[":(", ":)", ":(", ":)"],
[":)", ":(", ":)", ":)"],
[":(", ":)", ":)", ":("],
[":)", ":)", ":)", ":("]]
print(table)
print(table[0][0]) # outputs: ':('
print(table[0][3]) # outputs: ':)'
|
6055419061cc2e444f4c0fd671672a3b4e605cbf | Anjitha-Sivadas/luminarpythonprograms | /FUNCTIONAL PROGRAMMING/demo.py | 1,863 | 4.46875 | 4 | #camellin notation--used in java,js
#addTwonumbers()
#snake notation--python
#add_twonumbers()
#normal function.....
"""
def add(num1,num2):
return num1+num2
"""
#lambda fn--anonymous fn
add=lambda num1,num2: num1+num2
print(add(100,200))
sub=lambda num1,num2:num1-num2
print(sub(50,20))
cube=lambda num:num*3
print(cube(5))
#map()--condition that affect all the values
#filter()--extract some specific condition---condition that dosnt affect all the values
#reduce()--reduce and provide a single value
# these are predefined fns
#map()
# pass 2 arguments
# 1.which fn we should apply for each object
# 2.on which object we want to apply the fn
#calculate square of each num
lst=[10,20,30,21,22]
# squ=[]
# for num in lst:
# res=num**2
# print(res)
# squ.append(res)
# print(squ)
"""
def squ(no):
return no**2
squares=list(map(squ,lst))
print(squares)
"""
squares=list(map(lambda no:no**2,lst))
print(squares)
cubes=list(map(lambda no:no**3,lst))
print(cubes)
#filter()......................................................................................
#filter(fn,iterables)
even=list(filter(lambda num:num%2==0,lst))
print(even)
lst=["akhil","akshay","varun","vipin","aravind","ram"]
anames=list(filter(lambda name:name[0]=="a",lst))
print(anames)
#reduce()
lst=[10,20,30,50,80]
from functools import reduce
#map() and filter() are located builtin fn.
#reduce is located in functools
total=reduce(lambda no1,no2:no1+no2,lst)
print(total)
#terminary operator
# if (no1>no2):
# return no1
# else:
# return no2
# n1 if n1>n2 else n2
#highest elemnt.....................................................................
max=reduce(lambda no1,no2:no1 if no1>no2 else no2,lst)
print(max)
min=reduce(lambda no1,no2:no1 if no1<no2 else no2,lst)
print(min)
lst=[1,2,3,4]
squares=[num**2 for num in lst]
print(squares)
|
55b10d987cf5d406d4d52165453cebb307a46d04 | JM-Duval/P7_AlgoInvest-Trade | /optimized_2.py | 2,709 | 3.71875 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# This script is an algorithme in order to find the optimal combination of action to get maximum gain
import time
import csv
import pandas as pd
import numpy as np
class AlgoDynamique:
def __init__(self, row_data, capacity):
self.row_data = row_data
self.capacity = capacity * 100
def check_data(self, row_data):
data = row_data[~(row_data[:,1]<=0)] # delete line with number 0
return data * 100 # to run the script without float number
def profit(self, index):
return int (index[1] * index[2] )
def results(self, matrice):
data = self.check_data(self.row_data)
w = self.capacity
n = len(data)
action_selected = []
while w >= 0 and n >= 0: # tant que la capacité est >= à 0 et que nous n'avons pas parcourus tout les éléments
element = data[n-1]
if matrice[n][int(w)] == matrice[int(n-1)][int(w-element[1])] + self.profit(element):
action_selected.append(element)
w -= element[1]
n-=1
total_cost = 0
total_profit = 0
nb_letter_name = len(row_data[0][0]) # we do this because we have multiplied all data per 100
name_actions = []
for i in action_selected:
total_cost += i[1] / 100
total_profit += (i[1] / 100 * i[2] / 100 / 100)
name_actions.append(i[0][:nb_letter_name])
#print(name_actions)
for action in name_actions:
print(' ',action)
print('total cost', round(total_cost,2))
print('total profit', round(total_profit,2))
#answer = str(round(answer, 2))
def algo(self):
data = self.check_data(self.row_data)
matrice = [[0 for x in range (int((self.capacity + 1) ))] for x in range(len(data) + 1)]
colomns = len(matrice[0])
lines = len(matrice)
for i in range(1, lines): # ligne
for x in range(1, colomns): # colonne
if data[i-1][1] <= x: # si le prix de l'élément courant est inférieur à la capacité
matrice[i][x] = max( matrice[i-1][x] , # valeur de la ligne précédante
matrice[i-1][int(x - data[i-1][1])] + # matrice[i-1][capacité - poids de l'élément courant => place qui reste dispo]
self.profit(data[i-1]))# valeur de mon element courant
else:
matrice[i][x] = matrice[i-1][x] # on garde la valeur de i-1
return matrice
def run(self):
start = time.time() # calculate the working time of the program
self.results(self.algo())
end = time.time()
elapsed = end - start
print(f"Temps d'execution :{round(elapsed,2)} s.")
file_dataset1 = 'dataset1_Python+P7.csv'
file_dataset2 = 'dataset2_Python+P7.csv'
dt = pd.read_csv(file_dataset2)
df = pd.DataFrame(dt)
row_data = df.to_numpy()
budget = 500
algo_dataset = AlgoDynamique(row_data, budget)
algo_dataset.run()
|
6b5e103edc244317f6f4727f0bc8885f4d7f723b | emanoelmlsilva/ExePythonBR | /Exe.Funçao/Fun.12.py | 198 | 3.703125 | 4 | from random import shuffle
def embaralha(palavra):
lista=list(palavra)
shuffle(lista)
palavra= "".join(lista)
return palavra
nome = input("Informe a palavra desejada: ")
print(embaralha(nome))
|
a721a21237af3da774b0c1c062d4be6fc7d9be6e | yodirh/Data-Analysis-with-python | /part02-e13_diamond/src/diamond.py | 284 | 3.5 | 4 | #!/usr/bin/env python3
import numpy as np
def diamond(n):
i = np.eye(n, dtype=int)
m= i[:,1:]
j = np.concatenate((i[::-1],m), axis=1)
k= j[::-1]
l=np.concatenate((j,k[1:,]))
return l
def main():
print(diamond(4))
if __name__ == "__main__":
main()
|
f63ce555eb51095cba28a4cb333dd0e472a404b7 | jhgdike/leetCode | /leetcode_python/1-100/23.py | 2,724 | 3.734375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x, next=None):
self.val = x
self.next = next
def __gt__(self, other):
return self.val > other.val
def __lt__(self, other):
return self.val < other.val
def __eq__(self, other):
return self.val == other.val
def __ge__(self, other):
return self.val >= other.val
def __le__(self, other):
return self.val <= other.val
from operator import attrgetter
import heapq
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
heap = []
for curr in lists:
if curr:
heapq.heappush(heap, curr)
head = pre = None
while heap:
cur = heap[0]
if not head:
pre = head = cur
else:
pre.next = cur
pre = cur
cur = cur.next
if cur:
heapq.heapreplace(heap, cur)
else:
heapq.heappop(heap)
return head
def arr_to_list(nums):
if not nums:
return
origin = ListNode(nums[0])
l = origin
for num in nums[1:]:
l.next = ListNode(num)
l = l.next
return origin
s = Solution()
s.mergeKLists([
arr_to_list([1, 4, 5]),
arr_to_list([1, 3, 4]),
arr_to_list([2, 6])])
from operator import attrgetter
class Solution1:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
sorted_list = []
for head in lists:
curr = head
while curr is not None:
sorted_list.append(curr)
curr = curr.next
sorted_list = sorted(sorted_list, key=attrgetter('val'))
for i, node in enumerate(sorted_list):
try:
node.next = sorted_list[i + 1]
except:
node.next = None
if sorted_list:
return sorted_list[0]
else:
return None
"""time limit exceeded"""
class _Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
root = ListNode(0)
if not lists:
return root
root.next = lists[0]
for i in range(1, len(lists)):
self.merge_two(root, lists[i])
return root.next
def merge_two(self, node, node1):
while node.next and node1:
if node1.val < node.next.val:
tmp = node.next
node.next = node1
node1 = tmp
node = node.next
if node.next is None:
node.next = node1
|
945ad5eb50f5ff0a3034464bd97ff2968589b660 | mruga30/Network-Protocol | /client.py | 6,686 | 3.6875 | 4 | #CS 544-Computer Networks
#Developer: Mruga Shah
#6/7/2019
#This file contains the client side programming of the protocol that sends messages to the server.
#It also talks to the user and gets details like hostname/IP and crededntials.
#
#STATEFUL
import random
import struct
import pickle
import hashlib
from socket import *
sid =0
bool1 =0
bool2=0
serverName = input("Connect to(Server Name/IP):") #prompts the user to enter the name/IP of the machine they want to connect to
serverPort = 13000 #default server port
clientSocket = socket(AF_INET,SOCK_STREAM) #TCP connection
clientSocket.connect((serverName,serverPort)) #connect to the server with the serverName provided by the user
#STATE: INITIAL CLIENT STATE (NO CONNECTION)
#The following code sends a random number to the server and recieves another random number from the server to
#calculate a session id that will be used throughout this session of communication between the client and the server.
#Session Id = server_random*client_random
random_int = random.randint(1,100) #3rd field containing the random number sent by the client
cl = list(b'Client') #2nd field containing the string "Client"
comms = 0 #4th field that tells what stage (DFA state) is the system in
var = struct.pack(b'BBBBBBii', cl[0], cl[1], cl[2], cl[3], cl[4], cl[5], random_int, comms) #create the PDU
msg = [len(var),0,var] #add the 1st field that is the length of the data to the PDU
final_msg = pickle.dumps(msg)
clientSocket.send(final_msg) #send the message (PDU) to the server
mod_var = clientSocket.recv(12000) #recieve the reply from server
a = struct.unpack(b'6sii',mod_var)
if (a[2]==1 and a[0].decode('ascii')=='Server'): #if the state changes to 1 on the server and the message is from the server, the session is established
sid = random_int*a[1] #session id is calculated. It is equal to Client_Random_No*Server_Random_No
#print("Session Established...",sid)
comms = 1 #if everything went right change the state
else:
print("No connection established,try again...") #Else, throw error
comms = 0 #No change in state
#STATE: SESSION ESTABLISHED
#The following code makes sure that the server side and the client side are using the same protocol version.
#For our purposes, we have hardcoded the version number.
version = 10 #client protocol version
error_bit = 0
if comms ==1:
var1 = struct.pack('iiii', sid, version, comms, error_bit) #create PDU for sending out the client protocol version. Use sessiod id from above
#print(len(var1),var[0],var[1],var[2],var[3])
msg1 = [len(var1),1,var1] #In PDU,add the first field as the length of the message
final_msg1 = pickle.dumps(msg1)
clientSocket.send(final_msg1) #send PDU
mod_var1 = clientSocket.recv(12000) #recieve from server
a1 = struct.unpack('iiii',mod_var1)
if a1[2]==2 and error_bit==0: #if the state changes to 2 in server and the error_bit is not 1 implies that the versio was negotiated correctly
#print("Version Negotiated...")
#print(sid)
comms = 2 #if everything went right, change the state
else: #else,throw Version error
print("Version Mismatch...")
#STATE: VERSION NEGOTIATED
#The following code gets from the user their credentials and sends across the hash of those credentils for verification by the server.
#If the credentials cannot be verified,it throws an error and terminates the session.
if comms==1: #if the version did not change, terminate the session
print("Session Terminated Abruptly!")
else: #else, go on to authentication
username = input('Please enter your username:') #ask the user for their credentials
pwd = input('Please enter the password:')
cred = username+pwd #combine username,password into a string
m = hashlib.sha224(cred.encode('ascii')).hexdigest() #calculate the hash
var2 = struct.pack('iii', sid, error_bit,comms) #create the PDU
#print(len(var2))
msg2 = [len(var2),2,m,var2] #add the first field to the PDU i.e. the length of the message
final_msg2 = pickle.dumps(msg2)
clientSocket.send(final_msg2) #send the PDU
#print(m,len(m))
mod_var2 = clientSocket.recv(12000) #recieve reply from server
a2 = struct.unpack('iii',mod_var2)
if a2[2]==3 and error_bit==0: #if the state changes to 3 on the server and the error bit is not set(there is no error)
#print("Authenticated...")
comms = 3 #change the state
else:
print("Authenciation Error...") #else throw an error
#STATE: AUTHENTICATED
#The following code sends a list of algorithm names for the server to select from.
#It makes sure that the server selects one and only algorithm from the list.
if comms ==2:
print("Session Terminated Abruptly!") #if the user was not authenticated, terminate the session
else:
md = list(b'MD5')
sh = list(b'SHA1')
var3 = struct.pack(b'iBBBiBBBBii', sid, md[0], md[1], md[2], bool1, sh[0], sh[1], sh[2], sh[3], bool2, comms) #create the PDU
#print(len(var3))
msg3 = [len(var3),3,var3] #add the first field, length
final_msg3 = pickle.dumps(msg3)
clientSocket.send(final_msg3) #send the PDU
mod_var3 = clientSocket.recv(12000) #receive the reply from the PDU
a3 = struct.unpack(b'i3si4sii',mod_var3)
#print(a3[0],a3[2],a3[4],a3[5])
if a3[5]==4 and a3[2]!=a3[4]: #if the server changes the state, and the second condition is that one of the two algorithms is selected by the server
#print("Algorithm Selected")
print("Successful Negotiation...")
comms = 4 #change the state
else:
print("Not negotiated correclty...") #else, throw an error
print("Session Terminated Abruptly!")
#STATE: HASH ALGORITHM SELECTED
#The folowing code sends a termination message to the server. It also makes sure that the new session id is set to 0 on the server side.
new_sid = sid #initialize a new session id to the current session id. It should change to 0 by the end of the session
if comms == 3:
print("Session Terminated Abruptly!") #if the algorithm was selected incorreclty, terminate session
else:
var4 = struct.pack('iii',sid,comms,new_sid) #create PDU
msg4 = [len(var4),4,var4] #add first field, length
final_msg4 = pickle.dumps(msg4)
clientSocket.send(final_msg4) #send the PDU
mod_var4 = clientSocket.recv(12000) #recieve reply from server
a4 = struct.unpack('iii',mod_var4)
if a4[1]==5 and a4[2]==0: #if the server changes the state to 5 and the new session id is set to 0
print("Session Terminated...") #Session is terminated correctly
else:
print("Session Terminated Abruptly!") #Else,terminated abruptly
clientSocket.close() #close the connection
#STATE: INITIAL CLIENT STATE(TERMINATED CONNECTION)
|
149a7187f213016d3cfcf8c1e8a682e26cce6865 | mariaciornii/26.11.20 | /problema.2.py | 286 | 3.5625 | 4 | persoana = str(input('Introduceti numele si prenumele: '))
if (ord(persoana[0]) in range(65,91)) and (ord(persoana[persoana.find(' ')+1]) in range(65,91)):
print('Da, numele si pronumele a fost scris corect')
else:
print('Nu, numele si pronumele a fost scris gresit')
|
1f52b64eb7fa8ca83d64e2f7f18849088cd4b677 | agankur21/food-classification-deep-learning | /code/concatenate_features.py | 343 | 3.5625 | 4 | import pandas as pd
def read_file(file_path,num_columns):
df = pd.read_csv(file_path, sep=",",names=range(num_columns))
return df
def concatenate_df(df1,df2):
out = pd.merge(df1,df2,how='inner',on=0)
return out
def write_df(merged_table,out_file):
merged_table.to_csv(out_file, header=False,index=False)
|
8a19f2910ff31c4572a1d98ae447f292d02a3416 | vrashi/python-coding-practice | /lineareq.py | 805 | 3.640625 | 4 | #matrices
a = [[0 for x in range(2)] for y in range(2)]
#print("enter the coefficient of x and y of first equation and then 2nd equation")
tmp = [1, 1, 2, 4]
#temp = input("enter the coefficient of x and y of first equation and then 2nd equation")
#tmp = temp.split()
for i in range(2):
for j in range(2):
a[0][i] = tmp[j]
a[1][0] = 2
a[1][1] = 4
print(a)
a_inverse = [[0 for x in range(2)] for y in range(2)]
D1 = a[0][0]*a[1][1]
D2 = a[0][1]*a[1][0]
D = 1/(D1 - D2)
a_inverse[0][0] = D*a[1][1]
a_inverse[0][1] = -D*a[0][1]
a_inverse[1][0] = -D*a[1][0]
a_inverse[1][1] = D*a[0][0]
print (a_inverse)
b = [4, 10]
#b = input("enter RHS")
x = [0, 0]
p = (a_inverse[0][0]*b[0])
q = (a_inverse[0][1]*b[1])
x[0] = p + q
r = (a_inverse[1][0]*b[0])
s = (a_inverse[1][1]*b[1])
x[1] = r + s
print (x)
|
fa9f7819c2603e673ee85d278bc713d95196e61a | paintthetiger/boilerplate | /missing_integer.py | 408 | 3.59375 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
check = set()
max_value = 0
for el in A:
if el > max_value:
max_value = el
check.add(el)
candidate = 1
while candidate != max_value:
if candidate not in check:
return candidate
candidate += 1
return max_value + 1
|
831d6005d0a98a1e7a1125ac5612d84f6d32efca | Aasthaengg/IBMdataset | /Python_codes/p02701/s532611579.py | 138 | 3.640625 | 4 | from collections import Counter
N = int(input())
S = []
for i in range(N):
s = input()
S.append(s)
S = Counter(S)
print(len(S)) |
fbcc1dbdc48ae6a6eb929e1edabf8ff1fdf687aa | huffmp2/python | /restaurant.py | 812 | 4.1875 | 4 | class Restaurant():
"""A simple attempt to model a restaurant."""
def __init__(self, name, cuisine):
"""Initialize name and age attributes."""
self.name = name
self.cuisine= cuisine
self.numberserved= 0
def what(self):
"""Talk about the restaurant."""
print(self.name.title() + " is a " + self.cuisine + " restaurant.")
def open(self):
"""Announce the restaurant is open."""
print(self.name.title() + " is now open.")
def customers(self):
"""Detail the number served."""
print("This restaurant has served " + str(self.numberserved) + " customers.")
def updatenumberserved(self, people):
"""Update the number of customers served."""
self.numberserved= people
def incrementnumberserved(self, newpeople):
"""Add new customers."""
self.numberserved+= newpeople |
84abb4bfb7516d6c522f75c8eac8e0d6957d246b | fahmida185/Datacamp- | /Web Scraping/Scraping.py | 2,135 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
html = '''
<html>
<head>
<title>Intro HTML</title>
</head>
<body>
<p>Hello World!</p>
<p>Enjoy DataCamp!</p>
</body>
</html>
'''
# HTML code string
html = '''
<html>
<body>
<div class="class1" id="div1">
<p class="class2">Visit DataCamp!</p>
</div>
<div class="you-are-classy">
<p class="class2">Keep up the good work!</p>
</div>
</body>
</html>
'''
# Print out the class of the second div element
whats_my_class( html )
"""
Adding in attributes isn't supposed to be hard, but helps give character to HTML code and at times how it's rendered online.
"""
<html>
<head>
<title>Website Title</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="class1" id="div1">
<p class="class2">
Visit <a href="http://datacamp.com/">DataCamp</a>!
</p>
</div>
<div class="class1 class3" id="div2">
<p class="class2">
Or search for it on <a href="http://www.google.com">Google</a>!
</p>
</div>
</body>
</html>
"""
Both div elements belong to the class class1 (even though the second div element also belongs to class3), and both have an a element as a descendant (in this case, a grandchild). So, this direction points to two href attributes, the first is the desired URL, the second is http://www.google.com.
"""
<html>
<body>
<div>
<p>Good Luck!</p>
<p>Not here...</p>
</div>
<div>
<p>Where am I?</p>
</div>
</body>
</html>
"""
Where am I?
"""
xpath = '/html/body/div[2]/p[1]'
# Fill in the blank
"""
sing double forward-slash notation, assign to the variable xpath a simple XPath string navigating to all paragraph p elements within any HTML code
//table directed to all table elements with the HTML.
"""
xpath = '//p'
"""
xpath an XPath string which will select all span elements whose class attribute equals "span-class"
Remember that //div[@id="uid"] selects all div elements whose id attribute equals uid
"""
# Fill in the blank
xpath = '//span[@class="span-class"] |
df6618689e1fc8feaa4edbcf9a0996530c51839c | jalongod/LeetCode | /85.py | 1,891 | 3.734375 | 4 | '''
85. 最大矩形
给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-rectangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
'''
动态规划
dp[i][j] 以i,j为右下角的最大的矩形的面积
dp[0][0]==1 if m[0][0]=='1' else 0
[1:][1:]
dp[i][j]=
'''
class Solution:
def largestRectangleArea(self, h) -> int:
if len(h) == 0:
return 0
min_index = h.index(min(h))
leftLarge = self.largestRectangleArea(h[:min_index])
midLarge = h[min_index] * len(h)
rightLarge = self.largestRectangleArea(h[min_index + 1:])
return max(leftLarge, midLarge, rightLarge)
def maximalRectangle(self, m) -> int:
if not m:
return 0
height, width = len(m), len(m[0])
val = [[0 for _ in range(width)] for __ in range(height)]
res = 0
for j in range(width):
for i in range(height):
cur_val = 0 if m[i][j] == '0' else 1
if i == 0 or cur_val == 0:
val[i][j] = cur_val
else:
val[i][j] = val[i - 1][j] + cur_val
for i in range(len(val)):
res = max(res, self.largestRectangleArea(val[i]))
return res
sol = Solution()
res = sol.maximalRectangle([["0", "1"], ["1", "0"]])
# res = sol.maximalRectangle([["1", "0", "1", "0",
# "0"], ["1", "0", "1", "1", "1"],
# ["1", "1", "1", "1", "1"],
# ["1", "0", "0", "1", "0"]])
print(str(res))
|
abfa37bca07317def3accafeaf6e525aadd56324 | 01708712/Assessment2 | /question2/question2.py | 1,844 | 4.21875 | 4 | '''
question2.py
Fix the errors so that this code runs when called
from the test file and passes all tests.
TOTAL POINTS AVAILABLE: 5
Code Functionality (5)
5 points - no errors remain and code runs
4 points - only 1 error remains
1-3 points - multiple errors remain
0 points - all original errors remain or new ones introduced
'''
def decode_word(input_word):
'''Returns the string of an emoticon for a given string. Returns an empty
string if input is not a known string.
see https://en.wikipedia.org/wiki/List_of_emoticons for more about
emoticons'''
emoji_code = {'smiley':':-)', 'skeptical':':-8', 'frown':':-(',
'crying':':`-(', 'surprise':':-O', 'wink':';-)', 'kiss':':-*',
'tongue':':-P', 'horror':'D-:'}
# strip word and make lower case
input_word = input_word.strip().lower()
# check if word is valid emoticon code
if input_word not in emoji_code.keys():
# return empty string
return ''
# return the decoded word
return emoji_code.get(input_word,)
def word_to_emoticon(input_string):
'''Takes in a string containing a sequence of words and
returns a string where any of the words that can be represented
by an emoticon are replaced with that emoticon.'''
# create list of words from the string splitting at ' '
input_list = input_string.split(' ')
# create string to be returned
decoded_string = input_string
# go through list of words
for word in input_list:
# decode each word into its emoticon
decoded_word = decode_word(word)
# replace the word with the returned emoticon
if decoded_word != '':
decoded_string = decoded_string.replace(word,str(decoded_word))
# return new string of emoticons
return decoded_string |
dea1994ce9621e179a35f92f24df8aad76ee0600 | Erniejie/python-with-TIM_Python-Generators_Iterators_Part-1_Examples | /2021-09-19_Python_Generators_Part 1_Iterators&Examples.py | 2,030 | 4.5 | 4 | #Python Generators Explained
#Tech With Tim_yt- Aug 3,2021
#Part 1:Iterators
import sys
#Example 7: Creating Legacy Iterators
"Example 7: Making your own iterator using old legacy syntaxis "
class Iter:
def __init__(self,n):
self.n = n
def __iter__(self):
self.current = -1
return self
def __next__(self):
self.current += 1
if self.current >= self.n:
raise StopIteration
return self.current
x = Iter(19)
#for i in x:
# print(i)
itr = iter(x)
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
"""
"Example 6: iterator using <iter> function "
x = range(1,13)
print(next(iter(x)))
"""
"""
"Example 5: iterator for loop = iterator while loop"
x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14] # list
y = map(lambda i: i**2,x)
#A:For Loop
for i in y:
print(i)
#B: While Loop
while True:
try:
value = next(y)
print(value)
except StopIteration:
print("Done")
break
# A == B
"""
"""
"Example 4: Example 3 using dunder methods(doubleunderscore)"
x = [1,2,3,4,5,6,7,8,9,10,11] # list
y = map(lambda i: i**2,x)
print(y.__next__())
print("For Loop starts from here:")
for i in y:
print(i)
"""
""""
"Example 3: How an Iterator works:"
x = [1,2,3,4,5,6,7,8,9,10,11] # list
y = map(lambda i: i**2,x)
# special function : next
print(next(y))
print(next(y))
print(next(y))
print(next(y))
print("For Loop starts from here:")
for i in y:
print(i)
"""
"""
"Example 2: for loop- NO storying the sequence"
x = [1,2,3,4,5,6,7,8,9,10,11] # list
y = map(lambda i: i**2,x)
for i in y:
print(i)
"""
"""
"Example 1: no loop- storing the sequence"
x = [1,2,3,4,5,6,7,8,9,10,11] # list
y = map(lambda i: i**2,x)
print(list(y))
"""
|
cc30f26dbb75bfd21238bc6d2e343989326720ed | aidanrfraser/CompSci106 | /makePairs.py | 547 | 3.8125 | 4 | from cisc106 import assertEqual
animalWeights = {}
Animals = ['Lion', 'Cat', 'Dog', 'Cow', 'Snake', 'Person', 'Pig', 'Bird', 'Wombat', 'Hamster']
Weights = [420, 9, 70, 2400, 250, 137, 770, 10, 88, 0.5]
def make_pairs(alist, blist):
"""
Pairs alist and blist into a dictionary, alist and blist must have an equal amount of elements.
"""
if not alist:
return animalWeights
else:
animalWeights[alist[0]] = blist[0]
return make_pairs(alist[1:], blist[1:])
assertEqual(make_pairs([2], [3]), {2:3}) |
7b1e217165946ab89fa15d1d4208cdba289286c9 | noozip2241993/learning-python | /csulb-is-640/notes/quiz4.py | 256 | 3.828125 | 4 | my_list = ['a', 'b', 'c', 'd', 'a']
print(my_list.count('a'))
my_list_2 = my_list[::-1]
print(my_list)
print(my_list_2)
color = ('red')
color = 'red', 1
print(type(color))
print(color)
numbers = [1,2,3,4,5,6,7,8]
print(numbers[2:6])
print(numbers)
pass |
1ac10bc72a529d014958495adbc3ca3184ccbd89 | hritikralhan/Spychat | /pop1.py | 5,181 | 3.6875 | 4 | from spy_details import spy
print 'Hello!'
print 'Let\'s get started..'
STATUS_MESSAGES = ['Available','Busy','Sleeping','Typing','At School']
friends = [{'name' : 'Deep', 'age': 20,'rating':5.8,'is online':True },{'name' : 'Kavish', 'age': 19,'rating':4.5,'is online':True }]
def add_status(C_S_M):
if C_S_M !=None:
print 'Your current status is' + C_S_M
else:
print "You don't have status currently"
user_choice = raw_input("Do you want to select from old status? Y or N : ")
if user_choice.upper() == 'Y':
serial_no = 1
for old_status in STATUS_MESSAGES:
print str(serial_no) + ". " + old_status
serial_no = serial_no +1
user_status_selection = input('Which one do you want to set this time?')
new_status = STATUS_MESSAGES[user_status_selection-1]
elif user_choice.upper() == 'N':
new_status = raw_input('Write your status: ')
STATUS_MESSAGES.append(new_status)
else:
print 'Invalid Entry'
return new_status
def add_friend():
frnd = {
'name': ' ',
'age': 0,
'rating': 0.0,
'is_online': True
}
frnd['name'] = raw_input("Write your frnd's name: ")
frnd_sal = raw_input(' Mr or Miss: ')
frnd['name'] = frnd_sal + " " + frnd['name']
frnd['age'] = input('Write the age of your frnd: ')
frnd['rating'] = input('Write the rating of frnd: ')
if len(frnd['name'])>=2 and 50>frnd['age']>=12 and frnd['rating'] >= spy['rating']:
friends.append(frnd)
else:
print "Friend with these values cannot be added "
return len(friends)
def select_frnd():
serial_no = 1
for frnd in friends:
print str(serial_no) + " " + frnd[ 'name']
serial_no = serial_no + 1
user_selected_frnd = input('Which one you want to send or raed message from ? ' )
user_index= friends [user_selected_frnd-1]
return user_index
def send_message():
selected_frnd = select_frnd()
message = raw_input('What is your secret message? ')
original_iamge = raw_input('What is the name of your image? ')
output_path = 'output.png'
Steganography.encode(original_iamge,output_path,message)
print 'Message encrypted'
def read_message():
chosen_frnd = select_frnd()
output_path=raw_input("name of image to be decoded: ")
secret_text = Steganography.decode(output_path)
print 'Your secret message is ' + secret_text
def start_chat(spy_name,spy_age,spy_rating):
current_status_message = None
show_menu = True
while show_menu:
menu_choice = input('What do you want to do? \n 1. Add a status \n 2. Add a friend \n 3. Send a message \n 4. Read a Message \n 0. Exit \n')
if menu_choice==1 :
updated_status_message = add_status(current_status_message)
print 'Your new status is updated to '+ updated_status_message
elif menu_choice==2:
no_of_frnds = add_friend()
elif menu_choice==3:
selected_frnd= select_frnd()
print 'We are going to send message to ' + friends[selected_frnd()]
print "I have " + str(no_of_frnds) + " friends."
elif menu_choice==4:
read_message
elif menu_choice==0:
show_menu= False
else:
print 'Invalid choice'
question = raw_input('Are you a new user? Y or N: ')
if question.upper() == 'N':
print 'We already have your details'
start_chat(spy['name'],spy['age'],spy['rating'])
elif question.upper() =='Y':
spy = {
'name':'' ,
'age':0 ,
'rating':0.0 ,
'is_online': True
}
spy['name'] = raw_input('What is your name? ')
if len(spy['name'])> 3:
print 'Welcome ' + spy['name'] + ' glad to meet you'
spy_salutation = raw_input('What should i call you Mr or Miss or Mrs?')
spy['name'] = spy_salutation + " " + spy['name']
print 'Alright' + " " + spy['name'] + " " + 'i would like to know little more about you before we proceed...'
spy['age'] = input('What is your age? ')
if spy['name']>12 and spy['name']<50:
print 'You age is perfect to be a spy.'
spy['rating'] = input('What is rating of spy? ')
if spy['rating']>=5.0:
print 'Great spy'
elif spy['rating']<5.0 and spy['rating']>=4.5:
print 'You are one of the good ones.'
elif spy['rating']<4.5 and spy['rating']>=3.5:
print'Fine spy'
else:
print 'Useless spy'
spy_status_online = True
print 'Authentication complete. Welcome ' + spy['name'] + ' age: ' + str(spy['age']) + ' and rating of: ' + str(spy['rating']) + ' Proud to have you onboard'
start_chat(spy['name'], spy['age'], spy['rating'])
else:
print 'You age is not perfect to be a spy. '
else:
print 'Please enter valid name'
else:
print 'Invalid Entry'
|
59c1a347bf6c4c647b382b0b20194f9c641f3c45 | StivDC/AOC_2019 | /Chuzzy_Code/day01.py | 490 | 3.984375 | 4 | def fuel_needed_for_mass(mass):
return int(mass) // 3 - 2
def fuel_needed_for_module(mass):
fuel = fuel_needed_for_mass(mass)
if fuel < 7:
return fuel
else:
return fuel + fuel_needed_for_module(fuel) # A recursive solution because Im epic
# Part 1
with open("day01input.txt", "r") as f:
print(sum([fuel_needed_for_mass(mass) for mass in f]))
# Part 2
with open("day01input.txt", "r") as f:
print(sum([fuel_needed_for_module(mass) for mass in f]))
|
599ba13c99683bba249397cbf453595f3ae68a97 | orihasam810/NLPfromScratch | /count_vec.py | 3,116 | 3.609375 | 4 | import re
'''
テキストデータを扱いやすくするための前処理
・文字を小文字に統一
・カンマ、ピリオド、ダッシュ等の記号を分割
'''
def preprocess(text):
#テキストを全て小文字に統一する
text = text.lower()
#文末のピリオド、セミコロンを削除
text = re.sub('[.;]', '', text)
#単語ごとに分割してリストに格納
words = text.split(' ')
return words
'''
重複なしの単語リストを作成
'''
def mktuple(texts):
#重複なしタプルを作成する
words_tp = tuple(set(texts))
return words_tp
def txt2num(text, word_list):
#テキストに含まれる単語数の要素を持つリストを作成
num_text = [0] * len(text)
#各テキスト中にある単語が含まれる位置を返す
for i in range(len(word_list)):
num = [j for j, x in enumerate(text) if x == word_list[i]]
for n in num:
num_text[n] = i
return num_text
'''
単語出現頻度カウントによるベクトルの作成
'''
def count(all_words_num, id_text):
#記録用のテーブルを作成
table = [[0] * all_words_num for i in range(all_words_num)]
for k in id_text:
num_k = len(k)
for l in range(num_k):
element = table[k[l]]
if l == 0:#文章の開始単語の場合、右側単語のみを調べる
right = k[l+1]
element[right] += 1
elif l == num_k-1:#文章の終了単語の場合、左側単語のみを調べる
left = k[l-1]
element[left] += 1
else:#文章の途中の単語の場合、両側を調べる
left = k[l-1]
right = k[l+1]
element[left] += 1
element[right] += 1
return table
def main():
text1 = 'You can’t connect the dots looking forward;'
text2 = 'you can only connect them looking backwards.'
text3 = 'So you have to trust that the dots will somehow connect in your future.'
texts = []
id_text = []
text_list = [preprocess(text1), preprocess(text2), preprocess(text3)]
#入力テキストをご順を保持して表示
print('---入力テキスト---')
for t in text_list:
print(t)
#全テキストを連結したテキストを作成
for text in text_list:
texts += text
#重複なしの単語のタプルを作成
word_list = mktuple(texts)
all_words_num = len(word_list)#重複なし全単語数
#重複なしリストを表示
print('---単語一覧---')
print(word_list)
#単語をIDにに変換
for text in text_list:
id_text.append(txt2num(text, word_list))
#注目単語周りの単語の出現回数をカウント(ベクトル作成)
table = count(all_words_num, id_text)
#ベクトルの表示
print('---分散表現---')
for tbl in range(len(table)):
print(word_list[tbl] + ' : ', table[tbl])
if __name__ == '__main__':
main()
|
e4721b895c441be05ab35cfa0a29845b327b31a0 | idamini/python3 | /1_62re_pslit_groups.py | 198 | 3.65625 | 4 | import re
text ='''Paragraph one
on two lines.
paragraph two.
paragraph three.'''
print('with split:')
for num,para in enumerate(re.split(r'\n{2,}',text)):
print(num,repr(para))
print()
|
3983261276ad735bbd7f36eebd8ae06fe1df4b11 | cheol-95/Algorithm | /Python/117. 스택 상태/Stack_status.py | 382 | 3.609375 | 4 | stack = []
count = 0
input_size = int(input())
for i in range(input_size):
command = int(input())
if command == 1:
try:
stack.pop()
except:
print('underflow')
elif command == 0:
if len(stack) == 10:
print('overflow')
else:
tmp = input()
stack.append(tmp)
print(int(tmp))
else:
break
if stack:
print(' '.join(stack)) |
435d2354fba1c77b190eda85f978761008212e09 | RakeshKumar045/Artificial_Intelligence_Complete_1 | /Artificial_Intelligence/Complete_AI_DS_ML_DL_NLP/Complete-DS-ML-DL-PythonInterview/algorithms-master/sorting_algorithms.py | 1,669 | 4.28125 | 4 | '''
Implement sorting algorithms.
'''
def selection_sort(L):
'''
Sort `L` array in ascending order.
'''
sorted_array = []
for _ in range(len(L)):
# Use element at position 0 as a starting point
smallest_element = L[0]
smallest_index = 0
for i in range(1, len(L)):
if smallest_element > L[i]:
smallest_element = L[i]
smallest_index = i
# Add element to sorted_array and delete it from the input array L
sorted_array.append(L.pop(smallest_index))
return sorted_array
def quick_sort(L):
'''
Sort `L` array in ascending order using first element of an array as the
pivot.'''
# empty array or array with length zero is a sorted array
if len(L) < 2:
return L
else:
# Choose first element as pivot that will divide L into two sub-arrays
pivot = L[0]
left = [e for e in L[1:] if e <= pivot]
right = [e for e in L[1:] if e > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
def quick_sort_2(L):
'''
Sort `L` array in ascending order using random element from the array as
the pivot.'''
L = list(L)
import random
# empty array or array with length zero is a sorted array
if len(L) < 2:
return L
else:
# Choose first element as pivot that will divide L into two sub-arrays
pivot_index = random.randint(0, len(L))
pivot = L[pivot_index]
L.remove(pivot)
left = [e for e in L if e <= pivot]
right = [e for e in L if e > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
|
d741d349e6b0cbe6a647dae12b71e816f4e39404 | DainDwarf/AdventOfCode | /2015/Day8/day8.py | 1,817 | 3.625 | 4 | #!/usr/bin/python3
from __future__ import print_function
# That's handy, the Advent of Code gives unittests.
def UnitTest():
# Beware, we need some escaping of escaping sequences to test!
ex1 = '""'
ex2 = '"abc"'
ex3 = '"aaa\\"aaa"'
ex4 = '"\\x27"'
print("Unit test for Part One.")
print("Test {inp} has representation's length {r} but in-memory length {m}".format(inp=ex1, r=len(ex1), m=len(eval(ex1))))
print("Test {inp} has representation's length {r} but in-memory length {m}".format(inp=ex2, r=len(ex2), m=len(eval(ex2))))
print("Test {inp} has representation's length {r} but in-memory length {m}".format(inp=ex3, r=len(ex3), m=len(eval(ex3))))
print("Test {inp} has representation's length {r} but in-memory length {m}".format(inp=ex4, r=len(ex4), m=len(eval(ex4))))
print("All four inputs gives total difference {res}".format(res=partOne('\n'.join([ex1, ex2, ex3, ex4]))))
print("")
print("Unit test for Part Two.")
print("All four inputs need {res} more to encode.".format(res=partTwo('\n'.join([ex1, ex2, ex3, ex4]))))
def partOne(inp):
return sum(len(s) - len(eval(s)) for s in inp.split('\n'))
def partTwo(inp):
return sum(s.count('"') + s.count('\\') + 2 for s in inp.split('\n'))
if __name__ == '__main__':
from argparse import ArgumentParser, FileType
args = ArgumentParser()
args.add_argument("-t", "--test", help='Unit tests', action='store_true')
args.add_argument("-i", "--input", help='Your input file', type=FileType('r'))
options = args.parse_args()
if options.test:
UnitTest()
if options.input:
inp = options.input.read().strip()
print("Answer for part one is : {res}".format(res=partOne(inp)))
print("Answer for part two is : {res}".format(res=partTwo(inp)))
|
a4f114ffb592c97a954c933c2a3b3d91f09cead4 | eduDevCF/learndo | /helper.py | 9,885 | 3.65625 | 4 | from model import *
from flask import session
def add_class(teacher, class_name):
"""Create a new class in db and add the teacher to the class"""
new_class = Class(class_name=class_name)
db.session.add(new_class)
db.session.commit()
new_class.users.append(teacher)
db.session.commit()
return new_class.class_id
def show_classes(teacher):
"""Creates a dictionary of class name and list of student objects for each class_id
associated with a teacher. Used for printing a list of all the classes for a teacher.
Example:
{class_id: {'class_name': class_name, 'students': [<student object>, <student object>]}}
"""
class_list = {}
for each_class in teacher.classes:
class_list[each_class.class_id] = {'class_name' : each_class.class_name }
for student in each_class.users:
if student.is_teacher == 0:
if 'students' not in class_list[each_class.class_id]:
class_list[each_class.class_id]['students'] = []
class_list[each_class.class_id]['students'].append(student)
return class_list
def json_classes(teacher):
"""Creates a dictionary of class name and list of student objects for each class_id
associated with a teacher. Used for printing a list of all the classes for a teacher.
Example:
{class_id: {'class_name': class_name, 'students': [<student object>, <student object>]}}
"""
class_list = {}
for each_class in teacher.classes:
class_list[each_class.class_id] = {'class_name' : each_class.class_name }
for student in each_class.users:
if student.is_teacher == 0:
if 'students' not in class_list[each_class.class_id]:
class_list[each_class.class_id]['students'] = {}
class_list[each_class.class_id]['students'][student.user_id] = { 'first' : student.display_name,
'last' : student.last_name,
'username' : student.username }
return class_list
def list_teachers(student_id):
"""Returns a list of teachers associated with that student"""
student = User.query.get(student_id)
teachers = []
if student.is_teacher == 0:
for each_class in student.classes:
for user in each_class.users:
if user.is_teacher == 1:
teachers.append(user.user_id)
return teachers
def access_profile(user_id):
"""Does the user_id in session match the user_id in the route?
Or does the user_id belong to that student's teacher?"""
user = User.query.get(user_id)
teachers = list_teachers(user_id)
if session.get('user_id') == user_id:
return True
else:
for teacher_id in teachers:
if session.get('user_id') == teacher_id:
return True
return False
## No longer needed after restructing data model
# def find_class_by_task(task_id):
# """Finds class name given the task id so it can be displayed on the task page"""
# task = Task.query.get(task_id)
# teacher_id = task.created_by
# teacher = User.query.get(teacher_id)
# list_of_classes = teacher.classes
# class_dictionary = {} # key = class_id, value1 = class_name, value2 = student_ids_list
# for c in list_of_classes:
# class_dictionary[c.class_id] = { 'name' : c.class_name, 'users' : [] }
# for user in c.users:
# class_dictionary[c.class_id]['users'].append(user.user_id)
# class_dictionary[c.class_id]['users'].sort()
# assignment_list = Assignment.query.filter(Assignment.task_id == task_id).all()
# assigned_users = []
# for assignment in assignment_list:
# assigned_users.append(assignment.student_id)
# assigned_users.sort()
# for c in class_dictionary:
# if class_dictionary[c]['users'] == assigned_users:
# assigned_class = class_dictionary[c]['name']
# return assigned_class
def report_student_progress(task, assignment_list):
"""Generates a dictionary of students associated with the task's assignment and
their progress status. The student_id is the key and the values are first, last,
assigned, viewed, completed, overdue."""
student_progress = {}
now = datetime.now()
for assignment in assignment_list:
if not assignment.user.is_teacher:
student_id = assignment.student_id
first_name = assignment.user.first_name
last_name = assignment.user.last_name
assigned = assignment.assigned.strftime("%A %m/%d/%y %I:%M %p")
if assignment.viewed:
viewed = assignment.viewed.strftime("%A %m/%d/%y %I:%M %p")
else:
viewed = None
if assignment.completed:
completed = assignment.completed.strftime("%A %m/%d/%y %I:%M %p")
overdue = False
else:
completed = None
due_date = task.due_date
if now > due_date:
overdue = True
else:
overdue = False
student_progress[student_id] = { 'first' : first_name,
'last' : last_name,
'assigned' : assigned,
'viewed' : viewed,
'completed' : completed,
'overdue' : overdue }
return student_progress
def create_assignment_list(assignments_list):
"""Generates a dictionary with all the info needed for the assignment list feature."""
assignments = { 'list' : [] }
if session['acct_type'] == 'student':
for assignment in assignments_list:
to_add = {}
to_add['id'] = assignment.assign_id
to_add['ad'] = (assignment.assigned - datetime(1970,1,1)).total_seconds()
dd = (assignment.task.due_date - datetime(1970,1,1)).total_seconds()
to_add['dd'] = dd + float("."+str(assignment.task_id))
to_add['title'] = assignment.task.title
to_add['goal'] = assignment.task.goal
to_add['due_date'] = assignment.task.due_date.strftime("%A %m/%d/%y %I:%M %p")
to_add['assigned_by'] = db.session.query(User.display_name).filter(
User.user_id == (assignments_list[0].task.created_by)).first()[0]
to_add['assigned_on'] = assignment.assigned.strftime("%A %m/%d/%y %I:%M %p")
to_add['status'] = check_student_status(assignment)
assignments['list'].append(to_add)
if session['acct_type'] == 'teacher':
for task in assignments_list:
quantity = Assignment.query.filter(Assignment.task_id == task.task_id).all()
to_add = {}
if len(quantity) > 0:
assignment = Assignment.query.filter(Assignment.task_id == task.task_id,
Assignment.student_id == task.created_by).one()
to_add['id'] = task.task_id
to_add['ad'] = (assignment.assigned - datetime(1970,1,1)).total_seconds()
dd = (assignment.task.due_date - datetime(1970,1,1)).total_seconds()
to_add['dd'] = dd + float("."+str(assignment.task_id))
to_add['title'] = task.title
to_add['goal'] = task.goal
to_add['due_date'] = task.due_date.strftime("%A %m/%d/%y %I:%M %p")
to_add['assigned_to'] = task.assigned_class.class_name
to_add['assigned_on'] = assignment.assigned.strftime("%A %m/%d/%y %I:%M %p")
to_add['status'] = check_class_status(assignment)
assignments['list'].append(to_add)
else:
to_add['id'] = task.task_id
to_add['ad'] = 2000000000 + task.task_id
dd = (task.due_date - datetime(1970,1,1)).total_seconds()
to_add['dd'] = dd + float("."+str(task.task_id))
to_add['title'] = task.title
to_add['goal'] = task.goal
to_add['due_date'] = task.due_date.strftime("%A %m/%d/%y %I:%M %p")
to_add['assigned_to'] = 'no class yet'
to_add['assigned_on'] = 'no set date'
to_add['status'] = 'inactive'
assignments['list'].append(to_add)
return assignments
def check_student_status(assignment):
"""Checks assignment object for status as viewed, completed, or overdue."""
if assignment.viewed:
if assignment.completed:
status = 'completed'
elif datetime.now() > assignment.task.due_date:
status = 'overdue'
else:
status = 'viewed'
else:
status = 'inactive'
return status
def check_class_status(assignment):
"""Checks assignment object for status as viewed, completed, or overdue."""
status = 'inactive'
if assignment.assigned:
student_assignments = Assignment.query.filter(Assignment.task_id == assignment.task_id).all()
for assignment in student_assignments:
if assignment.student_id != session['user_id']:
if assignment.completed == None:
if datetime.now() > assignment.task.due_date:
status = 'overdue'
break
else:
status = 'viewed'
break
elif assignment.completed:
status = 'completed'
return status
|
2688f72610c07200a47bcbec59c28580917002bb | piratte/MLE-exercises | /HW1/big_diff.py | 791 | 3.53125 | 4 | import unittest
"""
function implementing the http://codingbat.com/prob/p184853 exercise
"""
def big_diff(nums):
try:
return reduce(max, nums) - reduce(min, nums)
except NameError: # reduce not available in python3
maxim = nums[0]
minim = nums[0]
for num in nums:
minim = num if num < minim else minim
maxim = num if num > maxim else maxim
return maxim - minim
class TestFrontTimes(unittest.TestCase):
def test_basic(self):
self.assertEqual(big_diff([10, 3, 5, 6]), 7)
self.assertEqual(big_diff([7, 7, 6, 8, 5, 5, 6]), 3)
self.assertEqual(big_diff([5, 1, 6, 1, 9, 9]), 8)
def test_small(self):
self.assertEqual(big_diff([6]), 0)
if __name__ == '__main__':
unittest.main() |
8af5b645a1bf565f29d9c85d1f79ce4cfcae96e6 | Palash51/Python-Programs | /program/thirty2.py | 263 | 3.984375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
meal = float(input())
tip = input()
tax = input()
total_Cost = meal + (tip*meal)/100 + (tax*meal)/100
print "The total meal cost is"+ " " + str(int(round(total_Cost))) + " dollars"
|
87cbb0568320f917b4c0cf2eed521b4892d5ef72 | Anjali-M-A/Code | /Code_7jump.py | 1,636 | 4.0625 | 4 | # Python code to implement Jump Search
"""
** Time complexity - O(√n)
** Input :
# Sorted array - arr
# x - search value
# step - jump size
# n - length of array
**Importatnt Points:
# Works only sorted arrays
# The time complexity of Jump Search is between Linear Search ((O(n)) and Binary Search (O(Log n))
*(O(Log n)) > O(√n) > ((O(n))
"""
#math module is used to access mathematical functions in the Python
import math
def jumpSearch( arr , x , n ):
# Finding block size to be jumped
step = math.sqrt(n)
# Finding the block where element is present (if it is present)
first = 0
# while loop to do something as long as the condition is met
# min() function returns the smallest of the input values
while arr[int(min(step, n)-1)] < x:
first = step
step = step + 1
# Doing a linear search for x in block beginning with first.
while arr[int(first)] < x:
first = first + 1
# If we reached next block or end of array,
# element is not present.
if first >= min(step, n):
return -1
# If element is found
if arr[int(first)] == x:
return first
return -1
# input or pre-requirements
arr = [ 1,2,3,4,5,6,7,8,9 ]
x = 4
n = len(arr)
# Find the index of 'x' using Jump Search
index = jumpSearch(arr, x, n)
# Print the index where 'x' is located
print("Number" , x, "is at index" ,"%.0f"%index)
print("Number" , x, "is at index" , + index)
|
b270bbe282427391e75ae6fe871484ec4a64195a | vvalorous/generic-similarity-search | /src/main/python/generic_similarity_search/index/index_row.py | 780 | 3.578125 | 4 | class IndexRow(object):
"""
Encapsulates one row within an index.
Clients are supposed to create index row objects based on lines of data.
"""
def __init__(self, pass_throughs: dict, dimensions: dict):
self.pass_throughs = pass_throughs
"""
Dictionary of arbitrary name:str and value:str pairs, e.g. for reference (IDs) or convenience.
A word of caution: the current implementation stores everything in memory!
Pass through values are not used to calculate distances.
"""
self.dimensions = dimensions
"""
Dictionary of name:str and value:float pairs.
Dimension values are used to calculate distances.
Dimension value names MUST correspond with weight names.
"""
|
2c720e5c551e16b438ed0a5f94e7b640e5e33ff7 | RichardJ16/Cormen-Introduction-To-Algorithms | /Chapter-2/Merge-Sort.py | 1,117 | 3.828125 | 4 | # Worst-Case Run-Time = O(n*log(n))
# Worst-Case Space-Complexity = O(n)
def MergeSort(A):
L, R = split(A)
if len(L) > 1:
MergeSort(L)
if len(R) > 1:
MergeSort(R)
i = 0
j = 0
k = 0
while i < len(L) and j < len(R):
if L[i] <= R[j]:
A[k] = L[i]
i = i+1
else:
A[k] = R[j]
j = j + 1
k +=1
while i < len(L):
A[k] = L[i]
i += 1
k += 1
while j < len(R):
A[k] = R[j]
j += 1
k += 1
return A
def split(Array):
split = len(Array) // 2
return Array[:split], Array[split:]
def Problems():
arr = [1, 2, 3, 4, 5]
arr2 = [5, 4, 3, 2, 1]
arr3 = [2, 3, 4, 5, 7, 2, 7, 3, 0, 1]
arr4 = [3, 1, 2, 4]
print("Problem 1", arr)
RunProblems(arr)
print("Problem 2", arr2)
RunProblems(arr2)
print("Problem 3", arr3)
RunProblems(arr3)
print("Problem 4", arr4)
RunProblems(arr4)
def RunProblems(Array):
print("Sorted", MergeSort(Array))
Problems() |
b7f574939e256370ddeb9db0b3c5905b8ddf6858 | bokukko7/AOJ_AtCoder | /AtCoder/ABC170/D-2.py | 597 | 3.515625 | 4 | def readinput():
n=int(input())
a=list(map(int,input().split()))
return n,a
def main(n,a):
maxa=10**6
isprime=[True]*(maxa+1)
sa=sorted(a)
prevx=0
for x in sa:
if isprime[x]==False:
continue
if prevx==x:
isprime[x]=False
continue
i=x*2
while(i<=maxa):
isprime[i]=False
i+=x
prevx=x
count=0
for x in sa:
if isprime[x]==True:
count+=1
return count
if __name__=='__main__':
n,a=readinput()
ans=main(n,a)
print(ans)
|
88c837950242c0a2944d63af1746c78c384c8929 | RotemBH/first_project | /leetcode_exe/arrays_and_list/roman_to_number.py | 758 | 3.59375 | 4 | """
turn roman number to integer
"""
class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
roman_number = 0
_index = 0
while _index < len(s):
if _index+1 < len(s) and s[_index:_index+2] in roman:
roman_number+= roman[s[_index:_index+2]]
_index+=2
else:
roman_number+= roman[s[_index]]
_index+=1
return roman_number
test = Solution()
assert test.romanToInt('III') == 3
assert test.romanToInt('IV') == 4
assert test.romanToInt('IX') == 9
assert test.romanToInt('LVIII') == 58
assert test.romanToInt('MCMXCIV') == 1994 |
008f23dcea5b9d4d726a03088bdd7441d493f0af | calebs77/01-IntroductionToPython | /src/m6_your_turtles.py | 1,803 | 3.703125 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Aaron Wilkin, their colleagues, and Caleb Shen.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# DONE: 2.
# You should have RUN the m5e_loopy_turtles module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOU WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT-and-PUSH when you are done with this module.
#
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
leonardo = rg.SimpleTurtle('turtle')
leonardo.pen = rg.Pen('green', 2)
leonardo.speed = 15
size = 150
for k in range(20):
leonardo.draw_circle(size)
leonardo.pen_up()
leonardo.forward(20)
leonardo.right(60)
leonardo.pen_down()
size = size - 4
window.tracer(100)
michaelangelo = rg.SimpleTurtle('square')
michaelangelo.pen = rg.Pen('blue', 2)
michaelangelo.forward(25)
for k in range(450):
michaelangelo.right(65)
michaelangelo.forward(k)
window.close_on_mouse_click() |
4260e297cfae7e03262df16983a6424c97750537 | satirskiy/silver-cat | /homework6.py | 443 | 3.984375 | 4 | while True:
day = 1
firstday = float(input("Введите результат в первый день:"))
result = float(input("Введите финальный результа:"))
if firstday <= 0 or result <= 0:
print("Вы ввели не верное значетие!")
else:
while result > firstday:
firstday += firstday * 0.1
day += 1
print(day)
break
|
b292cad4b4886e472aeee6dcdb07c9609e32765b | ALREstevam/Curso-de-Python-e-Programacao-com-Python | /Resolução de problemas II/liersGame.py | 1,138 | 3.59375 | 4 | import random
class Dices:
def roll(self, dices):
dices = []
for i in range(dices):
dices.append(random.randint(1,6))
return dices
def print(self, dices):
for dice in dices:
print('[{:2}], '.format(dice), end='')
print('\n')
class HumanPlayer:
def __init__(self, nome):
self.nome = nome
self.dices = 5
def takeAction(self, isFirstRound):
if isFirstRound
class Npc0:
def __init__(self):
i = 0
class Game:
def __init__(self):
ph = HumanPlayer('Teste')
npcA = Npc0()
npcB = Npc0()
npcC = Npc0()
self.players = [ph, npcA, npcB, npcC]
self.qtdPlayers = len(self.players)
self.playerRound = 0
self.isFirstRound = True
def nextRound(self):
self.playerRound = (self.playerRound + 1) % self.qtdPlayers
def play(self):
while True:
self.players[self.playerRound].takeAction(self.isFirstRound)
self.nextRound()
if self.isFirstRound == True:
self.isFirstRound == False
|
3367f58e097a6a907b114b93c307ca54efc051f7 | BatLancelot/PFund-Jan-Apr-2021-Retake | /07-02-Dictionaries-Exercise/02-A-Miner-Task.py | 550 | 3.796875 | 4 | data_dict = {}
while True:
resource = input()
if resource == 'stop':
break
quantity = int(input())
if resource not in data_dict:
data_dict[resource] = 0
data_dict[resource] += quantity
# elif data.isalpha():
# if data not in data_dict:
# data_dict[data] = 0
# current_key = data
# elif data.isdigit():
# data_dict[current_key] += int(data)
# else:
# print('Wrong data')
for resource, quantity in data_dict.items():
print(f'{resource} -> {quantity}')
|
6363e9d4755fa502e92363d515c16bf96e8ab748 | Refuse0126/My-Python-Code | /Practice/case4.py | 1,194 | 3.90625 | 4 | """
面向对象的猜数字游戏
Date:2019.5.17
"""
class game():
def __init__(self,start,end):
self.start=start
self.end=end
self.cnt=0
self.done=False
def randomint(self):
from random import randint
self.anwser=randint(self.start,self.end)
def check(self,temp):
if temp==self.anwser:
self.yes()
self.done=True
elif temp>self.anwser:
self.more()
self.cnt+=1
else:
self.less()
self.cnt+=1
def yes(self):
print('恭喜你,只猜了%d次就猜对啦!'%self.cnt)
def more(self):
print('好可惜呀,有点大了!再试一次吧')
def less(self):
print('好可惜呀,有点小了!再试一次吧')
def main():
start=int(input('请输入游戏边界上限:'))
end=int(input('请输入游戏边界下限:'))
g=game(start,end)
g.randomint()
print('开始游戏吧!我已经准备好啦')
while True:
temp=int(input('你猜有多大'))
g.check(temp)
if g.done:break
print('游戏结束,byebye')
if __name__ == "__main__":
main()
|
09c153e99c001c094a7f25f6be259fbad6236ae1 | JohnMai1994/CS116-2018_Winter_Term | /CS116/a02-j4mai/a02-j4mai/a02q1.py | 1,739 | 3.71875 | 4 | ##===============================================
## Jiadong Mai (20557203)
## CS 116 Winter 2018
## Assignment 02, Question 1
##===============================================
import check
import math
# Question 1
## earned_grade(assts, mid_exam, final_exam, clickers, tutorials) returns the
## basic grade based on the grading scheme, 20% Assts, 30% mid_exam, 45% final_exam
## 5% for clickers and tutorials times.
## earned_grade: Float, Float, Float, Float, Int => Int
## Require:
## assts, mid_exam, final_exam and clickers are floating point value between
## 0 and 100 (inclusive)
## tutorials is natural number between 1 and 12 (inclusive)
## Examples:
## earned_grade(60.0, 55.8, 40.0, 55.5, 9) => 45
## earned_grade(10.0, 5.0, 40.0, 12.0, 0) => 22
def earned_grade(assts, mid_exam, final_exam, clickers, tutorials):
assts_rate = 0.2
mid_rate = 0.3
final_rate = 0.45
part_rate = 0.05
exam_average = (mid_rate * mid_exam + final_rate * final_exam) /75
grade = (assts_rate * assts) + (mid_rate * mid_exam) +\
(final_rate * final_exam) + min(5, (part_rate*clickers) + 0.1*tutorials)
if exam_average >= 0.5:
return round(grade)
else:
return round(min(45, grade))
## Test1: exam average less than 50%, the grade is higher than 45
check.expect("Q1Test1", earned_grade(60.0,55.8,40.0,55.5,9), 45)
## Test2: exam average less than 50%, the grade is less than 45
check.expect("Q1Test2", earned_grade(10.0, 5.0, 40.0, 12.0, 0), 22)
## Test3: exam average higher than 50%, the grade is less than 45
check.expect("Q1Test3", earned_grade(0, 51, 51, 0, 0), 38)
## Test4: exam average higher than 50%, the grade is higher than 45
check.expect("Q1Test4", earned_grade(100, 100, 100, 100, 12), 100)
|
1d6efcd73c607a6261bfe769c13069ac288a8508 | rafa-acioly/circuitpy | /circuitpy/base.py | 2,476 | 3.78125 | 4 | import abc
from typing import Tuple
class Storage(abc.ABC):
@abc.abstractmethod
def increment(self, key: str) -> None:
"""Increment
Should increment a value to
keep track of how many errors
occurs so the circuit breaker can open
"""
pass
@abc.abstractmethod
def expire(self, key: str, ttl: int) -> None:
"""Expire
Should set a time to live (ttl) on the key,
the key should automatically vanish after the ttl defined
"""
pass
@abc.abstractmethod
def get(self, key: str) -> int:
"""Get
Should retrieve the value for the
failure_key
"""
pass
class BaseCircuitBreaker(abc.ABC):
@abc.abstractmethod
def storage(self) -> Storage:
"""Storage
Should retrieve a instance of Storage
that will be used to keep the circuit breaker
status
"""
pass
@abc.abstractmethod
def expected_exception(self) -> Tuple[Exception]:
"""Expected exceptions
Should return a tuple of all exceptions
that will be used to compute a fail
and increment the circuit breaker
"""
pass
@abc.abstractmethod
def failure_threshold(self) -> int:
"""Failure threshold
The amount of failures required to open the circuit.
"""
pass
@abc.abstractmethod
def recovery_timeout(self) -> int:
"""Recovery timeout
Defines for how long the circuit key will remain in seconds,
until it close the circuit again.
"""
pass
@abc.abstractmethod
def failure_key(self) -> str:
"""Failure key
Defines the key that will be used to store
the circuit breaker errors counter.
"""
pass
def is_open(self) -> bool:
"""Is open
Return rather the circuit is open or not
"""
return self.storage.get(self.failure_key) >= self.failure_threshold
def ping(self) -> None:
"""Ping
Increment the failure key when some of
the Exceptions defined on catch_exceptions occurs.
Every time that the key is incremented the expire
time will be renew
"""
self.storage.increment(self.failure_key)
self.storage.expire(self.failure_key, self.timeout)
|
658593501932b67c86b33a4f1a0ba2a1257e2de5 | jorzel/codefights | /interview_practice/hash_tables/possibleSums.py | 876 | 4.28125 | 4 | """
You have a collection of coins, and you know the values of the coins and the quantity of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins.
Example
For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be
possibleSums(coins, quantity) = 9.
Here are all the possible sums:
50 = 50;
10 + 50 = 60;
50 + 100 = 150;
10 + 50 + 100 = 160;
50 + 50 = 100;
10 + 50 + 50 = 110;
50 + 50 + 100 = 200;
10 + 50 + 50 + 100 = 210;
10 = 10;
100 = 100;
10 + 100 = 110.
As you can see, there are 9 distinct sums that can be created from non-empty groupings of your coins.
"""
def possibleSums(values, counts):
sums = {0}
for v, c in zip(values, counts):
sums |= {i + choice
for choice in range(v, v * c + 1, v)
for i in sums}
return len(sums) - 1
|
ba8a35759717c5447225d1d7a7801ca803f5437d | SpAiNiOr/mystudy | /learning/test/anti_vowel.py | 220 | 4.1875 | 4 | def anti_vowel(text):
result = ""
vowel = ['a','e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for k in range(len(text)):
if text[k] not in vowel:
result = result + text[k]
return result
|
d497c31727b8de742e5506954ee5ffcaa2e45333 | GratiaTechnologyResearchLab/SummerInternship-Python | /ArunavD/PIL_test/convertfiles.py | 1,264 | 3.53125 | 4 | import os
# Find all directory names
initialDirectoryName = 'pictures'
allDirectories = os.listdir(initialDirectoryName)
print allDirectories
for folders in allDirectories:
# Print foldername
print "Files inside folder: " + folders
# Go inside the corresponding folder
fullPath = os.path.join(initialDirectoryName, folders)
# Print all files inside the folder
allFilesinFolders = os.listdir(fullPath)
print allFilesinFolders
# Copy to some other directory
for files in allFilesinFolders:
# Source file
sourceFile = os.path.join(os.path.join(initialDirectoryName,folders), files)
###########################
# Change 'png' to the name of the directory you want to create the output files
###########################
# Check if directory exists or not
if not os.path.exists(os.path.join(initialDirectoryName, folders + '/png')):
os.makedirs(os.path.join(initialDirectoryName, folders + '/png'))
# Destination file
destFile = os.path.join(os.path.join(initialDirectoryName,folders + '/png'), files[:-4] + '.png')
# Convert file
os.system('convert ' + sourceFile + ' ' + destFile) |
2824b620294d254c80d2e897099895b0ee6dee7e | jchpmn/Code-Your-Own-Quiz | /Code a Python Quiz.py | 5,381 | 4.28125 | 4 | """ Used to update the displayed paragraph with the user's answers """
def word_in_current_paragraph(user_answer, answer_number, current_paragraph):
updated_paragraph = []
current_paragraph = current_paragraph.split()
for word in current_paragraph:
if word == "___" + (str(answer_number)) + "___":
word = user_answer
updated_paragraph.append(word)
else:
updated_paragraph.append(word)
updated_paragraph = " ".join(updated_paragraph)
return updated_paragraph
""" answer key for easy, medium, and hard levels """
answers = ['function', 'argument', 'none', 'byte', 'obvious', 'start', 'correct', 'short', 'sequence', 'append', 'mutate', 'elements']
#The following are the paragraphs displayed to the user depending on their selection of the level of difficulty
paragraph_easy = """A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by \
adding an ___2___ separated by commas between the parentheses. A ___1___ by default will return ___3___ if you\
don't specify the value to return. An ___2___ can be standard data types such as string, number, dictionary,\
tuple, and ___4___ or can be more complicated such as objects and lambda functions."""
paragraph_medium = """Comments are lines of code that are ignored by the computer. You should not\
comment ___1___ code. All functions should ___2___ with a comment. Comments should be kept up-to-date\
with ___3___ information. Comments should be ___4___ and explain only the most important details of your code."""
paragraph_hard = """Python has a number of list operations. Lists respond to all of the general ___1___ operations\
that are used on strings. An ___2___ can be used to add a new element to the end of a list. Plus produces a\
new list but does not ___3___ either of the two input lists. The output of len is the number of ___4___ in\
the input."""
print
""" This function prompts the user to select the level difficulty which is returned as user_input """
user_input = ""
def select_level():
user_selection = False
while user_selection == False:
user_input = raw_input("Please select a game difficulty by typing it in! Your choices are easy, medium, or hard." + " ").lower()
#user_input = user_input.lower()
if user_input == "easy" or user_input == "medium" or user_input == "hard":
user_selection = True
print "\n" + "You have chosen " + "\033[1m" + user_input.lower() + "\033[0m" + "."
print "\n" + "You will get 5 guesses per problem." + "\n"
else:
print "Please enter a valid selection."
return user_input
""" Sets the paragraph to the level of difficulty based on the user's difficulty level selection """
def allocate_quiz_current_paragraph():
difficulty = user_input
if difficulty == "easy":
current_paragraph = paragraph_easy
print current_paragraph + "\n"
elif difficulty == "medium":
current_paragraph = paragraph_medium
print current_paragraph + "\n"
else:
current_paragraph = paragraph_hard
print current_paragraph + "\n"
return current_paragraph
""" Determines which set of answers will be used based on the user's difficulty level selection """
def allocate_quiz_answer_index():
difficulty = select_level()
if difficulty == "easy":
easy_start_index = 0
answer_index = easy_start_index
elif difficulty == "medium":
medium_start_index = 4
answer_index = medium_start_index
else:
hard_start_index = 8
answer_index = hard_start_index
return answer_index
""" Initializes set up for the assigned variables for starting the quiz """
def run_quiz(answer_number, total_number_of_answers, number_of_guesses, no_guesses_remaining):
answer_index = allocate_quiz_answer_index()
current_paragraph = allocate_quiz_current_paragraph()
while (answer_number - 1) < total_number_of_answers and number_of_guesses >= no_guesses_remaining:
user_answer = raw_input("What should be subsituted in for ___" + (str(answer_number)) + "___?" + " ").lower()
if user_answer == answers[answer_index]:
answer_index += 1
print "\n" + "Correct!" + "\n"
current_paragraph = word_in_current_paragraph(user_answer, answer_number, current_paragraph)
print current_paragraph + "\n"
answer_number += 1
number_of_guesses = 4
else:
print "\n" + "That isn't the correct answer! Let's try again; you have " + (str(number_of_guesses)) + " trys left!" + "\n"
number_of_guesses -= 1
user_wins_loses_prompt(number_of_guesses)
""" Gives appropriate response for if the user wins or loses """
def user_wins_loses_prompt(number_of_guesses):
if number_of_guesses < 0:
print "You have failed. Too many wrong guesses. Game over!" + "\n"
else:
print "You Win!" + "\n"
""" Prompts the user to fill in the blanks with the appropriate answers and keeps track of the number of guesses.
If the user enters the correct answer for each selection they win. If the user makes 5 incorrect guesses for a
given blank the game is over. """
def play_game():
answer_number = 1
total_number_of_answers = 4
number_of_guesses = 4
no_guesses_remaining = 0
run_quiz(answer_number, total_number_of_answers, number_of_guesses, no_guesses_remaining)
play_game()
|
8a6d47270c9f5348cdd30ad393716b1339eefff3 | EgonFerri/Ex2_NN_backpropr | /Assignment/ex2_FCnet.py | 14,681 | 3.78125 | 4 | #-----------------------------------------------------------------------------------
# Implementing a Neural Network In this exercise we will develop a neural
# network with fully-connected layers to perform classification, and test it
# out on the CIFAR-10 dataset. A bit of setup
#-----------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from two_layernet import TwoLayerNet
from gradient_check import eval_numerical_gradient
from data_utils import get_CIFAR10_data
from vis_utils import visualize_grid
#-------------------------- * End of setup *---------------------------------------
#-------------------------------------------------------
# Some helper functions
# ------------------------------------------------------
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
def show_net_weights(net):
W1 = net.params['W1']
W1 = W1.reshape(32, 32, 3, -1).transpose(3, 0, 1, 2)
plt.imshow(visualize_grid(W1, padding=3).astype('uint8'))
plt.gca().axis('off')
plt.show()
#-------------------------- * End of helper functions *--------------------------------
#======================================================================================
# Q1: Implementing forward pass and the loss functions
#======================================================================================
# We will use the class `TwoLayerNet` in the file `two_layernet.py` to
# represent instances of our network. The network parameters are stored in the
# instance variable `self.params` where keys are string parameter names and
# values are numpy arrays. Below, we initialize toy data and a toy model that
# we will use to develop your implementation.
#--------------------------------------------------------------------------------------
# Create a small net and some toy data to check your implementations.
# Note that we set the random seed for repeatable experiments.
input_size = 4
hidden_size = 10
num_classes = 3
num_inputs = 5
def init_toy_model():
np.random.seed(0)
return TwoLayerNet(input_size, hidden_size, num_classes, std=1e-1)
def init_toy_data():
np.random.seed(1)
X = 10 * np.random.randn(num_inputs, input_size)
y = np.array([0, 1, 2, 2, 1])
return X, y
net = init_toy_model()
X, y = init_toy_data()
# Forward pass: compute scores. Open the file `two_layernet.py` and look at the
# method `TwoLayerNet.loss`. This function takes the
# data and weights and computes the per-class scores, the loss, and the gradients
# on the parameters.
#
# Implement the first part of the forward pass which uses the weights and
# biases to compute the scores for all inputs.
scores = net.loss(X)
print('Your scores:')
print(scores)
print()
print('correct scores:')
correct_scores = np.asarray([
[0.36446210, 0.22911264, 0.40642526],
[0.47590629, 0.17217039, 0.35192332],
[0.43035767, 0.26164229, 0.30800004],
[0.41583127, 0.29832280, 0.28584593],
[0.36328815, 0.32279939, 0.31391246]])
print(correct_scores)
print()
# The difference should be very small. We get < 1e-7
print('Difference between your scores and correct scores:')
print(np.sum(np.abs(scores - correct_scores)))
# Forward pass: compute loss. In the same function, implement the second part
# that computes the data and regularization loss.
loss, _ = net.loss(X, y, reg=0.05)
correct_loss = 1.30378789133
# should be very small, we get < 1e-12
print('Difference between your loss and correct loss:')
print(np.sum(np.abs(loss - correct_loss)))
#======================================================================================
# Q2:Computing gradients using back propogation
#======================================================================================
# Implement the rest of the function. This will compute the gradient of the
# loss with respect to the variables `W1`, `b1`, `W2`, and `b2`. Now that you
# have a correctly implemented forward pass, you can debug your backward pass
# using a numeric gradient check:
# Use numeric gradient checking to check your implementation of the backward
# pass. If your implementation is correct, the difference between the numeric
# and analytic gradients should be less than 1e-8 for each of W1, W2, b1, and
# b2.
loss, grads = net.loss(X, y, reg=0.05)
# these should all be less than 1e-8 or so
for param_name in grads:
f = lambda W: net.loss(X, y, reg=0.05)[0]
param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)
print('%s max relative error: %e' % (param_name, rel_error(param_grad_num, grads[param_name])))
#======================================================================================
# Q3: Train the network using gradient descent
#======================================================================================
# To train the network we will use stochastic gradient
# descent (SGD). Look at the function `TwoLayerNet.train` and fill in the
# missing sections to implement the training procedure. You will also have to
# implement `TwoLayerNet.predict`, as the training process periodically
# performs prediction to keep track of accuracy over time while the network
# trains.
# Once you have implemented the method, run the code below to train a
# two-layer network on toy data. You should achieve a training loss less than
# 0.02.
net = init_toy_model()
stats = net.train(X, y, X, y,
learning_rate=1e-1, reg=5e-6,
num_iters=100, verbose=True)
print('Final training loss: ', stats['loss_history'][-1])
# plot the loss history
plt.figure(1)
plt.plot(stats['loss_history'])
plt.xlabel('iteration')
plt.ylabel('training loss')
plt.title('Training Loss history')
plt.show()
# Load the data
# Now that you have implemented a two-layer network that passes
# gradient checks and works on toy data, it's time to load up our favorite
# CIFAR-10 data so we can use it to train a classifier on a real dataset.
# Invoke the get_CIFAR10_data function to get our data.
X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data()
print('Train data shape: ', X_train.shape)
print('Train labels shape: ', y_train.shape)
print('Validation data shape: ', X_val.shape)
print('Validation labels shape: ', y_val.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
# Visualize some images to get a feel for the data
plt.figure(2)
plt.imshow(visualize_grid(X_train[:100, :].reshape(100, 32,32, 3), padding=3).astype('uint8'))
plt.gca().axis('off')
plt.show()
# Train a network
# To train our network we will use SGD. In addition, we will
# adjust the learning rate with an exponential learning rate schedule as
# optimization proceeds; after each epoch, we will reduce the learning rate by
# multiplying it by a decay rate.
input_size = 32 * 32 * 3
hidden_size = 50
num_classes = 10
net = TwoLayerNet(input_size, hidden_size, num_classes)
# Train the network
stats = net.train(X_train, y_train, X_val, y_val,
num_iters=1000, batch_size=200,
learning_rate=1e-4, learning_rate_decay=0.95,
reg=0.25, verbose=True)
# Predict on the validation set
val_acc = (net.predict(X_val) == y_val).mean()
print('Validation accuracy: ', val_acc)
# Debug the training
# With the default parameters we provided above, you should get a validation
# accuracy of about 0.29 on the validation set, which is not very good.
#
# One strategy for getting insight into what is wrong is to plot the loss
# function and the accuracies on the training and validation sets during
# optimization.
#
# Another strategy is to visualize the weights that were learned in the first
# layer of the network. In most neural networks trained on visual data, the
# first layer weights typically show some visible structure when visualized.
# Plot the loss function and train / validation accuracies
plt.figure(3)
plt.subplot(2, 1, 1)
plt.plot(stats['loss_history'])
plt.title('Loss history')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.subplot(2, 1, 2)
plt.plot(stats['train_acc_history'], label='train')
plt.plot(stats['val_acc_history'], label='val')
plt.title('Classification accuracy history')
plt.xlabel('Epoch')
plt.ylabel('Classification accuracy')
plt.legend()
plt.show()
# Visualize the weights of the network
plt.figure(5)
show_net_weights(net)
# Tune your hyperparameters
#
# **What's wrong?**. Looking at the visualizations above, we see that the loss
# is decreasing more or less linearly, which seems to suggest that the learning
# rate may be too low. Moreover, there is no gap between the training and
# validation accuracy, suggesting that the model we used has low capacity, and
# that we should increase its size. On the other hand, with a very large model
# we would expect to see more overfitting, which would manifest itself as a
# very large gap between the training and validation accuracy.
#
# **Tuning**. Tuning the hyperparameters and developing intuition for how they
# affect the final performance is a large part of using Neural Networks, so we
# want you to get a lot of practice. Below, you should experiment with
# different values of the various hyperparameters, including hidden layer size,
# learning rate, numer of training epochs, and regularization strength. You
# might also consider tuning the learning rate decay, but you should be able to
# get good performance using the default value.
#
# **Approximate results**. You should be aim to achieve a classification
# accuracy of greater than 48% on the validation set. Our best network gets
# over 52% on the validation set.
#
# **Experiment**: You goal in this exercise is to get as good of a result on
# CIFAR-10 as you can (52% could serve as a reference), with a fully-connected
# Neural Network. Feel free to implement your own techniques (e.g. PCA to reduce
# dimensionality, or adding dropout, or adding features to the solver, etc.).
# **Explain your hyperparameter tuning process in the report.**
best_net = None # store the best model into this
#################################################################################
# TODO: Tune hyperparameters using the validation set. Store your best trained #
# model in best_net. #
# #
# To help debug your network, it may help to use visualizations similar to the #
# ones we used above; these visualizations will have significant qualitative #
# differences from the ones we saw above for the poorly tuned network. #
# #
# Tweaking hyperparameters by hand can be fun, but you might find it useful to #
# write code to sweep through possible combinations of hyperparameters #
#################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
"""
grid search to find the best hyper-parameters
"""
# import itertools
# from tqdm import tqdm
# import pandas as pd
#param_grid = {
#"hidden_size" : [200, 250], "niter" : [4000, 5000],"batch":[256, 512],
#"lerate": [1e-3,1e-4], "reg" : [1e-3,1e-4]}
#results_val = []
#results_train = []
#combinations = list(itertools.product(*param_grid.values()))
#for comb in tqdm(combinations):
#
#
# print("current combination :", comb)
# print("\n")
# # Train the network
# np.random.seed(123)
# net = TwoLayerNet(input_size, comb[0], num_classes)
# stats = net.train(X_train, y_train, X_val, y_val,
# num_iters=comb[1], batch_size=comb[2],
# learning_rate=comb[3], learning_rate_decay=0.95,
# reg=comb[4], verbose=False)
# val_acc = (net.predict(X_val) == y_val).mean()
# train_acc = (net.predict(X_train) == y_train).mean()
#
# results_val.append(val_acc)
# results_train.append(train_acc)
#
#best_comb = combinations[results_val.index([max(results_val)])]
#zipped = list(zip(combinations,results_train, results_val))
#pd.DataFrame(zipped).rename(columns = {0:"combinations",1:"train accuracy",2:"val accuracy"}).to_csv("results.csv")
import time
start = time.time()
best_comb = [250, 5000, 256, 0.001, 0.001]
np.random.seed(123)
best_net = TwoLayerNet(input_size, best_comb[0], num_classes)
stats = best_net.train(X_train, y_train, X_val, y_val,
num_iters=best_comb[1], batch_size=best_comb[2],
learning_rate=best_comb[3], learning_rate_decay=0.95,
reg=best_comb[4], verbose=True)
print("code execution time: ",time.time() - start)
# Predict on the validation set
print('-----------')
print('hidden size: ',best_comb[0], ', num_iters: ',best_comb[1], ', batch size: ',best_comb[2], ', learning_rate: ', best_comb[3], ', regula: ',best_comb[4] )
val_acc = (best_net.predict(X_val) == y_val).mean()
print('Validation accuracy: ', val_acc)
print('------------')
#plot
plt.figure(6)
plt.subplot(2, 1, 1)
plt.plot(stats['loss_history'])
plt.title('Loss history')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.subplot(2, 1, 2)
plt.plot(stats['train_acc_history'], label='train')
plt.plot(stats['val_acc_history'], label='val')
plt.title('Classification accuracy history')
plt.xlabel('Epoch')
plt.ylabel('Classification accuracy')
plt.legend()
plt.show()
#check stability running more simulations, since we have some randomness
#best_comb=[250, 5000, 256, 0.001, 0.001]
#results_val=[]
#results_train=[]
#for i in tqdm(range(15)):
#
# best_net = TwoLayerNet(input_size, best_comb[0], num_classes)
# stats = best_net.train(X_train, y_train, X_val, y_val,
# num_iters=best_comb[1], batch_size=best_comb[2],
# learning_rate=best_comb[3], learning_rate_decay=0.95,
# reg=best_comb[4], verbose=False)
# val_acc = (best_net.predict(X_val) == y_val).mean()
# train_acc = (best_net.predict(X_train) == y_train).mean()
# results_val.append(val_acc)
# results_train.append(train_acc)
#pd.DataFrame({'Train accuracy':results_train, 'Validation accuracy':results_val}).to_csv('simul.csv')
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# visualize the weights of the best network
plt.figure(7)
show_net_weights(best_net)
# Run on the test set
# When you are done experimenting, you should evaluate your final trained
# network on the test set; you should get above 48%.
test_acc = (best_net.predict(X_test) == y_test).mean()
print('Test accuracy: ', test_acc) |
3c1d18163de317f090f83a2df2de57578bca7d6f | Youssef-elhazmiri/coursPython | /main.py | 6,752 | 3.984375 | 4 |
#Variabes
nom = "Youssef"
age = "20"
ville_Orig = "El kelaa des Sraghna"
ville_Hab = "Rabat"
University = "ENS Rabat"
#mon_premier_programme:
print("Je suis "+nom+", j'ai "+age+" ans, ma ville d'origine est "+ville_Orig+", mais j'habite dans "+ville_Hab+" à cause de mes études dans l'"+University+".")
print("\n")
#ecrire_l'egillemet_dans_print:
print("youssef \"Elhazmiri\"")
print("\n")
#fonctions:_var.lower()_et_var.islower()_et_var.upper()_et_var.isupper():
#var.upper(): changer la forme du variable à Majuscule
#var.isupper(): voir es-ce-qu'il y a des majuscule dans le contenue de la variable si oui le programme donne "TRUE" si non il donne " FALSE"
print(nom.lower().islower())
print(nom.isupper())
print(nom.upper())
print("\n")
#fonction: len(var): //donner la taille de le contenue d'une variable
print(len(nom))
print("\n")
#fonction: nom[]: //Donner le contenue d'une adresse
print(nom[0])
print(nom[1])
print(nom[2])
print(nom[3])
print("\n")
#fonction:_nom.index(""): // Donner l'adresse d'une valeur
print(nom.index("o"))
print(nom.index("Y"))
print(nom.index("s"))
print(University.index("Rabat"))
print("\n")
#fonction:_nom.replace("","")
print(nom.replace("ou","az"))
print(nom)
#inserer_un_element_par_l'utilisateur:
#Variables:
nom1 = input("Donner votre nom: ")
prenom1 = input("Donner votre prenom: ")
age1 = input("Donner votre age: ")
University1 = input("Donner votre Universite: ")
#code:
print("votre nom complet est "+nom1+" "+prenom1+", vous avez "+age1+" ans, vous etudiez dans l'"+University1+".")
#variables:
num1 = input("Donner le nombre 1: ")
num2 = input("Donner le nombre 2: ")
print( num1 + num2 )
#La_somme_de_deux_variables (int):
num1 = input("Donner le nombre 1: ")
num2 = input("Donner le nombre 2: ")
result = int(num1) + int(num2)
print(result)
#La_somme_de_deux_variables (float):
num1 = input("Donner le nombre 1: ")
num2 = input("Donner le nombre 2: ")
result = float(num1) + float(num2)
print(result)
#Donner_les_variables:
cars = ["audi","bmw","mercedes","renault","ferrari"]
print(cars[0])
print(cars[1])
print(cars[2])
print(cars[-1])
print(cars[-2])
print(cars[-3])
#Donner les valeurs qu'ils sont avant et apres:
print("les valeurs avant bmw :\n")
print(cars[:1])
print("\n")
print("les valeurs apres bmw :\n")
print(cars[1:])
#Donner les valeurs de ... à :
print(cars[1:3])
#changer les valeurs:
print(cars)
cars[2] = "kia"
print(cars)
cars = ["renault","mercedes","bmw","Audi","Ferrari"]
speed = [14 , 1 , 100 , 13 , 300]
#fonction de var.extend(): // combiner deux groupes
print(cars)
#fonction de var.append(): ajouter une valeur dans une variable
cars.append("kia")
print(cars)
#fonction var.insert(,''): // ajouter une valeur dans une adresse
cars.insert(2,"kia")
print(cars)
#fonction var.remove(): //supprimer une valeur
cars.remove("renault")
print(cars)
#fonction var.clear(): //supprimer tous le contenue du variable
cars.clear()
print(cars)
#fonction var.pop(): // supprimer la derniere valeur
cars.pop()
print(cars)
#fonction var.count(): //calculer la repition de la valeur
count = cars.count("renault")
print(count)
#fonction de var.sort(): //grouper les valeurs d'une variables de Maj à Mun et de a à z :
cars.sort()
print(cars)
speed.sort()
print(speed)
#fonction var.reverse(): // sert de reverser l'ordre du contenue d'une variable:
cars.reverse()
print(cars)
speed.reverse()
print(speed)
#fonction var.copy(): //copier les valeurs d'une variable dans une autre variable:
cars2 = cars.copy()
print(cars2)
#Tuples: on ne peut pas modifier sur tuple
color = ("red" , "black" , "blue")
color[0] = "yellow"
print(color[0])
#-----------------------Fonctions-------------------------
#la fonction:
def salma():
name = input("donner votre nom: ")
poste = input("donner votre poste: ")
age = input("donner votre age: ")
print("bonjour "+name+", vous etes un "+poste+", vous avez "+str(age)+" ans.")
#tester
salma()
#return:
def cub(num):
print(num*num*num)
cub(2)
#la meme chose quand on utilise return:
def cube(num):
return num*num*num
print(cube(2))
#-----------if Statements---------------
homme = True
muslim = False
if homme and muslim:
print("vous etes un homme et muslim")
elif homme and not muslim:
print("vous etes un homme mais vous n'etes pas muslim")
elif not homme and muslim:
print ("vous etes une femme muslime")
else:
print("vous etes une femme non muslime")
#comparaison:
#fonction max():
def max( num1 , num2 , num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max(4 , 945 , 5))
#fonction min():
def min( num1 , num2 , num3):
if num1 <= num2 and num1 <= num3:
return num1
elif num2 <= num1 and num2 <= num3:
return num2
else:
return num3
print(min(456 , 1 , 6 ))
#exercice de faire une simple calculatrice:
num1 = float(input("Donner le premier nombre: "))
op = input("Donner l'operation: ")
num2 = float(input("Donner le deuxieme nombre: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
else:
print("Svp donner une operation")
#---------------------Dectionnaire--------------------
week = {
1:"lundi",
2:"Mardi",
3:"Mercredi",
4:"Jeudi",
5:"Vendredi",
6:"Samedi",
7:"Dimanche",
}
print(week[3])
print(week.get(3,"try again"))
#-------while--------:
i = 0
while i <= 20:
print(i)
i = i + 1 #ou bien i += 1
if i > 20 :
print("Terminer")
#------for------------:
for letter in "Youssef El Hazmiri":
print(letter)
cars2 = ["honda" , "mercides", "audi" , "bmw"]
for car in cars2:
print(car)
for num in range(5):
print(num)
for num in range(5,11):
print(num)
print("\n")
for num in range(len(cars2)):
print(num)
for num in range(len(cars2)):
print(cars2[num])
#exercice : LOG IN BANQUE
password = "2420"
mots = ""
count = 0
limit = 3
out = False
while mots != password and not out:
if count < limit :
mots = input("Le mots de passe: ")
count = count + 1
else:
out = True
if out:
print("vous avez echoué dans les 3 fois, votre carte banquaire est blocké")
else:
print("Vous êtes connecté, Bonjour Youssef")
|
39b36ba5ba1a7109544db8f5c09e5a9f4b256ebb | ema-rose/wordnik-repl | /practice/bitwise_operations/ex7.py | 1,152 | 4.3125 | 4 | # &) operator compares two numbers on a bit level and returns a number where the bits \
of that number are turned on if the corresponding bits of both numbers are 1
# the & operator can only result in a number that is less than or equal to the smaller of the two values
print bin(0b1110 & 0b101)
# OR (|) operator compares two numbers on a bit level and returns a number where the bits \
of that number are turned on if either of the corresponding bits of either number are 1
# can only create results that are greater than or equal to the larger of the two integer inputs
print bin(0b1110 | 0b101)
# prints 0b1111
# XOR (^) or exclusive or operator compares two numbers on a bit level and returns a number \
where the bits of that number are turned on if either of the corresponding bits of the two \
numbers are 1, but not both
print bin(0b1110 ^ 0b101)
# prints 0b1011
# NOT operator (~) just flips all of the bits in a single number.
# mathematically, this is equivalent to adding one to the number and then making it negative
print ~1 # prints -2
print ~2 # prints -3
print ~3 # prints -4
print ~42 # prints -43
print ~123 # prints -124
|
dff5cafb0f8003bd4a86ff39f913aa6513938726 | daniel-reich/ubiquitous-fiesta | /DG2HLRqxFXxbaEDX4_19.py | 124 | 3.609375 | 4 |
def return_only_integer(lst):
lstint = []
for s in lst:
if type(s) == int:
lstint.append(s)
return lstint
|
2c637b2ec2f13b172f7cc575d6d6718dca90abee | Zevic/Zevic-Novel | /Interactive Novel.py | 9,151 | 3.84375 | 4 | #Name: [Redacted]
#StartDate: 10/10/17
#Date: 17/10/17
#Project: Interactive Novel
import time
import random
Response_Count = "True"
Inventory = "False"
Key = "False"
Cell_Count = "True"
Desk_Count = "True"
Cell_Desk = "True"
Cell_Desk2 = "True"
Cell_Note = "True"
Cell_Three = "False"
def Cell_Text():
print("You awake in a dark dungeon, it's only a small cell but holds a bed, a desk and a hole in the floor")
print("You faintly hear footsteps...")
Cell_Text()
Cell_Move = input("Where do you go first? (Check Bed or Check Desk): ").upper()
while Cell_Count == "True":
if Cell_Move == "CHECK BED":
print("You find a key in your pillow and stuff it in your pocket")
print("+ silver key")
Key = "Silver Key"
Cell_Count = "False"
Cell_Two = "CHECK BED"
elif Cell_Move == "CHECK DESK":
Cell_Two = "CHECK DESK"
Cell_Three = "CHECK DESK"
print("There's a padlock, maybe if you had a key...")
Cell_Count = "False"
if Key == "Silver Key":
print("You use the key on the lock and look in the draw")
time.sleep(1)
print("There's a note")
Note_Read = input("Do you read the note? ")
while Desk_Count == "True":
if Note_Read == "YES":
print("This key can unlock any door within the castle dungeon...dont get caught")
print("You hear footsteps heading towards your cell")
time.sleep(1)
print("You stuff the note in your pocket and sit down on the bed")
Inventory = "Note"
Desk_Count = "False"
elif Note_Read == "NO":
print("You put the note in your pocket")
Inventory = "Note"
Desk_Count = "False"
else:
print("yes or no please")
Note_Read = input("Do you read the note? ")
else:
Cell_Three = "CHECK DESK"
else:
print("Invalid Response...please go to the bed or desk (Check them)")
Cell_Move = input("Where do you go first? (Check Bed or Check Desk ").upper()
while Cell_Desk == "True":
if Cell_Two == "CHECK BED":
print("You've found the key, now check out the desk")
Cell_Desk = "False"
Key = "Silver Key"
if Key == "Silver Key":
print("You use the key on the lock and look in the draw")
time.sleep(1)
print("There's a note")
Note_Read = input("Do you read the note? ").upper()
while Cell_Note == "True":
if Note_Read == "YES":
print("This key can unlock any door within the castle dungeon...dont get caught")
print("You hear footsteps heading towards your cell")
time.sleep(1)
print("You stuff the note in your pocket and sit down on the bed")
Inventory = "Note"
Cell_Desk = "False"
Cell_Note = "False"
elif Note_Read == "NO":
print("You put the note in your pocket")
Inventory = "Note"
Cell_Desk = "False"
Cell_Note = "False"
else:
print("yes or no please")
Note_Read = input("Do you read the note? ").upper()
else:
print("The bed might solve your answers...")
time.sleep(1)
print("you go to the bed")
time.sleep(1)
print("You find a key in your pillow and stuff it in your pocket")
print("+ silver key")
Key = "Silver Key"
Cell_Desk = "False"
Cell_Three = "CHECK DESK"
Cell_Desk2 = "True"
if Cell_Three == "CHECK DESK":
while Cell_Desk2 == "True":
print("Let's go back to the desk")
time.sleep(1)
print("You go back to the desk...the sound of distant footsteps is heard")
time.sleep(1)
print("You use the key on the lock and look in the draw")
time.sleep(1)
print("There's a note")
time.sleep(1)
Note_Reads = input("Do you read the note? ").upper()
while Cell_Note == "True":
if Note_Reads == "YES":
print("This key can unlock any door within the castle dungeon...dont get caught")
print("You hear footsteps heading towards your cell")
time.sleep(1)
print("You stuff the note in your pocket and sit down on the bed")
Inventory = "Note"
Cell_Note = "False"
Cell_Desk2 = "False"
elif Note_Reads == "NO":
print("You put the note in your pocket")
Inventory = "Note"
Cell_Note = "False"
Cell_Desk2 = "False"
else:
print("yes or no please")
Note_Read = input("Do you read the note? ").upper()
else:
print("The footsteps grow nearer...and nearer")
time.sleep(5)
print("Warden: Prisoner! Stand aside, by the desk!")
time.sleep(2)
print("You do as asked")
time.sleep(2)
print("The Warden unlocks the door and steps inside")
time.sleep(2)
print("Warden: What is your name!")
time.sleep(2)
Name = input("___: My name is ")
time.sleep(2)
print("Warden: Well",Name,"time for the block!")
time.sleep(2)
print("The Warden grabs you and throws you out of the cell")
time.sleep(2)
print("Warden: Get moving!")
time.sleep(2)
print("You walk along the corridors, hearing the moans and wails of other prisoners, you leave through a large wooden door")
time.sleep(2)
print("The sun blinds you, how long has it been since you have seen sunlight? Weeks? Months? It feels like them")
time.sleep(2)
print("You get thrown to the chopping block...the executioner raises his axe...")
time.sleep(5)
print("You pass out from exhaustion...a fire erupts from the building directly ahead of you...Everyone screams...")
time.sleep(15)
print("Strang: (in a hushed tone) Hey...wake up...",Name,"wake up! (They slap you awake)")
time.sleep(1)
print("(You awake..somehow alive)")
time.sleep(1)
print("(Not a scratch, not a mark)")
time.sleep(1)
print("Strang: hello...world to",Name)
time.sleep(1)
Response = input("(H..hi) (Hello...) (Hi there, and you are?) ").upper()
time.sleep(1)
while Response_Count == "True":
if Response == "H..HI":
print(Name+": H..hi")
Response_Count = "False"
elif Response == "HELLO...":
print(Name+": Hello...")
Response_Count = "False"
elif Response == "HELLO THERE, AND YOU ARE?":
print(Name+": Hello there, and you are?")
Response_Count = "False"
else:
print("(Please pick one of the three choices)")
Response = input("(H..hi) (Hello...) (Hi there, and you are?) ").upper()
time.sleep(1)
print("Stranger: finally...your'e awake")
time.sleep(2)
print("She steps off your body and stands aside")
time.sleep(2)
print("Stranger: Well...aren't you gonna ask my name?")
time.sleep(2)
print(Name+": Okay..what is your name...?")
time.sleep(2)
print("Stranger: That's for another day..let's go (She starts to walk off back towards the fort)")
time.sleep(2)
print(Name+": Hey..wait up!! (You get up and run to catch up)")
time.sleep(2)
print("Stranger: Well? Front door or sneaky entrance?")
time.sleep(2)
Response = input("(Front door)(Secret entrance)").upper()
print(Name+": let's go through the",Response)
Response_Count = "True"
while Response_Count == "True":
if Response == "FRONT DOOR":
print("You charge at the front door")
print("Stranger: let's go...i guess")
Response_Count = "False"
elif Response == "SECRET ENTRANCE":
print("Your'e a sneaky one, you take the back entrance")
print("Stranger: okay, my kind of entrance")
Response_Count = "False"
else:
Response = input("(Front door)(Secret entrance)").upper()
if Response == "FRONT DOOR":
print("As you charge in, a guard turns the corner and sees you\nthey're about to alert the others\nwhat do you do? (Run)(Tackle)")
elif Response == "SECRET ENTRANCE":
print("You sneak around the back and remove some foliage, you find a hole that has been mined out\nas you enter you see a guard staring right at you\nwhat do you do? (Charge)(Bargain)(run)")
time.sleep(2)
if Response == "FRONT DOOR":
Response_Count = "True"
Response = input("(Run)(Tackle) ").upper()
while Response_Count == "True":
if Response = "RUN":
print
elif Response = "TACKLE":
print
else:
ptint("Incorrect response please pick (Run) or (Tackle)")
Response = input("(Run)(Tackle) ").upper()
|
57c68e0d6edde6ed5c8e336e860f1ed41be42748 | Themis404/completed_tasks | /task_one.py | 579 | 4.0625 | 4 | def calculator(operation, a, b):
if operation == '*':
return a*b
elif operation == '/':
return a/b
elif operation == '-':
return a-b
elif operation == '+':
return a+b
else:
return "sorry"
def main():
s = "Let's go"
while s != 'stop':
a = int(input("Enter А "))
b = int(input("Enter В "))
operation = input("Select one from -,+,/,* ")
print (calculator(operation,a, b))
s = input("well done, if it's all, then must write 'stop' ")
if __name__ == '__main__':
main() |
20242d5295a017a1bdbbd057a2e95abed95f1300 | bernkastle/python-example | /Concurrency/sync_to_async.py | 998 | 3.625 | 4 | #!/usr/bin/env python
# encoding:utf-8
import asyncio
import requests
import time
async def download(url):
"""
同步函数,加上async关键字,宣称为awaitable
:param url:
:return:
"""
response = requests.get(url)
print(response.text)
async def wait_download(url):
"""
包装同步函数为一个原生的协程对象,等待同步函数完成
:param url:
:return:
"""
await download(url) # 这里download(url)就是一个原生的协程对象
print("get {} data complete.".format(url))
async def main():
start = time.time()
# 添加协程执行函数
await asyncio.wait([
wait_download("http://www.163.com"),
wait_download("http://www.mi.com"),
wait_download("http://www.baidu.com")])
end = time.time()
print("Complete in {} seconds".format(end - start))
# 添加时间循环,异步函数必须要有事件循环
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
|
1f134d1a6d6341bc22e4270b813d4fc22ceb1437 | nehapokharel/pythonPractice | /question19.py | 120 | 3.734375 | 4 | numberlist = [1, 34, 5, 7]
min = numberlist[0]
for num in numberlist:
if num < min:
min = num
print(min)
|
38c3d3f5506b6c3f4c06bd027018c3010aca039a | bronval/breakout_pygame | /ball.py | 2,651 | 3.9375 | 4 |
#####################################################
#
# breakout game with pygame
# for Python stage in Technofutur TIC (Belgium)
# Authors : Bastien Wiaux and Benoit Ronval
#
#####################################################
from constants import *
import math
import pygame
class Ball:
def __init__(self):
"""
Initialise un objet ball avec les constantes du fichier constants.py
"""
self.radius = BALL_RADIUS
self.center_x = BALL_START_X
self.center_y = BALL_START_Y
self.velocity = BALL_SPEED
self.angle = - math.pi / 2
self.rectangle = pygame.Rect(self.center_x - self.radius, self.center_y - self.radius, 2 * self.radius, 2 * self.radius)
self.color = "white"
self.save_pos = (self.center_x, self.center_y)
def draw(self, window):
"""
Dessine la balle sur la window et update l'attribut rectangle
"""
# sauvegarde rectangle pour les collisions
self.rectangle = pygame.draw.circle(window, self.color, (self.center_x, self.center_y), self.radius)
# pour afficher la hitbox de la balle
# pygame.draw.rect(window, "red", (self.rectangle.x, self.rectangle.y, self.rectangle.width, self.rectangle.height), 2)
def change_angle(self, new_angle):
"""
Met a jour l'attribut angle pour new_angle
"""
self.angle = new_angle
def bounce(self, orientation):
"""
Permet de faire rebondir la balle en changeant l'angle
"""
if orientation == "horizontal":
# rebond sur une surface horizontale
self.angle *= -1
elif orientation == "vertical":
# rebond sur une surface verticale
self.angle = math.pi - self.angle
else:
print("Not a valid bounce. Either horizontal or vertical")
def move(self, window):
"""
Bouge les positions de la balle et update l'attribut rectangle
"""
self.save_pos = (self.center_x, self.center_y) # sauvegarde la position avant de bouger
self.center_x = math.cos(self.angle) * self.velocity + self.center_x
self.center_y = math.sin(self.angle) * self.velocity + self.center_y
self.rectangle = pygame.draw.circle(window, self.color, (self.center_x, self.center_y), self.radius) # update le rectangle
def move_back(self):
"""
Permet de mettre la position de la balle a la derniere position connue
"""
self.center_x, self.center_y = self.save_pos
|
1c1ed04dfa64fa98bc2e36e4a880a8f1cbe37f27 | GastonCordeiro/Curso-Python-CiclosyMetodos | /solo_pares_refactor.py | 105 | 3.921875 | 4 | n = int(input("Ingrese un número para comenzar: \n"))
print()
for i in range(2, n+1, 2):
print(i) |
4b9accb0a81443ffc78be97f4cc75198864abbe7 | django-group/python-itvdn | /домашка/essential/lesson 2/Aliona Baranenko/task_1.py | 1,310 | 3.609375 | 4 | #створити клас едітор, котрий має методи едіт і вью
#метод едіт повинен виводити на екран інформацію, що редагування не доступно
#створити підклас проедітор, змінивши метод едіт в підклассі
#ключ ліцензії повинен вводитись з клавіатури
#і якщо він правильний, повинен створюватись екземпляр класу проедітор, а якщо ні - едітор
#викликати методи едіт і вью
class Editor:
def view_document(self):
print("you have access to viewing the current document")
def edit_document(self):
print("you have no access to editorial revision")
class ProEditor(Editor):
def edit_document(self):
key = input("enter the access key - ")
if key == "qwerty1234":
print("access granted")
editor = ProEditor()
else:
print("password is incorrect, you have no access to editorial revision")
editor = Editor()
def main():
editor.edit_document()
editor.view_document()
if __name__ == '__main__':
main() |
58633b2043af2f660da89416b16ceeb511b490ce | obhalerao/othello-ai | /fibs.py | 301 | 3.671875 | 4 | gFib = {}
def fibSLOW(n):
if(n <= 1): return n
if(n == 2): return 1
return fibSLOW(n-1) + fibSLOW(n-2)
def fib(n):
global gFib
if n in gFib: return gFib[n]
if(n <= 1):
gFib[n] = n
return n
gFib[n] = fib(n-1) + fib(n-2)
return gFib[n]
print(fib(1000)) |
a08939947988e3819dc783984d0cb83ed9db06ae | kruglov-dmitry/algos_playground | /majority_element_i.py | 922 | 3.90625 | 4 | # coding=utf-8
#
# https://leetcode.com/problems/majority-element/
#
# 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.
def majority_element(nums):
el = cnt = 0
for entry in nums:
if entry == el:
cnt += 1
elif cnt == 0:
cnt, el = 1, entry
else:
cnt -= 1
return el
# nums = [-1, 1, 1, 1, 2, 1] # 1
# nums = [32,41,21,29,7,53,97,76,71,53,53,53,72,53,53,14,22,53,67,53,53,53,54,98,53,46,53,53,62,53,76,20,60,53,31,53,53,53,95,27,53,53,53,53,36,59,40,53,53,64,53,53,53,21,53,51,53,53,2,53,53,53,53,53,50,53,53,53,23,88,3,53,61,19,53,68,53,35,42,53,53,48,34,54,53,75,53,53,50,44,92,41,71,53,53,82,53,53,14,53] # 53
nums = [2,2,1,1,1,2,2]
print majority_element(nums) |
4e8284462b1c08df5ed8e64bdeb630fb7ac83a29 | Xenovoyance/adventofcode2015 | /day3/day3.py | 1,436 | 3.796875 | 4 | #!/usr/local/bin/python3
run_env = "prod" # test or prod
if run_env == "test":
input = "input-test.txt"
else:
input = "input.txt"
theworld = {}
santapositionx = 0
santapositiony = 0
roboelfpositionx = 0
roboelfpositiony = 0
positioncounter = 0
def givepresent(x, y):
global theworld
theworld[x, y] = True
givepresent(santapositionx, santapositiony)
with open(input) as blockstream:
for row in blockstream:
for character in row:
# count, if even move santa else move robo
if positioncounter % 2:
if character == "<":
santapositionx -= 1
elif character == ">":
santapositionx += 1
elif character == "^":
santapositiony += 1
elif character == "v":
santapositiony -= 1
givepresent(santapositionx, santapositiony)
else:
if character == "<":
roboelfpositionx -= 1
elif character == ">":
roboelfpositionx += 1
elif character == "^":
roboelfpositiony += 1
elif character == "v":
roboelfpositiony -= 1
givepresent(roboelfpositionx, roboelfpositiony)
positioncounter += 1
print("Santa gave presents to " + str(len(theworld)) + " homes.")
|
9b5c5a2fe795efbede247b9e83ce51edb888599a | sendurr/spring-grading | /submission - Homework4/set2/DANIEL M HARPER_16925_assignsubmission_file_homework4/homework4/P3.py | 2,887 | 4.21875 | 4 | # Author: Daniel Harper
# Assignment: Homework4 - P3.py
# Original Date: 03/23/2016
# Last Updated: 03/23/2016
# Written using Python 3.4.3.7
# All rights reserved
#####################################################################
# Importation Section################################################
from math import * # basic math functions
#from cmath import * # complex math (solve for algebra equations)
#import random # random number generator
import matplotlib.pyplot as plt # plotting library
from numpy import * # arrays, linspaces, most math functions
#import operator # used in sorting dictionaries
import sys # take input from command line
import argparse # store input from command line
# Body Section#######################################################
#--------------------------------------------------------------------
# Work on the following problem. Name it as P3.py. You should be able
# to run it as:
# python P3.py 1 2.5 5
# which will generate 3 curves on the same figure. (Hint, use the
# hold() function to plot multiple curves on the same figure)
#
# Make a program that reads a set of v0 values from the command line
# and plots the corresponding curves y(t)=v0t-0.5gt^2 in the same
# figure (set g=9.81). Let t = [0,2v/g] for each curve, which implies
# that you need a different vector of t coordinates for each curve
# FUNCTION: heightFunction(v,lineType)-------------------------------
# Description: This function outputs a plot of an initial velocity.
# The formula the function is based on is:
# h(t) = v*t - 0.5*g*t^2
# t is the linspace of 100 points from 0 to 2*v/g
# v is the input parameter (mentioned below)
# g is constant at 9.81
# Input Parameters:
# v : initial velocity to base the height of the graph
# lineType: define the color and style of the graph's line
# Output : The plot of the height with the initial velocity of v
def heightFunction(v = 0, lineType = '-b'):
t = linspace(0,2*v/9.81,100)
y = []
for x in t:
y.append(v*x-(0.5)*(9.81)*x**2)
return plt.plot(t,y,lineType, label="%d m/s"%(v))
#--------------------------------------------------------------------
try:
B = [float(sys.argv[1]),float(sys.argv[2]),float(sys.argv[3])]
try:
L = ['-r','-g','-b']
i = 0
hv = vectorize(heightFunction) # vectorize for efficiency
for x in B:
hv(x,L[i])
i+= 1
plt.xlabel("Time(seconds)")
plt.ylabel("Height(meters)")
plt.title("Projectile Motion")
#plt.legend(["","b","","d","","f","g","h"])
# plt.legend (["v0 = "+str(sys.argv[1])+" m/s","v1 = "+str(sys.argv[2])+" m/s","v2: = "+str(sys.argv[3])+" m/s"])
plt.legend(loc='upper right', numpoints = 1,title='Initial Velocities')
# numpoints = 1 is supposed to stop the legend duplicates, but it doesn't seem to work
plt.show()
except:
print("CALCULATION ERROR: Something happened on my end")
except:
print("INPUT ERROR: Numerical values only")
|
96fd0ce8085886b72081ac85a63718e81b00ee9c | Mtmh/py.1nivel1 | /86ListaForNotas.py | 1,163 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 4 12:53:51 2017
@author: tizianomartinhernando
"""
nombres=[]
notas=[]
for x in range(4):
nom=input('Ingrese nombre del alumno: ')
nombres.append(nom)
no=int(input('Ingrese la nota de dicho alumno: '))
notas.append(no)
cantidad=0
for x in range(4):
print(nombres[x])
print(notas[x])
if notas [x]>=8:
print('Muy Buenos')
cantidad=cantidad+1
else:
if notas[x]>=4:
print('Bueno')
else:
print('Insuficiente')
print('La cantidad de alumnos muy buenos son: ')
print(cantidad)
'''
En un curso de 4 alumnos se registraron las notas de sus exámenes y se deben procesar de acuerdo a lo siguiente:
a) Ingresar nombre y nota de cada alumno (almacenar los datos en dos listas paralelas)
b) Realizar un listado que muestre los nombres, notas y condición del alumno. En la condición, colocar "Muy Bueno" si la nota es mayor o igual a 8, "Bueno" si la nota está entre 4 y 7, y colocar "Insuficiente" si la nota es inferior a 4.
c) Imprimir cuantos alumnos tienen la leyenda “Muy Bueno”.
'''
|
66a43fa251eee1971e53e58ff975797ed972e48d | sivacheerla93/python | /oop/Account.py | 2,384 | 4.03125 | 4 | class Account:
# class attribute or static attribute
minbal = 1000
# To get no of objects of a class
numOfInstances = 0
def __init__(self, acno, customer, balance=0):
self.__acno = acno
self.__customer = customer
self.__balance = balance
# To get no of objects of a class
Account.numOfInstances += 1
def __del__(self):
Account.numOfInstances -= 1
def print(self):
print("Account no: ", self.__acno)
print("Customer name: ", self.__customer)
print("Account balance: ", self.__balance)
def __str__(self):
return "{0} {1} {2}".format(self.__acno, self.__customer, self.__balance)
def get_balance(self):
return self.__balance
def deposit(self, amount):
self.__balance += amount
return print(amount, "deposited successfully! to account number", self.__acno, "Available balance is: ",
self.__balance)
def withdraw(self, amount):
if self.__balance - Account.minbal >= amount:
self.__balance -= amount
return print(amount, "has been withdrawn! from account number", self.__acno, "Available balance is: ",
self.__balance)
else:
return print("Insufficient balance to withdraw from your account number", self.__acno,
" Available balance is: ",
self.__balance)
def __eq__(self, other):
return self.__acno == other.__acno and self.__balance == other.__balance
@staticmethod
def set_minbal(new_minbal):
Account.minbal = new_minbal
@staticmethod
def get_instances():
return Account.numOfInstances
# objects
# we can set minbal from here using static method
Account.set_minbal(500)
c1 = Account(123456, "Siva", 1500)
c1.print()
print()
c2 = Account(123457, "Raju", 1500)
c2.print()
print()
print("String of c1 is: ", str(c1))
print()
print("Balance of c2 is: ", c2.get_balance())
print()
c1.deposit(5000)
c1.deposit(2500)
c1.withdraw(3500)
c2.withdraw(1000)
c2.withdraw(100)
print(c1 == c2)
print(c1.get_balance())
print(c2.get_balance())
c2.deposit(5000)
print()
print(c1.__dict__)
print(c2.__dict__)
print(Account.__dict__)
print("No. of objects present in the Account class are: ", Account.get_instances())
del c2
print(Account.get_instances())
|
cce974d39d052d60aa9497f162ba11bc7c831975 | isisisisisitch/python10 | /ca/bytetube/04_container/01_str/StrPractice1.py | 270 | 3.90625 | 4 | str1 = input('Please enter Main string you are looking into: ')
substr1 = input('Please enter substring you are looking for: ')
count = 0
for i in range(len(str1)):
tempstr1 = str1[i::]
if tempstr1.find(substr1) != -1:
count += 1
i += 1
print(count) |
2529a2e050e83a742e8bc9deb6ef8453f00e772d | mohanp79/python_training | /Lists_vs_tuples_Lists_manipulation.py | 402 | 4.28125 | 4 | #tuple is immutable where as List is mutable(can be changed)
# tuples are mainly used for variables asignment tuples use (), lists use []
def example():
return 15,20
a,b = example()
print(a)
print(b)
x = [4,6,3,8,7]
print(x, x[2])
x.append(13)
print(x)
x.insert(2,21)
print(x)
x.remove(3) # removes first element if there are multiple 3's
print(x)
print(x.count(3))
x.sort()
print(x)
|
91d54fe7d330b53c45a9e54585cecb1c034f4ad5 | zekoliu/CorePythonProgramming | /queue_and_stack_10.py | 550 | 3.875 | 4 |
class QueueAndStack(object):
def __init__(self, list):
self.list = list
def __shift__(self):
temp = self.list[0]
del self.list[0]
return temp
def __unshift__(self, newElememt):
return self.list.insert(0, newElememt)
def __push__(self, newElememt):
return self.list.append(newElememt)
def __pop__(self):
temp = self.list[len(self.list) - 1]
del self.list[len(self.list) - 1]
return temp
list = [1,2,3,4,5,6]
q = QueueAndStack(list)
print q.__shift__() |
a46b70573748d96f3da28c6b0c96f5b4d5cfc8b1 | ferayece/BDA | /files/BDA502ML/codes/WEEK-6.py | 20,814 | 3.734375 | 4 |
"""
BDA502
SPRING 2017-18
WEEK-06
Dimensionality Reduction (Unsupervised Learning)
- General Introduction
- Basic algorithm for PCA
- PCA with clustering (kmeans) on digits dataset
- Cancer dataset
- t-SNE versus PCA on digits data set
- Linear Discriminant Analysis (LDA)
"""
"""
Principal component analysis (PCA)
Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space.
Documentation: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html
"""
import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X)
PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
svd_solver='auto', tol=0.0, whiten=False)
print(pca.explained_variance_ratio_)
# [ 0.99244... 0.00755...]
print(pca.singular_values_)
# [ 6.30061... 0.54980...]
pca = PCA(n_components=2, svd_solver='full')
pca.fit(X)
PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
svd_solver='full', tol=0.0, whiten=False)
print(pca.explained_variance_ratio_)
# [ 0.99244... 0.00755...]
print(pca.singular_values_)
# [ 6.30061... 0.54980...]
pca = PCA(n_components=1, svd_solver='arpack')
pca.fit(X)
PCA(copy=True, iterated_power='auto', n_components=1, random_state=None,
svd_solver='arpack', tol=0.0, whiten=False)
print(pca.explained_variance_ratio_)
# [ 0.99244...]
print(pca.singular_values_)
# [ 6.30061...]
# When to use PCA? What does PCA do basically? What is the difference between n_comp =1 and 2?
# when we need to reduce the features, we use PCA. It is a feature selection method.
# n_comp=1 is dimentionaly reduction but while number of feature is 2, n_comp=2 does not select feature on this example.
#number of compenents kendimiz belırleyebilriz, ama feature sayısından az olmak zorunda.
####################################################################################################
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
np.random.seed(42)
digits = load_digits()
data = scale(digits.data)
n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target
sample_size = 300
print("n_digits: %d, \t n_samples %d, \t n_features %d"
% (n_digits, n_samples, n_features))
print(82 * '_')
print('init\t\ttime\tinertia\thomo\tcompl\tv-meas\tARI\tAMI\tsilhouette')
def bench_k_means(estimator, name, data):
t0 = time()
estimator.fit(data)
print('%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.labels_),
metrics.v_measure_score(labels, estimator.labels_),
metrics.adjusted_rand_score(labels, estimator.labels_),
metrics.adjusted_mutual_info_score(labels, estimator.labels_),
metrics.silhouette_score(data, estimator.labels_,
metric='euclidean',
sample_size=sample_size)))
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
name="k-means++", data=data)
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
name="random", data=data)
# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
name="PCA-based",
data=data)
#n_dıgıts=10, 10 component ıle bakıyoruz. 10 eksen olusturur. Kac eksen olusturacagımıza nası karar vercez?
#explained_varince: her eksenın varıanceı verıyor. >80, around 90 olanları secmelıyız. 99 a cekersek overfit riski var.
#elbow rule.
# PCA ın cıkarttıgı featureları K-Means a soktuk.
#Siluet skor dustu çünkü PCA ile her zaman kayıp verebiliriz. Ama performansı daha yuksek.
print(82 * '_')
# digit dataseti; 64 feature ile hangi sayı olduğunu tahmin ediyoruz.
# TASK-2: Please compare the outputs for kmeans including the one with PCA?
# accordıng to execution time, PCA-Based is extremely fast. So, when we need a good performance we should use PCA.
# but when we compare silhouette scores, PCA's score is the worst. Because always we should consider losing some value while doing PCA.
# 160 feature'umuz var, #components'ı 50'ye indirgedik. #2-3-4-5..50 accuracy nin artmasını(comp arttıkca azalarak artmasını bekleriz)
# bi noktadan sonra da dusmesını bekleriz.Cunku overfıt olur, daha fazla component means redundant feature ları da katmıs oluyoruz.
# explaıned_varıance %80-90, elbow rule = dırsegın kırıldıgı nokta
# #############################################################################
# Visualize the results on PCA-reduced data
# eksen olarak 2 tane - pca de en yuksek 2 feature-, 10 tane label ımız -centroıd- var.
reduced_data = PCA(n_components=2).fit_transform(data)
kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)
# Step size of the mesh. Decrease to increase the quality of the VQ.
h = .02 # point in the mesh [x_min, x_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() - 1, reduced_data[:, 0].max() + 1
y_min, y_max = reduced_data[:, 1].min() - 1, reduced_data[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
# TASK 2.5:
print(kmeans.predict([reduced_data[600]])) #8.cluster ı soyluyor. =predict
print(digits.target[600]) #600. label = gerçek. Yani gerçekte 2 olan sayıyı 8.clusterda olarak tahminledi.
# explained variance for 2 components: (ilk 2 bilesen;data ıcındekı varyansın 0.21 (0.12 +0.09) ini acıklıyor. Hedefimiz,
# %80-90 oldugu ıcın bu PCA basarısız.
print(pca.explained_variance_ratio_)
# TASK-3: Please explain what the demonstrated graph contain in detail.
# 64 feature ı 2 pc'a indirdik. Label ları bu 2 componentı eksen alan grafik ustune cizdik.
########################################################################################################
import numpy as np
import mglearn
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
mglearn.plots.plot_pca_illustration()
fig, axes = plt.subplots(15, 2, figsize=(10, 20))
malignant = cancer.data[cancer.target == 0]
benign = cancer.data[cancer.target == 1]
ax = axes.ravel()
for i in range(30):
_, bins = np.histogram(cancer.data[:, i], bins=50)
ax[i].hist(malignant[:, i], bins=bins, color=mglearn.cm3(0), alpha=.5)
ax[i].hist(benign[:, i], bins=bins, color=mglearn.cm3(2), alpha=.5)
ax[i].set_title(cancer.feature_names[i])
ax[i].set_yticks(())
ax[0].set_xlabel("Feature magnitude")
ax[0].set_ylabel("Frequency")
ax[0].legend(["malignant", "benign"], loc="best")
fig.tight_layout()
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(cancer.data)
X_scaled = scaler.transform(cancer.data)
from sklearn.decomposition import PCA
# keep the first two principal components of the data
pca = PCA(n_components=2)
# fit PCA model to beast cancer data
pca.fit(X_scaled)
# transform data onto the first two principal components
X_pca = pca.transform(X_scaled)
print("Original shape: {}".format(str(X_scaled.shape)))
print("Reduced shape: {}".format(str(X_pca.shape)))
# plot first vs. second principal component, colored by class
plt.figure(figsize=(8, 8))
mglearn.discrete_scatter(X_pca[:, 0], X_pca[:, 1], cancer.target)
plt.legend(cancer.target_names, loc="best")
plt.gca().set_aspect("equal")
plt.xlabel("First principal component")
plt.ylabel("Second principal component")
print("PCA component shape: {}".format(pca.components_.shape))
print("PCA components:\n{}".format(pca.components_))
plt.matshow(pca.components_, cmap='viridis')
plt.yticks([0, 1], ["First component", "Second component"])
plt.colorbar()
plt.xticks(range(len(cancer.feature_names)),
cancer.feature_names, rotation=60, ha='left')
plt.xlabel("Feature")
plt.ylabel("Principal components")
print(pca.explained_variance_ratio_) # around 0.63 which is not enough. Maybe we can add one more component to model.
#TASK-4: Please explain each of the figure shown in this part. What do the use of PCA have an impact?
# Figure 4:(renkli renkli yesil vs) show correlation between components for each feature. (meaningful around corr=0.5) In this graph, it s between 0.3 and -0.2
# So, components are fair combination of all features which is not good. No dominant features, so we cannot named the components.
# If we had 3 or 4 features which are correlated with compenent 1 with 0.6 correlation coefficient, we could name it.
#Figure 3:(sketterplot maningant vs bisi)
#########################################################################################################
# TASK-5: Please get the iris data set and apply PCA then determine if you can assign names for the components.
#########################################################################################################
from sklearn.datasets import fetch_lfw_people
people = fetch_lfw_people(min_faces_per_person=20, resize=0.7)
image_shape = people.images[0].shape
fig, axes = plt.subplots(2, 5, figsize=(15, 8),
subplot_kw={'xticks': (), 'yticks': ()})
for target, image, ax in zip(people.target, people.images, axes.ravel()):
ax.imshow(image)
ax.set_title(people.target_names[target])
print("people.images.shape: {}".format(people.images.shape))
print("Number of classes: {}".format(len(people.target_names)))
# count how often each target appears
counts = np.bincount(people.target)
# print counts next to target names:
for i, (count, name) in enumerate(zip(counts, people.target_names)):
print("{0:25} {1:3}".format(name, count), end=' ')
if (i + 1) % 3 == 0:
print()
mask = np.zeros(people.target.shape, dtype=np.bool)
for target in np.unique(people.target):
mask[np.where(people.target == target)[0][:50]] = 1
X_people = people.data[mask]
y_people = people.target[mask]
# scale the grey-scale values to be between 0 and 1
# instead of 0 and 255 for better numeric stability:
X_people = X_people / 255.
from sklearn.neighbors import KNeighborsClassifier
# split the data in training and test set
X_train, X_test, y_train, y_test = train_test_split(
X_people, y_people, stratify=y_people, random_state=0)
# build a KNeighborsClassifier with using one neighbor:
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, y_train)
print("Test set score of 1-nn: {:.2f}".format(knn.score(X_test, y_test)))
mglearn.plots.plot_pca_whitening()
pca = PCA(n_components=100, whiten=True, random_state=0).fit(X_train)
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
print("X_train_pca.shape: {}".format(X_train_pca.shape))
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train_pca, y_train)
print("Test set accuracy: {:.2f}".format(knn.score(X_test_pca, y_test)))
print("pca.components_.shape: {}".format(pca.components_.shape))
fig, axes = plt.subplots(3, 5, figsize=(15, 12),
subplot_kw={'xticks': (), 'yticks': ()})
for i, (component, ax) in enumerate(zip(pca.components_, axes.ravel())):
ax.imshow(component.reshape(image_shape),
cmap='viridis')
ax.set_title("{}. component".format((i + 1)))
"""
Manifold Learning with t-SNE
"""
from sklearn.datasets import load_digits
import pylab as plt
digits = load_digits()
fig, axes = plt.subplots(2, 5, figsize=(10, 5),
subplot_kw={'xticks':(), 'yticks': ()})
for ax, img in zip(axes.ravel(), digits.images):
ax.imshow(img)
# build a PCA model
pca = PCA(n_components=2)
pca.fit(digits.data)
# transform the digits data onto the first two principal components
digits_pca = pca.transform(digits.data)
colors = ["#476A2A", "#7851B8", "#BD3430", "#4A2D4E", "#875525",
"#A83683", "#4E655E", "#853541", "#3A3120", "#535D8E"]
plt.figure(figsize=(10, 10))
plt.xlim(digits_pca[:, 0].min(), digits_pca[:, 0].max())
plt.ylim(digits_pca[:, 1].min(), digits_pca[:, 1].max())
for i in range(len(digits.data)):
# actually plot the digits as text instead of using scatter
plt.text(digits_pca[i, 0], digits_pca[i, 1], str(digits.target[i]),
color = colors[digits.target[i]],
fontdict={'weight': 'bold', 'size': 9})
plt.xlabel("First principal component")
plt.ylabel("Second principal component")
from sklearn.manifold import TSNE
tsne = TSNE(random_state=42)
# use fit_transform instead of fit, as TSNE has no transform method
digits_tsne = tsne.fit_transform(digits.data)
plt.figure(figsize=(10, 10))
plt.xlim(digits_tsne[:, 0].min(), digits_tsne[:, 0].max() + 1)
plt.ylim(digits_tsne[:, 1].min(), digits_tsne[:, 1].max() + 1)
for i in range(len(digits.data)):
# actually plot the digits as text instead of using scatter
plt.text(digits_tsne[i, 0], digits_tsne[i, 1], str(digits.target[i]),
color = colors[digits.target[i]],
fontdict={'weight': 'bold', 'size': 9})
plt.xlabel("t-SNE feature 0")
plt.xlabel("t-SNE feature 1")
"""
Linear Discriminant Analysis (LDA)
A classifier with a linear decision boundary, generated by fitting class conditional densities to the data and using
Bayes’ rule.
The model fits a Gaussian density to each class, assuming that all classes share the same covariance matrix.
The fitted model can also be used to reduce the dimensionality of the input by projecting it to the most discriminative
directions.
The default solver is ‘svd’. It can perform both classification and transform, and it does not rely on the calculation
of the covariance matrix. This can be an advantage in situations where the number of features is large.
However, the ‘svd’ solver cannot be used with shrinkage. The ‘lsqr’ solver is an efficient algorithm that only works for
classification. It supports shrinkage.
The ‘eigen’ solver is based on the optimization of the between class scatter to within class scatter ratio. It can be
used for both classification and transform, and it supports shrinkage. However, the ‘eigen’ solver needs to compute the
covariance matrix, so it might not be suitable for situations with a high number of features.
"""
import numpy as np
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
y = np.array([1, 1, 1, 2, 2, 2])
clf = LinearDiscriminantAnalysis()
clf.fit(X, y)
LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage=None,
solver='svd', store_covariance=False, tol=0.0001)
print(clf.predict([[-0.8, -1]]))
"""
Shows how shrinkage improves classification.
http://scikit-learn.org/stable/auto_examples/classification/plot_lda.html#sphx-glr-auto-examples-classification-plot-lda-py
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
n_train = 20 # samples for training
n_test = 200 # samples for testing
n_averages = 50 # how often to repeat classification
n_features_max = 75 # maximum number of features
step = 4 # step size for the calculation
def generate_data(n_samples, n_features):
"""Generate random blob-ish data with noisy features.
This returns an array of input data with shape `(n_samples, n_features)`
and an array of `n_samples` target labels.
Only one feature contains discriminative information, the other features
contain only noise.
"""
X, y = make_blobs(n_samples=n_samples, n_features=1, centers=[[-2], [2]])
# add non-discriminative features
if n_features > 1:
X = np.hstack([X, np.random.randn(n_samples, n_features - 1)])
return X, y
acc_clf1, acc_clf2 = [], []
n_features_range = range(1, n_features_max + 1, step)
for n_features in n_features_range:
score_clf1, score_clf2 = 0, 0
for _ in range(n_averages):
X, y = generate_data(n_train, n_features)
clf1 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage='auto').fit(X, y)
clf2 = LinearDiscriminantAnalysis(solver='lsqr', shrinkage=None).fit(X, y)
X, y = generate_data(n_test, n_features)
score_clf1 += clf1.score(X, y)
score_clf2 += clf2.score(X, y)
acc_clf1.append(score_clf1 / n_averages)
acc_clf2.append(score_clf2 / n_averages)
features_samples_ratio = np.array(n_features_range) / n_train
plt.plot(features_samples_ratio, acc_clf1, linewidth=2,
label="Linear Discriminant Analysis with shrinkage", color='navy')
plt.plot(features_samples_ratio, acc_clf2, linewidth=2,
label="Linear Discriminant Analysis", color='gold')
plt.xlabel('n_features / n_samples')
plt.ylabel('Classification accuracy')
plt.legend(loc=1, prop={'size': 12})
plt.suptitle('Linear Discriminant Analysis vs. \
shrinkage Linear Discriminant Analysis (1 discriminative feature)')
plt.show()
"""
The Iris dataset represents 3 kind of Iris flowers (Setosa, Versicolour and Virginica) with 4 attributes: sepal
length, sepal width, petal length and petal width.
Principal Component Analysis (PCA) applied to this data identifies the combination of attributes (principal components,
or directions in the feature space) that account for the most variance in the data. Here we plot the different samples
on the 2 first principal components.
Linear Discriminant Analysis (LDA) tries to identify attributes that account for the most variance between classes. In
particular, LDA, in contrast to PCA, is a supervised method, using known class labels.
"""
print(__doc__)
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
iris = datasets.load_iris()
X = iris.data
y = iris.target
target_names = iris.target_names
pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)
# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
% str(pca.explained_variance_ratio_))
plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of IRIS dataset')
plt.figure()
for color, i, target_name in zip(colors, [0, 1, 2], target_names):
plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.8, color=color,
label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of IRIS dataset')
plt.show()
|
fea5a0ebe7c9044eb15980351d126cf5184a698a | apratim1988/python-selenium-framework | /ExcelDemoPackage/exceldemo.py | 1,101 | 3.84375 | 4 | import openpyxl
#reading value from xcel
book = openpyxl.load_workbook("C:\\Users\\aprat\\PycharmProjects\\PythonSelFramework\\pythonxcel.xlsx")
sheet = book.active
Dict ={}
cell = sheet.cell(row=1,column=2)
print(cell.value)
#writing value from xcel
sheet.cell(row=2,column=2).value = "Apratim"
#to check t he number of rows/columns in the sheet
sheet.max_row
sheet.max_column
#to print the values of all row and all columns using for loop
for i in range(1,sheet.max_row+1):
for j in range(1,sheet.max_column+1):
print(sheet.cell(row=i,column=j))
#to print the values of a selected row
for i in range(1,sheet.max_row+1):
if sheet.cell(row=i,column=1).value == "TestCase2":
for j in range(1,sheet.max_column+1):
print(sheet.cell(row=i,column=j))
#from the below code,the firstname ,lastname and gender will be printed
for i in range(1,sheet.max_row+1):
if sheet.cell(row=i,column=1).value == "TestCase2":
for j in range(1,sheet.max_column+1):
Dict[sheet.cell(row=1,column=j).value] = sheet.cell(row=i,column=j).value
print(Dict)
|
85cf9b6a1a9814f7bcd0c01c4f82f91b18cd1aea | camruggles/Cancer-Classification | /k means/hyperparameter.py | 2,235 | 3.609375 | 4 | import read_clean
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from ggplot import *
# Getting the Data
X,y = read_clean.getCleanedData("data.csv")
###############################################
# Good Value of K
###############################################
# I used the elbow method to help me find the best value of k.
#The idea is to choose a small value of k that still has a low SSE, and the elbow usually represents
#where we start to have diminishing returns by increasing k.
inertia = {}
for i in range(1,10):
# Getting the Data
X,y = read_clean.getCleanedData("data.csv")
kmeans = KMeans(n_clusters = i, random_state = 1)
kmeans = kmeans.fit(X)
inertia[i] = kmeans.inertia_
print(kmeans.inertia_)
plt.figure()
plt.plot(list(inertia.keys()), list(inertia.values()))
plt.xlabel("Number of clusters")
plt.ylabel("Inertia")
plt.show()
###############################################
# Visualizing Cluster data
###############################################
# As shown in the graph below, the elbow of the graph is 2.
# So, 2 is a good value of K and it makes sense as the tumor is either malignant or benign
elbow = 2
X,y = read_clean.getCleanedData("data.csv")
kmeans = KMeans(n_clusters = elbow, random_state = 3)
kmeans = kmeans.fit(X)
y_kmeans = kmeans.predict(X)
# Converting X to a dataframe
X_predict_pd = pd.DataFrame(X)
# Appending y
X_predict_pd['diagnosis'] = y_kmeans
print(ggplot(aes(x=0 , y=1, color = 'diagnosis'), data= X_predict_pd) + geom_point() + xlab("Dimension 1") + ylab("Dimension 2") + ggtitle("Cluster Data"))
###############################################
# Visualizing Actual data
###############################################
# Malignant is denoted by 1 and Benign as -1 in the original dataset
# Converting benign to 0
X,y = read_clean.getCleanedData("data.csv")
y = [0 if x == -1 else x for x in y]
# Converting X to a dataframe
X_pd = pd.DataFrame(X)
# Appending y
X_pd['diagnosis'] = y
print(ggplot(aes(x=0 , y=1, color = 'diagnosis'), data= X_pd) + geom_point() + xlab("Dimension 1") + ylab("Dimension 2") + ggtitle("Actual Data"))
|
8a062a671e132771f681947d9f321b667e72dcdb | MTamara95/Codility-Exercises-Solutions | /7_StacksAndQueues/2_Nesting.py | 380 | 3.703125 | 4 | # task: https://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/
def solution(S):
stack = []
for i in range(0, len(S)):
if(S[i] == '('):
stack.append('(')
else: # S[i] = ')'
if(len(stack) == 0):
return 0
stack.pop()
i = i+1
if(len(stack) == 0):
return 1
return 0 |
26c5ce1029d6e17b5fabbc8a35c9ff99d2880432 | acrodeon/pythonInteractive-algos | /topologicalSort.py | 955 | 3.984375 | 4 | #####################################################################################
# Topological Sort #
# takes a directed acyclic graph and produces a linear ordering of all its vertices #
# such that if the graph G contains an edge (v,w) then the vertex v comes before #
# the vertex w in the ordering #
#####################################################################################
# from depthFirstSearch import DFSGraph
def topologicalSort(g):
"""return list of vertices sorted according to topological sort of a directed acyclic graph g"""
# Depth First Search to compute finish time for each vertex of g as DFSGraph
g.dfs()
# vertices in a list in decreasing order of finish time
vertices = [vert for vert in g]
vertices.sort(key=lambda vert: vert.getFinish())
return vertices
|
8973accb9a703b6679c3138e24dcc89de101c2d5 | knt/merge_pdf | /merge_pdf.py | 1,186 | 3.578125 | 4 | #!/usr/bin/python
from pyPdf import PdfFileWriter, PdfFileReader
import sys
#Requires Python 2.7
#import argparse
#parser = argparse.ArgumentParser(description="Merges a series of pdf files into a single pdf")
#parser.add_argument('destFile', metavar="D", type=file, nargs='1', help="desired filename of the final merged pdf")
#parser.add_argument('pdfFiles', metavar='I', type=file, nargs='+',
# help="filename of a pdf you'd like to merge into the destination")
def merge_pdf(argv=None):
# Parse arguments
if argv is None:
argv = sys.argv
args = sys.argv[1:]
if len(args) < 2:
print "Usage: merge_pdf.py dest.pdf input1.pdf...inputn.pdf"
sys.exit(1)
dest = args[0]
pdfFiles = args[1:]
# Add pages to write
output = PdfFileWriter()
outputStream = file(dest, 'wb')
for f in pdfFiles:
inputF = PdfFileReader(file(f, "rb"))
numPages = inputF.getNumPages()
for pageNum in xrange(numPages):
output.addPage(inputF.getPage(pageNum))
# Write output
output.write(outputStream)
outputStream.close()
if __name__ == "__main__":
merge_pdf()
|
9dc96610987adf7b6dbd457c6d4254582c977d36 | ctociojosh/Codility-Python | /CountSemiprimes_low_performance.py | 1,829 | 3.796875 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
import math
def solution(N, P, Q):
# write your code in Python 3.6
# 1
# find primes: use 'Sieve of Eratosthenes'
prime_list = []
# put all values
# be careful about the range
for index in range( 2, N+1 ):
prime_list.append(index)
#print(prime_list)
# 2
# remove 'not prime'
# be careful about the range
for item in range( 2, math.floor(math.sqrt(N))+1 ):
not_prime_first = item + item
for not_prime in range( not_prime_first, N+1, item ):
if not_prime in prime_list:
prime_list.remove(not_prime)
#print(prime_list)
# 3
# find semi-primes
semiprime_list = []
for i in range( len(prime_list) ):
for j in range( i, len(prime_list) ):
semiprime = prime_list[i] * prime_list[j]
if semiprime <= N:
semiprime_list.append(semiprime)
semiprime_list.sort()
#print(semiprime_list)
# 4
# count the number of semi-primes
count_semiprime_list = [0] * (N+1)
num_semiprime_so_far = 0
for i in range(N+1):
if i in semiprime_list:
num_semiprime_so_far += 1
count_semiprime_list[i] = num_semiprime_so_far
#print(count_semiprime_list)
# 5
# return answers to all the queries
answer_list = [0] * len(P)
for i in range( len(P) ):
begin_value = P[i]
end_value = Q[i]
#print(count_semiprime_list[end_value])
#print(count_semiprime_list[begin_value])
# be very careful about the 'begin_value' (not included)
answer_list[i] = count_semiprime_list[end_value] - count_semiprime_list[ (begin_value-1) ]
#print(answer_list)
return answer_list
|
4b83d5e88cb7d744d783dd5c3624dc887ed233b7 | CodingDojoTulsaMay2018/claire_elliott | /python-stack/python-fun/function_intermediate1.py | 762 | 4.28125 | 4 | # As part of this assignment, please create a function randInt() where
# randInt() returns a random integer between 0 to 100
# randInt(max=50) returns a random integer between 0 to 50
# randInt(min=50) returns a random integer between 50 to 100
# randInt(min=50, max=500) returns a random integer between 50 and 500
# Create this function without using random.randInt() but you are allowed to use random.random().
import random
def rand_int(min = False, max = False):
if max:
num = random.random()*max
return int(num)
elif min:
num = range(min, 100)
return int(random.choice(num))
elif max and min:
num = range(min, max)
return int(random.choice(num))
num = random.random()*100
return int(num) |
4f7afab8da63963c7b5ebff4939dcd4d46b2696f | PanosDimo/MovieFlix2020_E14038_Dimakakos_Panagiotis | /src/movieflix/utils/crypto.py | 538 | 3.53125 | 4 | """Encryption utilities."""
import bcrypt
def hashify(plain: str) -> bytes:
"""Hash a string.
:param plain: The string to hash.
:return: The hashed version of ``plain``.
"""
return bcrypt.hashpw(plain.encode(), bcrypt.gensalt(10))
def verify(plain: str, crypted: bytes) -> bool:
"""Verify hashed string.
:param plain: The string to verify.
:param crypted: The encrypted string to verify against.
:return: Whether the string is verified.
"""
return bcrypt.checkpw(plain.encode(), crypted)
|
a850014f7a18facfae1b37027a67977109fe1e4b | Lioncat2002/computerProjPy | /pyplotyx2.py | 155 | 3.921875 | 4 | '''11.WAP to plot the function y=x^2 with pyplot library'''
import matplotlib.pyplot as plt
x=range(-100,100)
y=[i*i for i in x]
plt.plot(x,y)
plt.show() |
22cb17e68b34ee0ce9dd83dd604c538d54b9d9e8 | Phillyclause89/reddit_scripts | /some_problem_with_list_ans_swapping_value/Henrik.py | 1,890 | 4.125 | 4 | # Uendelig liste Melli oppgave >:)
# Infinite list Melli task> :)
# eternal list = []
evig_liste = []
# again = "yes"
en_gang_til = "ja"
# print ("Enter the desired number in the list:")
print("Skriv inn ønsket tall i listen: ")
# while again == "yes" or again == "Yes":
def validate_input(inpu):
try:
return int(inpu)
except ValueError:
return inpu
def adding_to_evig_liste(e_g_t):
if e_g_t.lower() == "ja":
return True
return False
while adding_to_evig_liste(en_gang_til):
# add = int (input ("Enter the number you want to add to the list:"))
legg_til = validate_input(input("Skriv inn tallet du ønsker å legge til i listen: "))
# eternal list + = [int (add)]
evig_liste += [legg_til]
# again = input ("Do you want to add more numbers to the list?:")
en_gang_til = input("ønsker du å legge til flere tall i listen? :")
# print ("your list so far:", forever list)
print("listen din til nå: ", evig_liste)
# smallest number = everlasting list [0]
minste_tall_index = 0
minste_tall = evig_liste[minste_tall_index]
# highest numbers = everlasting list [0]
hoyeste_tall_index = 0
hoyeste_tall = evig_liste[hoyeste_tall_index]
# for in in range (1, len (perpetual list)):
for i, n in enumerate(evig_liste):
if n <= minste_tall:
minste_tall_index = i
minste_tall = n
if n >= hoyeste_tall:
hoyeste_tall_index = i
hoyeste_tall = n
# print ("smallest number in list", smallest number)
print("minste tallet i listen", minste_tall)
# print ("smallest number in list", smallest number)
print("høyeste tallet i listen", hoyeste_tall)
temp = evig_liste[minste_tall_index]
temp2 = evig_liste[hoyeste_tall_index]
evig_liste[minste_tall_index] = temp2
evig_liste[hoyeste_tall_index] = temp
print(temp)
print("listen med byttet høyeste og laveste tall", evig_liste)
|
8c5498b935164c457447729c6de1553b390664e5 | andremmfaria/exercises-coronapython | /chapter_06/chapter_6_6_8.py | 522 | 4.34375 | 4 | # 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.
pet_0 = {
'kind' : 'dog',
'owner' : 'Juliana'
}
pet_1 = {
'kind' : 'cat',
'owner' : 'Ana'
}
pet_2 = {
'kind' : 'fish',
'owner' : 'Joao'
}
pets = [pet_0, pet_1, pet_2]
for p in pets:
print(p) |
c43617233eb421931bd3f9749c60f81b35e159d2 | thiagosouzalink/my_codes-exercices-book-curso_intensivo_de_python | /Capitulo_09/exercise9_8.py | 1,640 | 4.34375 | 4 | """
9.8 – Privilégios: Escreva uma classe Privileges separada. A classe deve ter um
atributo privileges que armazene uma lista de strings conforme descrita no
Exercício 9.7. Transfira o método show_privileges() para essa classe. Crie
uma instância de Privileges como um atributo da classe Admin. Crie uma nova
instância de Admin e use seu método para exibir os privilégios.
"""
class User:
def __init__(self, first_name, last_name, age, email):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.email = email
self.login_attempts = 0
def describe_user(self):
print("\nInformações do Usuário:")
print(f"Nome: {self.first_name}")
print(f"Sobrenome: {self.last_name}")
print(f"Idade: {self.age}")
print(f"E-mail: {self.email}")
def greet_user(self):
print(f'Olá, {self.first_name}! Seja bem vindo(a)!')
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
class Admin(User):
def __init__(self, first_name, last_name, age, email):
super().__init__(first_name, last_name, age, email)
self.privilege = Privileges()
class Privileges:
def __init__(self):
self.privileges = ['Pode add post', 'Pode excluir post', 'Pode banir usuário']
def show_privileges(self):
print(f'Privilégios do administrador: ')
for privilege in self.privileges:
print (privilege)
admin = Admin('Paulo', 'Oliveira', 35, 'paulo@mail.com')
admin.privilege.show_privileges() |
3b67b0d2f8a79aa76fd646ddf4607a4fd1219661 | nikhilkumarsingh/Parallel-Programming-in-Python | /06. Sharing data using Server Process/data_sharing2.py | 1,035 | 4.25 | 4 | import multiprocessing
def print_records(records):
"""
function to print record(tuples) in records(list)
"""
for record in records:
print("Name: {0}\nScore: {1}\n".format(record[0], record[1]))
def insert_record(record, records):
"""
function to add a new record to records(list)
"""
records.append(record)
print("New record added!\n")
if __name__ == '__main__':
with multiprocessing.Manager() as manager:
# creating a list in server process memory
records = manager.list([('Sam', 10), ('Adam', 9), ('Kevin',9)])
# new record to be inserted in records
new_record = ('Jeff', 8)
# creating new processes
p1 = multiprocessing.Process(target=insert_record, args=(new_record, records))
p2 = multiprocessing.Process(target=print_records, args=(records,))
# running process p1 to insert new record
p1.start()
p1.join()
# running process p2 to print records
p2.start()
p2.join()
|
b11b0e1a9d8b6422bf6f453ec45a99b47e88b504 | stt106/pythonbeyondbasics | /iterables/comprehension.py | 686 | 3.90625 | 4 | """ Comprehensions
Shorthand syntax for creating collection and iterable objects
"""
### multiple inputs comprehensions ###
values = [x / (x - y)
for x in range(100) if x > 50
for y in range(100) if x - y != 0
]
# it's possible to refer the former clause in the latter clause
points = [(x, y) for x in range(10) for y in range(x)]
print(len(points))
### nested comprehensions
vals = [[y * 2 for y in range(x)] for x in range(10)]
# multiple and nested comprehensions apply to other collection types as well
unique_prodcuts = {x * y for x in range(10) for y in range(10)}
# generator comprehension
g = ((x, y) for x in range(10) for y in range(x))
|
d8d06838dd0d835446dbd1dcf3032b143b5036d7 | linhtruc/linhngo-fundermentals-c4e28 | /Section3/ex1.py | 400 | 3.828125 | 4 | from random import randint
i = randint (0,100)
print (i)
count = 0
loop = True
while loop:
n = int(input("Enter a number(0-100): "))
if count < 3:
if n < i:
print ("Lower")
elif n > i:
print ("Higher")
else:
print ("Bingo")
loop = False
count += 1
else:
loop = False
print ("Game over")
|
b64c11d1580a1be1a70a07dfc3997c0a0d1f658d | relax-space/python-ccc | /practice1/2l.py | 517 | 3.734375 | 4 | '''
问题2
使用给定的整数n,编写程序以生成包含(i,i * i)的字典,该字典为1到n之间的整数(都包括在内)。然后程序应打印字典。
假设将以下输入提供给程序:8
然后,输出应为:{1:1、2:4、3:9、4:16、5:25、6:36、7:49、8:64}
提示:
如果将输入数据提供给问题,则应假定它是控制台输入。
考虑使用dict()
'''
num = int(input("请输入一个正整数:"))
print({i: i**2 for i in range(1, num+1)})
|
46ae1407720b2c79a5b6fcd783bc386bc5476db9 | drakonorozdeniy/Programming | /Practice/Autum/Python/17. Казино.py | 815 | 3.734375 | 4 | m=37
numbers=[0]*m
red = 0
black = 0
a = 0
print(len(numbers))
array_red = [ 1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36 ]
array_black = [2,4,6,8,10,11,13,15,17,20,22,24,26,28,29,31,33,35 ]
while (1):
numb=int(input("Введите число\n"))
if numb < 0 or numb > 36:
break
else:
numbers[numb]+=1
for color in range (18):
if (numb == array_red[color]):
red = red + 1
elif (numb == array_black[color]):
black = black + 1
for s in range(m):
if (numbers[s] > a):
a = numbers[s]
for s in range(m):
if (numbers[s] == a):
print(s, end='')
for s in range(m):
if (numbers[s] == 0):
print(s, end=' ')
print("\n",red,black)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.