blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4a31285c6557c05b4c813e848c1f1af938d4e621 | jlyons6100/Wallbreakers | /Week_1/number_of_islands.py | 1,252 | 3.5625 | 4 | # Number of Islands: Given a 2d grod map of 1's(land) and 0's (water), counts the number of islands.
class Solution:
# b_first(grid, tup, visited): Adds (row, col) tuples to set of visited islands
def b_first(self, grid, tup, visited) -> None:
invalid_row = tup[0] < 0 or tup[0] > len(grid) - 1
invalid_col = tup[1] < 0 or tup[1] > len(grid[0]) - 1
if not (invalid_row or invalid_col or tup in visited or grid[tup[0]][tup[1]] == "0"):
visited.add(tup)
self.b_first(grid, (tup[0] - 1, tup[1]), visited)
self.b_first(grid, (tup[0] + 1, tup[1]), visited)
self.b_first(grid, (tup[0], tup[1] - 1), visited)
self.b_first(grid, (tup[0], tup[1] + 1), visited)
# numIslands(grid): Finds number of islands (Groups of 1's) in a matrix
def numIslands(self, grid: List[List[str]]) -> int:
visited = set()
island_count = 0
for row in range(len(grid)):
for col in range(len(grid[0])):
if grid[row][col] == "1":
tup = (row, col)
if not tup in visited:
island_count += 1
self.b_first(grid,tup, visited)
return island_count |
35e7796ff0e8abb10a0be1df0824ab4d5156948e | ezhilmaran1612/days | /day12.py | 729 | 3.875 | 4 | def decimalToBinary(num, k_prec) :
binary = ""
Integral = int(num)
fractional = num - Integral
while (Integral) :
rem = Integral % 2
binary += str(rem);
Integral //= 2
binary = binary[ : : -1]
binary += '.'
while (k_prec) :
fractional *= 2
fract_bit = int(fractional)
if (fract_bit == 1) :
fractional -= fract_bit
binary += '1'
else :
binary += '0'
k_prec -= 1
return binary
if __name__ == "__main__" :
n = 4.47
k = 3
print(decimalToBinary(n, k))
n = 6.986
k = 5
print(decimalToBinary(n, k)) |
850d8f28011c695e9a35d8c45e474f7f0f887e63 | dopqob/Python | /Python学习笔记/进程丨线程丨协程/线程的使用.py | 1,105 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/14 10:06
# @Author : Bilon
# @File : 线程的使用.py
import threading
from time import sleep, ctime
"""
# =====================================
# 线程的创建、启动、阻塞
# =====================================
"""
def loop(nsec):
"""
先申明一个loop函数,传入一个sleep时间,打印一下启动时间,然后sleep几秒
"""
print('Start loop: {:>30}'.format(ctime()))
print('Sleep {} seconds'.format(nsec))
sleep(nsec)
def main():
"""
然后申明一个main函数,targe是要调用的函数名字,args是要传递给targe函数的参数
args是一个元组,如果只有一个参数,后面要加逗号
用t.start()来启动线程,用t.join()阻塞,一直等到线程完成,打印'All Done'
"""
print('Starting: {:>30}'.format(ctime()))
t = threading.Thread(target=loop, args=(3,))
t.start() # 开始线程
t.join() # 等待线程结束
print('All Done: {:>30}'.format(ctime()))
if __name__ == '__main__':
main()
|
94f7c4d11a8a34875bf28f37cb014b650f52a554 | ArslanShafique1998/SPL-Technical-Assessment | /Advanced/Search/pair_of_target_number.py | 1,395 | 4.25 | 4 | def find_pairs(array,target):
pairs=[]
l=len(array)
#initialize the tuple
p=()
#We add each element with the rest of high index elements For example array=[1,2,3,4]
#Then take first element 1 and add other high index 1+2,1+3,1+4, then take 2 and 2+3,2+4
# then take 3 so add high index 3+4. By this we can check each possibility by edition.
for i in range (0,l,1):
for j in range (i,l,1):
if array[i]+array[j]==target: #if the addition equals to target value
p=(array[i],array[j]) #then put that pair in tuple and then put that tuple in array
pairs.append(p)
l=len(pairs)
for i in range (0,l,1):
for j in range (i+1,l,1):
if pairs[i][0]==pairs[j][1] and pairs[i][1]==pairs[j][0]:#if we have identical tuples then it remove on tuple
pairs.remove(pairs[i])
elif pairs[i][0]==pairs[j][0] and pairs[i][1]==pairs[j][1]:
pairs.remove(pairs[i])
return pairs
#Take the length of array
n=int(input("Enter the length of array:"))
array=[]
#Take elements of array
for i in range (0,n,1):
num=int(input("Enter the element of array:"))
array.append(num)
#Take target value
target=int(input("Enter the target value:"))
#Pass the array and target value
pairs= find_pairs(array,target)
print("Pairs are:",pairs) |
ff939aca103da9842ec82c5b564a74c32af51161 | llgeek/leetcode | /441_ArrangingCoins/solution.py | 288 | 3.5 | 4 | from math import sqrt, floor
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
for i in range(floor(sqrt(2*n)), -1, -1):
if i*(i+1) <= 2*n and (i+1)*(i+2) > 2*n:
return i
return 0
|
895ba260d75f74ae06443769dbdfff7b58ee237b | germanoso/GeekBrains | /Max_in_num.py | 753 | 4.125 | 4 | # 4. Пользователь вводит целое положительное число.
# Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
# К сожалению, не знаю как через цикл while сделать это задание (((
user_num = list(input('Введите целое положительное число: '))
# Приводим введенное число ввиде строки к списку
num_list = list(user_num)
for i in range(len(num_list)):
num_list[i] = int(num_list[i])
print('Максимальная цифра в вашем числе: ', max(num_list))
|
0cf2e4123bab6c8186c8b3bcf743296b0748816b | sz982005/quant_study | /lesson5/homework0/FeatureUtils/ATR.py | 1,572 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 4 12:58:42 2018
@author: zhangjue
"""
#Wilder started with a concept called True Range (TR), which is defined as the greatest of the following:
#
#Method 1: Current High less the current Low
#Method 2: Current High less the previous Close (absolute value)
#Method 3: Current Low less the previous Close (absolute value)
#Current ATR = [(Prior ATR x 13) + Current TR] / 14
#
# - Multiply the previous 14-day ATR by 13.
# - Add the most recent day's TR value.
# - Divide the total by 14
import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
#def ATR(data,n):
# for i in len(data)
#
# data = data.join(ATR)
# return data
data = ts.get_k_data('600000',start='2010-01-01', end='2016-01-01')
data = pd.DataFrame(data)
# ATR
def ATR(data,n =1):
TR_lst = [data.iloc[0]['high']-data.iloc[0]['low']]
for i in range(1,len(data)):
current_high = data.iloc[i]['high']
current_low = data.iloc[i]['low']
previous_close = data.iloc[i-1]['close']
TR1 = current_high - current_low
TR2 = current_high - previous_close
TR3 = current_low - previous_close
TR = max(TR1,TR2,TR3)
TR_lst.append(TR)
ATR = []
for i in range(0,14):
ATR.append(TR_lst[i])
ATR.append(sum(ATR)/len(ATR))
for i in range(15,len(TR_lst)):
ATR.append((ATR[i-1]*13 + TR_lst[i])/14)
ATR = pd.Series(ATR, name = 'Actual True Range')
data = data.join(ATR)
return data
|
be8ec587f5abcbc1c89293ca9a5c35efa31681be | dixitk13/python-scripts | /python-day/python-1.py | 2,666 | 3.671875 | 4 | #!/usr/bin/python
import re
from sys import argv
import heapq
import random
from os.path import exists
class Point():
def __init__(self, _x, _y):
self.x = _x
self.y = _y
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __str__(self):
return str(self.__dict__)
def __repr__(self):
return self.__str__()
def __lt__(self, other):
if self.x == other.x:
return self.y < other.y
else:
return self.x < other.x
def __ne__(self, other):
return not self.__eq__(other)
def __gt__(self, other):
return other.__lt__(self)
def __hash__(self):
return hash(self.x) + hash(self.y)
class PowTwo:
"""Class to implement an iterator
of powers of two"""
def __init__(self, max = 0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
# indata = open("cover_letter.txt").read()
# with open("cover_letter.txt") as f:
# for line in f:
# print line
# lst = [11,12,31]
# for i,e in enumerate(lst):
# print i, e
# print exists("cover_letter.txt")
# print exists("cover_letter1.txt")
mylist = [x*x for x in range(3)]
mygenerator = (x*x for x in range(3))
p1 = Point(1,1)
p2 = Point(2.2, 2.2)
p11 = Point(1,1)
p3 = Point(1,3)
print p1, p2, p3
print p1 == p3
print p1 == p2
lst = []
lst.append(p1)
lst.append(p2)
lst.append(p3)
lst2 = [p1, p2, p3, p11]
print lst
print 'sorted on x => ', sorted(lst)
lst.sort()
print 'lst.sort() on lst', lst
print 'lambda sorted on y => ', sorted(lst, key=lambda x: x.y, reverse=True)
print 'lambda sorted on x => ', sorted(lst, key=lambda x: x.x, reverse=True)
print 'new lst ', lst2
lst3 = lst2
print 'before removing lst3 = ', lst3, ' lst2', lst2
lst3.remove(p1)
print 'after removing lst3 = ', lst3, ' lst2', lst2
lst_set = set(lst2)
print 'new set ', lst_set
q = random.sample(range(10), 10)
# xrange(0, 10) iss same as range(10)
# for i in xrange(0, 10):
# q.append(i)
print q
heapq.heapify(q)
print q
heapq.heappush(q, 10)
print q
# print indata
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'C', 10),
('1dave', 'D', 1),
]
def reverse3rd(t1, t2):
return t1[2] - t2[2]
def reverse3rd2(t1, t2):
return t2[2] - t1[2]
print sorted(student_tuples, key=lambda x : x[0], reverse = True)
print sorted(student_tuples, cmp=reverse3rd)
print sorted(student_tuples, cmp=reverse3rd2)
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
|
59fb1bd4709ed909057deab7fe3972d5c843cd7e | kislayanika/amis_python | /km73/Kysla_Veronika/Homework 4/task12.py | 295 | 3.75 | 4 | n = int(input("Enter height: "))
m = int(input("Enter width: "))
k = int(input("Enter number of cells you need to cut off: "))
if (((k % n) == 0) or ((k % m) == 0)) & ((m * n) >= k):
print("You can cut the piece off in one step")
else:
print("You can't cut in one step")
input()
|
c334e80f099a34d97e88fb15feedfdcd1ca14ed3 | vcooley/Code_Abbey_Problems | /prob19.py | 1,494 | 4.15625 | 4 | def bracket_check(check_str):
"""
Takes a string and checks for bracket validity
by removing all other characters
from the string and eliminating adjacent
pairs of corresponding open and close brackets.
Returns 1 for valid brackets and 0 for invalid brackets.
"""
brackets = ['[' , ']' , '(' ,')', '{', '}', '<', '>']
open_brackets = ['[', '(', '{', '<']
close_brackets = [']', ')', '}', '>']
bracket_map = {}
for num in range(len(open_brackets)):
bracket_map[close_brackets[num]] = open_brackets[num]
str_list = list(check_str)
check_all = []
validity = 1
k = 0
#for loop to remove all characters except brackets.
for num in range(len(str_list)):
if str_list[num] in brackets:
check_all.append(str_list[num])
if len(check_all) % 2 != 0:#If not even number of brackets, validity = 0
validity = 0
while k <= len(check_all) and validity == 1:
#Checks for a close bracket at beginning or open bracket at end of list.
if check_all == []:
break
elif check_all[0] in close_brackets:
validity = 0
break
elif check_all[len(check_all) - 1] in open_brackets:
validity = 0
break
if check_all[k] in close_brackets:
if check_all[k - 1] == bracket_map[check_all[k]]:
del check_all[k]
del check_all[k - 1]
k -= 1
else:
validity = 0
break
else:
k += 1
if check_all != []:
validity = 0
return validity
inp = open('test.txt', 'r')
N = int(inp.readline())
for num in range(N):
print bracket_check(inp.readline()),
|
3f3d7760636e874e01e669b22b63c439e3b1ee44 | MickeyYQ/PyTest | /test/test1.py | 547 | 4.03125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
list = ['runoob', 786, 2.23, 'john', 70.2]
tinylist = [123, 'john']
print list # 输出完整列表
print list[0] # 输出列表的第一个元素
print list[1:3] # 输出第二个至第三个元素
print list[2:] # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2 # 输出列表两次
print list + tinylist # 打印组合的列表
list = [] ## 空列表
list.append('Google') ## 使用 append() 添加元素
list.append('Runoob')
print list
print "list内容:",list |
88059bbe5b3ca7052ada95e1a8bf3166d300e59d | RAYMOND-A/python-tipCalculator-project | /tipCalculator.py | 3,657 | 4.40625 | 4 | # Data types
# primitive data types
# String
name = "Hello"
print("first character is " + name[0])
print("Last character is " + name[-1])
print("123" + "345")
# Integers
print(123 + 456)
# Large integers
large_number = 123_456_789 # this helps humans to easily read large number values
print(large_number)
# Float
pi = 3.14159
# boolearn
a = True
b = False
# Type Error, Type Checking and Type Conversion
num_char = len(input("what's your name?"))
print(type(num_char))
new_num_char = str(num_char)
print("your name has " + new_num_char + " characters")
# data types challenge
two_digit_number = input("Type a two digit number: ")
print(type(two_digit_number))
# new_two_digit_number = str(two_digit_number)
first_number_string = two_digit_number[0]
last_number_string = two_digit_number[-1]
print(first_number_string)
print(type(first_number_string))
first_number_int = int(first_number_string)
last_number_int = int(last_number_string)
print(first_number_int)
print(type(first_number_int))
sum_of_input_number = first_number_int + last_number_int
print(sum_of_input_number)
print(type(sum_of_input_number))
sum_converted_to_string = str(sum_of_input_number)
print("sum of two digit number inputted is " + sum_converted_to_string)
# when you dividing two number it always returns a Float
print(6/3)
# exponent in python
# PEMDAS LR [parenthesis, Exponent, Multiplication&Division, Addition&Substraction] [Left to Right]
# ()
# **
# */
# +-
print( 2 ** 3)
# building BMI calculator exercise
# BMI = Weight in kg / square of height in meters
height = input("enter your heught in m: ")
weight = input("enter your weight in kg: ")
float_weight = float(weight)
float_height = float(height)
float_BMI = float_weight / (float_height**2)
int_BMI = int(float_BMI)
print("BMI is " + str(int_BMI))
# rounding floating points numbers we use the round function
# rounding to whole number or int
print(round(2.6666666))
# rounding to a give precision or to 2 d.p in the case below
print(round(2.6666666, 2))
# another way to round a floating point value is by using // operator
# example 8//3 gives you 2
print(type(8 // 3))
result = 4/2
result /= 2 # result = result / 2
score = 0
height = 1.8
isWinning = True
# f-Sring incorporates various types and print to the console
print(f"your score is {score}, your height is {height}, your winning is {isWinning}")
# your life in weeks challenge
age = input("what is your current age: ")
int_age = int(age)
days_spent = int_age * 365
months_spent = int_age * 12
weeks_spent = int_age * 52
days_in_90years = 90 * 365
months_in_90years = 90 * 12
weeks_in_90years = 90 * 52
days_left = days_in_90years - days_spent
weeks_left = weeks_in_90years - weeks_spent
month_left = months_in_90years - months_spent
print(f"if you are to die at 90years, you have {days_left} days, {weeks_left} weeks and {month_left} months left")
# project tip calculator
print("Welcome to the tip calculator")
total_bill = input("What was the total bill? $")
percentage_tip = input("What percentage tip would you like to give? 10, 12, or 15? ")
people_to_split = input("how many people to split the bill? ")
float_total_bill = float(total_bill)
float_percentage_tip = float(percentage_tip)
float_people_to_split = float(people_to_split)
percentage_tip_amount = (float_percentage_tip / 100) * float_total_bill
total_and_percentage_tip_amount = float_total_bill + percentage_tip_amount
amount_each_person_pay = total_and_percentage_tip_amount / float_people_to_split
rounded_amount_pay_per_person = round(amount_each_person_pay, 2)
print(f"Each person should pay: ${rounded_amount_pay_per_person}") |
19f751cf3378ae0cfa0ac2eacf44bd0946dfc4b5 | anuj0721/100-days-of-code | /code/python/day-55/print_stars_in_reverse_pyramid_shape.py | 202 | 4.0625 | 4 | rows = int(input("How many rows?: "))
k = 0
for row in range(rows,0,-1):
for col in range(0,k):
print(end=" ")
for col in range(0,row):
print("*",end=" ")
print()
k += 1
|
872e6db27e611b4033f31c1fae8f6d63d2603dcb | Teanlouise/Blackjack | /Hand.py | 2,280 | 3.96875 | 4 | class Hand:
""" A hand holds the cards that have been dealt to a player from the deck.
It also calculates the value of the those cards and adjusts for aces when
appropriate.
"""
def __init__(self, round):
self.cards = [] # start with an empty list
self.value = 0 # start with zero value
self.aces = 0 # add an attribute to keep track of aces
self.round = round
self.game = round.game
self.deck = self.game.deck
def setup(self):
# Add two cards to each players hand
self.add_card(self.deck.deal())
self.add_card(self.deck.deal())
def add_card(self, card):
# Add a card to the hand
self.cards.append(card)
# Add new cards value, according to rank, to the hand sum
self.value += self.deck.values[card.rank]
# Keep track of how many aces are in the hand
if card.rank == 'Ace':
self.aces += 1
def adjust_for_ace(self):
# Check if there are aces in the hand and the player has bust
while self.aces and self.value > 21:
# Yes, so change the value of the ace to 1 instead of 11
self.value -= 10
# Remove ace from count as it has been adjusted
self.aces -= 1
# Continue to check until there are no aces left in the hand
def hit(self):
# Add a new card to the hand from the deck
self.add_card(self.deck.deal())
# Check if needs to be adjusted for aces
self.adjust_for_ace()
def hit_or_stand(self):
# Ask user if they want to hit (pressing any key returns true)
# or stand (pressing entering will return false)
self.game.playing = bool(input(
"Do you want to hit (press any key) or stand (press enter)? "))
if self.game.playing:
# User wants to hit
self.hit()
if self.value <= 21:
# Show cards (but keep one dealer card hidden)
self.round.show_hands()
def __str__(self):
# start with an empty string
hand_str = ''
# start with an empty string
for card in self.cards:
hand_str += '\n '+ card.__str__()
return 'hand is:' + hand_str |
df43455f8cf5baca3c78cbf1303a0f8a5883c16f | ColeTrammer/cty_2014_intro_to_computer_science | /Day 3/My Programs/Python Project/Practice.py | 1,639 | 3.96875 | 4 |
def gcd_iterative(a, b):
if a > b:
range0 = a
elif b > a:
range0 = b
else:
return a
for i in range(1, range0):
if a % i == 0 and b % 1 == 0:
output = i
return output
"""
@param a first number to be computed
@param b second number to be computed
@return gives the GCD of a and b
iterative method
"""
def gcd_recursive(a, b):
"""
@param a first number to be computed
@param b second number to be computed
@return gives the GCD of a and b
recursive method
"""
def reverse_str_iterative(str):
out = ""
for i in range(len(str) - 1, -1, -1):
out += str[i]
return out
"""
@param str str to reverse
@return reversed str
iterative method
"""
def reverse_str_recursive(str):
"""
@param str str to reverse
@return reversed str
recursive method
"""
def converter_iterative(a, b):
output = ""
while b != 0:
quotient = b // a
remainder = b % a
output += str(remainder)
b = quotient
return output[::-1]
"""
@param a the base to convert to
@param b the number to be converted
@return the converted answer
iterative method
"""
def converter_recursive(a, b):
if b == 0:
"""
@param a the base to convert to
@param b the number to be converted
@return the converted answer
iterative method
"""
def main():
print gcd_iterative(40, 80)
print gcd_recursive(40,80)
print reverse_str_iterative("asdf")
print reverse_str_recursive("asdf")
print converter_iterative(8, 69)
print converter_recursive(8, 69)
if __name__ == "__main__":
main() |
cd315782dd125609befb9b557ee39952d6abd69d | rahusriv/python_tutorial | /python_batch_2/class6/problem3.py | 943 | 3.859375 | 4 |
def modifyInteger(a):
#print(a)
a = 100
#print(a)
def modifyFloat(b):
b=2.5
def modifyString(s):
s = "Modified this"
def modifyList(l):
l.append("Addeed new value")
def modifyDictionary(d):
d[10]="Ten"
a = 10
print("Before function call : a = {}".format(a))
modifyInteger(a)
print("After function call : a = {}".format(a))
print("*"*50)
b = 10.5
print("Before function call : b = {}".format(b))
modifyFloat(b)
print("After function call : b = {}".format(b))
print("*"*50)
s = "Original"
print("Before function call : s = {}".format(s))
modifyString(s)
print("After function call : s = {}".format(s))
print("*"*50)
l = ["First", "Second"]
print("Before function call : l = {}".format(l))
modifyList(l)
print("After function call : l = {}".format(l))
print("*"*50)
d = {1:"One",2:"Two"}
print("Before function call : d = {}".format(d))
modifyDictionary(d)
print("After function call : d = {}".format(d))
|
6a382dac739554fa0afadb206255f0e4413707f1 | Razcle/COMPGI99 | /AW-SGD for Model Free Rl/max_binary_heap.py | 2,273 | 3.703125 | 4 | import itertools
class max_binary_heap(object):
def __init__(self):
self.heap_list = [0]
self.heap_size = 0
self.counter = itertools.count()
self.d = {}
def is_empty(self):
if self.heap_size == 0:
return True
def swap(self,i,j):
self.d[self.heap_list[i][2]] = j
self.d[self.heap_list[j][2]] = i
self.heap_list[i],self.heap_list[j] = self.heap_list[j],self.heap_list[i]
def size(self):
return self.heap_size
def get_max(self):
return self.heap_list[1]
def perc_up(self,i):
while i/2 > 0:
if self.heap_list[i] > self.heap_list[i/2]:
self.swap(i,i/2)
i = i/2
def perc_down(self,i):
while i*2 <= self.heap_size:
mc = self.max_child(i)
if self.heap_list[i] < self.heap_list[mc]:
self.swap(i,mc)
i = mc
def max_child(self,i):
if i*2 + 1 > self.heap_size:
return 2*i
elif self.heap_list[2*i] > self.heap_list[2*i+1]:
return 2*i
else:
return 2*i +1
def insert(self, priority, task):
if task not in self.d:
self.d[task] = self.heap_size + 1
count = next(self.counter)
entry = [priority, count, task]
self.heap_list.append(entry)
self.heap_size = self.heap_size + 1
self.perc_up(self.heap_size)
else:
index = self.d[task]
cmp = priority - self.heap_list[index][0]
count = next(self.counter)
entry = [priority, count, task]
self.heap_list[index] = entry
if cmp < 0.0:
self.perc_down(index)
else:
self.perc_up(index)
def del_max(self):
if self.is_empty() is True:
return "Heap is Empty"
retval = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.heap_size]
self.d[self.heap_list[1][2]] = 1
self.heap_size = self.heap_size - 1
self.heap_list.pop()
self.perc_down(1)
del self.d[retval[2]]
return retval
|
045f4904c71138abb0f84b47a24b1d1d991a69bf | FernandoFalcone-dev/exercicios-Python | /pacote-Download/pythontestes/desafio035.py | 351 | 4.0625 | 4 | print('-=-' * 15)
print('ANALISADOR DE TRIÂNGULOS')
print('-=-' * 15)
a = float(input('Primeiro segmento: '))
b = float(input('Segundo segmento: '))
c = float(input('Terceiro segmento: '))
if a + b > c and a + c > b and b + c > a:
print('Os segmentos PODEM formar um triângulo.')
else:
print('Os segmentos NÃO PODEM formar um triângulo.')
|
5261a62ca3dac5eba058b1d78e539d2c79b1ced9 | stvnc/Python-Project | /Modul02/day02/weather.py | 905 | 3.734375 | 4 | from datetime import datetime
from dateutil import tz
import requests
apiKey = "5e155ca16611b1d08678b090b42129c6"
continentDictionary = {
1 : 'Asia',
2 : 'Europe',
3 : 'South America',
4 : 'North America',
5 : 'Africa',
6 : 'Australia',
7 : 'Antarctica'
}
print(continentDictionary)
continentInput = int(input('Pilih kontinen yang diinginkan: '))
continentValue = continentDictionary.get(continentInput)
userInput = input('Masukkan nama kota yang ingin dicek: ')
url = f"http://api.openweathermap.org/data/2.5/weather?q={userInput}&APPID={apiKey}"
data = requests.get(url)
weather = data.json()
sunrise = weather["sys"]["sunrise"]
sunset = weather["sys"]["sunset"]
temperature = weather["main"]["temp"]
print ('%0.2f' %(temperature - 273) ) #Karena suhunya dalam kelvin
myzone = tz.gettz(f"{continentValue}/{userInput}")
currentTime = datetime.utcfromtimestamp(int(sunrise))
print (currentTime)
|
743ec5e5999b814eed8b10aa4fcf9413e3438d2a | cjbarb7/Python-Coding-Assignments | /first.py | 209 | 3.796875 | 4 | ##first assignment
##to add
##declare your variables
firstVariable = 5
secondVariable = 10
##adding the two variables
thirdVariable = firstVariable + secondVariable
##print to the screen
print thirdVariable |
1af62501c6e6aeb6c09952672a007cae3388b737 | masaponto/project-euler | /p002/p002.py | 273 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def solve(n: int) -> int:
a, b = 1, 2
s = 0
while a < n:
if a % 2 == 0:
s += a
a, b = b, a+b
return s
def main():
print(solve(4000000))
if __name__ == "__main__":
main()
|
29b3bea5abfe67c9b0b6484a7489458c772aea90 | KushRawat/CN-Python-Problems | /Find Character Case.py | 170 | 3.84375 | 4 | def printNum(x):
if 'A' <= x <= 'Z':
print(1)
elif 'a' <= x <= 'z':
print(0)
else:
print(-1)
char = input()
c = char[0]
printNum(c)
|
849acdc64d1620d7e97f92c9f95ad7382f7b0ab8 | Viscivous/Computer-Science-Exam---Semester-1 | /main.py | 2,608 | 4.25 | 4 | #### Describe each datatype below:(4 marks)
## 4 = integer (whole number)
## 5.7 = float (decimal number)
## True = boolean (True or false)
## Good Luck = string (Words or numbers)
#### Which datatype would be useful for storing someone's height? (1 mark)
## Answer - integer
#### Which datatype would be useful for storing someone's hair colour?(1 mark)
## Answer - string
####Create a variable tha will store the users name.(1 mark)
name = input("Enter name: ")
print("Hello", name)
####Create a print statement that will print the first 4 characters of the person's name.(3 marks)
name = input("Enter name: ")
str(name)
print(name[0:4])
####Convert the user's name to all uppercase characters and print the result
name = input("Enter name: ")
print(name.upper())
####Find out how many times the letter A occurs in the user's name
name = input("Enter name: ")
print(name.count("a"))
#### Create a conditional statement to ask a user to enter their age. If they are older than 18 they receive a message saying they can enter the competition, if they are under 18, they receive a message saying they cannot enter the competition.
age = int(input("Please enter your age: "))
if age > 18:
print("Competition access granted")
elif age < 18:
print("Competition access denied")
#### Create an empty list called squareNumbers (3 marks)
squareNumbers = []
#### Square numbers are the solutions to a number being multiplied by itself( example 1 is a square number because 1 X 1 = 1, 4 is a square number because 2 X 2 = 4 ).
###Calculate the first 20 square numbers and put them in the list called squareNumbers. (With loop and .append 10 marks, without, Max 6 marks).
for num in range(21):
square = num * num
squareNumbers.append(square)
####Print your list (1 mark)
print(squareNumbers)
####Create a variable called userSquare that asks the user for their favourite square number
userSquare = input("Enter your favourite square number: ")
#### Add this variable to the end of your list called SquareNumbers
squareNumbers.append(userSquare)
print(squareNumbers)
### Create a variable called choice. This variable should choose a random element from your list. Print the variable called choice.(3 marks)
import random
choice = squareNumbers[random.randint(0, 22)]
print(choice)
####Create another print statement that prints tha following output: The random square number is: XX, where XX is where the random square number chosen by the computer.(4 marks)
print("The random square number is", choice, "where", choice, "is the random square number chosen by the computer") |
fa9436c3905af2e55af27ae720edd5723c1c4828 | wuxu1019/leetcode_sophia | /medium/math/test_50_Pow(x,_n).py | 1,396 | 3.78125 | 4 | """
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−231, 231 − 1]
"""
class Solution(object):
def myPow_recursive(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if n < 0:
n = -n
return self.myPow(1/x, n)
if n % 2 == 0:
return self.myPow(x*x, n/2)
return self.myPow(x*x, n/2) * x
def myPow_iter(self, x, n):
if n == 0:
return 1
if n < 0:
n = -n
x = 1/x
ans = 1
while n > 0:
if n % 2 == 1:
ans *= x
x *= x
n = n >> 1
return ans
def myPow_bitmap(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if n < 0:
n = -n
x = 1 / x
bitmap = bin(n)[2:]
ans = 1
for bit in bitmap[::-1]:
if bit == '1':
ans *= x
x = x * x
return ans
|
c445034de0ffaf04d0b3aac02ba17c9c89e1e04a | bing0109/learning2019 | /a_python_base_db/python_base/1124补充/1124-b08元组.py | 1,447 | 3.734375 | 4 | # coding=utf-8
# author = cjb
学习目标
掌握元组常见操作
课程内容
a.元组的定义
b.元组和列表的区别
c.创建元组
d.访问元组
e.删除元组
f.元组的索引和切片
g.补充
a.元组的定义
元组和列表类似,小括号表示元组,以逗号进行分割
(1,3,4)
('hai','jam')
b.元组和列表的区别
1.元组不可变,列表可变
2.元组速度快
处理动态数据时,需要经常更新数据,就用列表
敏感信息传递给一个不了解的函数时,希望这个数据不被修改,就使用元组
c.创建元组
注意,如果元组值包含一个元素,需要在后面加逗号以消除歧义
a = (1,)
d.访问元组
a = (1,2,3)
>>> print(a)
(1, 2, 3)
>>> for i in a:
... print(i)
...
e.删除元组
>>> b = (1,3,3)
>>> del b
>>> print(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
>>>
f.元组的索引和切片
和列表一样,索引理解为下标,左边从0开始,右边从-1开始
>>> c=(1,3,4,5,2,6,7)
>>> c[0]
1
>>> c[-2]
6
>>> c[2:-2]
(4, 5, 2)
g.补充
len()
max()
min()
tuple.index() 元组中某值第一次出现匹配的索引
tuple.count() 元组中某值出现的次数
注意:max,min 必须是同一种数据类型才能做比较
>>> c=(1,3,4,5,2,6,7,4,5,5)
>>> len(c)
10
>>> min(c)
1
>>> max(c)
7
>>> c.count(5)
3
>>> c.index(4)
2
|
12f472b9e68d5d1171657b79ea9417a97cce9485 | mignev/mypy | /lib/file_utils.py | 389 | 3.75 | 4 | import os
def ropen(file_path):
""" Reading file backwards """
file = open( file_path, 'r' )
file_size = os.path.getsize( file_path )
file_range = range(file_size)
for i in file_range:
file.seek(file_range[-i])
char = file.read(1)
if char == "\n":
line = file.readline()
if len(line) > 1:
print( line )
|
03bade0bf4d8951e6103fc6826a87bc5914b41f7 | syed-ali-jibran-rizvi/hacktober2021 | /Python/reversestring.py | 195 | 4.28125 | 4 | def reverse_string(str):
str1 = ""
for i in str:
str1 = i + str1
return str1
str = "potato"
print("default string is: ", str)
print("reversed string is", reverse_string(str))
|
ba94b42994e9cb551279e54f7105a46cb323e071 | rsummers618/rcfbscraper | /Old Stuff/NCAAsavant_Compiler/Stat_Compiler.py | 8,035 | 3.828125 | 4 |
import re
import csv
import C
from Team_Game_Stat import *
#=============================================================================================================
# FUNCTION DEFINITIONS
#=============================================================================================================
# Returns the contents of a .csv file in an array
def Read_CSV(file_name):
data = []
with open(file_name, "r") as csvfile:
data_reader = csv.reader(csvfile)
for row in data_reader:
data.append(row)
for i in range(0, len(data)):
for j in range(0, len(data[i])):
data[i][j] = re.sub("\"", "", data[i][j])
return data
# Writes the contents of data to a .csv file
def Write_CSV(data, file_name):
with open(file_name, "w") as csvfile:
data_writer = csv.writer(csvfile, lineterminator = '\n')
data_writer.writerows(data)
# Changes an abbreviated team name to its team number
def Find_Abbv_Team(data, abbv, team_arr, abbv_arr):
# Check if it is already matched
if abbv_arr != 0:
for team in abbv_arr:
if abbv == team[0]:
return (team[1], team[2], abbv_arr)
team_sort = []
for i in range(0, len(team_arr)):
team_sort_tmp = [0] * 3 # naming correlation
team_sort_tmp[1] = team_arr[i][0] # team number
team_sort_tmp[2] = team_arr[i][1] # team name
abbv_ltrs = list(abbv)
team_ltrs = list(team_arr[i][1])
pos = 0
tot = 0
# Find the correlation in naming
for j in range(0, len(abbv_ltrs)):
ltr = abbv_ltrs[j]
if ltr == "U" or None == re.search(r"[a-zA-Z]", ltr):
continue
inc = 0
while None == re.search(ltr, team_ltrs[pos], re.IGNORECASE):
inc += 1
pos += 1
if pos >= len(team_ltrs):
break
if pos >= len(team_ltrs):
tot = 1000
break
else:
tot += inc
team_sort_tmp[0] = tot
team_sort.append(team_sort_tmp)
team_sort = sorted(team_sort, key=lambda arr: arr[0])
# Check the sorted teams for the correct match
i = 0
while i < len(team_sort):
print "\nGuess: " + str(abbv) + " = " + str(team_sort[i][2])
user_in = raw_input("Enter 0 for incorrect match, 1 for correct match, or 2 for unknown: ")
for name in team_arr:
if user_in == name[1]:
if abbv_arr != 0:
abbv_arr.append([abbv, name[0], name[1]])
Write_CSV(abbv_arr, "2014 Stats/abbrevations.csv")
return (name[0], name[1], abbv_arr)
if user_in == "":
print "Please enter 1 or 0"
continue
if user_in == "":
break
if user_in == "1":
break
if user_in == "2":
print "The next option is " + str(team_sort[i + 1][2])
continue
i += 1
if i == len(team_sort):
i = 0
if abbv_arr != 0:
abbv_arr.append([abbv, team_sort[i][1], team_sort[i][2]])
Write_CSV(abbv_arr, "2014 Stats/abbrevations.csv")
return (team_sort[i][1], team_sort[i][2], abbv_arr)
# Return game date (MM/DD/YYYY) in YYYYMMDD format
def Get_Date(date):
m1 = re.match(r"(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<year>\d{4})", date)
m2 = re.match(r"(?P<year>\d{4})\-(?P<month>\d{1,2})\-(?P<day>\d{1,2})", date)
if None == m1 and None == m2:
print date
raw_input()
if None != m1:
return str(m1.group("year")).zfill(2) + str(m1.group("month")).zfill(2) + str(m1.group("day")).zfill(2)
elif None != m2:
return str(m2.group("year")).zfill(2) + str(m2.group("month")).zfill(2) + str(m2.group("day")).zfill(2)
# Converts pbp date from NCAAsavant to my format
def Convert_PBP_Data(pbp_file):
# Read in play-by-play data
print "Reading raw play-by-play data..."
pbp_data = Read_CSV(pbp_file)
print "Done"
# Read in team and abbreviation data
team_data = Read_CSV("2014 Stats/team.csv")
team_data = team_data[1:]
try:
abbv_arr = Read_CSV("2014 Stats/abbrevations.csv")
except:
print "WARNING: abbrevations.csv not found\n"
abbv_arr = []
# Replace team names with numbers
for line in pbp_data[1:]:
teams = []
# find home team
(number, name, abbv_arr) = Find_Abbv_Team(pbp_data, line[C.HOME], team_data, abbv_arr)
line[C.HOME] = number
teams.append([number,name])
# find away team
(number, name, abbv_arr) = Find_Abbv_Team(pbp_data, line[C.VSTR], team_data, abbv_arr)
line[C.VSTR] = number
teams.append([number,name])
# find team dir
if len(line[C.DIR]) > 0 and line[C.DIR] != "ERROR":
(number, name, abbv_arr) = Find_Abbv_Team(pbp_data, line[C.DIR], teams, abbv_arr)
line[C.DIR] = number
# find team penalty
if len(line[C.PENTM]) > 0:
(number, name, abbv_arr) = Find_Abbv_Team(pbp_data, line[C.PENTM], teams, abbv_arr)
line[C.PENTM] = number
# find defense
(number, name, abbv_arr) = Find_Abbv_Team(pbp_data, line[C.DEF], team_data, abbv_arr)
line[C.DEF] = number
# find offense
(number, name, abbv_arr) = Find_Abbv_Team(pbp_data, line[C.OFF], team_data, abbv_arr)
line[C.OFF] = number
# fix position
if line[C.DIR] != line[C.OFF] and line[C.DIR] != line[C.DEF] and line[C.TYPE] != "KICK" and line[C.TYPE] != "EXTRA POINT" and line[C.TYPE] != "PENALTY":
#print "These teams don't know where they're going!\n"
#print "TYPE: " + line[C.TYPE]
#print "OFF: " + str(line[C.OFF])
#print "DEF: " + str(line[C.DEF])
#print "DIR: " + str(line[C.DIR])
#raw_input()
line[C.DIR] = "ERROR"
if line[C.OFF] == line[C.DIR]:
line[C.YARD] = 100 - int(line[C.YARD])
# parse game date
line[C.GCODE] = str(line[C.VSTR]).zfill(4) + str(line[C.HOME]).zfill(4) + Get_Date(line[C.DATE])
Write_CSV(pbp_data, "2014 Stats/play-by-play.csv")
#=============================================================================================================
# MAIN FUNCTION
#=============================================================================================================
# Convert PBP
pbp_file = "Raw PBP/pbp-2014.csv"
Convert_PBP_Data(pbp_file)
print "Done converting file...\n"
# Read in statistics
print "Reading play-by-play data..."
file_name = "2014 Stats/play-by-play.csv"
pbp_data = Read_CSV(file_name)
print "Done.\n"
# Compile stats
print "Compiling stats from play-by-play data..."
prev_game = 0
tgs_home = Team_Game_Stat(0, 0, 0)
tgs_visit = Team_Game_Stat(0, 0, 0)
tgs_array = []
tgs_array.append(tgs_home.Team_Game_Stats_Header())
use_game = True # game is valid for use
home_bad_plays = 0
visit_bad_plays = 0
max_bad_plays = 3 # if a number of bad plays occur in a row, discard game
for i in range(1, len(pbp_data)):
play = pbp_data[i]
if i + 1 < len(pbp_data):
next_play = pbp_data[i + 1]
# Check for a new game
if prev_game != play[C.GCODE]:
if tgs_home.Game_Code != 0 and use_game: # add data to array
tgs_array.append(tgs_home.Compile_Stats())
tgs_array.append(tgs_visit.Compile_Stats())
tgs_home = Team_Game_Stat(play[C.GCODE], play[C.HOME], play)
tgs_visit = Team_Game_Stat(play[C.GCODE], play[C.VSTR], play)
home_bad_plays = 0
visit_bad_plays = 0
use_game = True
# Add this play to T-G-Stats
try:
offense = int(play[C.OFF])
except:
print "WARNING: Couldn't get offense, ignoring play"
print " Game Code: " + str(play[C.GCODE])
continue
if tgs_home.Team_Code == offense: # home
# Check for a bad game
if home_bad_plays >= max_bad_plays and use_game:
use_game = False
if home_bad_plays == max_bad_plays:
print "WARNING: Not using game " + str(tgs_home.Game_Code)
continue
# Extract play
elif use_game:
error = tgs_home.Extract_Play_Data(play, next_play)
if error == 1:
home_bad_plays += 1
else:
home_bad_plays = 0
elif tgs_visit.Team_Code == offense: # visitor
# Check for a bad game
if visit_bad_plays >= max_bad_plays and use_game:
use_game = False
if visit_bad_plays == max_bad_plays:
print "WARNING: Not using game " + str(tgs_visit.Game_Code)
continue
# Extract play
elif use_game:
error = tgs_visit.Extract_Play_Data(play, next_play)
if error == 1:
visit_bad_plays += 1
else:
visit_bad_plays = 0
prev_game = play[C.GCODE]
print "Done.\n"
print "Writing team-game-stats data..."
Write_CSV(tgs_array, "2014 Stats/team-game-stats.csv")
print "Done.\n"
# END
raw_input("Press ENTER to finish...") |
34d179893d6ff4cdeeae090d7810a7541eb71e50 | joekreatera/python_va_basic_python_2 | /23_01_2021/practice2.py | 441 | 3.640625 | 4 | from random import random
r = int(random()*100)
resp = int(input('Si piensas que mi numero es mayor a 60, responde (2) , si piensas que es menor a 40, responde (0), si piensas que está entre 40 y 60 responde (1)') )
if( resp == 0 and r < 40 ):
print("ganaste")
elif( resp == 1 and r <= 60 and r >= 40 ):
print("ganaste")
elif( resp == 2 and r > 60):
print("ganaste")
else:
print("perdiste")
print(f"Habia pensado en {r}")
|
3ff660418d259285c73f8cc5ff2e79ab764b349b | FeHioe/dymanic_programming | /coin_change.py | 474 | 3.578125 | 4 | def coin_change(change, coin_list):
store_coins = []
store_coins.append(0)
for i in range(1, change+1):
store_coins.append(-99)
for coin in coin_list:
if (i - coin >= 0) and (store_coins[i - coin] != -99) and (store_coins[i] > store_coins[i - coin] or store_coins[i] == -99):
store_coins[i] = 1 + store_coins[i - coin]
if store_coins[change] == -99:
return "Not possible."
else:
return "Can be made out of " + str(store_coins[change]) + " coins."
|
9692f8269809ec0530a5523d4b9f159fa71e7c07 | tainenko/Leetcode2019 | /leetcode/editor/en/[2744]Find Maximum Number of String Pairs.py | 2,105 | 4.15625 | 4 | # You are given a 0-indexed array words consisting of distinct strings.
#
# The string words[i] can be paired with the string words[j] if:
#
#
# The string words[i] is equal to the reversed string of words[j].
# 0 <= i < j < words.length.
#
#
# Return the maximum number of pairs that can be formed from the array words.
#
# Note that each string can belong in at most one pair.
#
#
# Example 1:
#
#
# Input: words = ["cd","ac","dc","ca","zz"]
# Output: 2
# Explanation: In this example, we can form 2 pair of strings in the following
# way:
# - We pair the 0ᵗʰ string with the 2ⁿᵈ string, as the reversed string of word[0
# ] is "dc" and is equal to words[2].
# - We pair the 1ˢᵗ string with the 3ʳᵈ string, as the reversed string of word[1
# ] is "ca" and is equal to words[3].
# It can be proven that 2 is the maximum number of pairs that can be formed.
#
# Example 2:
#
#
# Input: words = ["ab","ba","cc"]
# Output: 1
# Explanation: In this example, we can form 1 pair of strings in the following
# way:
# - We pair the 0ᵗʰ string with the 1ˢᵗ string, as the reversed string of words[
# 1] is "ab" and is equal to words[0].
# It can be proven that 1 is the maximum number of pairs that can be formed.
#
#
# Example 3:
#
#
# Input: words = ["aa","ab"]
# Output: 0
# Explanation: In this example, we are unable to form any pair of strings.
#
#
#
# Constraints:
#
#
# 1 <= words.length <= 50
# words[i].length == 2
# words consists of distinct strings.
# words[i] contains only lowercase English letters.
#
#
# Related Topics Array Hash Table String Simulation 👍 146 👎 6
# leetcode submit region begin(Prohibit modification and deletion)
from collections import defaultdict
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
res = 0
cnt = defaultdict(int)
for word in words:
if word in cnt:
res += cnt[word]
cnt[word[::-1]] += 1
return res
# leetcode submit region end(Prohibit modification and deletion)
|
38d285df808be73f6358c3073bb6918a3cfaae77 | yurriiko/Aritmatika | /AritmatikaInput.py | 556 | 3.78125 | 4 | A = 8
B = 3
C = 2
print ("==== Program Aritmatika ====")
print (" Nilai A = 8")
print (" Nilai B = 3")
print (" Nilai C = 2")
print ("==== Hasil Perhitungan ====")
hasil = A + B
print ("A + B = ",hasil)
hasil = A - B
print ("A - B = ",hasil)
hasil = A * B
print ("A * B = ",hasil)
hasil = A / B
print ("A / B = ",hasil)
hasil = A % B
print ("A % B = ",hasil)
hasil = A // B
print ("A // B = ",hasil)
hasil = A ** B
print ("A ** B = ",hasil)
hasil = (A-B)/C
print ("(A - B) / C = ",hasil)
hasil = A-B/C
print ("A - B / C = ",hasil) |
3cfa2b76a7997319e82c89c0730bdaf8669fd1c7 | AssiaHristova/SoftUni-Software-Engineering | /Programming Fundamentals/text_processing/replace_repeating_chars.py | 220 | 3.734375 | 4 | text = input()
text_list = [char for char in text]
for i in range(len(text_list) - 1, -1, -1):
if not i == 0:
if text_list[i] == text_list[i - 1]:
text_list.pop(i)
print(''.join(text_list))
|
7540fe1a9e3fa13febb60ce654c103910774b699 | Zavhorodnii/Project_Euler | /Exe_9.py | 681 | 3.90625 | 4 | from datetime import datetime
def start():
var = int(input("Enter value: "))
time = datetime.now()
point_1 = int(var/2)
while True:
point_2 = point_1 - 1
while True:
point_3 = var - (point_2 + point_1)
if point_3**2 + point_2**2 == point_1**2:
print("{} + {} = {}".format(point_3, point_2, point_1))
print(point_3 * point_2 * point_1)
print("time: ", datetime.now()-time)
return
if point_2 == 1:
break
point_2 -= 1
if point_1 == 2:
break
point_1 -= 1
if __name__ == '__main__':
start() |
3365bcddfa38bcfa2a5f966640d46e39e5f350f8 | dattran1997/trandat-fundamental-c4e17 | /Session1/Homework/multi_circle.py | 122 | 3.578125 | 4 | from turtle import *
speed(0)
for i in range (100):
color("yellow","yellow")
circle(50)
right(5)
mainloop()
|
5a9feae840ba3905fc7bcd9eacc6f728e84f8a81 | PetarSP/SoftUniFundamentals | /REGEX/4.Extract Emails.py | 331 | 3.640625 | 4 | import re
# email format: "{user}@{host}"
emails = input()
pattern = rf"(?P<Email>(?P<User>(?<=\s)[A-Za-z0-9]+[\.\-\_]*[A-Za-z0-9]+)\@(?P<Domain>(([A-Za-z\-?]+)[A-Za-z]+(\.[A-Za-z]+)+)))"
valid_emails = re.finditer(pattern,emails)
valid_emails = [valid_mail.group() for valid_mail in valid_emails]
print("\n".join(valid_emails)) |
c1044e2a8330015c0c531e7f7618b0bfd5282680 | vunv2404/nguyenvanvu-fundamental-C4E22 | /session3/ex_2_list.py | 125 | 3.703125 | 4 | items = ["spire", "popcorn", "cocacola", "pepsi", "bread"]
print(items)
items.append(input("add your menu : "))
print(items) |
b126dd63f2090d0762e1f2f6b7b9f8a5182d9b24 | saikumar176/python | /eighteen.py | 238 | 3.8125 | 4 | less = int(input())
high = int(input())
for numb in range(less,high + 1):
sum = 0
temp = numb
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if numb == sum:
print(numb,end=" ")
|
f6a58cfb5c2f6b8dc80da9aed4777dac9c73f6c4 | ianzim/Calculadora | /mat_basica.py | 1,490 | 3.640625 | 4 | import math
def soma():
print()
s = 0
quant = int(input('Quantos números quer somar? '))
for cont in range(quant):
s += float(input(f'{cont + 1}º número: '))
return f'RESULTADO: {s}'
def subt():
print()
inicial = float(input('Digite o número inicial: '))
sub = float(input(f"{inicial} - "))
return f'RESULTADO: {inicial - sub}'
def mult():
print()
print("OBS: A MULTIPLICAÇÃO SERÁ FEITA DA FORMA: AxBxCx... = Z")
print()
quant = int(input('Quantos números serão multiplicados? '))
for c in range(quant):
if c == 0:
a = float(input('1º Número: '))
else:
a *= float(input(f'{c + 1}º Número: '))
return f'RESULTADO: {a}'
def div():
print()
n = float(input('Numerador: '))
d = float(input('Denominador: '))
return f'RESULTADO: {(n/d)}'
def pot():
print()
b = float(input('Base: '))
exp = float(input('Expoente: '))
return f'RESULTADO: {(b**exp)}'
def rad():
print()
i = float(input('Índice da raíz: '))
r = float(input('Radical: '))
return f'RESULTADO: {(r**(1/i))}'
def baskhara():
print()
a = float(input('A = '))
b = float(input('B = '))
c = float(input('C = '))
delta = (b**2 - (4 * a * c))
rD = delta**(1/2)
x1 = (-b + rD) / (2*a)
x2 = (-b - rD) / (2*a)
if rD < 0:
return 'A RAÍZ DE DELTA É NEGATIVA'
else:
return f'X1 = {x1:.2f}\nX2 = {x2:.2f}' |
e4385f90b43900b52a40343fb1b8d5486f76f72b | AnetaFeliksiak/excercise_lists_1 | /file_manager.py | 729 | 4.03125 | 4 | def read_from_file(filename='default_words.txt'):
'''
Reads lists from file
>>> read_from_file()
[['aaa', 'bbbb', 'cccccc'], ['dd', 'eeeeee', 'fffffffff']]
'''
list_of_lines = []
file = open(filename, 'r')
for line in file:
line = line.strip().split(',')
stripped_elements = [element.strip() for element in line]
list_of_lines.append(stripped_elements)
file.close()
return list_of_lines
def write_to_file(items, filename='longest_words.txt'):
file = open(filename, "a")
for item in items:
item_strings = [str(element) for element in item]
line_to_write = ",".join(item_strings)
file.write(line_to_write + '\n')
file.close()
|
6d78c9ca12a88cd35179f1a0eb2ce5faebc2e4e2 | SissonJ/tikTakToe | /tiktaktoe.py | 9,004 | 3.546875 | 4 | import numpy as np
import sys
def createGameBoard():
gameboard = np.empty([11,11],dtype=object)
counter = 1
for i in range(11):
#gameboard[i]=np.zeros(11)
for j in range(11):
gameboard[j,i]=' '
if i==3 or i==7:
gameboard[j,i]='-'
if j==3 or j==7:
gameboard[j,i]='|'
if (j==1 or j==5 or j==9) and (i==1 or i==5 or i==9):
gameboard[j,i]=counter
counter = counter+1
return gameboard
def printGameBoard(board):
for i in range(11):
for j in range(11):
print(board[j,i],end =""),
print('\n')
def isGameWon(board):
col=1
row=1
trackerDiag =np.array( [board[1,1],board[1,9]])
tracker = 0
for i in range(3):
col=1+i*4
row=1+i*4
if board[1,col]==board[5,col] and board[9,col]==board[5,col]:
#print("Player", board[1,col], "has won the game!", sep=" ")
return False
elif board[row,1]==board[row,5] and board[row,9]==board[row,5]:
#print("Player", board[row,1], "has won the game!", sep=" ")
return False
elif trackerDiag[0] == board[5,5] and board[9,9]==board[5,5]:
#print("Player", board[5,5], "has won the game!", sep=" ")
return False
elif trackerDiag[1] == board[5,5] and board[5,5] == board[9,1]:
#print("Player", board[5,5], "has won the game!", sep=" ")
return False
else:
for i in range(11):
for j in range(11):
if board[j,i]=='O' or board[j,i]=='X':
tracker = tracker + 1
#print(tracker)
if tracker == 27:
return False
return True
def whoWon(board):
col=1
row=1
trackerDiag =np.array( [board[1,1],board[1,9]])
tracker = 0
catsGame='C'
for i in range(3):
col=1+i*4
row=1+i*4
if board[1,col]==board[5,col] and board[9,col]==board[5,col]:
#print("Player", board[1,col], "has won the game!", sep=" ")
return board[1,col]
elif board[row,1]==board[row,5] and board[row,9]==board[row,5]:
#print("Player", board[row,1], "has won the game!", sep=" ")
return board[row,1]
elif trackerDiag[0] == board[5,5] and board[9,9]==board[5,5]:
#print("Player", board[5,5], "has won the game!", sep=" ")
return board[5,5]
elif trackerDiag[1] == board[5,5] and board[5,5] == board[9,1]:
#print("Player", board[5,5], "has won the game!", sep=" ")
return board[5,5]
else:
for i in range(11):
for j in range(11):
if board[j,i]=='O' or board[j,i]=='X':
tracker = tracker+1
if tracker == 27:
return 0
return catsGame
def gameMove(board,player,move, isReset):
dummy=0
x=1
y=1
if not isReset:
move = isMoveValid(board, move, False)
for i in range(9):
dummy=i+1
if x>9:
x=1
else:
pass
if dummy==4 or dummy==7:
y=y+4
else:
pass
if move==dummy:
if player:
#print('O')
board[x,y]='O'
break
else:
#print('x')
board[x,y]='X'
break
x=x+4
else:
for i in range(9):
dummy=i+1
if x>9:
x=1
else:
pass
if dummy==4 or dummy==7:
y=y+4
else:
pass
if move==dummy:
board[x,y]=' '
x=x+4
return board
def isMoveValid(board, move, isBool):
if not isBool:
validMove=False
x=1
y=1
dummy=1
while not validMove:
for i in range(9):
dummy=i+1
if x>9:
x=1
else:
pass
if dummy==4 or dummy==7:
y=y+4
else:
pass
if move==dummy:
if board[x,y]=='O' or board[x,y]=='X':
print("That move is not valid")
move = input("Please enter a new move (1-9): ")
move = int(move)
move = isMoveValid(board, move, False)
else:
validMove=True
break
x=x+4
return move
else:
validMove=False
x=1
y=1
dummy=1
while not validMove:
for i in range(9):
dummy=i+1
if x>9:
x=1
else:
pass
if dummy==4 or dummy==7:
y=y+4
else:
pass
if move==dummy:
if board[x,y]=='O' or board[x,y]=='X':
return False
else:
validMove=True
return True
x=x+4
def bestMove(board,isMax,maxDepth):
score = 0
hiScore = -1000000
loScore = 1000000
move = 0
dumdum=0
dumBoard = 0
availMoves = np.array([])
for i in range(9):
dumdum=i+1
if isMoveValid(board,dumdum,True):
availMoves = np.append(availMoves, dumdum)
if len(availMoves) == 9:
return 9
print(availMoves)
dumMoves = np.copy(availMoves)
for i in range(len(availMoves)):
dumMoves = np.copy(availMoves)
dumBoard = np.copy(board)
dumBoard = gameMove(dumBoard, isMax, availMoves[i], False)
dumMoves = np.delete(dumMoves, i)
score = minimax(dumBoard,not isMax, 0, 0, 0, dumMoves)
print(score)
if isMax:
if score >= hiScore:
hiScore = score
move = availMoves[i]
else:
if score <= loScore:
loScore = score
move = availMoves[i]
return move
def minimax(board,isMax,h, currDepth,maxDepth,availMoves):
#O wants to max, X wants to min
dumdum=np.copy(availMoves)
dumBoard = board
hiScore = -1000000
loScore = 10000000
score = 0
if whoWon(board)=='X':
return -10+currDepth
elif whoWon(board)=='O':
return 10-currDepth
elif whoWon(board)==0:
return 0
else:
for i in range(len(availMoves)):
dumdum = np.copy(availMoves)
dumBoard =np.copy(board)
dumBoard = gameMove(dumBoard,isMax,availMoves[i],False)
dumdum = np.delete(dumdum, i)
score = minimax(dumBoard, not isMax, h, currDepth+1, maxDepth, dumdum)
if isMax:
hiScore = max(hiScore,score)
else:
loScore = min(loScore,score)
if isMax:
return hiScore
else:
return loScore
sys.setrecursionlimit(10**6)
gameBoard = createGameBoard()
pvp = input("Would you like to play agains the computer (y/n)? ")
player = "X"
if pvp=="y":
pvp = False
player = input("Would you like to play as X or O? ")
else:
pvp = True
player2 = True
if player == "X":
player = False
else:
player = True
player2 = False
isPlayerOsMove=True
if pvp:
while isGameWon(gameBoard):
printGameBoard(gameBoard)
if(isPlayerOsMove):
move = input("O's move (1-9): ")
move = int(move)
gameBoard=gameMove(gameBoard,True,move,False)
isPlayerOsMove = not isPlayerOsMove
else:
move = input("X's move (1-9): ")
move = int(move)
gameBoard=gameMove(gameBoard,False,move,False)
isPlayerOsMove = not isPlayerOsMove
printGameBoard(gameBoard)
else:
while isGameWon(gameBoard):
printGameBoard(gameBoard)
if player:
move = input("O's move (1-9): ")
move = int(move)
gameBoard=gameMove(gameBoard,True,move,False)
player = not player
else:
gameBoard = gameMove(gameBoard, False, bestMove(gameBoard, player2, 5), False)
player = not player
printGameBoard(gameBoard)
|
986a73d1f3a05510f9f795d15cb7dd6f0553cb49 | alecvogel/hello-world | /a_vogel_wk6_lab5_A.py | 593 | 3.59375 | 4 | mexicoPop = int(1.21 * 10**8)
USPop = int(3.15 * 10**8)
years = 0
data = []
header = ['Year', 'Mexico Pop.', 'US Pop.']
data.append(header)
initial = [years, mexicoPop, USPop]
data.append(initial)
def computePop (mexicoPop, USPop, years):
while USPop > mexicoPop:
mexicoPop = mexicoPop * 1.0101
USPop = USPop * .9985
years = years + 1
newData = [years, int(mexicoPop), int(USPop)]
data.append(newData)
for rows in data:
print('{:5} {:10} {:10}'.format(*rows))
print('It took ', years, ' years')
computePop(mexicoPop, USPop, years)
|
17de151f1647ab1e112c81a5de25d05867e642be | rblis/Python-Coding-Competitions | /Implementations/Naive_Hedging_Algorithm.py | 3,945 | 3.734375 | 4 | '''
Naive Hedging Algorithm
Programming challenge description:
Problem Statement
In order to properly offload risk, we need to implement a trading algorithm which places trades to offset the risk of incoming trades (this is called hedging). Each incoming trade has some risk associated with it, defined as quantity * riskPerUnit
For example, if an incoming trade has bought 20 units of risk, we should sell 20 units of risk to offset it. If the incoming trade buys 20.9 units of risk, we should still sell 20 units of risk to offset it because we cannot buy fractions of a stock. However, we should remember that there is still 0.9 risk to be covered, and add it to the amount of risk for the next trade.
Given two incoming trades, each with 0.5 units of risk, we should not make any trades when we receive the first trade, and then sell 1 when we receive the second trade.
For each incoming trade, you'll output the corresponding trade to offset the risk, and the average fill price.
We can define the average fill price of a trade as
AvgFillPrice = Sum(quantity_i * price_i) / Sum(quantity_i)
When we make a trade, we trade against the given market data, affecting the state of the market for future trades. For example, if the best price/quantity in the market to buy was quantity 100 for price $1850, and we bought 75 for $1850, there would only be 25 remaining at that price level. If, for example, our next trade was for a quantity of 30, we would execute 25 at the remaining price level, and then the remaining 5 at the next-best price level.
Input:
The first two lines of each test case will represent the market data. Each line of market data will always have exactly 3 quantities and exactly 3 prices. You can assume there is enough quantity to fully offset all the risk of all incoming trades.
The first line will represent the "offers", or prices you can buy at. The second line will represent the "bids", or prices you can sell at. When trading with the market, we buy at the cheapest price available, and sell at the highest price available.
Market data will be formatted as follows
<quantity1> <price1> <quantity2> <price2> <quantity3> <price3>
100 1850.00 200 1850.25 300 1850.50
100 1849.75 200 1849.50 300 1849.25
This means that the first 100 purchased will be bought at a price of 1850.00, and the next 200 will be bought at a price of 1850.25. Similarily, the first 100 sold will be sold at 1849.75, and the next 200 will be sold at 1849.50
If we were to purchase 300, we would fill 100 at 1850.00, and 200 at 1850.25, for an average fill price of 1850.17 (rounded to two decimal places).
Incoming trades are formatted as follows:
<signed_quantity> <risk_per_unit>
+10 0.20
+15 -0.20
-40 0.50
This means we traded, in order
Buy quantity 10, risk per unit of 0.20 (risk is +2)
Buy quantity 15, risk per unit of -0.20 (risk is -3)
Sell quantity 40, risk per unit of 0.50 (risk is -20)
NOTE: You have been given skeleton code to help parse this input. You may alter this code as you wish, including not using it at all.
Output:
We should output the trades required to offset the risk, as well as the average fill price. Buying is represented as a positive quantity, and selling is represented as a negative quantity.
The average fill price should output exactly two decimal places, rounded. For example, 1849.6666666 should be rounded to 1849.67.
For the above input, this is the correct output
<quantity bought/sold> <average fill price>
-2 1849.75
3 1850.00
20 1850.00
Test 1
Test Input
100 1850.00 200 1850.25 300 1850.50
100 1849.75 200 1849.50 300 1849.25
+10 0.20
+15 -0.20
-40 0.50
Expected Output
-2 1849.75
3 1850.00
20 1850.00
Test 2
Test Input
100 1850.00 200 1850.25 300 1850.50
100 1849.75 200 1849.50 300 1849.25
+15 0.25
+1 0.25
Expected Output
-3 1849.75
-1 1849.75
''' |
baae332ba4e51d97e4f3b7e0490b22ea3edd8096 | md0505/blockchain | /src/wired3d.py | 847 | 3.71875 | 4 | '''
=================
3D wireframe plot
=================
A very basic demonstration of a wireframe plot.
'''
from utils import *
#from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
def plot3d():
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
#X, Y, Z = axes3d.get_test_data(0.05)
msmts = pickleload("measurements.pickle")
X = twod(list(map(lambda x: list(repeat(x, len(msmts[0]))), range(len(msmts)))))
Y = twod(list(map(lambda x: list(range(len(msmts[x]))), range(len(msmts)))))
Z = twod(list(map(lambda x: list(msmts[x]), range(len(msmts)))))
print("X = " + str(X.shape))
print("Y = " + str(Y.shape))
print("Z = " + str(Z.shape))
# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
|
ae09fac0b1e1aec153fee7fec4348e016705804c | CAM603/Python-JavaScript-CS-Masterclass | /Sorting/Python/selection_sort.py | 381 | 3.96875 | 4 | def selection_sort(arr):
for i in range(len(arr) - 1):
smallest = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[smallest]:
smallest = j
if i != smallest:
arr[i], arr[smallest] = arr[smallest], arr[i]
return arr
print(selection_sort([4, 1, 3, 2]))
print(selection_sort([1, 5, 8, 4, 2, 9, 6, 0, 3, 7]))
|
fb9c31072184c7cb385cda3b5254a654d51df57e | qspin/python-course | /exercise10.py | 860 | 3.65625 | 4 | __author__ = 'kristof'
class Person(object):
def __init__(self, name, location):
self.name = name
self.goto(location)
def goto(self, location):
self.location = location
class RestrictedPerson(Person):
restricted_locations = ['Waardamme', 'Brugge', 'Ieper']
def __isallowed(self, location):
if location in self.restricted_locations:
raise Exception('Location {0} is not allowed'.format(location))
def goto(self, location):
self.__isallowed(location)
super(RestrictedPerson, self).goto(location)
els = Person('Els', 'Waardamme')
print(els.location)
els = RestrictedPerson('Els', 'Waardamme')
print(els.location)
kristof = RestrictedPerson('Kristof', 'Oostkamp')
print(kristof.location)
kristof.goto('Gent')
print(kristof.location)
kristof.goto('Brugge')
print(kristof.location) |
8aa192a61ccf1184faaf8e66f720babca5cbbdff | cameron-teed/ICS3U-6B-PY | /tet.py | 827 | 4.1875 | 4 | #!/usr/bin/env python3
# Created by: Cameron Teed
# Created on: Nov 2019
# This program calculates the surface area of a tetrahedron
import math
def sa_calculator(height):
# calculates the volume
# process
sa = math.sqrt(3) * height**2
return round(sa, 2)
def main():
# This is asks for the user input
# Welcomes user
print("This program calculates the surface area of a tetrahedron. ")
while True:
try:
# input
height = float(input("What is the lenght: "))
# runs volume_calculator()
sa = sa_calculator(height=height)
# output
print("\nThe surface area is " + str(sa) + " cm2.")
break
except ValueError:
print("Please put in integer.\n")
if __name__ == "__main__":
main()
|
f1a2ceeea899520d3a3a5b3f11c5599ff1ee4903 | apmcdaniels/CAAP-CS | /Lab2/Lab2/game/game.py | 1,873 | 3.828125 | 4 | # imports multiple clases from the python library and some of our
# own modules.
from sys import exit
from random import randint
from map import Map
from leaderboard import Leaderboard
from scores import Score
from game_engine import Engine
# global variables to keep track of score, player, and leaderboard
moves = 0
name = ''
leaderboard = Leaderboard()
# what happens when the game is over
# takes in a boolean parameter
# should update leaderboard, global variables, and print leaderboard
def game_over(won):
global name
global moves
score = Score(name, moves)
if won:
leaderboard.update(score)
print ("\nGame Over.")
name = ''
moves = 0
leaderboard.print_board()
# initializes/updates global variables and introduces the game.
# starts the Map and the engine.
# ends the game if needed.
def play_game():
while True:
global name
global moves
print("Welcome to The Program. This Program is running from an AI chip that was inserted\ninto your arm by the Hostile Political Party as a means of maintaining control.")
print(" ")
print("Because you committed a small infraction, this Program was initiated\nas a way to eliminate you. In the Program, you'll be transported through a series of scenarios.")
print(" ")
print ("In each of the scenarios, you will be faced with a series of tasks which you will have to complete.\nYour goal is to complete all the tasks so that you can terminate the Program and reclaim your livelihood!\nTo quit enter :q at any time. You will have 5 lives.\nHope you will make it!")
print("*****************************************************************")
name = input("\nLet's play. Enter your name. > ")
if (name == ':q'):
exit(1)
a_map = Map('treehouse_jungle')
a_game = Engine(a_map)
moves = a_game.play()
game_over(a_game.won())
play_game()
|
ceff82db2f42c5dd330d5f314e7098eb9814be66 | powerticket/algorithm | /Practice/실습/201105/그룹나누기_전원표.py | 694 | 3.765625 | 4 | def findTeam(team, x):
if team[x] == x:
return x
team[x] = findTeam(team, team[x])
return team[x]
def unionTeam(team, a, b):
a = findTeam(team, a)
b = findTeam(team, b)
if a < b:
team[b] = a
else:
team[a] = b
T = int(input())
for t in range(1, T+1):
N, M = map(int, input().split())
arr = list(map(int, input().split()))
team = list(range(N+1))
count = [0] * (N+1)
for i in range(M):
a, b = arr[2*i], arr[2*i+1]
unionTeam(team, a, b)
for i in range(N+1):
findTeam(team, i)
for i in range(1, N+1):
count[team[i]] = 1
result = sum(count)
print('#{} {}'.format(t, result))
|
fe9dcd36bd68918dc131efdecb2eb7efce7a8ce4 | ImLeosky/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/rectangle.py | 4,994 | 3.953125 | 4 | #!/usr/bin/python3
"""
Class Rectangle
"""
from models.base import Base
class Rectangle(Base):
"""
Class Rectangle that inherits from Base:
"""
def __init__(self, width, height, x=0, y=0, id=None):
"""
the class Rectangle that inherits from Base:
"""
super().__init__(id)
self.width = width
self.height = height
self.x = x
self.y = y
@property
def width(self):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
return(self.__width)
@width.setter
def width(self, value):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
if not isinstance(value, int):
raise TypeError("width must be an integer")
elif value <= 0:
raise ValueError("width must be > 0")
else:
self.__width = value
@property
def height(self):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
return(self.__height)
@height.setter
def height(self, value):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
if not isinstance(value, int):
raise TypeError("height must be an integer")
elif value <= 0:
raise ValueError("height must be > 0")
else:
self.__height = value
@property
def x(self):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
return(self.__x)
@x.setter
def x(self, value):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
if not isinstance(value, int):
raise TypeError("x must be an integer")
elif value < 0:
raise ValueError("x must be >= 0")
else:
self.__x = value
@property
def y(self):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
return(self.__y)
@y.setter
def y(self, value):
"""
the class Rectangle by adding validation of
all setter methods and instantiation (id excluded):
"""
if not isinstance(value, int):
raise TypeError("y must be an integer")
elif value < 0:
raise ValueError("y must be >= 0")
else:
self.__y = value
def area(self):
"""
the class Rectangle by adding the public method def
area(self): that returns the area value of the
Rectangle instance.
"""
return(self.__width * self.__height)
def display(self):
"""
class Rectangle by adding the public method def
display(self): that prints in stdout the Rectangle
instance with the character
# - you don’t need to handle x and y here.
"""
str1 = "".join(" " * self.__x)
str2 = "".join("#" * self.__width)
for index in range(self.__y):
print()
for index in range(self.__height):
print(str1 + str2)
def __str__(self):
"""
the class Rectangle by overriding
the __str__ method so that it returns
"""
str1 = "[{}] ({}) ".format(Rectangle.__name__, self.id)
str2 = "{}/{} - ".format(self.__x, self.__y)
return(str1 + str2 + "{}/{}".format(self.__width, self.__height))
def update(self, *args, **kwargs):
"""
the class Rectangle by improving the public
method def display(self):
"""
if len(args) > 0:
self.id = args[0]
if len(args) > 1:
self.__width = args[1]
if len(args) > 2:
self.__height = args[2]
if len(args) > 3:
self.__x = args[3]
if len(args) > 4:
self.__y = args[4]
if args is None or len(args) == 0:
for key, value in kwargs.items():
if key == "id":
self.id = value
if key == "width":
self.__width = value
if key == "height":
self.__height = value
if key == "x":
self.__x = value
if key == "y":
self.__y = value
def to_dictionary(self):
"""
that returns the dictionary representation of a Rectangle:
"""
dicts = {
"x": self.x,
"y": self.y,
"id": self.id,
"width": self.width,
"height": self.height}
return(dicts)
|
601139d7c2c6e059af770e42a5b3d84803fe4023 | haafidz-jp/8-ball-pool-bot | /ball-vision/manual-labelling.py | 4,026 | 3.640625 | 4 | """
A script to allow the user to manually declare the centre of a ball and label it's type.
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as mpimg
import os
# checksum, type, x, y
LABELS_FILE_HEADER = "filename,type,x,y"
LABELS_FILE = "./ball-labels.csv"
ball_data = {}
if os.path.isfile(LABELS_FILE):
with open(LABELS_FILE, "r") as file:
rows = [row[:-1].split(",") for row in file.readlines()[1:]]
for row in rows:
ball_data[row[0]] = [int(row[1]), float(row[2]), float(row[3])]
print("Read {} labelled balls".format(len(ball_data.keys())))
# print(ball_data)
# plt.ion()
class Ball_Labeller(object):
def __init__(self, ax):
self.images = os.listdir('ball-images')
print("Total no. images: {}".format(len(self.images)))
self.current_idx = -1
self.current_image = None
self.ax = ax
self.circle1 = plt.Circle((0, 0), 0.1, color='r')
self.circle2 = plt.Circle((0, 0), 13, color='r', fill=False)
# text location in axes coords
# self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
self.clicking = True
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
self.circle1.center = (x,y)
self.ax.add_patch(self.circle1)
self.circle2.center = (x,y)
self.ax.add_patch(self.circle2)
# self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
self.ax.figure.canvas.draw()
def mouse_click(self, event):
if (event.dblclick) or (not event.inaxes) or (not self.clicking):
return
if event.button == 3:
print("Skipping image")
self.next_image()
self.clicking = True
return
prev_center = plt.Circle((event.xdata, event.ydata), 0.2, color='#00ffff')
self.ax.add_patch(prev_center)
self.clicking = False
while True:
ball_num = input("Enter ball number: ")
if not ball_num.isnumeric() or int(ball_num) < 0 or int(ball_num) > 15:
print("Invalid ball number")
continue
ball_data[self.current_image] = [int(ball_num), event.xdata, event.ydata]
print("You entered", ball_num)
break
self.clicking = True
print("Labelled {}".format(self.current_image))
self.next_image()
def next_image(self):
self.ax.clear()
# Find first un-labelled image
missing_labels = [i for i in self.images if i not in ball_data.keys()]
if len(missing_labels) == 0:
plt.close()
return
self.current_image = missing_labels[0]
# self.current_idx += 1
# if self.current_idx == len(self.images):
# plt.close()
# return
# self.current_image = self.images[self.current_idx]
# self.current_image = missing_labels[0]
img = mpimg.imread('ball-images/{}'.format(self.current_image))
self.ax.imshow(img)
if self.current_image in ball_data:
prev_ball_data = ball_data[self.current_image]
print("Currently labelled as {}".format(prev_ball_data[0]))
prev_center = plt.Circle((prev_ball_data[1], prev_ball_data[2]), 0.2, color='#00ff00')
self.ax.add_patch(prev_center)
fig,ax = plt.subplots()
ball_labeller = Ball_Labeller(ax)
fig.canvas.mpl_connect('motion_notify_event', ball_labeller.mouse_move)
fig.canvas.mpl_connect('button_press_event', ball_labeller.mouse_click)
ball_labeller.next_image()
plt.show()
# Save when user closes plot
print("Saving and Exiting")
with open(LABELS_FILE, "w") as file:
file.write(LABELS_FILE_HEADER + "\n")
for key in ball_data.keys():
row = ",".join([key, str(ball_data[key][0]), str(ball_data[key][1]), str(ball_data[key][2])])
row += "\n"
file.write(row)
|
1e990387a600b5c749dcb0078471a269dc295dac | Kyam13/PythonStudy | /GUI/radio_button.py | 944 | 3.578125 | 4 | import tkinter as tk
#ラジオボタンに表示する文字列を用意
item = ['庭の掃除','窓拭き',' 車の洗車','庭のワックスがけ']
root = tk.Tk()
root.geometry('200x150')
val = tk.IntVar() #IntVarオブジェクトを作成して変数に代入
#ラジオボタンの作成と配置
#itemリストの要素の数だけ処理を繰り返す
for i in range(len(item)):
tk.Radiobutton(root,
value=i,
variable=val,
text=item[i]).pack(anchor=tk.W)
#ラジオボタンの状態を通知する関数
def choice():
ch = val.get() #IntVarオブジェクトの値を取得
#リストitemのインデックスをchに指定して要素を出力
print('明日は'+item[ch]+'をやりましょう')
#ボタンの作成と配置
button = tk.Button(root,
text='明日やること',
command = choice).pack()
root.mainloop()
|
621cc7bf0ca12c70df427453ff9c6f29e42b8f5e | Frost-Studios/seven_shell | /seven_shell.py | 4,898 | 4.0625 | 4 | """
Adam Cherun
1/23/2017
This project's purpose is to create a Python module that can process the English language.
----
TODO:
...
"""
class Base:
@staticmethod
def return_punc():
"""
purpose:
to return any possible puncuation
variables:
punc = ['.', ',', '/', '!', '(', ')', '[', ']', '{', '}', "'", '"']
returns:
punc
"""
punc = ['.', ',', '/', '!', '(', ')', '[', ']', '{', '}', "'", '"']
return punc
@staticmethod
def return_vowels():
"""
purpose:
to return the vowels of the English language
variables:
vowels = ['a', 'e', 'i', 'o', 'u']
returns:
variables
"""
vowels = ['a', 'e', 'i', 'o', 'u']
return vowels
class Filter:
"""
purpose:
to contain functions relevant to filtering sentences
"""
def __init__(self):
"""
purpose:
to initalize the Filter class
variables:
self.filter_words = None
"""
self.filter_words = None
def load_filter_words(self):
"""
purpose:
to load the hardcoded set of filter filter filter_words
"""
self.filter_words = ["a", "an", "but", "can", "do", "for", "get", "it", "just",
"there", "that", "the"]
def add_filter_words(self, w):
"""
purpose:
to add filter words to self.filter_words
"""
if type(w) is str:
self.filter_words.append(w)
else:
print("Error: not string. || add_filter_words(self,w)")
def print_filter_words(self):
"""
purpose:
to print filter_words
"""
print(self.print_filter_words)
def return_filter_words(self):
"""
purpose:
to return the list self.filter_words
returns:
list of filter'd words
"""
return self.filter_words
def filter_sentence(self, s, t):
"""
purpose:
to filter a word; remove all words that are in self.filter_words
returns:
final seperated into a list or string (if t = 0, return is list; if t = 1, return is a string)
"""
temp_word_list = []
temp_buffer = ""
length = len(s)
i = 0
for letter in s:
i += 1
if i == length and not temp_buffer in self.filter_words:
temp_buffer += letter
temp_word_list.append(temp_buffer)
elif letter == " ":
if temp_buffer in self.filter_words:
temp_buffer = ""
pass
else:
temp_word_list.append(temp_buffer)
temp_buffer = ""
else:
temp_buffer += letter
if t == 1:
return temp_word_list
elif t == 2:
temp_string = ""
for item in temp_word_list:
temp_string += item
temp_string += " "
return temp_string
else:
print("Error: type not found. || filter_sentence()")
A = Filter()
A.load_filter_words()
f = A.filter_sentence("Hello my name is Bob I am an rhino", 2)
print(f)
|
4fc3f6e1b7274ba9a319a562999d827f8fdf4104 | danylipsker/PYTHON-INT-COURSE | /DANY-PYTHAGORAS.py | 751 | 4.3125 | 4 | # Pythagoras example
from math import *
#from math import sin, cos, tan, asin, acos, atan
# input of dat from user
print('enter a')
a = int(input())
print('enter b')
b = int(input())
#squares calculation
sq_a = a * a
sq_b = b * b
#square root calculation
c = sqrt(sq_a + sq_b)
#angle calculations
first_angle = acos(a / c) * (180.0 / 3.14159263)
second_angle = asin(a / c) * (180.0 / 3.14159263)
#outputs
print("You entered:", a)
print("a Squared equals:", sq_a)
print()
print("You entered:", b)
print("b Squared equals:", sq_b)
print()
print("The Pythagoras of a and b is:", c)
print()
print("The angle between a and c is: ", first_angle)
print()
print("The angle between b and c is: ", second_angle)
print() |
1f661fb60808fe6be375d8f2aeaeb65254075aa6 | lily01awasthi/python_assignment | /27_replace_list.py | 641 | 4.1875 | 4 | """27. Write a Python program to replace the last element in a list with another list.
Sample data : [1, 3, 5, 7, 9, 10], [2, 4, 6, 8]
Expected Output: [1, 3, 5, 7, 9, 2, 4, 6, 8] """
def get_list():
no_of_items=int(input("enter the no of items you want in list: "))
inp_list=[]
for i in range(no_of_items):
inp=input("enter the list items: ")
inp_list.append(inp)
print(inp_list)
return inp_list
print("Enter your first list:")
first_list=get_list()
print("enter the list you want to replace: ")
second_list=get_list()
first_list.remove(first_list[-1])
first_list.append(second_list)
print(first_list) |
2550614df63557c6d26ed6e6758ec796c7c9bab6 | sunho-park/Notebook | /textbook/9_pandas2.py | 10,457 | 3.8125 | 4 | import numpy as np
import pandas as pd
# 지정된 인덱스와 컬럼을 가진 DataFrame을 난수로 생성하는 함수입니다
def make_random_df(index, columns, seed):
np.random.seed(seed)
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 101), len(index))
df.index = index
return df
# 인덱스와 컬럼이 일치하는 DataFrame을 만듭니다
columns = ["apple", "orange", "banana"]
df_data1 = make_random_df(range(1, 5), columns, 0)
df_data2 = make_random_df(range(1, 5), columns, 1)
# df_data1과 df_data2를 세로로 연결하여 df1에 대입하세요
df1 = pd.concat([df_data1, df_data2], axis=0)
# df_data1과 df_data2를 가로로 연결하여 df2에 대입하세요
df2 = pd.concat([df_data1, df_data2], axis=1)
print(df1)
print(df2)
import numpy as np
import pandas as pd
# 지정된 인덱스와 컬럼을 가진 DataFrame을 난수로 생성하는 함수입니다
def make_random_df(index, columns, seed):
np.random.seed(seed)
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 101), len(index))
df.index = index
return df
columns1 = ["apple", "orange", "banana"]
columns2 = ["orange", "kiwifruit", "banana"]
# 인덱스가 1,2,3,4이고 컬럼이 columns1인 DataFrame을 만듭니다
df_data1 = make_random_df(range(1, 5), columns1, 0)
# 인덱스가 1,3,5,7이고 컬럼이 columns2인 DataFrame을 만듭니다
df_data2 = make_random_df(np.arange(1, 8, 2), columns2, 1)
# df_data1과 df_data2를 세로로 연결하여 df1에 대입하세요
df1 = pd.concat([df_data1, df_data2], axis=0)
# df_data1과 df_data2를 가로로 연결하여 df2에 대입하세요
df2 = pd.concat([df_data1, df_data2], axis=1)
print(df1)
print(df2)
import numpy as np
import pandas as pd
# 지정된 인덱스와 컬럼을 가진 DataFrame을 난수로 생성하는 함수입니다
def make_random_df(index, columns, seed):
np.random.seed(seed)
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 101), len(index))
df.index = index
return df
columns = ["apple", "orange", "banana"]
df_data1 = make_random_df(range(1, 5), columns, 0)
df_data2 = make_random_df(range(1, 5), columns, 1)
# df_data1과 df_data2를 가로로 연결하고, keys로 "X", "Y"를 지정하여 MultiIndex로 만든 뒤 df에 대입하세요
df = pd.concat([df_data1, df_data2], axis=1, keys=["X", "Y"])
# df의 "Y" 라벨 "banana"를 Y_banana에 대입하세요
Y_banana = df["Y", "banana"]
print(df)
print()
print(Y_banana)
import numpy as np
import pandas as pd
data1 = {"fruits": ["apple", "orange", "banana", "strawberry", "kiwifruit"],
"year": [2001, 2002, 2001, 2008, 2006],
"amount": [1, 4, 5, 6, 3]}
df1 = pd.DataFrame(data1)
data2 = {"fruits": ["apple", "orange", "banana", "strawberry", "mango"],
"year": [2001, 2002, 2001, 2008, 2007],
"price": [150, 120, 100, 250, 3000]}
df2 = pd.DataFrame(data2)
# df1, df2의 내용을 확인하세요
print(df1)
print()
print(df2)
print()
# df1 및 df2의 "fruits"를 Key로 내부 결합한 DataFrame을 df3에 대입하세요
df3 = pd.merge(df1, df2, on="fruits", how="inner")
# 출력합니다
# 내부 결합의 동작을 확인합시다
print(df3)
import numpy as np
import pandas as pd
data1 = {"fruits": ["apple", "orange", "banana", "strawberry", "kiwifruit"],
"year": [2001, 2002, 2001, 2008, 2006],
"amount": [1, 4, 5, 6, 3]}
df1 = pd.DataFrame(data1)
data2 = {"fruits": ["apple", "orange", "banana", "strawberry", "mango"],
"year": [2001, 2002, 2001, 2008, 2007],
"price": [150, 120, 100, 250, 3000]}
df2 = pd.DataFrame(data2)
# df1, df2의 내용을 확인하세요
print(df1)
print()
print(df2)
print()
# df1 및 df2을 "fruits"를 Key로 외부 결합한 DataFrame을 df3에 대입하세요
df3 = pd.merge(df1, df2, on="fruits", how="outer")
# 출력합니다
# 외부 결합의 동작을 확인합시다
print(df3)
import pandas as pd
# 주문 정보입니다
order_df = pd.DataFrame([[1000, 2546, 103],
[1001, 4352, 101],
[1002, 342, 101]],
columns=["id", "item_id", "customer_id"])
# 고객 정보입니다
customer_df = pd.DataFrame([[101, "Tanaka"],
[102, "Suzuki"],
[103, "Kato"]],
columns=["id", "name"])
# order_df를 바탕으로 "id"를 customer_df와 결합하여 order_df에 대입하세요
order_df = pd.merge(order_df, customer_df, left_on="customer_id", right_on="id", how="inner")
print(order_df)
import pandas as pd
# 주문 정보입니다
order_df = pd.DataFrame([[1000, 2546, 103],
[1001, 4352, 101],
[1002, 342, 101]],
columns=["id", "item_id", "customer_id"])
# 고객 정보입니다
customer_df = pd.DataFrame([["Tanaka"],
["Suzuki"],
["Kato"]],
columns=["name"])
customer_df.index = [101, 102, 103]
# customer_df를 a바탕으로 "name"을 order_df와 결합하여 order_df에 대입하세요
order_df = pd.merge(order_df, customer_df, left_on="customer_id", right_index=True, how="inner")
print(order_df)
import numpy as np
import pandas as pd
np.random.seed(0)
columns = ["apple", "orange", "banana", "strawberry", "kiwifruit"]
# DataFrame을 생성하고 열을 추가합니다
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 11), 10)
df.index = range(1, 11)
# df의 첫 3행을 취득해 df_head에 대입하세요
df_head = df.head(3)
# df의 끝 3행을 취득해 df_tail에 대입하세요
df_tail = df.tail(3)
# 출력합니다
print(df_head)
print(df_tail)
import numpy as np
import pandas as pd
import math
np.random.seed(0)
columns = ["apple", "orange", "banana", "strawberry", "kiwifruit"]
# DataFrame을 생성하고 열을 추가합니다
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 11), 10)
df.index = range(1, 11)
# df의 각 요소를 두 배로 만들어 double_df에 대입하세요
double_df = df * 2 # double_df = df + df도 OK입니다
# df의 각 요소를 제곱하여 square_df에 대입하세요
square_df = df * df #square_df = df**2도 OK입니다
# df의 각 요소의 제곱근을 계산하여 sqrt_df에 대입하세요
sqrt_df = np.sqrt(df)
# 출력합니다
print(double_df)
print(square_df)
print(sqrt_df)
import numpy as np
import pandas as pd
np.random.seed(0)
columns = ["apple", "orange", "banana", "strawberry", "kiwifruit"]
# DataFrame을 생성하고 열을 추가합니다
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 11), 10)
df.index = range(1, 11)
# df의 통계 정보 중 "mean", "max", "min"을 꺼내 df_des에 대입하세요
df_des = df.describe().loc[["mean", "max", "min"]]
print(df_des)
import numpy as np
import pandas as pd
np.random.seed(0)
columns = ["apple", "orange", "banana", "strawberry", "kiwifruit"]
# DataFrame을 생성하고 열을 추가합니다
df = pd.DataFrame()
for column in columns:
df[column] = np.random.choice(range(1, 11), 10)
df.index = range(1, 11)
# df의 각 행에 대해, 2행 뒤와의 차이를 계산한 DataFrame을 df_diff에 대입하세요
df_diff = df.diff(-2, axis=0)
# df와 df_diff의 내용을 비교해 처리 결과를 확인하세요
print(df)
print(df_diff)
import pandas as pd
# 도시 정보를 가진 DataFrame을 만듭니다
prefecture_df = pd.DataFrame([["Tokyo", 2190, 13636, "Kanto"],
["Kanagawa", 2415, 9145, "Kanto"],
["Osaka", 1904, 8837, "Kinki"],
["Kyoto", 4610, 2605, "Kinki"],
["Aichi", 5172, 7505, "Chubu"]],
columns=["Prefecture", "Area",
"Population", "Region"])
# 출력합니다
print(prefecture_df)
# prefecture_df을 지역(Region)으로 그룹화하여 grouped_region에 대입하세요
grouped_region = prefecture_df.groupby("Region")
# prefecture_df의 지역별 면적(Area)과 인구(Population)의 평균을 mean_df에 대입하세요
mean_df = grouped_region.mean()
# 출력합니다
print(mean_df)
import pandas as pd
# 두 DataFrame을 정의합니다
df1 = pd.DataFrame([["apple", "Fruit", 120],
["orange", "Fruit", 60],
["banana", "Fruit", 100],
["pumpkin", "Vegetable", 150],
["potato", "Vegetable", 80]],
columns=["Name", "Type", "Price"])
df2 = pd.DataFrame([["onion", "Vegetable", 60],
["carrot", "Vegetable", 50],
["beans", "Vegetable", 100],
["grape", "Fruit", 160],
["kiwifruit", "Fruit", 80]],
columns=["Name", "Type", "Price"])
# 여기에 해답을 기술하세요
# 결합합니다
df3 = pd.concat([df1, df2], axis=0)
# 과일만 추출하여 Price로 정렬합니다
df_fruit = df3.loc[df3["Type"] == "Fruit"]
df_fruit = df_fruit.sort_values(by="Price")
# 야채만 추출하여 Price로 정렬합니다
df_veg = df3.loc[df3["Type"] == "Vegetable"]
df_veg = df_veg.sort_values(by="Price")
# 과일과 야채의 상위 세 요소의 Price 합을 각각 계산합니다
print(sum(df_fruit[:3]["Price"]) + sum(df_veg[:3]["Price"]))
import pandas as pd
index = ["taro", "mike", "kana", "jun", "sachi"]
columns = ["국어", "수학", "사회", "과학", "영어"]
data = [[30, 45, 12, 45, 87], [65, 47, 83, 17, 58], [64, 63, 86, 57, 46,], [38, 47, 62, 91, 63], [65, 36, 85, 94, 36]]
df = pd.DataFrame(data, index=index, columns=columns)
# df에 "체육"이라는 새 열을 만들어 pe_column의 데이터를 추가하세요
pe_column = pd.Series([56, 43, 73, 82, 62], index=["taro", "mike", "kana", "jun", "sachi"])
df["체육"] = pe_column
print(df)
print()
# 수학을 오름차순으로 정렬합니다
df1 = df.sort_values(by="수학", ascending=True)
print(df1)
print()
# df1의 각 요소에 5점을 더하세요
df2 = df1 + 5
print(df2)
print()
# df의 통계 정보 중에서 "mean", "max", "min"을 출력하세요
print(df2.describe().loc[["mean", "max", "min"]])
|
33b7ddb169e0830b2afddcf390157c936da345fe | PeterM358/python_advanced_r | /function_advanced/exe/1_even_numbers.py | 140 | 3.625 | 4 | def filter_even(iters):
return list(filter(lambda x: x % 2 == 0, iters))
number = map(int, input().split())
print(filter_even(number)) |
78e8d5feeadf26fb9245bb97a7166d783e2b9f22 | hujosh/magical_tests | /magical/items.py | 4,160 | 3.765625 | 4 | import random
import string
class Item:
''' This class represents an item.
Instantiating an object of this class without parametres creates a random, valid item.
'''
# order of attributes matters
ATTRIBUTES = ['itemName', 'price', 'friends', 'occasions',
'location', 'privacy', 'description', 'qty', 'validatedItemName', 'validatedItemPrice']
NAMES = ['car', 'computer', 'playstation', 'xbox', 'book']
# pre_defined_item is a name in the items array
# attributes is a dictionary
def __init__(self, pre_defined_item = None, attributes = None):
if pre_defined_item is not None:
attributes = get_item(pre_defined_item)
else:
attributes = {}
for attribute in Item.ATTRIBUTES:
try:
setattr(self, attribute, attributes[attribute])
except KeyError:
setattr(self, attribute, self._getValueFor(attribute))
def _getRandomName(self):
return random.choice(Item.NAMES) + str(self._getRandomNumber())
def _getRandomPrice(self):
return str(round(random.random() * 999999, 2))
def _getValueFor(self, value_for):
switch = {
'itemName' : self._getRandomName,
'price' : self._getRandomPrice,
'friends' : str,
'occasions' : str,
'location' : str,
'privacy' : self._getItemPrivacy,
'description' : self._getItemDescription,
'qty' : self._getRandomQty,
'by' : str,
'validatedItemName' : self._getValidatedItemName,
'validatedItemPrice' : self._getValidatedItemPrice,
}
return switch[value_for]()
def _getRandomNumber(self):
return int(random.random()*9999)
def _getItemPrivacy(self):
return 'myfriends'
def _getItemDescription(self):
return 'This item is called %s'%(self.itemName)
def _getRandomQty(self):
return self._getRandomNumber()
def _getValidatedItemName(self):
# Remove trailing and leading white space
return self.itemName.strip()
def _getValidatedItemPrice(self):
# Whatever gets put in into the price field, only numbers, commas and a decimal can come out.
punctuation = string.punctuation.replace(",", "")
punctuation = punctuation.replace(".", "")
punctuation = punctuation.replace("$", "")
validation_string = "%s %s"%(string.ascii_letters, punctuation)
self.price = self._roundDown(self.price)
try:
return str("${:,.2f}".format(float(self.price.strip(validation_string))))
except:
return '$0.00'
def _roundDown(self, price):
return price[:8]
def __str__(self):
return self.itemName
# pre-defined items
# add more here if you need to...
items = [
{'name' : 'priceIsEmpty', 'price' : ''},
{'name' : 'priceHasLetters', 'price' : '2a'},
{'name' : 'priceTooLarge', 'price' : '9999999999999'},
{'name' : 'priceHas3DecimalPlaces', 'price' : '44.994'},
{'name' : 'itemNameIsEmpty', 'itemName' : '', "validatedItemName" : "No name entered"},
{'name' : 'itemNameHasNumbersAndLetters', 'itemName' : 'name123name'},
{'name' : 'itemNameHasOnlyNumbers', 'itemName' : '123'},
{'name' : 'itemNameContainsOnlyZero', 'itemName' : '0'},
{'name' : 'itemNameContainsOnlyNegative1', 'itemName' : '-1'},
{'name' : 'itemNameContainsOnlyASpace', 'itemName' : ' ', "validatedItemName" : "No name entered"},
{'name' : 'priceIsNegative', 'price' : '-4'},
{'name' : 'priceIsZero', 'price' : '0'},
{'name' : 'itemNameHasFunnyCharacters' , 'itemName' : 'Pökémön'}
]
def get_item(name):
for item in items:
if item['name'] == name:
return item
raise KeyError("\n Item %s is not defined, enter a valid item.\n" %name) |
717e7ec20933ee99fda0515d9d40970f20e07c95 | abs0lut3pwn4g3/RootersCTF2019-challenges | /forensics/stego2/audio_enc.py | 1,105 | 3.5625 | 4 | # We will use wave package available in native Python installation to read and write .wav audio file
import wave
# read wave audio file
song = wave.open("elliot_main.wav", mode='rb')
# Read frames and convert to byte array
frame_bytes = bytearray(list(song.readframes(song.getnframes())))
# The "secret" text message
string='Mr. Robot is an American drama thriller television series created by Sam Esmail. http://tiny.cc/72nwdz'
# Append dummy data to fill out rest of the bytes. Receiver shall detect and remove these characters.
string = string + int((len(frame_bytes)-(len(string)*8*8))/8) *'#'
# Convert text to bit array
bits = list(map(int, ''.join([bin(ord(i)).lstrip('0b').rjust(8,'0') for i in string])))
# Replace LSB of each byte of the audio data by one bit from the text bit array
for i, bit in enumerate(bits):
frame_bytes[i] = (frame_bytes[i] & 254) | bit
# Get the modified bytes
frame_modified = bytes(frame_bytes)
# Write bytes to a new wave audio file
with wave.open('song_embedded.wav', 'wb') as fd:
fd.setparams(song.getparams())
fd.writeframes(frame_modified)
song.close() |
0f7de0327a29dd96ddc3629f7100978a53684d6c | ParsaYadollahi/leetcode | /linked_list_cycle.py | 629 | 3.671875 | 4 | '''
https://leetcode.com/explore/interview/card/microsoft/32/linked-list/184/
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
node1 = head
node2 = head
while(True):
if ((node1 == None or node2 == None) or (node1.next == None or node2.next == None)):
return False
else:
node1 = node1.next
node2 = node2.next.next
if (node1 == node2):
return True
|
43428c3d82575a7f5d3d433650c49d4c2dc3db3a | BeninGitHub/Text.txt | /Ben's_Text.py | 576 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 20 19:30:42 2021
@author: bnzr
"""
def revword(word):
i=len(word)
newstring= " "
while i>0:
i =i-1
newstring = newstring + word[i]
return newstring.lower()
def countword()->int:
file= open('text.txt')
line1 = file.readline()
counter=0
for line in file:
line=line.rsplit()
for word in line:
word= revword(word)
if word in line1:
counter= counter+1
return(counter)
|
435ddb313153c4674a2650ca3845ae576350ad07 | Mario263/Python-Projects | /RungeKutta.py | 1,113 | 4.09375 | 4 | #Numerical Integration
import math
def dydx(x, y):
return (y**2-2*x)/(y**2+x)
# Finds value of y for a given x using step size h
# and initial value y0 at x0.
def rungeKutta(x0, y0, x, h):
# Count number of iterations using step size or
# step height h
n = (int)((x - x0)/h)
# Iterate for number of iterations
y = y0
for i in range(1, n + 1):
print("i : ",i,"\nx0 : ",x0)
"Apply Runge Kutta Formulas to find next value of y"
k1 = h * dydx(x0, y)
k2 = h * dydx(x0 + 0.5 * h, y + 0.5 * k1)
k3 = h * dydx(x0 + 0.5 * h, y + 0.5 * k2)
k4 = h * dydx(x0 + h, y + k3)
print("k1 : ", k1)
print("k2 : ", k2)
print("k3 : ", k3)
print("k4 : ", k4)
print("\nk : ",(1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4))
# Update next value of y
y = y + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4)
print("y",i," is ",y,sep="")
print()
# Update next value of x
x0 = x0 + h
return y
x0 = 0
y = 1
x = 0.5
h = 0.1
print('The value of y at x is:', rungeKutta(x0, y, x, h))
|
ae7afcbea41bcc6c19b48a73566044f7a1822b8c | yuhuanhuan36/test | /yhh/basic/TupleTest.py | 1,382 | 3.796875 | 4 | #coding utf-8
# @Time: 2019/9/4 15:58
# @Author: yuhuanhuan
#Python 的元组与列表类似,不同之处在于元组的元素不能修改。
# 元组使用小括号,列表使用方括号。
#元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
tup1 = ('Rita', 'honey', 1989, 2017)
tup2 = (1, 2, 6, 3, 5)
tup3 = ("a", "b", "c", "d")
print(type(tup3)) #<class 'tuple'>
#创建空元组
tup4 = ()
#元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用
tup5 =(50)
print("type tup5", type(tup5))
tup6 = (50,)
print("type tup6", type(tup6))
#访问元组,元组与字符串类似,下标索引从0开始,可以进行截取,组合等。
print("tup1[2]:", tup1[2])
print("tup2[1:2]:", tup2[1:2])
#修改元组,元组中的元素值是不允许修改的,但我们可以对元组进行连接组合
tup7 = tup1 + tup3
print("tup7:", tup7)
#删除元组
del tup7
#print("tup7:", tup7)
#元组运算符
print("len:", len(tup1))
print("tup2*4:", tup2*4)
print('Rita' in tup1)
#元组索引,截取
print("tup1[2]:", tup1[2])
print("tup1[-2]:", tup1[-2])
print("tup1[2:]", tup1[2:])
#元组内置函数
#len(tuple)#计算元组元素个数。
#max(tuple)#返回元组中元素最大值。
#min(tuple)#返回元组中元素最小值。
#tuple(seq)#将列表转换为元组。
|
a5726c3d881d201a8fee0aa975f7e2a204f7e9db | galid1/Algorithm | /python/baekjoon/2.algorithm/implementation/4659.비밀번호 발음하기.py | 1,538 | 3.640625 | 4 | import sys
def solve(word):
print_ans(word, decide_acceptable(word))
def decide_acceptable(word):
bef = ""
bef_type = ""
vowel_cnt = 0
continuous_cnt = 1
for c in word:
c_type = get_type(c)
if c_type == bef_type:
continuous_cnt += 1
else:
continuous_cnt = 1
# 모음 또는 자음 3번이상 안됌
if continuous_cnt >= 3:
return False
# 같은 글자 판단
if bef == c and c != "e" and c != "o":
return False
# 후처리 (모음 수 증가, 이전 글자 갱신)
if c_type == "VOWEL":
vowel_cnt += 1
bef, bef_type = c, c_type
if vowel_cnt < 1:
return False
return True
def get_type(c):
if c in ["a", "i", "o", "u", "e"]:
return "VOWEL"
return "CONSONANT"
def print_ans(word, is_right=True):
template = "is acceptable."
if not is_right:
template = "is not acceptable."
print("<" + word + ">" , template)
while True:
word = sys.stdin.readline().strip()
if word == 'end':
break
solve(word)
# get type test
# for num in range(97, 97+26):
# print("========")
# print("cur c ", chr(num))
# print(get_type(chr(num)))
# aab
# c
# i
# caccac
# abeecoo
# 같은 타입 3번 테스트
# aei
# aie
# oui
# euo
# end
# eeo
# eei
# ooe
# ooi
# eie
# oio
# eee
# ooo
# end
# 같은 글자 두번 테스트
# aa
# bb
# cc
# dd
# ee
# ff
# gg
# hh
# ii
# jj
# kk
# oo
# uu
# end
|
970cbdac0e6e3df54eb256296ff08ed501a7a359 | urbanfog/python | /60001x/person.py | 1,252 | 4 | 4 | import datetime
class Person (object):
def __init__(self, name):
""" Create a person with a name and birthday"""
self.name = name
self.birthday = None
self.lastName = name.split(' ')[-1]
def __str__(self):
""" returns self's full name as a string"""
return self.name
def __lt__(self, other):
if self.lastName == other.lastName:
return self.name < other.name
return self.lastName < other.lastName
def getLastName(name):
""" return self's last name"""
return self.lastName
def setBirthday(self, month, day, year):
self.birthday = datetime.date(year, month, day)
def getAge(age):
""" Returns self's birthday in days"""
if self.birthday == None:
raise ValueError
return (datetime.date.today() - self.birthday).days
class MITPerson(Person):
nextIDnum = 0
def __init__(self, name):
Person.__init__(self, name)
self.IDNum = MITPerson.nextIDnum
MITPerson.nextIDnum += 1
def getIDNum(self):
return self.IDNum
def __lt__(self, other):
return self.IDNum < other.IDNum
def speak(self, utterance):
return (self.getLastName() + " says: " + utterance)
a = Person('James Smith')
b = Person('John Smith')
personList = [b, a, a]
print(personList) |
0c90f18ca9d342d2e1cb79aea646c1a9c1ae42bb | Zolton/Intro-Python-I | /src/05_lists.py | 816 | 4.25 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print("problem 1: ", x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
x.extend([8, 9, 10])
print("problem 2: ", x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
x.remove(8)
print("problem 3: ", x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
x.insert(5, 99)
print("problem 4: ", x)
# Print the length of list x
# YOUR CODE HERE
print("problem 5: lenght is ", len(x))
# Print all the values in x multiplied by 1000
# YOUR CODE HERE
for element in x:
print ("problem 6: ", element*1000)
|
9e12596b80e910828f7a829a59a2a6883229c524 | erikoang/basic-python-b4-c | /Pertemuan2/formatting.py | 278 | 3.578125 | 4 | age = 36
tinggi = 167.23698478
text = "Umur saya adalah {} dan tinggi saya adalah {:.2f}".format(age,tinggi)
print(text)
#Atau
print("Umur saya adalah {} dan tinggi saya adalah {:.2f}".format(age,tinggi))
#p = 5
#l = 3
#print("Luasnya adalah {}".format(p*l))
#print(type(p)) |
2a8fab4974928abf54f942cc9ab6e2376edf13f4 | Mityai/contests | /camps/lksh-2015/AS.small/days-plans/01.bash/lection/python/operator.py | 502 | 3.8125 | 4 | # -*- coding: utf8 -*-
class Student:
def __init__(self, name, age) :
self.name = name
self.age = age
def __eq__(self, other):
return self.name == other.name
def __add__(self, other):
return self.name + other.name
def __str__(self):
return "Я оператор вывода! Меня зовут " + self.name
a = Student("vasya", 14)
b = Student("petya", 13)
c = Student("vasya", 15)
print(a == b)
print(c == b)
print(a == c)
print(a + b)
print(a)
|
3e723115a0087a4d5a175cdb4ee3bc227e411985 | Aiman-Jabaren/G13_ECE143_Project | /plot_us_maps.py | 3,345 | 3.625 | 4 | import plotly.plotly as py
import plotly.figure_factory as ff
import plotly.graph_objs as go
from plotly.offline import plot, iplot
import numpy as np
import pandas as pd
def plot_map(df,low,high,title='Diabetes'):
'''
Function to plot US map given a dataframe. Low and high values need to be specified for the scale according to input data
Title will be shown according to input
:param: df
:type: pd.DataFrame
:param: low
:type: int
:param: high
:type: int
:param: title
:type: str
:return type: plotly plot
'''
assert isinstance(df,pd.DataFrame)
assert isinstance(title,str)
assert isinstance(low,int)
assert isinstance(high,int)
idxs = []
# List of available years
years = [2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
# Find the column index for each year
cls = list(df)
for year in years:
idxs.append(cls.index(year))
# list of dataframes
list_df = []
for x,y in list(zip(idxs,years)):
list_df.append(create_df(x,y,df))
# Setting colorscale of the map
colorscale = ["#deebf7","#c6dbef","#85bcdb","#57a0ce","#3082be","#1361a9","#0b4083"]
# Endpoints of value scale
endpts = list(np.linspace(low, high, len(colorscale) - 1))
# FIPS codes
fips = list_df[-1]['FIPS Codes'].astype(float).tolist()
# Values
temp = list_df[-1]['age-adjusted percent'].tolist()
# If data is not available
temp = [np.NaN if x=='No Data' else x for x in temp]
values = temp
fig = ff.create_choropleth(
fips=fips, values=values,
binning_endpoints=endpts,
colorscale=colorscale,
show_state_data=False,
show_hover=False, centroid_marker={'opacity': 0},
asp=2.9, title=title+' prevalence % in '+str(years[-1]),
font=dict(family='Arial', color='black')
)
return iplot(fig, filename='choropleth_usa_'+title)
def create_df(idx,year,df):
'''
Function to create sub-dataframe for each year given column id and year
:param: idx
:type: int
:param: year
:type: int
:param: df
:type: pd.DataFrame
:return type: pd.DataFrame
'''
assert isinstance(idx,int)
assert isinstance(year,int)
assert isinstance(df,pd.DataFrame)
# First 3 columns are common
f = df.iloc[:,0:3]
# column names
headers = f.iloc[0]
# New dataframe with first row as columns headers
fn = pd.DataFrame(f.values[1:], columns=headers)
# Take 7 columns
t = df.iloc[:,idx:idx+7]
# Add a new column year
t.loc[0,'year'] ='year'
t.loc[1:,'year'] = year
# add header
headers = t.iloc[0]
# Series to Dataframe
new_df = pd.DataFrame(t.values[1:], columns=headers)
# Concatenate two dataframes
new_df = pd.concat([fn,new_df],axis=1)
return new_df
def get_df(df):
'''
Function to return list of dataframes after modifications from the original dataframe
'''
idxs = []
# List of available years
years = [2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
# Find the column index for each year
cls = list(df)
for year in years:
idxs.append(cls.index(year))
# list of dataframes
list_df = []
for x,y in list(zip(idxs,years)):
list_df.append(create_df(x,y,df))
return list_df |
1af27b0304b3f8e47c8710d82f320872597953a8 | HighEnergyDataScientests/bnpcompetition | /feature_analysis/correlation.py | 1,843 | 3.5625 | 4 | # -----------------------------------------------------------------------------
# Name: correlation
# Purpose: Calculate correlations and covariance
#
#
# -----------------------------------------------------------------------------
"""
Calculate correlations and covariance
"""
import pandas as pd
import numpy as np
import xgboost as xgb
import operator
from sklearn import preprocessing
from sklearn.cross_validation import train_test_split
import matplotlib
matplotlib.use("Agg") # Needed to save figures
import matplotlib.pyplot as plt
# --- Import data ---
print("## Loading Data")
train = pd.read_csv('../inputs/train.csv')
# --- Process data ---
print("## Data Processing")
# Define parameters
output_col_name = "target"
id_col_name = "ID"
train = train.drop(id_col_name, axis=1)
# --- Calculate matrices and save to csv ---
print("## Calculating matrices")
print(" - Pearson correlation matrix")
correlation_p = train.corr() # Pearson method
correlation_p.to_csv('stats/correlation_matrix_pearson.csv')
# print(" - Kendall Tau correlation matrix")
# correlation_k = train.corr(method='kendall') # Kendall Tau
# correlation_k.to_csv('stats/correlation_matrix_kendall.csv')
print(" - Spearman correlation matrix")
correlation_s = train.corr(method='spearman') # Spearman
correlation_s.to_csv('stats/correlation_matrix_spearman.csv')
covariance = train.cov()
covariance.to_csv('stats/covariance_matrix.csv')
# --- Plot matrices ---
print("## Plotting")
plt.matshow(correlation_p)
plt.savefig('stats/correlation_matrix_pearson.png')
plt.clf()
# plt.matshow(correlation_k)
# plt.savefig('stats/correlation_matrix_kendall.png')
# plt.clf()
plt.matshow(correlation_s)
plt.savefig('stats/correlation_matrix_spearman.png')
plt.clf()
plt.matshow(covariance)
plt.savefig('stats/covariance_matrix.png')
plt.clf() |
9bba95356505288ab388a7d140e6379000dde932 | christina57/lc-python | /lc-python/src/lock/159. Longest Substring with At Most Two Distinct Characters.py | 928 | 3.71875 | 4 | """
159. Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”,
T is "ece" which its length is 3.
"""
class Solution(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
dicts = {}
res = 0
cur = 0
for i, c in enumerate(s):
if c in dicts or len(dicts) < 2:
cur += 1
else:
smallk = 0
smallv = i
for (k, v) in dicts.items():
if v < smallv:
smallk = k
smallv = v
dicts.pop(smallk)
cur = i - smallv
res = max(res, cur)
dicts[c] = i
return res
|
2e2ec0ed26652d21ee1cf0cb0f92f5021c7daaf3 | Lmackenzie6/Year9DesignPythonLM | /practiceapr20.py | 1,180 | 3.640625 | 4 | import tkinter as tk
import tkinter.font as tkFont
def motion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
return
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=400)
canvas.pack()
canvas.create_rectangle(100,50,200,250, fill = "grey") #building frame
#row 1 squares
canvas.create_rectangle(110,80,130,100, fill = "blue")
canvas.create_rectangle(140,80,160,100, fill = "blue")
canvas.create_rectangle(170,80,190,100, fill = "blue")
#row 2 squares
canvas.create_rectangle(110,120,130,140, fill = "blue")
canvas.create_rectangle(140,120,160,140, fill = "blue")
canvas.create_rectangle(170,120,190,140, fill = "blue")
#row 3 squares
canvas.create_rectangle(110,160,130,180, fill = "blue")
canvas.create_rectangle(140,160,160,180, fill = "blue")
canvas.create_rectangle(170,160,190,180, fill = "blue")
#door
canvas.create_rectangle(140,200,160,240, fill = "brown")
#doorknob
canvas.create_oval(155,230,160,234)
fontStyle = tkFont.Font(family="Lucida Grande", size=50)
for i in range(0,60,3):
canvas.create_oval(0,0 + i,60,0 + i)
canvas.create_oval(0 + i,0,0 + i,60)
canvas.bind('<Motion>',motion)
root.mainloop(); |
adadd963dd7bf7570fdb2dbbe31cf757ec2f74b9 | unsalfurkanali/codeChallenge | /q3.py | 441 | 3.5 | 4 | def prime(x):
for i in range(2, x, 1):
if not x%i:
return False
return True
def palandoken(x):
strX = str(x)
for i in range(0, len(strX), 1):
if not prime(int(strX[0 : i : ] + strX[i + 1 : :])):
return False
return True
sum = 0
for i in range(10, 50000, 1):
if prime(i):
if palandoken(i):
sum = sum + i
print(i)
print("Total = {}".format(sum)) |
61b075ac3c8d941727b242b45a1deb6e7b4c6c19 | codengers/python | /findallposofsubstring.py | 398 | 4.09375 | 4 | #display all positions of sub string in string.
#Enter string and sub string below
str=input("Please enter string: ")
sub=input("Please enter sub string: ")
i=0
n=len(str)
flag=False
while i<n:
pos=str.find(sub, i, n)
if pos!=-1:
print("Here is sub string: ", pos+1)
i=pos+1
flag=True
else:
i=i+1
if flag==False:
print("sub string not found.")
|
a3c02580ef17e8fe04ffee44fbecc29232cf3af5 | libertad78/START-UP-PYTHON | /practice2.py | 508 | 3.859375 | 4 | sentence = input("이름을 입력하세요 : ")
print(sentence)
print(sentence[0])
print(sentence[-1])
print(sentence[2:6])
print(sentence + sentence)
print(sentence * 3)
print(sentence, sentence)
word = sentence + sentence
word2 = sentence * 4
print(word)
print(word2)
print(sentence.count('u'))
print(sentence.lstrip())
print(sentence.rstrip())
print(sentence.strip())
print(sentence.upper())
print(sentence.lower())
print(sentence.index('u'))
print(sentence.replace('u','a')) |
75a52e32f0a4a6d874747db04073d47d98ccd51f | starligtht/leson-12345-hw | /untitled0.py | 360 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 21 21:01:14 2021
@author: 88697
"""
score = int(input('enter grade 0-100 '))
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print ('C')
elif score >= 60:
print('D')
elif score == 0:
print('what are you doing in class?')
else:
print ('E') |
3a51f273bc062d37f0bd3c1d92845da67b2a752a | sakshi13-cmd/tathastu_week_of_code | /tathastu_week_of_cod/p5.py | 765 | 3.921875 | 4 | run_p1=int(input("enter the runs of p1 scored in 60 balls:"))
run_p2=int(input("enter the runs of p2 scored in 60 balls:"))
run_p3=int(input("enter the runs of p3 scored in 60 balls:"))
str_1 = run_p1 * 100 / 60
str_2 = run_p2 * 100 / 60
str_3 = run_p3 * 100 / 60
print("strike rate of player_1 is:",str_1)
print("strike rate of player_2 is:",str_2)
print("strike rate of player_3 is:",str_3)
print("runs scored by p_1 if he plaayed 60 more balls:",run_p1*2)
print("runs scored by p_2 if he plaayed 60 more balls:",run_p2*2)
print("runs scored by p_3 if he plaayed 60 more balls:",run_p3*2)
print("max no of sixs played by p_1:",run_p1//6)
print("max no of sixs played by p_2:",run_p2//6)
print("max no of sixs played by p_3:",run_p3//6)
|
b1af9ed773b4ef987e2697582d7271ea6ce2fedf | Jhynn/programming-concepts-and-logic | /solutions/1st-operators/l1_a1.py | 127 | 3.953125 | 4 | a = float(input('Type a number, please: '))
b = float(input('Type another one: '))
print(f'The sum of {a} + {b} is {a + b}.')
|
dc843a37170e119aa17343390ecee461328424c8 | printfoo/leetcode-python | /problems/0026/remove_duplicates_from_sorted_array.py | 544 | 3.890625 | 4 | """
Solution for Remove Duplicates from Sorted Array, time O(n) space O(1).
Idea:
"""
# Solution.
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
j = 0
for i in range(len(nums)):
if nums[i] == nums[j]: continue
else:
j += 1
nums[j] = nums[i]
return j + 1
# Main.
if __name__ == "__main__":
nums = [1]
print(Solution().removeDuplicates(nums))
|
3169d504fde613f8da2e842c52441534554d708d | sheldonbarry/houseprice_ANN | /property-ann.py | 2,643 | 3.578125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from math import sqrt
from keras.layers import Dense
from keras.models import Sequential
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# King County, Washington State, USA house data
# historic data of houses sold between May 2014 to May 2015
# https://github.com/dbendet/coursera_machine_learning/blob/master/kc_house_data.csv
data = pd.read_csv("kc_house_data.csv")
# check data
# print(data.columns.values)
# drop data with zero bedrooms and bathrooms and bedrooms outlier
data = data.drop(data[data.bedrooms == 0].index)
data = data.drop(data[data.bedrooms == 33].index)
data = data.drop(data[data.bathrooms == 0].index)
# drop columns that we won't be using
data = data.drop(['id', 'date', 'zipcode'], axis=1)
# scale data to values between 0 and 1
scaler = MinMaxScaler()
data_scaled = scaler.fit_transform(data) # numpy array
# convert numpy array to dataframe with data columns names
data_scaled = pd.DataFrame(data_scaled, columns=data.columns.values)
# dependent variable
y_scaled = data_scaled[['price']].values
# extract independent variables (all columns except price)
X_scaled = data_scaled.drop(['price'], axis=1).values
# randomly split data into train and test
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y_scaled, test_size = 0.2)
x_len = len(X_scaled[0])
model = Sequential([
# dense layer with 32 neurons, relu activation and x_len features
Dense(32, activation='relu', input_shape=(x_len,)),
# dense layer with 16 neurons and relu activation (constrain to 0 to 1)
Dense(16, activation='relu'),
# dense output layer with one neuron
Dense(1, activation='linear'),
])
# build the model
model.compile(optimizer='adam',
loss='mean_squared_error')
# train model
hist = model.fit(X_train, y_train,
batch_size=32, epochs=50,
validation_data=(X_test, y_test))
# make some predictions using the model
y_pred = model.predict(X_test)
# evaluate model based on the predictions
print ('Model evaluation:')
print ('R squared:\t {}'.format(r2_score(y_test, y_pred)))
# calculate RMSE based on unscaled value
rmse = sqrt(mean_squared_error(y_test, y_pred)) * (data['price'].max() - data['price'].min())
print ('RMSE:\t\t {}'.format(rmse))
# visualise loss during training
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training loss', 'Validation loss'], loc='upper right')
plt.tick_params(labelsize=8)
plt.tight_layout()
plt.show()
|
59e790766d2345154b1afe9c09f2967e6f3157a7 | Velu2498/codekata-array-python | /14.py | 463 | 3.875 | 4 | """
Given a number N, print the odd digits in the number(space seperated) or print -1 if there is no odd digit in the given number.
Input Size : N <= 100000
Sample Testcase :
INPUT
2143
OUTPUT
1 3
"""
s=int(input())
v=[]
new=[]
sum=0
while(s > 0):
n=s%10
v.append(n)
s=s//10
v=v[::-1]
for i in range(len(v)):
val=int(v[i])
if(val%2 != 0):
new.append(val)
sum+=1
if(sum==0):
print(-1)
else:
print(" ".join(map(str,new))) |
0f14fc742270beea34abe3b5b53b9c72043f8cde | AswinBarath/python-dev-scripts | /II OOP/Exercise_Extending_List.py | 355 | 3.9375 | 4 | class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
super_list1.append(5)
print(super_list1)
print(len(super_list1))
print(super_list1[0])
print(issubclass(SuperList, list))
print(issubclass(list, object))
# Note: Everything in Python is an object
# that inherits from the base 'object' class
|
d157f804c04b756961316969b77774496803acab | tlops/Python-4-web | /wk6-jsonAssg.py | 1,067 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# programming for web by Dr chuck
# University of Michigan
# Written as an assignment by Tlops
# Nov. 2015
# what this code does:
# The program will prompt for a URL, read the JSON data from that URL
# using urllib and then parse and extract the comment counts from the
# JSON data, compute the sum of the numbers in the file
# sample link:
# http://python-data.dr-chuck.net/comments_42.json (sum = 2482)
# http://python-data.dr-chuck.net/comments_191502.json
import json
import urllib
while True:
url = raw_input('Enter URL: ')
if len(url) < 1 : break
print '\nRetrieving: ', url
urlhandler = urllib.urlopen(url) # open url
output = urlhandler.read() # read url
infojs = json.loads(output) # json is parsed here
#print infojs
result = infojs["comments"]
#print result
print 'Comment count: ', len(result)
total = 0 # initialiaze total
for js in result:
total =total + int(js['count'])
print total
|
408e076994da64a308a6dcfdbbfc4b8905c0d354 | dw2008/coding365 | /201904/0416.py | 420 | 4.09375 | 4 | #Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order.
#Example 1:
#Input: [-4,-1,0,3,10]
#Output: [0,1,9,16,100]
#Example 2:
#Input: [-7,-3,2,3,11]
#Output: [4,9,9,49,121]
numbers = [1, 2, 3, 4]
def returnIntegers(alist) :
result = list()
for x in alist :
result.append(x * x)
return result
print(returnIntegers(numbers)) |
4ff27ec4413426a99af324eb0c332976415a3325 | touhiduzzaman-tuhin/python-code-university-life | /Practice_StartBit/60.py | 174 | 3.53125 | 4 | li = [1,2, 3, 4, 5.5, 9, 3.3, "tuhin", 3+8j]
print(li[2])
print(li[4])
print(li[7])
print(li[8])
print(type(li[0]))
print(type(li[4]))
print(type(li[7]))
print(type(li[8])) |
535471fc720afe2fdb719914de980b2253749e0e | sidv/Assignments | /sufail/aug19/rectangle.py | 1,000 | 4.09375 | 4 | class Rectangle:
"""implementing doc"""
def __init__(self,length,width):
self.length=length
self.width=width
def area(self):
return self.length*self.width
def __add__(self,r2):
return self.length+self.width+r2.length+r2.width
def __str__(self):
return f"The lenth is {self.length} breadth is {self.width}"
def __gt__(self,r2):
if self.area() > r2.area():
return True
else:
return False
def __eq__(self,r2):
if self.area() == r2.area():
return True
else:
return False
l1=int(input("Enter length of first rectangle"))
w1=int(input("Enter width"))
r1=Rectangle(l1,w1)
print("Area of first rectangle",r1.area())
l2=int(input("Enter length of second rectangle"))
w2=int(input("Enter width"))
r2=Rectangle(l2,w2)
print("Area of second rectangle",r2.area())
addition=r1+r2
print("Addition of rectangles",addition)
greatest=r1>r2
print("rectangle 1 is greater than rectangle 2",greatest)
eq=(r1==r2)
print("both are equal :",eq)
print(str(r1))
print(Rectangle.__doc__)
|
e9721d343c364835051660250c0308c512b9e6dd | chloemcgarry/project-pands | /scatterplotpl.py | 419 | 3.921875 | 4 | #Importing pandas library
import pandas as pd
#Importing matplolib library
import matplotlib.pyplot as plt
#Read csv file and call it data
data = pd.read_csv('iris_data_set.csv')
#labelling x axis and y axis
x = data.species
y = data.petal_length
plt.scatter(x,y)
#Naming the scatter plot of the petal length data
title = ("Petal Length Comparison Plot")
#Plotting the petal length data on a petal plot
plt.show() |
d7f5ae2690b1d87e93b9a8c625353998f036750f | Svalorzen/morl_guts | /gp_preference/pymodem/Value.py | 7,354 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 22 15:51:03 2016
@author: Diederik M. Roijers (University of Oxford)
"""
import numpy
def maxDifferenceAcrossObjectives(vector1, vector2):
"""
Returns the maximal difference across objectives between a vector v
another vector u:
max_i |v_i - u_i|
"""
diff = 0
for i in range(len(vector1)):
newdiff = numpy.absolute(vector1[i]-vector2[i])
if(newdiff > diff):
diff = newdiff
return diff
def equalVectors(vector1, vector2):
"""
Returns whether two vectors are equal in all elements
"""
for i in range(len(vector1)):
if(not vector1[i] == vector2[i]):
return False
return True
def inner_product(vector1, vector2):
"""
Returns vector1 . vector2
"""
result = 0
for i in range(len(vector1)):
result = result + vector1[i]*vector2[i]
return result
def maxDifferenceAcrossObjectivesSet(vvs1, vvs2):
"""
Returns the maximal difference between a vector in set 2
and the closest vector in set 1:
max_{v \in vvs2} min_{v' \in vvs1}
maxDifferenceAcrossObjectives(v, v')
Usage: if vvs2 is a new set (that will probably contain more vectors
than vvs1), e.g., resulting from a multi-objective Bellman backup,
how much different is it from the set in the previous iteration (vvs1)?
"""
diff = 0
for i in range(len(vvs2.set)):
mindiff = numpy.Infinity
for j in range(len(vvs1.set)):
newdiff = maxDifferenceAcrossObjectives(vvs1.set[j],
vvs2.set[i])
if(newdiff < mindiff):
mindiff = newdiff
if(mindiff > diff):
diff = mindiff
return diff
def maxDifferenceAcrossValueFunctions(v1, v2):
diff = 0
for i in range(len(v1.tables)):
newdiff = maxDifferenceAcrossObjectivesSet(v1.tables[i],
v2.tables[i])
if(newdiff > diff):
diff = newdiff
return diff
def testValueVectorSet():
result = ValueVectorSet()
result.add(numpy.array([1.0, 0.0]))
result.add(numpy.array([0.0, 1.0]))
result.add(numpy.array([0.6, 0.6]))
result.add(numpy.array([0.9, 0.15]))
result.add(numpy.array([0.11, 0.8]))
return result
class ValueVectorSet:
"""
"""
def __init__(self):
"""
"""
self.set = []
def add(self, vector):
"""
"""
self.set.append(vector)
def addAll(self, vectors):
"""
Add all vectors in in 'vectors' to the set
:param vectors: A list of vectors
"""
for i in range(len(vectors)):
self.set.append(vectors[i])
def empty(self):
"""
"""
return len(self.set) == 0
def translate(self, vector):
"""
Return a new set identical to this set, but translated with 'vector'
"""
newSet = []
for i in range(len(self.set)):
newSet.append((self.set[i]+vector))
result = ValueVectorSet()
result.addAll(newSet)
return result
def multiplyByScalar(self, scalar):
"""
Return a new set identical to this set, but translated with 'vector'
"""
newSet = []
for i in range(len(self.set)):
newSet.append((scalar*self.set[i]))
result = ValueVectorSet()
result.addAll(newSet)
return result
def crossSum(self, vvset):
"""
Return a new set being the cross sum of this set and another set
"""
if(len(self.set) == 0):
result = ValueVectorSet()
result.addAll(vvset.set)
return result
if(len(vvset.set) == 0):
result = ValueVectorSet()
result.addAll(self.set)
return result
newSet = []
for i in range(len(self.set)):
for j in range(len(vvset.set)):
newSet.append((self.set[i]+vvset.set[j]))
result = ValueVectorSet()
result.addAll(newSet)
return result
def __str__(self):
"""
"""
result = ""
for i in range(len(self.set)):
result = result + str(i) + ": " + str(self.set[i]) + "\n"
return result
def removeVec(self, vector):
"""
Return a new set identical to self, but from which vector
has been removed.
"""
setprime = []
for i in range(len(self.set)):
if(not equalVectors(self.set[i], vector)):
setprime.append(self.set[i])
vvs = ValueVectorSet()
vvs.addAll(setprime)
return vvs
def removeMaximisingLinearScalarisedValue(self, weight):
"""
Remove the vector that maximises the scalarised value
for a given scalarisation weight, and return a tuple
with this vector and the value set from which this
vector has been removed
"""
maxscalval = -numpy.Infinity
maxvec = None
for i in range(len(self.set)):
scalval = inner_product(self.set[i], weight)
if(scalval > maxscalval):
maxvec = self.set[i]
maxscalval = scalval
vvs = self.removeVec(maxvec)
return (maxvec, vvs)
def removeMaximisingForExtrema(self):
"""
Remove the vectors that maximises the scalarised value
at the extrema of the weight space, and return a tuple
with these vectors and the value set from which these
vectors have been removed
"""
if(self.empty()):
return (None, None)
nObjectives = len(self.set[0])
rest = self
maximising = []
for o in range(nObjectives):
maxscalval = -numpy.Infinity
maxvec = None
for i in range(len(self.set)):
scalval = self.set[i][o]
if(scalval > maxscalval):
maxvec = self.set[i]
maxscalval = scalval
if(maxvec is not None):
rest = rest.removeVec(maxvec)
maximising.append(maxvec)
vvs = ValueVectorSet()
vvs.addAll(maximising)
return (vvs, rest)
class ValueFunction:
"""
A class containing a multi-objective value function indexed
with an integer state: V(S), returning a ValueVectorSet
"""
def __init__(self, nStates):
"""
"""
self.tables = []
for i in range(nStates):
vvs = ValueVectorSet()
self.tables.append(vvs)
def addVectorToAllSets(self, vector):
"""
"""
for i in range(len(self.tables)):
vvs = self.tables[i]
vvs.add(vector)
def __str__(self):
"""
"""
result = ""
for i in range(len(self.tables)):
result = result+str(i)+":\n" + self.tables[i] + "\n\n"
return result
def getValue(self, stateIndex):
"""
"""
return self.tables[stateIndex]
def setValue(self, stateIndex, vvs):
"""
"""
self.tables[stateIndex] = vvs
|
d27d8063a24b81763cb353565f47243b6236c5b4 | Stranger65536/AlgoExpert | /hard/maxPathSum/program.py | 2,412 | 4.15625 | 4 | #
# Max Path Sum In Binary Tree
# Write a function that takes in a Binary Tree and returns its max
# path sum.
#
# A path is a collection of connected nodes in a tree where no node
# is connected to more than two other nodes; a path sum is the sum of
# the values of the nodes in a particular path.
#
# Each BinaryTree node has an integer value, a left child node, and a
# right child node. Children nodes can either be BinaryTree nodes
# themselves or None / null.
#
# Sample Input
# tree = 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
# Sample Output
# 18 // 5 + 2 + 1 + 3 + 7
# Hints
# Hint 1
# If you were to imagine each node in a Binary Tree as the root of
# the Binary Tree, temporarily eliminating all of the nodes that come
# above it, how would you find the max path sum for each of these newly
# imagined Binary Trees? In simpler terms, how can you find the max path
# sum for each subtree in the Binary Tree?
#
# Hint 2
# For every node in a Binary Tree, there are four options for the max
# path sum that includes its value: the node's value alone, the node's
# value plus the max path sum of its left subtree, the node's value plus
# the max path sum of its right subtree, or the node's value plus the
# max path sum of both its subtrees.
#
# Hint 3
# A recursive algorithm that computes each node's max path sum and uses
# it to compute its parents' nodes' max path sums seems appropriate, but
# realize that you cannot have a path going through a node and both its
# subtrees as well as that node's parent node. In other words, the
# fourth option mentioned in Hint #2 poses a challenge to implementing
# a recursive algorithm that solves this problem. How can you get around
# it?
#
# Optimal Space & Time Complexity
# O(n) time | O(log(n)) space - where n is the number of nodes in the
# Binary Tree
def maxPathSum(tree):
def traverse(tree):
if tree is None:
return 0, 0
left_max_b, left_max_p = traverse(tree.left)
right_max_b, right_max_p = traverse(tree.right)
max_child_sum_b = max(left_max_b, right_max_b)
value = tree.value
max_sum_b = max(max_child_sum_b + value, value)
max_sum_root = max(left_max_b + value + right_max_b, max_sum_b)
max_path_sum = max(left_max_p, right_max_p, max_sum_root)
return max_sum_b, max_path_sum
_, maxSum = traverse(tree)
return maxSum
|
5276a5e03f4c39a6f4e3451ed21da74c47ccddfc | joostgrunwald/data-visualization | /data_vis.py | 12,299 | 3.546875 | 4 |
from matplotlib import pyplot as plt
from prettytable import PrettyTable
# * Seaborn dependencies
import pandas as pd
import numpy as np
import seaborn as sns
# * Settings
show_matplotlib = False
show_seaborn = True
if (show_matplotlib == True):
#?############
#* HISTOGRAM #
#?############
# values on the y axis
y = [14, 3, 6, 9]
# plotting histogram
plt.hist(y)
# showing plot
plt.show()
#?##########
#* BOX PLOT#
#?##########
# values on the y axis
y = [14, 3, 6, 9]
# plotting histogram
plt.boxplot(y)
# showing plot
plt.show()
#?###########
#* Bar Plot #
#?###########
# values on the x axis
x = [5, 2, 9, 4, 7]
# values on the y axis
y = [14, 3, 6, 9, 1]
# plotting bar
plt.bar(x, y)
# showing plot
plt.show()
#?############
#* Line Plot #
#?############
# values on the x axis
x = [5, 2, 9, 4, 7]
# values on the y axis
y = [14, 3, 6, 9, 1]
# plotting line
plt.plot(x, y)
# showing plot
plt.show()
#?############
#* Pie Chart #
#?############
# The labels are the names for the parts
label_set = '7', '6', '8+', '5-'
# we give each label a size
sizes = [20, 45, 15, 20]
# we use explode to show a particular slide
explode = (0, 0, 0, 0.1)
# subplots
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=label_set,
autopct='%1.1f%%', shadow=True, startangle=90)
# make sure its a circle
ax1.axis('equal')
# showing plot
plt.show()
#?###############
#* Scatter Plot #
#?###############
# values on the x axis
x = [5, 2, 9, 4, 7, 6, 3, 1, 4, 11, 4, 4, 5]
# values on the y axis
y = [14, 3, 6, 9, 1, 3, 1, 2, 7, 8, 3, 4, 11]
# make the actual scatter plot
plt.scatter(x, y)
# showing plot
plt.show()
#?###################
#* Plot Customizing #
#?###################
# values on the x axis
x = [5, 2, 9, 4, 7, 6, 3, 1, 4, 11, 4, 4, 5]
# values on the y axis
y = [14, 3, 6, 9, 1, 3, 1, 2, 7, 8, 3, 4, 11]
# values on the x axis of second set
x2 = [14, 3, 6, 9, 1, 3, 1, 2, 7, 8, 3, 4, 11]
# values on the y axis of second set
y2 = [5, 2, 9, 4, 7, 6, 3, 1, 4, 11, 4, 4, 5]
# adjust the size of the plot
plt.figure(figsize=(12, 8))
# make the actual scatter plot
plt.scatter(x, y, label="first set")
# we do the scattering again to plot 2 different sets inside the same plot
# Note that we used alpha to chagne the opacity of the plot
plt.scatter(x2, y2, alpha=0.5, label="second set")
# adjust the x and y label (side text)
plt.xlabel('X coordinate')
plt.ylabel('Y coordinate')
# adjust the plot title
plt.title("2D map of x and y coordinates")
# add a legend #?(depends on label in .scatter)
plt.legend()
# showing plot
plt.show()
#?####################
#* Creating Subplots #
#?####################
# values on the x axis
x = [5, 2, 9, 4, 7, 6, 3, 1, 4, 11, 4, 4, 5]
# values on the y axis
y = [14, 3, 6, 9, 1, 3, 1, 2, 7, 8, 3, 4, 11]
# values on the x axis of second set
x2 = [14, 3, 6, 9, 1, 3, 1, 2, 7, 8, 3, 4, 11]
# values on the y axis of second set
y2 = [5, 2, 9, 4, 7, 6, 3, 1, 4, 11, 4, 4, 5]
# alternative way to chance the size of the plot
fig = plt.figure(figsize=(12, 8))
# we create a sublpot
ax1 = plt.subplot2grid((2, 2), (0, 0))
# make the actual scatter plot
ax1 = plt.scatter(x, y, label="first set")
# adjust the x and y label (side text)
ax1 = plt.xlabel('X coordinate')
ax1 = plt.ylabel('Y coordinate')
# adjust the plot title
ax1 = plt.title("2D map of x and y coordinates")
# we create a sublpot
ax2 = plt.subplot2grid((2, 2), (0, 1))
# make the actual scatter plot
ax2 = plt.scatter(x2, y2, label="second set")
# adjust the x and y label (side text)
ax2 = plt.xlabel('X coordinate')
ax2 = plt.ylabel('Y coordinate')
# adjust the plot title
ax2 = plt.title("2D map of x and y coordinates")
# make histogram for ax2
ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=2)
ax2 = plt.hist(y2)
# showcase result
fig.tight_layout()
#?##############
#* prettytable #
#?##############
# specifying column names
mytable = PrettyTable(["Student Name", "Class", "Section", "Percentage"])
# adding rows
mytable.add_row(["Serra", "X", "B", "91.2%"])
mytable.add_row(["Penny", "B", "C", "61.2%"])
mytable.add_row(["Erik", "B", "B", "90.2%"])
mytable.add_row(["Josso", "X", "A+", "100%"])
mytable.add_row(["Luka", "X", "B", "88.1%"])
# output
print(mytable)
#?###################
#* testing comments #
#?###################
# the following section is for testing better comments
# TODO: Implement x and y
# ? This is a query
# * this is hightlighted, way better then the stupid plain default comments
# ! this is very important
if (show_seaborn == True):
#?###################
#* Seaborn data Vis #
#?###################
# set the style of sns
sns.set_style('darkgrid')
"""
* This are possible options to use for sns.set_style()
? darkgrid
? whitegrid
? dark
? white
? ticks
"""
# load the student database we use for this examples
df = pd.read_csv('data.csv')
df.head()
#?###############
#* Scatter plot #
#?###############
# do scatter with as input x and y coordinates
sns.scatterplot(x=df['math score'], y=df['reading score'])
# show the actual plot
plt.show()
"""
* We can implement this using multiple ways:
? plt.figure(figsize = (9,6))
? sns.scatterplot(x = 'math score', y = 'reading score',data = df)
"""
#?#######################
#* Scatter plot extended#
#?#######################
# set the plot figure size
plt.figure(figsize=(9, 6))
# plot data labels x and y, data df, differentiate in gender and use alpha for opacity.
sns.scatterplot(x='math score',
y='reading score',
hue='gender',
data=df,
alpha=0.8
)
# show the actual plot
plt.show()
#?############
#* Count Plot#
#?############
# set the plot figure size
plt.figure(figsize=(9, 6))
# plot countplot with x label and data df
sns.countplot(x='race/ethnicity',
data=df
)
# show the actual plot
plt.show()
#?###############
#* Distance Plot#
#?###############
# set the plot figure size
plt.figure(figsize=(9, 6))
# plot distance plot with x data df, and kde false (don't show kde of the distribution)
sns.distplot(x=df['math score'], kde=False)
# show the actual plot
plt.show()
#?##############
#* KDE plotting#
#?##############
# * KDE stands for Kernal Density Estimate, more information about it is available here:
# ? https://mathisonian.github.io/kde/
# set the plot figure size
plt.figure(figsize=(9, 6))
# Do a kernal density plot with data math score
sns.kdeplot(x=df['math score'])
# show the actual plot
plt.show()
#?#########################
#* Regression scatter plot#
#?#########################
# set the plot figure size
plt.figure(figsize=(9, 6))
# this creates a scatter plot with a regression line. the regression line tells about the relationship between two points
# x data = df(math score), y data = df(reading score), the scatter is set to pink, the line to red, we use somehow similar colours
sns.regplot(x=df['math score'],
y=df['reading score'],
scatter_kws={'color': 'pink'},
line_kws={'color': 'red'}
)
# show the actual plot
plt.show()
#?################################
#* Subset regresiion scatter plot#
#?################################
# do a plot with x data, y data, making a gender based differentiaton
# this method automaticly makes a regression line for every subset in the plot
sns.lmplot(x='math score',
y='reading score',
hue='gender',
data=df
)
# show the actual plot
plt.show()
#?#################
#* Paired plotting#
#?#################
# * This kind of plot is somewhat harder --> what does it do?
# ? It pairwise plots distrutions of a dataset with different methods
# ? It does this in numeric columns
# ? The input is the subsets of the data with columns you want to plot distributions in between
# We do a pairplot with 3 different inputs (should result in 9 outputs)
sns.pairplot(df[['math score',
'reading score',
'writing score']]
)
# show the actual plot
plt.show()
#?#######################################
#* univariate and bivariate distribution#
#?#######################################
# * This plot also pluts univariate and bivariate distributions at the top and side
# ? the distribution density for x and y if you want to put it different
# We do a jointplot with 2 different inputs from df
sns.jointplot(x='math score',
y='reading score',
data=df
)
# show the actual plot
plt.show()
#! This method works better when using hue
# ? This because this way it shows differences and overlaps
# We do a jointplot with 2 different inputs from df, differentiating on gender
sns.jointplot(x='math score',
y='reading score',
hue='gender',
data=df
)
# show the actual plot
plt.show()
#?#############
#* Boxplotting#
#?#############
# A boxplot is an excellent way to show data spread and data outliers of a dataset
# * Single Boxplot:
# We do a boxplot with as data math score from df
sns.boxplot(x='math score',
data=df
)
# Show the actual boxplot
plt.show()
# ? Multi Boxplot:
# We do a boxplot for all numerical collumns inside the dataset
sns.boxplot(data=df)
# Show the actual boxplot
plt.show()
#?################
#* Swarm Plotting#
#?################
# * This plots a scatterplots per category with its points being non overlapping
# ? Swarm plots form good complement to box or violin plots
# We set the figure size
plt.figure(figsize=(12, 8))
# We do a swarm plot with x label and y label, data df and an opacity of 0.8
sns.swarmplot(x='race/ethnicity',
y='math score',
data=df,
alpha=0.8
)
# Show the actual plot
plt.show()
#?##################
#* Heatmap Plotting#
#?##################
# * This plot plots a heatmap of the input data, this is most commonly used for correlation heatmaps
# ? annot=True enables displaying the value of the cells, setting it to false would disable this
# We do a heatmap plot with correlation of the input data, annot true and add an inferno bar to it
sns.heatmap(df.corr(),
annot=True,
cmap='inferno')
# Show the actual plot
plt.show()
#?###################
#* Colour adjustment#
#?###################
"""
*plt.figure(figsize = (12,8))
*
? colors = [
? '#F8D030',
? '#E0C068',
? '#EE99AC',
? '#C03028',
? '#F85888'
? ]
*
* sns.stripplot(x = 'race/ethnicity',
* y = 'math score',
* data = df,
* palette = colors
* )
*
* plt.show()
"""
#! For even more ways to plot data, make sure to check out the following url:
# * http://seaborn.pydata.org/examples/
|
d2f0a5e3dcf6ec822a4f97f6b0cc04eecbf7103e | ahmadner/python_apps | /login.py | 867 | 4.03125 | 4 | #username = admin
#password = 123
#|===================|
#| coder : ahmadNer |
#|===================|
print ("\n")
username = input("Enter The Username: ")
password = str (input("Enter The Password: "))
count = 3 #num of trys
while username != "admin" or password != "123":
count -=1
if count == 0:
print ("\n you try many time wrong try again later .\n")
break
else:
print("\nwrong password or username , try again \n")
print("you have a " +str (count)+ " of trys \n")
username = input("Enter The Username: ")
password = input("Enter The Password: ")
while username == "admin" and password == "123":
print ("\n welcome to your program \n")
print ("""
|===================|
| coder : ahmadNer |
|===================|
""")
break
|
6aa428adbaee825aca2d1c9b426743bcb980e028 | Mohit130422/python-code | /pm.py | 269 | 3.640625 | 4 | def main():
a=1
b=101
for i in range(a,b):
f=0
for j in range(2,(i//2)+1):
if(i%j==0):
f=1
break
if(f==0):
print(i,' is prime')
if __name__=="__main__":
main() |
82b60e82f253894c40f29b28cc744abcf6ad1b84 | g1isgone/stanford_algorithms_specialization | /course1/karatsuba_algorithm.py | 2,747 | 3.734375 | 4 | '''
==================================================================================
Date: 05/02/2020
==================================================================================
Implementation of the Karatsuba algorithm
Practice of a divide and conquer approach
==================================================================================
'''
import sys
from math import ceil
'''
A fast multiplication algorithm of two n-digit numbers
'''
def karatsuba(num1, num2):
num_digits_num1 = len(str(num1))
num_digits_num2 = len(str(num2))
#==================================================================================
#BASE CASE
#==================================================================================
# x,y are base elements "divided" or split into the most rudimentary base elements
# now we must "combine" these into one product
#==================================================================================
if num_digits_num1 == 1 and num_digits_num2 == 1:
return num1*num2
max_num_digits = max(num_digits_num1, num_digits_num2)
half_num_digits = ceil(max_num_digits/2) #ceil for max_num_digits is odd
halfway_divisor = 10**(half_num_digits)
#split the digit sequences at the center
a = num1 // halfway_divisor
b = num1 % halfway_divisor
c = num2 // halfway_divisor
d = num2 % halfway_divisor
#==================================================================================
#RECURSIVE STEPS
#==================================================================================
# to find the products ac and bd by calling karatsuba recursively
# this will further split the factors a,b,c,d til it reaches the base case
# especially helpful incases where the num digits is still large
#==================================================================================
ac = karatsuba(a,c)
bd = karatsuba(b,d)
sum_ad_bc = karatsuba(a+b, c+d) - ac - bd
return ac * 10**(2*half_num_digits) + bd + sum_ad_bc * 10**(half_num_digits)
def main():
user_inputs = sys.argv
if len(user_inputs) < 3:
raise Exception("You need at least 2 numbers to multiply for the Karatsuba algorithm")
if len(user_inputs) > 3:
raise Exception("You can only multiply 2 numbers using this algorithm")
if(len(user_inputs[1]) != len(user_inputs[2])):
raise Exception("The length of num1 and num2 must have the same number of digits")
num1 = int(user_inputs[1])
num2 = int(user_inputs[2])
print("The user input numbers given: "+ user_inputs[1] +", " + user_inputs[2])
product = karatsuba(num1, num2)
print("This is the product: " + str(product))
if __name__ == "__main__":
main()
|
a09c639cfdb0ee063669d40b6902884e832f5c51 | JohnWFraser/PBD_JF | /CA3_final/Rental2_JFraser.py | 5,931 | 3.75 | 4 |
from carR1_JFraser import Car, ElectricCar, PetrolCar, DieselCar, HybridCar
class Dealership(object):
def __init__(self):
self.electric_cars = []
self.petrol_cars = []
self.diesel_cars = []
self.hybrid_cars = []
self.electric_rentlist = []
self.electric_customerlist = []
self.petrol_rentlist = []
self.petrol_customerlist = []
self.diesel_rentlist = []
self.diesel_customerlist = []
self.hybrid_rentlist = []
self.hybrid_customerlist = []
def create_current_stock(self, p, e, d, h):
for i in range(e):
self.electric_cars.append(ElectricCar())
for i in range(p):
self.petrol_cars.append(PetrolCar())
for i in range(d):
self.diesel_cars.append(DieselCar())
for i in range(h):
self.hybrid_cars.append(HybridCar())
#return 45
def stock_count(self):
print 'petrol cars in stock ' + str(len(self.petrol_cars))# could print the list using: , self.petrol_cars
print 'electric cars in stock ' + str(len(self.electric_cars))
print 'diesel cars in stock ' + str(len(self.diesel_cars))
print 'hybrid cars in stock ' + str(len(self.hybrid_cars))
def stock_check(self):
count = len(self.petrol_cars)+ len(self.electric_cars)+len(self.diesel_cars)+len(self.hybrid_cars)
return count
def rent(self, car_list, rent_list, cust_list, amount, name):
# print car_list
# print rent_list
if len(car_list) < amount:
print 'Not enough cars in stock'
return
total = 0
while total < amount:
rent_list.append(car_list.pop(0)) #this actually reads the first element of car_list into rent_list, then deletes it from car_list!!
cust_list.append(name)
total = total + 1
print "rented list for this car type: ", rent_list# depending on purpose, this might not be printed, but I include to aid checking/ examiner
print "customer list for this car type: ", cust_list# as for rent_list, could line be omitted
def process_rental(self):
answer = 'y'
# above line now superfluous, but easier to set at y than delete and change indentations below... raw_input('would you like to rent a car? y/n')
if answer == 'y':
answer = raw_input('what type (petrol, electric, diesel or hybrid) would you like? - enter p/e/d/h: ')
amount = int(raw_input('how many would you like to rent?'))
name = raw_input('Please enter your name: ')
if answer == 'p':
self.rent(self.petrol_cars, self.petrol_rentlist, self.petrol_customerlist, amount, name)
elif answer == 'e':
self.rent(self.electric_cars, self.electric_rentlist, self.electric_customerlist, amount, name)
elif answer == 'h':
self.rent(self.hybrid_cars, self.hybrid_rentlist, self.hybrid_customerlist, amount, name)
else:
self.rent(self.diesel_cars, self.diesel_rentlist, self.diesel_customerlist, amount, name)
print self.diesel_cars
x = len(self.diesel_rentlist)
print "cars now assigned to you: ", self.diesel_rentlist[x-amount:]# just showing the car(s) assigned to latest customer only
#print self.diesel_customerlist
self.stock_count()
def returnn(self, car_list, rent_list, cust_list, testmarker):
amt = len(rent_list)
total = 0
if testmarker > 0:
number = testmarker-1# remember that this only applies when testing
if testmarker == 0:
while total < amt:
print total,": ", rent_list[total]
total = total + 1
number = int(raw_input('enter number above which you want to return: '))
car_list.append(rent_list.pop(number))
cust_list.pop(number)
def process_return(self):
testmarker = 0 # this will allow function returnn to differentiate between testsuite run and actual run
answer = raw_input('what type ((petrol, electric, diesel or hybrid) are you returning? p/e/d/h: ')
if answer == 'p':
self.returnn(self.petrol_cars, self.petrol_rentlist, self.petrol_customerlist, testmarker)
elif answer == 'e':
self.returnn(self.electric_cars, self.electric_rentlist, self.electric_customerlist, testmarker)
elif answer == 'h':
self.returnn(self.hybrid_cars, self.hybrid_rentlist, self.hybrid_customerlist, testmarker)
else:
print "assumed diesel car being returned"# doesn't actually check that d was entered, hence this comment
self.returnn(self.diesel_cars, self.diesel_rentlist, self.diesel_customerlist, testmarker)
print "cars in stock: ", self.diesel_cars
print "cars now rented out: ", self.diesel_rentlist
print "customer list for above: ", self.diesel_customerlist
# above 3 lines would only be printed if app meant for use by a company operator - would be deleted otherwise; I include as may help for examination/marking purposes!
self.stock_count()
dealership = Dealership()
p = 20
e = 4
d = 8
h = 8
dealership.create_current_stock(p, e , d, h)
# added July4:
dealership.stock_count()
#end July4
proceed1 = raw_input("if you wish to use this app to rent or return a car, please enter y now; for running tests only please enter n: ")
if proceed1 == 'y':
proceed = 'y'
else:
proceed = 'n'
while proceed == 'y':
rent = raw_input('Do you wish to rent a car? y/n')
if rent == 'y':
totalstock = dealership.stock_check()
print "totalstock: ", totalstock
if totalstock == 0:
print ("Sorry, nothing to rent, please try again later")
proceed = 'n'
else:
dealership.process_rental()
else:
returnn = raw_input('Do you wish to return a car? y/n')
if returnn == 'y':
dealership.process_return()
proceed = raw_input('continue? y/n')
|
1793db68820fc49c61234694ec2d5468228c142e | DanielPra/-t-Andre | /18if.py | 1,436 | 3.515625 | 4 | # Bulls räknas inte korrekt
# The number generated by the computer is 4162
# Guess four digits: 4444
# We got 1 cows
# We got 3 bulls
import random
import string
cows = 0 # Correct digit AND correct place
bulls = 0 # Correct digit NOT in correct place
def randomString(stringLength=4): # Generera lottonummer
numbers = string.digits
return ''.join(random.choice(numbers) for i in range(stringLength))
fourdigits = randomString(4)
print(f"\nThe number generated by the computer is {fourdigits}")
userguess = input("\nGuess four digits: ")
# Check first digit
if fourdigits[0] == userguess[0]: # Check cows
cows = cows + 1
if fourdigits[0] != userguess[0]: # If not cow check bulls
if userguess[0] in fourdigits:
bulls = bulls +1
# Check second digit
if fourdigits[1] == userguess[1]:
cows = cows + 1
if fourdigits[1] != userguess[1]: # Stämmer inte om fourdigits[0] == userguess[0]
if userguess[1] in fourdigits: # Unless it's a cow
bulls = bulls +1
# Check third digit
if fourdigits[2] == userguess[2]:
cows = cows + 1
if fourdigits[2] != userguess[2]:
if userguess[2] in fourdigits:
bulls = bulls +1
# Check fourth digit
if fourdigits[3] == userguess[3]:
cows = cows + 1
if fourdigits[3] != userguess[3]:
if userguess[3] in fourdigits:
bulls = bulls +1
print(f"\nWe got {cows} cows")
print(f"We got {bulls} bulls")
|
91d28e54cb60845d345984066077f4e033c706f0 | PanMaster13/Python-Programming | /Week 2/Tutorial Files/Week 2, Exercise 5.py | 259 | 3.96875 | 4 | import datetime
now = datetime.datetime.now()
app_name = input("Enter the applicant's name:")
int_name = input("Enter the interviewer's name:")
print(int_name, "will interview", app_name, "at 9.30 am on", now.year,
"-", now.month + 1, "-", now.day)
|
fb5fe3a6388547106a27748095fa19915562a416 | CodeCure-SMU/DS-and-Algorithm-2021 | /choiyoungho/Baekjoon_5885_youngho.py | 306 | 3.515625 | 4 | import sys
N = int(sys.stdin.readline()) # 1 <= N <= 100
for i in range(N):
for j in range(N - i - 1): # 왼쪽 별
print(" ", end='')
print("*", end='')
for j in range(i * 2 -1): # 오른쪽 별
print(" ", end='')
if i == 0: # 0일경우 별이 곂침.
print() # 엔터
continue
print("*")
|
72823db699fa2777ac27483d2a55c886ee8608f4 | repinnick/teachmeskills | /day4/ex4_matrix.py | 759 | 3.875 | 4 | import random
def generate_two_matrix():
data = [] # первая матрица
data2 = [] # вторая матрица
for i in range(3):
pstr = []
for j in range(3):
number = random.randrange(1, 10)
pstr.append(number)
data.append(pstr)
for i in range(3):
pstr2 = []
for j in range(3):
number = random.randrange(3)
pstr2.append(number)
data2.append(pstr2)
data3 = [] # сумма матриц
for i in range(len(data)):
cx = []
for j in range(len(data[i])):
cx.append(data[i][j] + data2[i][j])
data3.append(cx)
print(data)
print(data2)
print(data3)
print(generate_two_matrix())
|
2fd6460887a75c7aa039cb8ff53fa9e8861829d3 | Nazdorovye/VeAPython | /2020_lecture_13_tasks/py_turtle/task04.py | 493 | 3.578125 | 4 | from circle import Circle
from point import Point
from random import randint
RC = 200
HW = 250
HH = HW
POINTS = 20
crcl = Circle((0, 0), RC)
points = [Point((randint(-HW, HW), randint(-HH, HH))) for _ in range(POINTS)]
print("Canvas bounds <(x0=%d, x1=%d)(y0=%d, y1=%d)>" % (-HW, HW, -HH, HH))
print("Bounding circle %s", crcl)
print("Points:")
idx = 0
for p in points:
dist = p.distance(crcl)
print("#%d: %s, distance: %d, inside: %s" % (idx, p, dist, dist <= crcl.radius))
idx += 1 |
55bb929827ec125535244bc27c7dcef41011763d | Dwxasd/MWMTrackingSoftware | /cnn.py | 963 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Code used for object tracking. Primary purpose is for tracking a mouse in
the Morris Water Maze experiment.
cnn.py: this file contains the code for implementing a convolutional neural
network to detect a mouse location during swimming during the tracking.
"""
class Network:
"""
Convolutional Neural Network class
"""
def __init__(self):
"""constructor"""
self.model = self.create_model()
def create_model(self):
"""
create model
:return: return the model
"""
#TODO: Build Keras model
return
def train(self):
"""
train the neural network
"""
#TODO: Train Keras model
pass
def query(self):
"""
query the neural network to find output
:return:
"""
return
if __name__ == '__main__':
print("Please run the file 'main.py'")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.