blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
a612118878a2c7c3a5ea5f26cb6ab025fdceb804
|
Sirdan247/A_to_Z_ML
|
/Templates/KMeans.py
| 1,472 | 3.640625 | 4 |
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing dataset with pandas
dataset = pd.read_csv('Mall_Customers.csv')
dataset.head()
X = dataset.iloc[:,[3,4]].values
# Using the elbow method to find the optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10,random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)#inertia_ computes the wcss
plt.plot(range(1,11),wcss)
plt.title('The Elbow Method')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS')
# Applying K-means to the dataset (from the elbow method, k=5)
kmeans = KMeans(n_clusters=5, init='k-means++', max_iter=300, n_init=10,random_state=0)
y_kmeans = kmeans.fit_predict(X)
# Visualizing the clusters
plt.scatter(X[y_kmeans==0,0],X[y_kmeans==0,1],s=100, c='red', label='Careful')
plt.scatter(X[y_kmeans==1,0],X[y_kmeans==1,1],s=100, c='green', label='Standard')
plt.scatter(X[y_kmeans==2,0],X[y_kmeans==2,1],s=100, c='blue', label='Target')
plt.scatter(X[y_kmeans==3,0],X[y_kmeans==3,1],s=100, c='cyan', label='Careless')
plt.scatter(X[y_kmeans==4,0],X[y_kmeans==4,1],s=100, c='magenta', label='Sensible')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300, c='yellow',label='centroids')
plt.title('Clusters of Clients')
plt.xlabel('Annual Income(K$)')
plt.ylabel('Spending Score(1-100)')
plt.legend()
|
c9621d3f5799b82458b3d9f5fe32d4419f2def7f
|
Bunty-Bot/Codechef-Problems-
|
/HelpingChef.py
| 1,171 | 4.21875 | 4 |
Question:
Write a program, which takes an integer N and if the number is less than 10 then display "Thanks for helping Chef!" otherwise print "-1".
Input:
The first line contains an integer T, total number of testcases. Then follow T lines, each line contains an integer N.
Output:
For each test case, output the given string or -1 depending on conditions, in a new line.
Constraints:
1 ≤ T ≤ 1000
-20 ≤ N ≤ 20
Example:
Input
3
1
12
-5
Output
Thanks for helping Chef!
-1
Thanks for helping Chef!
Code:
t=int(input())
for i in range(t):
n=int(input())
if n<10:
print('Thanks for helping Chef!')
else:
print(-1)
# This is the code for Helping Chef problem. This is one of the most easiest problem for any beginner. But there is a problem in this problem.
# You should be careful while writing 'Thanks for helping Chef!' Because I forgot to give the exclamation mark after end of the sentence and
# due to this even I wrote perfect code it was not accepting it. So be careful while solving any problem.
# if You like the code:
# Give a star
# else:
# Give a star
|
8d8385f84f3ce45173e7b283ead06db8e9f8e08e
|
TechKrowd/sesion1python_03062020
|
/cadenas/04.py
| 245 | 4.03125 | 4 |
"""
Pedir dos cadenas por teclado
y comprobar si la primera es subcadena de la segunda.
"""
cad1 = input("Introduce la primera cadena: ")
cad2 = input("Introduce la segunda cadena: ")
print("Cadena encontrada: {}".format(cad2.find(cad1)!=-1))
|
8bf9c69cd6128261cc38ca2f7634438466bd1a78
|
jeankyj/dsp-assignment3
|
/src/data.py
| 2,391 | 3.734375 | 4 |
# To be filled by students
import streamlit as st
from dataclasses import dataclass
import pandas as pd
@dataclass
class Dataset:
name: str
df: pd.DataFrame
def get_name(self):
"""
Return filename of loaded dataset
"""
return self.name
def get_n_rows(self):
"""
Return number of rows of loaded dataset
"""
return self.df.shape[0]
def get_n_cols(self):
"""
Return number of columns of loaded dataset
"""
return self.df.shape[1]
def get_cols_list(self):
"""
Return list column names of loaded dataset
"""
return self.df.columns.tolist()
def get_cols_dtype(self):
"""
Return dictionary with column name as keys and data type as values
"""
return self.df.dtypes.to_dict()
def get_n_duplicates(self):
"""
Return number of duplicated rows of loaded dataset
"""
return self.df.duplicated().sum()
def get_n_missing(self):
"""
Return number of rows with missing values of loaded dataset
"""
return self.df.isnull().sum().sum()
def get_head(self, n=5):
"""
Return Pandas Dataframe with top rows of loaded dataset
"""
return self.df.head(n)
def get_tail(self, n=5):
"""
Return Pandas Dataframe with bottom rows of loaded dataset
"""
return self.df.tail(n)
def get_sample(self, n=5):
"""
Return Pandas Dataframe with random sampled rows of loaded dataset
"""
return self.df.sample(n)
def get_numeric_columns(self):
"""
Return list column names of numeric type from loaded dataset
"""
col_list = self.get_cols_list()
num_col_list = []
for i in col_list:
if self.df[i].dtype != "object" :
num_col_list.append(i)
return num_col_list
def get_text_columns(self):
"""
Return list column names of text type from loaded dataset
"""
col_list = self.get_cols_list()
text_col_list = []
for i in col_list:
if self.df[i].dtype == "object" :
text_col_list.append(i)
return text_col_list
def get_date_columns(self):
"""
Return list column names of datetime type from loaded dataset
"""
# All non-numerical value in pandas dataframe are object,
# So cannot get list column names of datetime type in
# Datetime type columns are implemented in main.py
return None
|
2b6b39f1b8c5b033dcc9b2422acdc8eadcb660ba
|
ariser/Innopolis
|
/y3s1/DSA/bucket_sort/countingsort.py
| 635 | 3.703125 | 4 |
def _sort(source, min_v, max_v):
if source is None or len(source) == 0:
return
if min_v > max_v:
raise ValueError("min can't be bigger than max")
counter = [0 for i in range(min_v, max_v + 1)]
for item in source:
counter[item - min_v] += 1
write_index = 0
for i in range(min_v, max_v + 1):
for j in range(counter[i - min_v]):
source[write_index] = i
write_index += 1
class CountingSort(object):
@staticmethod
def sort(source):
if source is None or len(source) == 0:
return
_sort(source, min(source), max(source))
|
db3605d03f3172e362d920326cb38597c8aaa59e
|
olawalejuwonm/Capstone-Projects
|
/Monsuru Lawal - Hotel Management System.py
| 7,802 | 3.75 | 4 |
from datetime import datetime
import string
import random
import time
from pprint import pprint
from sys import exit
name,number,mail,address,Night,code,details,database,price,Atm,Price,pincode,Roomcode,My_select,rum= "Admin","08162210489","","No 17, Surulere. Soka, Ibadan","","",{},{"Admin" : {"Name" : "Monsuru",
"Number" : "08162210489",
"Roomcode" : "001",
"Number": "08162210489"}
},0,"",1000000,"001","","",""
print("-"*60)
print("\t Welcome to SNP Hotel Management portal \n \t We are Happy to have you here !!! \n ".upper())
print("-"*60)
def Verification():
reserve= input("\n\nDo you have a reservation here ? Yes or No ! : ").title()
if reserve=="No":
Welcome_page()
elif reserve =="Yes" :
print("Please let us verify your booking!!")
Login()
else:
Verification()
def Welcome_page():
global database,details,pincode,name,address,number
rand="".join((random.sample(string.digits,3)))
print("\n Please let's have your details for room allocation !")
print("Fill in your details ")
print()
name=input("Enter your Full name : ")
while len(name)<3:
print("Invalid Name, Please Enter a valid name!")
name =input("Enter your full name : ")
address = input("Enter your full address : ")
while address.isalpha()==True or address.isdigit()==True:
print("Invalid Address, please your address details should combined Texts and Digit !")
address=input("Enter your full address : ")
number=input("Please enter your phone number : ")
while number.isalpha()==True or len(number) !=11:
print("Invalid Phone number, number should be 11 by counting and must be strictly numbers ")
number=input("Please enter your phone number : ")
pincode=rand
print(f"Your Pincode is {pincode}")
details["Full_name"] =name
details["Address"] = address
details["Number"] = number
details["Pincode"] = pincode
database[name]=details
print("\n\tYour information is saved...\n Your details is \n ")
print("-"*60)
pprint(details)
print("-"*60)
details={}
More=input("Would you like to book more reservations ? Yes or No !").title()
if More=="Yes":
Verification()
elif More =="No":
print("Let's proceed for Room Bookings")
level()
else:
while More !="Yes" or More !="No":
More=input("Your choice does not exist. please choose valid options (Yes or No) : ").title()
Login()
level()
def Login():
global name,pincode,My_select
check_name=input("Please enter the name used for the booking : ")
code=input("Enter your Pincode : ")
print("\n Please wait while we're verifying your informations ")
time.sleep(3)
if check_name in database.keys() and code in database[check_name].values():
print("\tYes, you have a booking here already ! ")
name=check_name
pincode=code
level()
else:
print("You do not have any reservation yet ")
book= input("Will you book a reservation now ? Yes or No ! : ").title()
if book=="Yes":
Welcome_page()
else:
print("You can take your leave now")
def level():
global price,Night,My_select
print("\n\t\t You are welcome here".upper())
print("\n \t\t Select the room of your choice ".upper())
print("\n\t 1. Master_of All : \t #60,000\n\t 2. Comfortable : \t #40,000 \n\t 3. Moderate :\t \t #20,000 \n\t 4. Mini : \t \t #5,000" )
My_select = input ("\n Select any of the options above : ")
if My_select=="1":
print()
print("Hey! , You chose Master_of_All Room ")
Night=int(input("\tHow many Nights you intend to spend : "))
price =60000 * Night
Room()
elif My_select=="2":
print("Hey! , You chose Comfortable Room ")
Night=int(input("\tHow many Nights you intend to spend : "))
price =40000* Night
Room()
elif My_select =="3":
print("Hey! , You chose Moderate Room ")
Night=int(input("\tHow many Nights you intend to spend : "))
price =20000 * Night
Room()
elif My_select =="4":
print("Hey! , You chose Mini Room ")
Night=int(input("\tHow many Nights you intend to spend : "))
price =5000 * Night
Room()
while My_select !="1" or My_select !="2" or My_select !="3" or My_select !="4" :
print("You are selecting invalid code , please select the correct options : ")
level()
def Room():
global price,rum
print("\n We have other activies you can engage in \n They includes : ")
print("\t 1. Swimming : \t #5,000 \n \t 2. Table Tennis cost : #3,000 \n\t 3. Full Packaged Food : #4,000 \n\t 4. Not Interested ")
new_price=input("Please select any of the option above : ")
if new_price =="1":
price +=5000
print(f"Your Bill in total is #{price} ")
elif new_price=="2":
price +=3000
print(f"Your Bill in total is #{price} ")
elif new_price=="3":
price +=4000
print(f"Your Bill in total is #{price} ")
else:
print(f"Your Bill is #{price}")
receipt()
exit()
Activity = input("Do you wish to engage in more activities ? Yes or No : ").title()
if Activity == "No":
print(f"\t\tYour Price is #{price} ")
receipt()
exit()
elif Activity == "Yes":
while Activity=="Yes":
Room()
exit()
while Activity !="Yes" or Activity != "No":
Activity = input("Do you wish to engage in more activities ? Yes or No : ").title()
print("Wrong input!!! ")
if Activity == "No":
print(f"\t\tYour Price is #{price} ")
receipt()
exit()
elif Activity == "Yes":
while Activity=="Yes":
Room()
exit()
def valid():
global Atm,Roomcode
while Atm.isdigit()==False:
Atm=input("Your Atm is strictly numbers : ")
numbers=Atm
num= list(numbers)
number=[]
for k in num:
k = int(k)
number.append(k)
number=number[::-1]
list1,list2,list3,list4,list5=[],[],[],[],[]
n=0
for i in number:
if number.index(i,n)%2==1:
list1.append(i)
n+=1
else:
list2.append(i)
n+=1
for j in list1:
j=j*2
list3.append(j)
for j in list3:
j=str(j)
if len(j)==2:
list4.append(j)
else:
c=int(j)
list5.append(c)
for y in list4:
g=int(y[0])
u=int(y[1])
x=g+u
list5.append(x)
for o in list2:
list5.append(o)
new_list=sum(list5)
if new_list%10==0:
return "Valid Pin"
else:
return "Invalid Pin"
def atm():
global Atm,Roomcode
print("-"*60)
print("\n \t\tSession for Payment!!".upper())
print("-"*60)
Atm=input("Enter your Valid Atm 16 Digit Numbers : ")
Roomcode=input("Enter your Pincode : ")
def receipt():
global price,Roomcode,pincode,address,Price,My_select,rum
if My_select =="1":
rum="Master_of All"
elif My_select =="2":
rum="Comfortable"
elif My_select =="3":
rum="Moderate"
elif My_select =="4":
rum="Mini"
atm()
valid()
print("\nPlease wait for few seconds while we check for the authentication of your card details.........")
time.sleep(3)
if valid()=="Valid Pin" and Roomcode==pincode:
print("\n\tAuthentication successful!!")
print(f"\nThe balance in your Account is #{Price}\n")
print(f"And your new balance is #{Price-price} \n \t\t Your Payment was Successful !!!")
print("\n\t Please wait, while we process your receipt ....")
time.sleep(5)
print("-"*60)
print("\t\t\t Your Receipt")
print("-"*60)
print(f" Name : {name} \n Address : {address} \n Contact : {number} \n Pincode : {pincode} \n DaySpent : {Night} \n Room Type: {rum} \n Amount Paid : #{price} \n\n " )
print("-"*60)
print(f"\t Designed by Monsaw {datetime.now()} ")
print("-"*60)
while valid() != "Valid Pin" or Roomcode!=pincode:
print("\n You enter either Invalid Card Pin or Your Pincode is incorrect !!")
receipt()
print("\n Do you wish to perform task again or Exit?")
exite=input("\n Press Yes to Continue or Anykey to Exit the program : ").title()
print()
if exite =="Yes":
print("-"*60)
print("\t Welcome to SNP Hotel Management portal \n \t We are Happy to have you here !!! \n ".upper())
print("-"*60)
Verification()
else:
exit()
Verification()
|
9e9b5339a7e55399b95fa88f7763f74877497db7
|
bogwien/mipt_labs
|
/3_turtle/1_for_odd_or_even.py
| 448 | 4.25 | 4 |
# Для каждого положительного числа, меньшего n, напечатайте odd,
# если число является нечётным, и even, если оно является чётным
print('Input number:')
inputData = input()
number = int(inputData) if inputData != '' else 0
if number > 1:
for val in range(1, number):
print(val, 'even' if val % 2 == 0 else 'odd')
else:
print('Empty')
|
6f290bfe7481d2f66dda847868ce59eb64cd5adc
|
arpitiiitv/maximl
|
/maximl_test.py
| 559 | 3.65625 | 4 |
def count_distinct(s):
return len(set(s))
def maximl(s):
dist = count_distinct(s)
minm = dist
maxm = len(s)
for i in range(len(s)):
if dist == count_distinct(s[i:]):
temp = s[i:]
else:
break
ss = temp[::-1]
for i in range(len(ss)):
if dist == count_distinct(ss[i:]):
temp2 = ss[i:]
else:
break
print(temp2)
return len(temp2)
if __name__ == "__main__":
s = input("input string of lowercase : ")
print(maximl(s))
|
efa3dfd86f5e8831a573f49773df49e6fe6a7b9b
|
ko-tech/pythone-dev
|
/Chapter 8 pt 2/cars.py
| 429 | 3.953125 | 4 |
#8-14: Cars -
def car_profile(manufacturer, model, **car_info):
"""Build a dictionary containing information about car."""
information = {}
information['manufacturer'] = manufacturer
information['model'] = model
for key, value in car_info.items():
information[key] = value
return information
car_profile = car_profile('dodge', 'challenger',
color='gray',
engine='hemi')
print(car_profile)
|
a91ef80491f2bb3b5f76f90db79a68d72f22299c
|
jihoonyou/problem-solving
|
/leetcode/copy-list-with-random-pointer.py
| 818 | 3.703125 | 4 |
'''
https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/585/week-2-february-8th-february-14th/3635/
'''
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
dup_node_dict = {}
node = head
while node:
dup_node_dict[node] = Node(node.val)
node = node.next
node = head
while node:
dup_node_dict[node].next = dup_node_dict.get(node.next)
dup_node_dict[node].random = dup_node_dict.get(node.random)
node = node.next
return dup_node_dict.get(head)
|
749658e20e47a3e1ac68c20e642f71de16214314
|
adrianurdar/100DaysOfCode-Bootcamp
|
/Day-032/main.py
| 1,489 | 3.578125 | 4 |
# Birthday Wisher (Extra-hard)
import datetime as dt
import smtplib
import pandas
import random
# 1. Update the birthdays.csv
# Name,Email,YYYY,MM,DD
# 2. Check if today matches a birthday in the birthdays.csv
now = dt.datetime.now()
birthday_df = pandas.read_csv("birthdays.csv")
birthday_dict = birthday_df.set_index("name").T.to_dict()
for key in birthday_dict:
if now.month == birthday_dict[key]["month"] and now.day == birthday_dict[key]["day"]:
birthday_name = key
birthday_email = birthday_dict[key]["email"]
# 3. If step 2 is true, pick a random letter from letter templates and replace the [NAME] with the person's
# actual name from birthdays.csv
letter_template = f"letter_{random.randint(1, 3)}.txt"
with open(f"./letter_templates/{letter_template}") as file:
letter_content = file.read()
letter_content = letter_content.replace("[NAME]", birthday_name)
print(letter_content)
# 4. Send the letter generated in step 3 to that person's email address.
user = "****@gmail.com"
password = "****"
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=user, password=password)
connection.sendmail(
from_addr=user,
to_addrs=birthday_email,
msg=f"Subject: Happy bday! \n\n"
f"{letter_content}".encode("utf-8")
)
|
9638cd2079c8e05126e2bc2107feeddb4ee86d9a
|
KBabic/MY-PROJECTS
|
/avg_ratings.py
| 1,778 | 3.875 | 4 |
# The input file contains three columns: id - a unique identifier for each row, year - the year and quarter of the rating, and rating - the approval rating.
# Write output to a new CSV with three columns:
# year will contain whole years (i.e., 1975 but no information about specific quarters),
# mean will have the mean approval rating for that year,
# median will have the median approval rating for that year.
# As some quarters are missing ratings (NA) you will have to exclude those from the mean/median calculations.
import csv
import statistics
csv_file = open('C:\\Users\\Kaja\\Desktop\\MY-PROJECTS\\presidents.csv')
content = csv.reader(csv_file)
# this line enables reading the csv multiple times without open/close each time:
data = [row for row in content]
csv_file.close()
years = list()
# dictionary where key is year and value is list of ratings for that year:
d = dict()
for row in data:
#starting from the second row:
if row[1][0:4] != 'year':
year = row[1][0:4]
years.append(year)
# for each unique year give me list of all ratings:
for year in set(years):
d[year] = list()
for row in data:
if row[1][0:4] == year and row[2] != 'NA':
d[year].append(int(row[2]))
# print(d)
means = dict()
for year in d:
means[year] = round(sum(d[year])/len(d[year]),2)
# print(means)
medians = dict()
for year in d:
medians[year] = round(statistics.median(d[year]),2)
# print(medians)
output_file = open('C:\\Users\\Kaja\\Desktop\\MY-PROJECTS\\presidents_output.txt','w+')
output_file.write('year,mean,median\n')
# writing rows to output file sorted by years (ascending order):
for year in sorted(d.keys()):
output_file.write(year+','+str(means[year])+','+str(medians[year])+'\n')
output_file.close()
|
f91919d4d690431abb1be1fb6b840bb3a8bde352
|
hyeri2565/python-_algorithm
|
/1655.py
| 491 | 3.609375 | 4 |
from bisect import bisect_left
N=input()
num_list=[]
num_list.append(int(input()))
print(num_list[0])
for i in range(int(N)-1):
num = int(input())
# 숫자가 삽입 될 인덱스 찾기
index = bisect_left(num_list, num)
# 숫자 삽입, array 길이 1 증가
num_list.insert(index, num)
if len(num_list)%2==1:
ind=int(len(num_list)/2)
print(num_list[ind])
else:
ind=int(len(num_list)/2-1)
print(num_list[ind])
|
6d9d81d45698e6e76fc0003158cda46db3cef802
|
13834319675/python
|
/02 高级语法系列/cp 爬虫/基础/v26.py
| 219 | 3.65625 | 4 |
"""
findall
"""
import re
pattern = re.compile(r'\d+')
s = pattern.findall("i am 18 yes old and 185 high")
print(s)
s = pattern.finditer("i am 18 yes old and 185 high")
print(s)
print(type(s))
for i in s:
print(i)
|
038ae2d15b9006c595455008e882636c97fb9f6f
|
math4tots-misc/keep_talking_and_nobody_explodes
|
/word.py
| 485 | 3.5 | 4 |
from sys import argv
poss = argv[1:]
words = [
'about', 'after', 'again', 'below', 'could',
'every', 'first', 'found', 'great', 'house',
'large', 'learn', 'never', 'other', 'place',
'plant', 'point', 'right', 'small', 'sound',
'spell', 'still', 'study', 'their', 'there',
'these', 'thing', 'think', 'three', 'water',
'where', 'which', 'world', 'would', 'write',
]
copy = set(words)
for i, p in enumerate(poss):
copy = set(w for w in copy if w[i] in p)
print(copy)
|
cf77c42a2240369b19e7af1dd1c1a8fb93104d8b
|
achowDMA/Machine-Learning
|
/AI and Machine Learning/PyCharm/Calculator.py
| 229 | 3.625 | 4 |
import sys
print(2 + 2)
command = sys.argv[1]
if command == "add":
x = int(sys.argv[2])
y = int(sys.argv[3])
print(x + y)
if command == "countto":
x = int(sys.argv[2])
for i in range(x):
print(i)
|
a634c0fd3783b41c8f366a1a204cd07512500e79
|
Shao-junliang/Python
|
/day01/04-认识数据类型.py
| 301 | 3.828125 | 4 |
"""
--检测数据类型-- type(数据)
"""
num1 = 1
num2 = 1.1
a = 'hello world'
b = True
print(type(num1))
print(type(num2))
print(type(a))
print(type(b))
c = [10, 20, 30]
d = (10, 20, 30)
e = {10, 20, 30}
f = {'name': 'Tom', 'age': 18}
print(type(c))
print(type(d))
print(type(e))
print(type(f))
|
412c7876b1636aae8ca500a3479b56ba8756c552
|
love-adela/algorithm-ps
|
/acmicpc/1213/1213.py
| 205 | 3.640625 | 4 |
from itertools import permutations, combinations
def is_palin(name:str)->bool:
name
for e in lst:
if e == e[::-1]:
return True
return False
s = input()
print(is_palin(s))
|
635f323da217bdc09c2d6d5c8dd72c2e728e58a5
|
k-schmidt/Coding_Problems
|
/HackerRank/easy/implementation/mini_max_sum.py
| 1,120 | 3.8125 | 4 |
"""
Given five positive integers,
find the minimum and maximum values that can be calculated
by summing exactly four of the five integers.
Then print the respective minimum and maximum values as a
single line of two space-separated long integers.
Input Format
A single line of five space-separated integers.
Constraints
Each integer is in the inclusive range [0, 10^9]
Output Format
Print two space-separated long integers denoting the respective
minimum and maximum values that can be calculated by summing
exactly four of the five integers.
(The output can be greater than 32 bit integer.)
Sample Input
1 2 3 4 5
Sample Output
10 14
"""
def main(input_list):
total_sum = sum(input_list)
for i, x in enumerate(input_list):
if i == 0:
min_sum = total_sum - x
max_sum = total_sum - x
else:
if total_sum - x < min_sum:
min_sum = total_sum - x
if total_sum - x > max_sum:
max_sum = total_sum - x
return min_sum, max_sum
# Other Solution
a = sorted(map(int,raw_input().split()))
print sum(a[:4]),sum(a[1:])
|
dea13070ebc37161642c930c4862f0559d6b8218
|
handdole/PYTHON
|
/파이썬강의(함수부르기등)/mega/가위바위보.py
| 1,915 | 3.59375 | 4 |
import random
list1 = ['가위!', '바위!', '보!']
while True:
print('가위 바위 보 게임 시작.')
print("------------------------------")
print("종료는 9 번을 눌러주세요")
my = int(input('가위 0 바위 1 보 2 ! >> '))
if my not in (0,1,2,9):
print("제대로 입력해주세요.")
cum = random.randint(0, 2)
if my == 0:
print("나는 가위!")
print("컴퓨터는",list1[cum])
print("------------------------------")
if my == cum:
print("무승부군요")
print("------------------------------")
elif my + 1 == cum:
print("지셨군요...")
print("------------------------------")
else:
print("이기셨군요!")
print("------------------------------")
if my == 1:
print("나는바위!")
print("컴퓨터는", list1[cum])
print("------------------------------")
if my == cum:
print("무승부군요")
print("------------------------------")
elif my - 1 == cum:
print("이기셨군요!")
print("------------------------------")
else:
print("지셨군요...")
print("------------------------------")
if my == 2:
print("나는보!")
print("컴퓨터는", list1[cum])
print("------------------------------")
if my == cum:
print("무승부군요")
print("------------------------------")
elif my - 1 == cum:
print("이기셨군요!")
print("------------------------------")
else:
print("지셨군요...")
print("------------------------------")
elif my == 9 :
print('게임을 종료합니다.')
break
|
1eb4edd352a9177ee0b757e919a3e49a4824fcc2
|
sm171190/problems
|
/python1_Solutions.py
| 3,578 | 4.28125 | 4 |
#P1.Given the variables:
planet = "Earth"
diameter = 12742
# use the .format() to print the following string: The diameter of Earth is 12742 kilometers.
# Solution1
#print('The diameter of {0} is {1} kilometers.'.format(planet,diameter))
#Strings are essentially a list of characters. So we should be able to extract any character as we would , an item from a list
name = "Saurabh"
#P2. Extract the letter 'b' from this variable
#Expected Output : b
#Solution2
# print(name[5])
#You can even extract a substring from a string
#Run the below commands to see the patterns
shortenedName = name[:3]
print(shortenedName)
shortenedName2 = name[1:3]
print(shortenedName2)
shortenedName = name[2:]
print(shortenedName)
#P3.Use the string indexing from the above example to extract the substring 'calc' from the variable below
someString = "calculator"
#Expected Output : 'calc'
#Solution 3
# print(someString[:4])
#There are 2 ways in python to access the last item in a list. Here's one way :
newList = [1,2,3,4,5,6,7,"Take me out of here!"]
lastItem = newList[-1] # Python also counts/indexes items from the end of the list. The last item is index -1, the 2nd last item is -2, and so on..
#P4. Based on the methods you know, write another way of accessing the last element of newList
#Expected Output : "Take me out of here!"
#Solution 4
# print(newList[7])
#Strings can be split into lists of words! That's really neat! If str is a string with space-separated words, str.split() will generate a list of the words
#P5. Split this string into a list
s = "Hi there Sam!"
#Expected output : ['Hi', 'there', 'Sam!']
# Solution 5
#print(s.split())
#A list can contain ANY type of items. It can even containt another list as an item!! -
#For example
myList = [1,"Two",3, ["One",2,"Three"],"This is the last item"]
#myList has 4 elements! Don't beleive me? Try this out
print('myList has {0} elements!'.format(len(myList)))
#P6.Uncomment and run the following. What do you expect the result to be, in each case ?
# print(myList[0])
# print(myList[1])
# print(myList[2])
# print(myList[3])
# print(myList[4])
#P7. Given this nested list, use indexing to grab the word "hello"
lst = [1,2,[3,4],[5,[100,200,['hello']],23,11],1,7]
#Expected output : "Hello"
#Solution 7
# print(lst[3][1][2][0])
#P8. In the following string print the words which start with s. Use split() , stiring indexing and remember that a string is just a list of characters
st = 'Print only the words that start with s in this sentence'
#Solution 8
# wordList = st.split()
# for word in wordList:
# if word[0]=='s':
# print(word)
#P9. Write a program that prints the integers from 1 to 100. #But for multiples of 3 print "3 likes me" instead of the number
#Solution 9
# for n in range(1,101):
# if n%3==0:
# print('3 likes me')
# else:
# print(n)
#P10.Write a program that prints the integers from 1 to 100. But for multiples of 3 print "3 likes me" instead of the number, and for the multiples of five print "5 likes me". For numbers which are multiples of both three and five print "I'm strange".
#Solution 10
# for n in range(1,101):
# if n%15==0:
# print("I'm strange")
# elif n%3==0:
# print('3 likes me')
# elif n%5==0:
# print('5 likes me')
# else:
# print(n)
#P11. Write a function that accepts a positive integer and returns 0 if the input is prime. Else it returns -1.
#Solution 11
def isPrime(n):
if n==1:
return '1 is strange'
if n==2 or n==3:
return 0
else:
for i in range(2,n//2):
if n%i==0:
return -1
return 0
print(isPrime(2441))
|
2dc5384c4172c93f88c10c575bd165aa232fb2b3
|
JayTheriault/pkrbot
|
/advanced_strategy_bot_tory_v1/player.py
| 12,285 | 3.515625 | 4 |
'''
Simple example pokerbot, written in Python.
'''
from skeleton.actions import FoldAction, CallAction, CheckAction, RaiseAction
from skeleton.states import GameState, TerminalState, RoundState
from skeleton.states import NUM_ROUNDS, STARTING_STACK, BIG_BLIND, SMALL_BLIND
from skeleton.bot import Bot
from skeleton.runner import parse_args, run_bot
class Player(Bot):
'''
A pokerbot.
'''
def __init__(self):
'''
Called when a new game starts. Called exactly once.
Arguments:
Nothing.
Returns:
Nothing.
'''
values = ['2','3','4','5','6','7','8','9','T','J','Q','K','A']
card_strength = {v:values.index(v) for v in values}
#creates dictionary to see what cards win
#create a directed graph with 13 nodes and if a certain card beats another add a node
def handle_new_round(self, game_state, round_state, active):
'''
Called when a new round starts. Called NUM_ROUNDS times.
Arguments:
game_state: the GameState object.
round_state: the RoundState object.
active: your player's index.
Returns:
Nothing.
'''
my_bankroll = game_state.bankroll # the total number of chips you've gained or lost from the beginning of the game to the start of this round
game_clock = game_state.game_clock # the total number of seconds your bot has left to play this game
round_num = game_state.round_num # the round number from 1 to NUM_ROUNDS
my_cards = round_state.hands[active] # your cards
big_blind = bool(active) # True if you are the big blind
pass
def handle_round_over(self, game_state, terminal_state, active):
'''
Called when a round ends. Called NUM_ROUNDS times.
Arguments:
game_state: the GameState object.
terminal_state: the TerminalState object.
active: your player's index.
Returns:
Nothing.
'''
my_delta = terminal_state.deltas[active] # your bankroll change from this round
previous_state = terminal_state.previous_state # RoundState before payoffs
street = previous_state.street # 0, 3, 4, or 5 representing when this round ended
my_cards = previous_state.hands[active] # your cards
opp_cards = previous_state.hands[1-active] # opponent's cards or [] if not revealed
self.updateCardStrength(my_delta, previous_state, street, my_cards, opp_cards)
def get_action(self, game_state, round_state, active):
'''
Where the magic happens - your code should implement this function.
Called any time the engine needs an action from your bot.
Arguments:
game_state: the GameState object.
round_state: the RoundState object.
active: your player's index.
Returns:
Your action.
'''
legal_actions = round_state.legal_actions() # the actions you are allowed to take
street = round_state.street # 0, 3, 4, or 5 representing pre-flop, flop, river, or turn respectively
my_cards = round_state.hands[active] # your cards
board_cards = round_state.deck[:street] # the board cards
my_pip = round_state.pips[active] # the number of chips you have contributed to the pot this round of betting
opp_pip = round_state.pips[1-active] # the number of chips your opponent has contributed to the pot this round of betting
my_stack = round_state.stacks[active] # the number of chips you have remaining
opp_stack = round_state.stacks[1-active] # the number of chips your opponent has remaining
continue_cost = opp_pip - my_pip # the number of chips needed to stay in the pot
my_contribution = STARTING_STACK - my_stack # the number of chips you have contributed to the pot
opp_contribution = STARTING_STACK - opp_stack # the number of chips your opponent has contributed to the pot
if RaiseAction in legal_actions:
min_raise, max_raise = round_state.raise_bounds() # the smallest and largest numbers of chips for a legal bet/raise
min_cost = min_raise - my_pip # the cost of a minimum bet/raise
max_cost = max_raise - my_pip # the cost of a maximum bet/raise
if street==0:#pre flop strategy
if cards[0][0]==cards[1][0]:#pairs
return RaiseAction()
if cards[0][0]==self.values[12] or cards[1][0]==self.values[12]:#rwhenever there is an Ace
return RaiseAction()
elif cards[0][1]!=cards[1][1]:#different suit absolutes
if self.values.index[cards[0][0]]+self.values.index[cards[1][0]]<10:#folding on low values
return FoldAction()
elif self.values.index[cards[0][0]]+self.values.index[cards[1][0]]>16:
return RaiseAction()
elif cards[0][0]==self.values[8] and cards[1][0]==self.values[3]:
return FoldAction()
elif cards[0][0]==self.values[3] and cards[1][0]==self.values[8]:
return FoldAction()
elif cards[0][0]==self.values[8] and cards[1][0]==self.values[2]:
return RaiseAction()
elif cards[0][0]==self.values[2] and cards[1][0]==self.values[8]:
return RaiseAction()
elif cards[0][0]==self.values[7] and cards[1][0]==self.values[3]:
return RaiseAction()
elif cards[0][0]==self.values[3] and cards[1][0]==self.values[7]:
return RaiseAction()
elif cards[0][1]==cards[1][1]:#same suit absolutes
if cards[0][0]==self.values[0] or if cards[1][0]==self.values[0]:
if self.values.index[cards[0][0]]+self.values.index[cards[1][0]]<9#folding on low values
return FoldAction()
elif self.values.index[cards[0][0]]+self.values.index[cards[1][0]]>11:#raising high
return RaiseAction()
elif cards[0][0]==self.values[1] or cards[1][0]==self.values[1]:
if self.values.index[cards[0][0]]+self.values.index[cards[1][0]]<11:
if self.values.index[cards[0][0]]+self.values.index[cards[1][0]]>4:
return FoldAction()
elif cards[0][0]==self.values[6] and cards[1][0]==self.values[5]:
return RaiseAction()
elif cards[0][0]==self.values[5] and cards[1][0]==self.values[6]:
return RaiseAction()
elif cards[0][0]==self.values[5] and cards[1][0]==self.values[4]:
return RaiseAction()
elif cards[0][0]==self.values[4] and cards[1][0]==self.values[5]:
return RaiseAction()
#code to be copied in small and big for kings w 2-8 w opposite
elif active==True:#big blind
return CallAction()
else:#small blind
return RaiseAction() #maybe call under 10 value
#yellow=[jack opp 7-10, diff 13 and up, same 5 and 4]
#red=[ rest of diff, same 2 and 3]
#green=[rest of same]
#if cards[0][0]==self.values[0] and cards[1][0]==self.values[10] and cards[0][1]==cards[1][1]:
#small blind goes second
#call=match check=next raise=big fold=quit
#green raise
#yellow small raie big call
#light orange small call red call
#dark orange small call red fold
#red fold fold
if CheckAction in legal_actions: # check-call
return CheckAction()
return CallAction()
def checkFlush(self, cards, board_cards):
'''
Returns True if there is a flush, False otherwise
'''
clubs = diamonds = hearts = spades = 0
for card in range(len(cards)):
if cards[card][1] == 'c':
clubs += 1
elif cards[card][1] == 'd':
diamonds += 1
elif cards[card][1] == 'h':
hearts += 1
else:
spades += 1
for card in range(len(board_cards)):
if board_cards[card][1] == 'c':
clubs += 1
elif board_cards[card][1] == 'd':
diamonds += 1
elif board_cards[card][1] == 'h':
hearts += 1
else:
spades += 1
# print('test')
if clubs >= 5 or diamonds >= 5 or spades >= 5 or hearts >= 5:
return True
return False
def updateCardStrength(self, my_delta, previous_state, street, my_cards, opp_cards):
board_cards = previous_state.deck[:street]
if self.checkFlush(my_cards, board_cards) or self.checkFlush(opp_cards, board_cards):
print('flush')
print(my_cards, opp_cards, board_cards)
pass
if my_delta == 0:
#check for same high card
#share high card or high pair
#check for pairs, if either of us has pair that both don't have we know there must be a straight
#check if we have the same high card, if so then do nothing
#if different high cards swap highest card with highest shared card
pass
elif my_delta >= 0:
#see how my hand is better than opp hand, update cards as needed
#check if both of us have pairs
#if so update highest card
#check if hand strength doesn't amkes sense --> implies straight
pass
elif my_delta <= 0:
#see how opp hand is better than my hand, update cards as needed
pass
def determineHandStrength(self, my_cards, board_cards, active):
big_blind = bool(active) #small blind has position advantage
pass
def determinePlayerRange(self, board_cards, Opp = True):
pass
def CreateValueDict():
"""all u need to do is plug in the values found online"""
card1=[0,1,2,3,4,5,6,7,8,9,10,11,12]
card2=[0,1,2,3,4,5,6,7,8,9,10,11,12]
cardcombos=[]
handcombos=[]
carddict={}
for card in card1:
for cards in card2:
if (cards,card) not in cardcombos:
cardcombos.append((card,cards))
#print(cardcombos)
sameopp=["s","o"]
for sign in sameopp:
for combo in cardcombos:
handcombos.append((combo,sign))
#print(handcombos)
vallist=[]
#print(len(pre_flop_val_list))
for i in range(182):
carddict[handcombos[i]]=vallist[i]
return carddict
def PreFlopStrat():
"""filled with pre flop values"""
card1=[0,1,2,3,4,5,6,7,8,9,10,11,12]
card2=[0,1,2,3,4,5,6,7,8,9,10,11,12]
cardcombos=[]
handcombos=[]
carddict={}
for card in card1:
for cards in card2:
if (cards,card) not in cardcombos:
cardcombos.append((card,cards))
#print(cardcombos)
sameopp=["s","o"]
for sign in sameopp:
for combo in cardcombos:
handcombos.append((combo,sign))
#print(handcombos)
pre_flop_val_list=[50, 1.7,1.8,2,2,2.1,2.5,3.7,6.5,8.8,13,19,48,50,10,13,7.1,2.5,2.7,4.9,8,11,14,20,50,50,24,16,14,10,7,11,14,16,26,50,50,29,24,19,14,12,16,24,32,50,50,36,31,27,25,19,29,36,50,50,43,36,36,32,20,49,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,50,1.4,1.4,1.5,1.5,1.6,2,2,3,5,7,12,29,50,2,2,2,2,2,2,3,5,7.5,13,32,50,2,2,2,2,3,4,5,8,13,35,50,2,3,3,4,4,6,9,14,37,50,11,7,5,6,7,10,15,35,50,16,11,10,9,10,16,41,50,21,18,14,13,19,43,50,32,29,24,24,45,50,46,46,50,50,50,50,50,50,50,50,50,50,50,50]
#print(len(pre_flop_val_list))
for i in range(182):
carddict[handcombos[i]]=pre_flop_val_list[i]
return carddict
if __name__ == '__main__':
run_bot(Player(), parse_args())
|
842938b66f413e4a260395823d59a0a589bbdecf
|
newkstime/PythonLabs
|
/Lab03 - Selection Control Structures/Lab03P2.py
| 824 | 4.21875 | 4 |
secondsSinceMidnight = int(input("Please enter the number of seconds since midnight:"))
seconds = '{:02}'.format(secondsSinceMidnight % 60)
minutesSinceMidnight = secondsSinceMidnight // 60
minutes = '{:02}'.format(minutesSinceMidnight % 60)
hoursSinceMidnight = minutesSinceMidnight // 60
if hoursSinceMidnight < 24 and hoursSinceMidnight >= 12:
meridiem = "PM"
hours = hoursSinceMidnight - 12
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
elif hoursSinceMidnight < 12:
meridiem = "AM"
hours = hoursSinceMidnight
if hours == 0:
hours = 12
print("The time is ", str(hours) + ":" + str(minutes) + ":" + str(seconds), meridiem)
else:
print("The input seconds exceeds the number of seconds in a single day.")
|
819d738bfb211ac2e843e9fe11e498b3198f03be
|
jpgrennier/pylot_ng
|
/app/controllers/Play.py
| 2,145 | 3.84375 | 4 |
"""
Sample Controller File
A Controller should be in charge of responding to a request.
Load models to interact with the database and load views to render them to the client.
Create a controller using this template
"""
from system.core.controller import *
from datetime import datetime
import random
class Play(Controller):
def __init__(self, action):
super(Play, self).__init__(action)
"""
This is an example of loading a model.
Every controller has access to the load_model method.
self.load_model('WelcomeModel')
"""
""" This is an example of a controller method that will load a view for the client """
def index(self):
try:
session['gold']
except:
session['gold'] = 0
try:
session['activities']
except:
session['activities'] = []
return self.load_view('index.html')
def process_money(self):
if request.form['where'] == 'farm':
session['gold'] = random.randrange(10,21)
elif request.form['where'] == 'cave':
session['gold'] = random.randrange(5,11)
elif request.form['where'] == 'house':
session['gold'] = random.randrange(2,6)
elif request.form['where'] == 'casino':
session['gold'] = random.randrange(-50,51)
activity = ''
time = datetime.now().strftime('%Y/%m/%d %I:%M %p')
if session['gold'] >= 0:
activity += 'Earned ' + str(session['gold']) + ' gold from the ' + str(request.form['where']) + '!' + '(' + str(time) + ')'
else:
activity += 'Entered Casino and lost ' + str(session['gold']) + ' gold... Ouch.' + '(' + str(time) + ')'
session['gold'] += session['gold']
session['activities'].insert(0, activity)
return redirect('/')
def reset(self):
session.clear()
return redirect('/')
"""
A loaded model is accessible through the models attribute
self.models['WelcomeModel'].get_all_users()
"""
|
8afa2351afec30f516a710b054fb5b95776238fa
|
JamesTeachingAccount/PythonDemos
|
/selectiondemo.py
| 1,976 | 4.46875 | 4 |
import random
#I am an example of selection")
#The program will choose which statements to execute based on conditions
#A simple 'if' statement will do an instruction if a condition is met
firstRan = random.randint(1,10)
if (firstRan==10): #notice the colon at the end of this line and the indentation (one tab or four space, use the same each time) at the start of the next
print("I just picked a random number. You'll only see this line if it was a ten. If it wasn't, this line doesn't appear")
#Adding an 'else' clause tot he 'if' statement will allow us to one thing if the condition is met and a different thing if it isn't
secondRan = random.randint(1,10)
if (secondRan>5):
print("I picked another random number. You'l only see this message if it's above 5")
else: #again, colon, indentation. Else doesn't need a condition though - it's condition is basically "the first one isn't met
print("I picked another random number. You'l only see this message if it's 5 or below")
#If we have many options, we can add 'elif' blocks. These function the same as if blocks")
thirdRan=random.randint(1,10)
if (thirdRan==1):
print("I picked yet another number. You'll see this line if it was one")
elif (thirdRan==2):#colon, indentation
print("I picked yet another number. You'll see this line if it was two")
else:
print("I picked yet another number. You'll see this line if it neither one nor two")
#the line below is too long for my screen so I've split it into two. Each individual part is surrounded by "s but there's only one set of brackets
print("We can also have multiple lines inside an 'if', 'elif' or 'else'. This line is in the else block so "#why is there a space after so?
"will only appear if the number was neither one nor two, like the one above")
#So the order of instructions remains the same, like in sequence, but the computer makes a decision as to which line to use")
|
eb7b463c9bfc7bd9862f0814fa3c6b99737fb362
|
lf-pereiram/MisionTIC-2022
|
/Ciclo 1/python/Actividades/Promedio.py
| 213 | 3.625 | 4 |
a = float(input("numero 1: "))
b = float(input("numero 2: "))
c = float(input("numero 3: "))
d = float(input("numero 4: "))
e = float(input("numero 5: "))
prom = (a+b+c+d+e)/5
#print(prom)
print(-75.943>-75.877)
|
6ff2866d5025a3a594634bb92787768a2ab89eb8
|
otseobande/keywords
|
/positional_tf_idf.py
| 2,121 | 4.25 | 4 |
import math
def get_tf(term, document):
"""Calculates the frequency of a term in a document
Args:
term (str): The term (word) to find the frequency of.
document (str): The document to search for the term in.
Returns:
float: The term frequency (tf)
"""
term_list = [term.lower() for term in document.split()]
num_of_words_in_doc = len(document.split())
term_count_in_doc = term_list.count(term)
return term_count_in_doc / num_of_words_in_doc
def get_idf(term, documents):
"""Calculates the total number of documents divided by the
number of documents containing the term (word)
Args:
term (str): The term (word) to search for
documents (list): A list of all the documents to search through
Returns:
float: The inverse document frequency (idf) rounded to 5 digits
"""
number_of_docs = len(documents)
documents_containing_term = len([document for document in documents if term in document])
idf = math.log10(number_of_docs / documents_containing_term)
return round(idf, 5)
def get_tf_idf(term, document, documents):
"""Multiplies the term frequency (tf) with the
inverse document frequency (idf) to return the tf-idf
Args:
term (str): The term (word) to search for
document (str): The document to search for the term in.
documents (list): A list of all the documents to search through
Returns:
float: The tf-idf
"""
tf_idf = get_tf(term, document) * get_idf(term, documents)
return round(tf_idf, 5)
def get_positional_score(term, document):
"""Calculates the score of a term in a document based on its
position. Terms that appear earlier in the document are score higher.
Args:
term (str): The term (word) to calculate score for
document (str): The document to search for the term in.:
Returns:
float: The positional score of the term
"""
score = 0
number_of_words_in_doc = len(document.split())
for position, word in enumerate(document.split()):
if word.lower() == term.lower():
score += (number_of_words_in_doc - position) / number_of_words_in_doc
return round(score, 5)
|
ce8ee6b43dc1c967e2e1417ac7224f8c06d6a9d0
|
chiragcj96/Algorithm-Implementation
|
/Dynamic Programming/Pascal's Triangle/solution.py
| 1,081 | 3.8125 | 4 |
'''
Dynamic Programming -
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
Using a list[list[]] is used to build a [numRows x numRows] matrix, initialized with all 1's
We then calculate each value for the pascal triangle by adding -> matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
This populates the whole matrix with correct values
Then we just run for all the levels of the triangles(0->numRows), then for each (x, numRows-x) pairs, we append the values to result
Return result
Time: O(N^2)
Space: O(N^2)
'''
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
matrix = [[1 for _ in range(numRows)] for _ in range(numRows)]
result = []
for i in range(1, numRows):
for j in range(1, numRows):
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
i = 0
while i<numRows:
temp = []
x = 0
while x<=i:
temp.append(matrix[x][i-x])
x += 1
result.append(temp)
i += 1
return result
|
2679589e3ff39400eb0a5b81596df762e4090f32
|
adriellison/UFC
|
/1-Semestre/Curso extra de python/aula 05/parametroPadrao.py
| 233 | 3.75 | 4 |
def insira(n = 1):
return n * 2
def parametros(msg = "VALOR DEFAULT"):
return msg
print(insira())
msg = input("Digite uma frase")
if(msg == ""):
print(parametros())#se deixar vazio chama o default
else:
print(parametros(msg))
|
03ae595dac34fec2880915279f8fb8ccad9708cc
|
nettercm/timing
|
/t.py
| 2,731 | 3.890625 | 4 |
import time
from time import monotonic as now
from time import sleep
import sys
print(sys.argv)
interval = float(int(sys.argv[1])) / 1000000.0
offset = float(int(sys.argv[2])) / 1000000.0
def jitter_test(iterations):
for j in range(0,iterations):
min=99999.0
max=0.0
avg=0.0
sum=0.0
i=0
t_print = now()
while now() - t_print < 1.0:
i=i+1
t1=now()
time.sleep(interval - offset)
t2=now()
t3=t2-t1
if t3>max:
max=t3
if t3<min:
min=t3
sum=sum+t3
avg=sum/i
avg=(avg*1000000)
min=(min*1000000)
max=(max*1000000)
print("min,avg,max, range = %7.1f , %7.1f , %7.1f , %7.1f " % (min,avg,max,max-min))
def loop_test(iterations):
t_next = float(int(now())+1)
t1=t_next
t2=t_next
print("%9.6f" % (t_next))
min = 9999999.0
max = 0.0
i = 0
for j in range(0,iterations*int(1.0/interval)):
i = i + 1
#calculate the next time at which we are supposed to do the work; i.e. t_next is a point of time in the future
#note: this is kept simple on purpose; no attempt to account for numerical issues that will eventually come in
t_next = t_next + interval
#now calculagte the appropriate amount of sleep time, i.e. "point in time when we want to wake up" - "current time"
sleep_time = t_next - now()
#now account for the configurable fixed offset, i.e. to deal with the fact that sleep(N) always takes at
#least N+offset amount of time
sleep_time = sleep_time - offset
#in case we missed the bus completely, and we have falled way behind (sleep_time is negative), account for that
if sleep_time < 0: sleep_time=0
#do the actual sleep()
sleep( sleep_time )
#let's see when we actually woke up from sleep
t1=now()
#we were supposed to wake up at exactly t_next - calculate the error so we can show some stats
t_error = t1 - t_next
t_error = t_error*1000000.0 #in microseconds, please....
#eliminate the outlier from the first time through the loop
if i==1: t_error = 0
if t_error > max: max = t_error
if t_error < min: min = t_error
#do some useful work here;
#the amount of time this workload requires may not be 100% fixed,
#hence the need for our loop to account for that - which it is....
#show some stats...
print("%9.6f, %9.6f, error=%4.0f min,max,range/jitter=%5.0f,%5.0f,%5.0f" % ( t1, t1-t2 , t_error,min,max,max-min ))
#eliminate the outlier from the first time through the loop
if i==1: min = 99999.0
t2=t1
jitter_test(10)
loop_test(10)
|
f9b472888ffb3cd08f873027efb7a817cca7f352
|
lamsnakesgit/42bootcamppython
|
/day00/ex04/operations.py
| 1,096 | 4.09375 | 4 |
import sys
import string
def usage():
print("Usage: python operations.py <number1> <number2>\nExample:\n" + " python operations.py 10 3")
def operations():
if len(sys.argv) < 3:
print("InputError: two arguments needed") # optional
usage()
elif len(sys.argv) == 3:
try:
print(f'{"Sum:":<15}' + f'{int(sys.argv[1])+int(sys.argv[2])}')
print(f'{"Difference:":<15}' + f'{int(sys.argv[1])-int(sys.argv[2])}')
print(f'{"Product:":<15}' + f'{int(sys.argv[2])*int(sys.argv[1])}')
if int(sys.argv[2]) == 0:
print(f'{"Quotient:":<15}' + "ERROR (div by zero)")
print(f'{"Remainder:":<15}' +"ERROR (modulo by zero)")
else:
print(f'{"Quotient:":<15}' + f'{int(sys.argv[1])/int(sys.argv[2])}')
print(f'{"Remainder:":<15}' + f'{int(sys.argv[1])%int(sys.argv[2])}')
except ValueError:
print("InputError: only numbers\n")
usage()
else:
print("InputError:too many argumnets\n")
usage()
operations()
|
b4cfd3df53a04f368b15ac04783943d1a194deb8
|
doplab/act-tp
|
/2022/week07_conso1/solutions/overlap.py
| 209 | 3.875 | 4 |
def overlap(list1,list2):
res=[]
for elm in list1:
if elm in list2:
if not(elm in res):
res.append(elm)
return res
print(overlap([1, 2, 3, 4], [9, 4, 3, 7, 1]))
|
cc4b8a2b8caa1f53554e4630c1a0088f60de5c7e
|
harerakalex/code-wars-kata
|
/python/fold_array.py
| 1,542 | 4.46875 | 4 |
'''
In this kata you have to write a method that folds a given array of integers by the middle x-times.
An example says more than thousand words:
Fold 1-times:
[1,2,3,4,5] -> [6,6,3]
A little visualization (NOT for the algorithm but for the idea of folding):
Step 1 Step 2 Step 3 Step 4 Step5
5/ 5| 5\
4/ 4| 4\
1 2 3 4 5 1 2 3/ 1 2 3| 1 2 3\ 6 6 3
----*---- ----* ----* ----* ----*
Fold 2-times:
[1,2,3,4,5] -> [9,6]
As you see, if the count of numbers is odd, the middle number will stay. Otherwise the fold-point is between the middle-numbers, so all numbers would be added in a way.
The array will always contain numbers and will never be null. The parameter runs will always be a positive integer greater than 0 and says how many runs of folding your method has to do.
If an array with one element is folded, it stays as the same array.
The input array should not be modified!
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
'''
def fold_array(array, runs):
if runs<=0: return array
n=len(array)
list=[]
for i in range(n//2):
list.append(array[i]+array[n-i-1])
if n%2==0:
return fold_array(list,(runs-1))
else:
list.append(array[n//2])
return fold_array(list,(runs-1))
|
984ccba7696d30aae3ca574dec139266285000a1
|
dbracewell/pyHermes
|
/hermes/util/timer.py
| 1,152 | 3.734375 | 4 |
from datetime import datetime
class Timer:
def __init__(self, started=False):
self._elapsed = 0
self._start = None if not started else datetime.now()
def running(self):
return self._start is not None
def start(self):
if self._start:
raise Exception("Already started")
self._start = datetime.now()
def stop(self):
if not self._start:
raise Exception("Not started")
self._elapsed = (datetime.now() - self._start)
self._start = None
def elapsed(self):
if self._start:
return datetime.now() - self._start
return self._elapsed
def reset(self):
if self._start:
raise Exception("Running")
self._start = None
self._elapsed = 0
def elapsed_str(self):
return str(self)
def elapsed_seconds(self):
return self.elapsed().total_seconds()
def __str__(self) -> str:
delta = self.elapsed()
s = delta.seconds
ms = int(delta.microseconds / 1000)
return '{:02}:{:02}:{:02}.{:03}'.format(s // 3600, s % 3600 // 60, s % 60, ms)
|
167e8b39b63c82e117f46f1e8723e12982166ebe
|
quintelabm/PrmFitting
|
/venv/Lib/site-packages/numpoly/array_function/where.py
| 1,759 | 4.03125 | 4 |
"""Return elements chosen from `x` or `y` depending on `condition`."""
import numpy
import numpoly
from ..dispatch import implements
@implements(numpy.where)
def where(condition, *args):
"""
Return elements chosen from `x` or `y` depending on `condition`.
.. note::
When only `condition` is provided, this function is a shorthand for
``np.asarray(condition).nonzero()``. Using `nonzero` directly should be
preferred, as it behaves correctly for subclasses. The rest of this
documentation covers only the case where all three arguments a re
provided.
Args:
condition (numpy.ndarray, bool):
Where True, yield `x`, otherwise yield `y`.
x (numpoly.ndpoly): array_like
Values from which to choose. `x`, `y` and `condition` need to be
broadcastable to some shape.
Returns:
(numpoly.ndpoly):
An array with elements from `x` where `condition` is True, and
elements from `y` elsewhere.
Examples:
>>> poly = numpoly.variable()*numpy.arange(4)
>>> poly
polynomial([0, q0, 2*q0, 3*q0])
>>> numpoly.where([1, 0, 1, 0], 7, 2*poly)
polynomial([7, 2*q0, 7, 6*q0])
>>> numpoly.where(poly, 2*poly, 4)
polynomial([4, 2*q0, 4*q0, 6*q0])
>>> numpoly.where(poly)
(array([1, 2, 3]),)
"""
if isinstance(condition, numpoly.ndpoly):
condition = numpy.any(condition.coefficients, 0).astype(bool)
if not args:
return numpy.where(condition)
poly1, poly2 = numpoly.align_polynomials(*args)
out = numpy.where(condition, poly1.values, poly2.values)
out = numpoly.polynomial(out, names=poly1.indeterminants)
return out
|
41f32c34e8b054dee321e0faf91c9062b0a912ad
|
Zaargh/exercism
|
/python/anagram/anagram.py
| 208 | 3.546875 | 4 |
from collections import Counter
def detect_anagrams(word, candidates):
return [c for c in candidates
if Counter(c.lower()) == Counter(word.lower())
if c.lower() != word.lower()]
|
682e7b4863cc218fc563976cf4fa515072043a3f
|
JoshuaW1990/algorithm016
|
/Week_03/permute.py
| 671 | 3.671875 | 4 |
class Solution:
# def permute(self, nums: List[int]) -> List[List[int]]:
def permute(self, nums):
"""
依然是迭代做路径枚举
:param nums:
:return:
"""
result = []
nums.sort()
def dfs(path, remain_nums):
if len(path) == len(nums):
result.append([item for item in path])
return
for index, num in enumerate(remain_nums):
dfs(path+[num], remain_nums[:index] + remain_nums[index+1:])
return
dfs([], nums)
return result
solution = Solution()
nums = [1, 3, 4, 9, 7]
print(solution.permute(nums))
|
4e197aef602d076d30e487dd29f4b1e47e24cdc5
|
saalim-mohammed/python
|
/flowcontrols/dicisionmaking/student.py
| 332 | 3.984375 | 4 |
m1=int(input("mark of s1:"))
m2=int(input("mark of s2:"))
m3=int(input("mark of s3:"))
total=m1+m2+m3
print("total is",total)
if(total>145):
print("A+")
elif((total>=140)&(total<=145)):
print("A")
elif((total>=135) & (total<=140)):
print("B+")
elif((total>=130) & (total<=135)):
print("B")
else:
print("fail")
|
a1f37e8e109d34c971ffcafc697c35e65cab9177
|
omryry/wog
|
/guess_game.py
| 821 | 3.890625 | 4 |
import random
def generate_number(difficulty):
secret_number = random.randint(1, difficulty)
return secret_number
def get_guess_from_user(difficulty):
user_guess = 0
while user_guess < 1 or user_guess > difficulty:
user_guess = input("Please choose a number between 1 and " + str(difficulty) + ": ")
return user_guess
def compare_results(random_num, user_guess):
if random_num == user_guess:
return True
else:
return False
def play(difficulty):
num1 = generate_number(difficulty)
num2 = get_guess_from_user(difficulty)
if compare_results(num1, num2):
print("You Won :)")
print("The number was " + str(num1))
return True
else:
print("You Lost :(")
print("The number was " + str(num1))
return False
|
1532985082648ee9250a114dabf827f33f4bb37d
|
Mespn520/400B_Klein
|
/Homeworks/Homework7/GalaxyMass.py
| 4,488 | 3.53125 | 4 |
# This is a program that will return the total mass of any desired galaxy component
import numpy as np
import astropy.units as u
from ReadFile import read
# Function for the Component Mass of the specified galaxies
def ComponentMass(filename, par_type):
# Inputs:
# filename, this designates the file from which data will be taken from
# par_type designates the particle type, which are classified by numbers 1-3 with 1 being Halo type, 2 being Disk type, and 3 being Bulge type.
#Returns:
# M_tot, this is the total mass of a specific galaxy component
time, total, data = read(filename) #This will pull those 3 'data sets' from the ReadFile
index = np.where(data['type'] == par_type) # This creates an index for all the particles
mnew = data['m'][index] * 1e10 * u.Msun #This stores the components in the index and for final answer clarity sake was multiplied by 1e10 to clear up the 10^10 Msun that the masses are labeled as in the file
M_tot = np.sum(mnew) #This is the total mass
return M_tot
# Using the function to compute the total mass of each component of each galaxy (MW, M31, and M33) and storing the results in a Table, taking into consideration that M33 does not possess a bulge, so par_type 3 for M33 will not exist
M_MW_1 = np.round(ComponentMass("MW_000.txt",1)/1e12,3) # This will round the mass to 3 decimal places, the 1 indicates the particle type
M_MW_2 = np.round(ComponentMass("MW_000.txt",2)/1e12,3)
M_MW_3 = np.round(ComponentMass("MW_000.txt",3)/1e12,3)
#print("The total mass in the Milky Way Halo is: ", M_MW_1)
#print("The total mass in the Milky Way Disk is: ", M_MW_2)
#print("The total mass in the Milky Way Bulge is: ", M_MW_3)
# Doing the same for M31 now, where the number following the letter M_M31_# is the particle type
M_M31_1 = np.round(ComponentMass("M31_000.txt",1)/1e12,3)
M_M31_2 = np.round(ComponentMass("M31_000.txt",2)/1e12,3)
M_M31_3 = np.round(ComponentMass("M31_000.txt",3)/1e12,3)
#print("The total mass in the M31 Halo is: ", M_M31_1)
#print("The total mass in the M31 Disk is: ", M_M31_2)
#print("The total mass in the M31 Bulge is: ", M_M31_3)
#Doing the same for M33 now, where the number following the letter M_M33_# is the particle type
M_M33_1 = np.round(ComponentMass("M33_000.txt",1)/1e12,3)
M_M33_2 = np.round(ComponentMass("M33_000.txt",2)/1e12,3)
M_M33_3 = np.round(ComponentMass("M33_000.txt",3)/1e12,3)
#print("The total mass in the M33 Halo is: ", M_M33_1)
#print("The total mass in the M33 Disk is: ", M_M33_2)
#print("M33 does not posses a bulge")
# Now we have to compute the total mass of each galaxy (all components combined) and add it to the table
# Summing all components will look something like M_Galaxy = M_Galaxy_# + M_Galaxy_# + M_Galaxy_#
M_MW = M_MW_1 + M_MW_2 + M_MW_3
M_M31 = M_M31_1 + M_M31_2 + M_M31_3
M_M33 = M_M33_1 + M_M33_2 + M_M33_3
#print("The total mass of the MW is: ", M_MW)
#print("The total mass of M31 is: ", M_M31)
#print("The total mass of M33 is: ", M_M33)
# Then we have to compute the total mass of the Local Group (labelled LG)
# This will be the sum of the total masses of each galaxy and will look something like M_LG = M_MW + M_M31 + M_M33
M_LG = M_MW + M_M31 + M_M33
#print("The total mass of the Local Group is: ", M_LG)
# And finally we have to compute the baryon fraction f_bar
# The baryon fraction looks like f_bar_Galaxy = total stellar mass (M_Galaxy_2 + M_Galaxy_3) / total mass (M_Galaxy)
# First I will calculate the stellar mass and round it to 3 decimal places to keep significant figures consistent
# This will look like M_Stellar_Galaxy = (M_Galaxy_2 + M_Galaxy_3)
M_Stellar_MW = np.round(M_MW_2 + M_MW_3,3)
# Then f_bar
f_bar_MW = np.round((M_Stellar_MW/M_MW),3)
# M31
M_Stellar_M31 = np.round(M_M31_2 + M_M31_3,3)
f_bar_M31 = np.round((M_Stellar_M31/M_M31),3)
# M33
M_Stellar_M33 = np.round(M_M33_2 + M_M33_3,3)
f_bar_M33 = np.round((M_Stellar_M33/M_M33),3)
#print("The baryon fraction for the MW is: ", f_bar_MW)
#print("The baryon fraction for M31 is: ", f_bar_M31)
#print("The baryon fraction for M33 is: ", f_bar_M33)
# Then calculating the baryon fraction for the whole Local Group
# This will look like M_Stellar = M_Stellar_Galaxy + M_Stellar_Galaxy + M_Stellar_Galaxy and then f_bar_LG = M_Stellar/M_LG
M_Stellar = M_Stellar_MW + M_Stellar_M31 + M_Stellar_M33 #LG Stellar mass
f_bar_LG = np.round((M_Stellar/M_LG),3)
#print("The baryon fraction for the Local Group is: ", f_bar_LG)
|
2c9706eb213b39cc5ddcf52b9d6f345ccce6ae44
|
TreidynA/CP1404_Practicals
|
/Prac_01/loops.py
| 514 | 4.1875 | 4 |
for i in range(1, 21, 2):
print(i, end=' ')
print()
#a count in 10s from 0 to 100
for i in range(0, 110, 10):
print(i, end=" ")
print()
#b count down from 20 1
for i in range(20, 0, -1):
print(i, end=" ")
print()
#c print n stars. Ask the user for a number, then print that many stars (*), all on one line
num_stars = int(input("Number of stars: "))
for i in range(1, num_stars):
print("*", end="")
print()
#d. print n lines of increasing stars
for i in range(1, num_stars + 1):
print("*" * i)
|
1f7c3e0412843767513052346ef0a5a364095281
|
wwtang/code02
|
/lcsrecursive.py
| 556 | 3.96875 | 4 |
def lcs(xs, ys):
'''Return a longest common subsequence of xs and ys.
Example
>>> lcs("HUMAN", "CHIMPANZEE")
['H', 'M', 'A', 'N']
'''
if xs and ys:
xb = xs[:-1]
xe = xs[-1]
yb = ys[:-1]
ye = ys[-1]
#*xb, xe = xs
#*yb, ye = ys
if xe == ye:
return lcs(xb, yb) + [xe]
else:
return max(lcs(xs, yb), lcs(xb, ys))
else:
return []
def main():
x = "ABCBDAB"
y = "BDCABA"
print lcs(x,y)
if __name__=='__main__':
main()
|
a22e15570aef88449b98c3da9b2ef47aad1c2fb5
|
june0313/programmers-python
|
/level2/소수찾기/number_of_prime.py
| 338 | 3.765625 | 4 |
def numberOfPrime(n):
# 1부터 n사이의 소수는 몇 개인가요?
return len(list(filter(isPrime, range(1, n + 1))))
def isPrime(n):
return list(filter(lambda i: n % i is 0, range(1, n + 1))) == [1, n]
# 아래는 테스트로 출력해 보기 위한 코드입니다.
print(numberOfPrime(10))
print(numberOfPrime(5))
|
6ce5dec51ac0ee53f3675c5515c4520e657ce0a1
|
Rochan01/B1ackPyramid
|
/rock paper scissors.py
| 1,052 | 4.09375 | 4 |
# Rock Paper Scissors
import random
options = ["r", "p", "s"]
player_wins = 0
comp_wins = 0
no_of_games = 5
rounds_left = 5
print(f'Rounds left = {rounds_left}')
while no_of_games > 0:
comp = random.choice(options)
player = input("enter your choice: r for rock,p for paper and s for scissors: ").lower()
if player == "r" and comp == "s" or player == "s" and comp == "p" or player == "p" and comp == "s":
print("You win this round.")
player_wins = player_wins +1
no_of_games = no_of_games - 1
rounds_left = rounds_left - 1
else:
print("Computer wins this round.")
comp_wins = comp_wins +1
no_of_games = no_of_games - 1
rounds_left = rounds_left - 1
print(f"Rounds left = {rounds_left}")
if player_wins == comp_wins:
print("Its a draw.")
elif player_wins < comp_wins:
print("Computer is the winner.")
else:
print("You win !!!")
print(f"Computer won {comp_wins} times.")
print(f"And, You won {player_wins} times.")
|
75a2e414e491199c72391b6ffbc8e2d5027fed4c
|
UULIN/automation_test
|
/unit6_unittest_sample/more/test_skip.py
| 997 | 3.96875 | 4 |
"""
测试跳过某些测试用例
unittest.skip(reason) 无条件的跳过装饰器的测试,需要标明跳过的原因
unittest.skipIF(condition, reason) 如果条件为真,则跳过装饰器的测试
unittest.skipUnless(condition, reason) 当条件为真时,执行装饰器的测试
unittest.expectedFailure() 不管执行是否失败,都将测试标记为失败
"""
import unittest
class My_test(unittest.TestCase):
@unittest.skip("测试无条件跳过测试用例")
def test_skip(self):
print("aaa")
@unittest.skipIf(3>2,"测试当条件为真时,跳过测试用例")
def test_skipif(self):
print("bbb")
@unittest.skipUnless(3>2, "测试当条件为真时,执行测试用例")
def test_skipunless(self):
print("ccc")
# 不管执行是否失败,直接标记为失败
@unittest.expectedFailure
def test_expectedfailure(self):
self.assertEqual(2, 3)
if __name__ == '__main__':
unittest.main()
|
9aaf6bcee9b912d44d65f61b0a130f19e2201bc2
|
kadey001/puzzle_solver
|
/utility.py
| 497 | 4.125 | 4 |
position_dict = {}
goal_state = []
def set_position_dict(n = 3):
"""
Creates a dict for each value's correct position and builds
a goal state for goal checking
"""
value = 1
for i in range(n):
row = []
for j in range(n):
if (i + 1) * (j + 1) >= n**2:
position_dict[0] = (i, j)
row.append(0)
else:
position_dict[value] = (i, j)
row.append(value)
value += 1
goal_state.append(row)
|
f850ddd956a5deccd7b24230f029d7c2ee0de354
|
PacktPublishing/Mastering-OpenCV-4-with-Python
|
/Chapter05/01-chapter-content/saturation_arithmetic.py
| 649 | 4.0625 | 4 |
"""
Example to show how saturation arithmetic work in OpenCV
"""
import numpy as np
import cv2
# There is a difference between OpenCV addition and Numpy addition.
# OpenCV addition is a saturated operation while Numpy addition is a modulo operation.
x = np.uint8([250])
y = np.uint8([50])
# OpenCV addition: values are clipped to ensure they never fall outside the range [0,255]
# 250+50 = 300 => 255:
result_opencv = cv2.add(x, y)
print("cv2.add(x:'{}' , y:'{}') = '{}'".format(x, y, result_opencv))
# NumPy addition: values wrap around
# 250+50 = 300 % 256 = 44:
result_numpy = x + y
print("x:'{}' + y:'{}' = '{}'".format(x, y, result_numpy))
|
c37337aa2470f570ab08f350b94f74f6022bbc6c
|
sssmrd/pythonassignment
|
/7.py
| 111 | 4.21875 | 4 |
#program to calculate length of string
str=input("Enter a string=");
print("Length of ", str, "is", len(str))
|
bc4295dd17c71962d4a5c0544b2a1a0e226b6874
|
RodrigoZea/Miniproyecto4
|
/ai_player.py
| 3,307 | 3.734375 | 4 |
import utils
import random
import hashlib
import copy
random.seed(69)
def apply_move(board, move, p1_turn, scores):
board = copy.deepcopy(board)
stones = board[move]
board[move] = 0
move_index = (move + 1) % 12
repeat_turn = False
last_move_index = -1
while stones > 0:
# jugador 1 paso por su mancala, sumarle punto
if move_index == 6 and p1_turn:
stones -= 1
scores['p1'] += 1
# ends turn in mancala
if stones == 0:
another_turn = True
break
# AI paso por su mancala, sumarle punto
if move_index == 0 and not p1_turn:
stones -= 1
scores['p2'] += 1
# ends turn in mancala
if stones == 0:
another_turn = True
break
# agregar una piedra en la casilla actual y restar la cantidad
# de piedras restantes en la mano del jugador; por ultimo,
# avanzar una casilla
board[move_index] += 1
stones -= 1
if stones == 0:
last_move_index = move_index
break
move_index = (move_index + 1) % 12
# jugador deja ultima piedra en un espacio vacio propio, captura su piedra
# y las de enfrente del otro jugador
if last_move_index >= 0 and board[last_move_index] == 1:
if p1_turn and last_move_index < 6:
scores['p1'] += (board[11 - last_move_index] + 1)
board[last_move_index] = 0
board[11 - last_move_index] = 0
elif not p1_turn and last_move_index >= 6:
scores['p2'] += (board[11 - last_move_index] + 1)
board[last_move_index] = 0
board[11 - last_move_index] = 0
return board, repeat_turn
def board_move(board, p1_score, p2_score, limit = 10):
temp_board = copy.deepcopy(board)
scores = {
'p1': p1_score,
'p2': p2_score,
6: 0,
7: 0,
8: 0,
9: 0,
10: 0,
11: 0
}
iters = 0
p1_turn = False
path = []
while iters < limit:
moves = utils.legal_moves(temp_board, p1_turn)
move = random.choice(moves)
# se guarda el tiro solo si es el turno del AI
if not p1_turn:
path.append(move)
# bla bla
temp_board, repeat_turn = apply_move(temp_board, move, p1_turn, scores)
if not repeat_turn:
p1_turn = not p1_turn
# bla bla
if utils.game_over(temp_board):
p1_l, p2_l = utils.leftovers(temp_board)
scores['p1'] += p1_l
scores['p2'] += p2_l
if scores['p1'] > scores['p2']:
scores[path[0]] -= 1
else:
scores[path[0]] += 1
p1_turn = False
iters += 1
temp_board = copy.copy(board)
scores['p1'] = 0
scores['p2'] = 0
path.clear()
legal_moves = utils.legal_moves(board, False)
score_max = -float('inf')
score_max_index = legal_moves[0]
for i in legal_moves:
if i in scores:
if scores[i] > score_max:
score_max = scores[i]
score_max_index = i
return score_max_index
|
74dce1645dcca1992095c3b4dcf8d809fc6cfa80
|
mat-green/stealth-co
|
/stealthco/models.py
| 2,715 | 4 | 4 |
'''
Created on 24 Jan 2016
@author: Matthew Green
@copyright: 2016 New Edge Engineering Ltd. All rights reserved.
@license: MIT
'''
class Graph(object):
'''
Object that plots vectors as lines and render to ascii characters.
'''
def __init__(self, width, height):
'''
Constructor.
:param width: Width of the graph as a Integer.
:param height: Height of the graph as a Integer.
'''
grid = []
a = 0
while a < height:
b = 0
row = []
while b < width:
row.append(" ")
b += 1
grid.append(row)
a += 1
self.grid = grid
def plot(self, start, end):
'''
Updated the graph with a plotted line
:param start: The start coordinate as a Coordinate
:param end: The end coordinate as a Coordinate
'''
# determine direction
rise = end.y - start.y
run = end.x - start.x
if(rise != 0 and run != 0):
slope = float(abs(rise)) / float(abs(run))
else :
slope = 0
# insert X into grid
x = start.x
y = start.y
if(rise >= 0):
while x <= (end.x) and y <= (end.y):
self.grid[y][x] = "X"
if(slope > 0):
if(slope < 1):
x += int(round(slope, 0))
else:
x += int(slope)
y += 1
else: # use rise and run to determine direction.
if(rise > 0):
y += 1
else:
x += 1
elif(rise <= 0):
while x <= (end.x) and y >= (end.y):
self.grid[y][x] = "X"
if(slope > 0):
if(slope < 1):
x += int(round(slope, 0))
else:
x += int(slope)
y -= 1
else: # use rise and run to determine direction.
if(rise < 0):
y -= 1
else:
x += 1
def render(self):
'''
Basic render of data.
:return: Ascii string of characters
'''
result = [ ''.join(line) for line in self.grid ]
return '\n'.join(result)
class Coordinate(object):
'''
Holds coordinates
'''
def __init__(self, x, y):
'''
Constructor.
:param x: X position as a Integer.
:param y: Y position as a Integer.
'''
self.x = x
self.y = y
|
d89db8638265803ee88083527e864d886644ec47
|
adityabettadapura/TicTacToe-game
|
/main.py
| 1,427 | 3.546875 | 4 |
import random
from board import Board
from randomai import RandomAI
from pseudorandomai import PseudoRandomAI
from humanai import HumanAI
from tictactoe import TicTacToe
if __name__ == "__main__":
while True:
board = Board()
ttt = TicTacToe()
print "Choose the match-up:"
print "Type 1 for Random AI v/s Pseudo Random AI"
print "Type 2 for Pseudo Random AI v/s Pseudo Random AI"
print "Type 3 for Random AI v/s You"
print "Type 4 for Pseudo Random AI v/s You"
print "Type 5 for a 2 player game"
choice = int(raw_input("Type in your choice: "))
if choice == 1:
ttt.start(board, RandomAI(), PseudoRandomAI())
elif choice == 2:
ttt.start(board, PseudoRandomAI(), PseudoRandomAI())
elif choice == 3:
humanPlayer = HumanAI()
ttt.start(board, RandomAI(), humanPlayer)
elif choice == 4:
humanPlayer = HumanAI()
ttt.start(board, humanPlayer, PseudoRandomAI())
elif choice == 5:
humanPlayer1 = HumanAI()
humanPlayer2 = HumanAI()
humanPlayer1.setName("Player 1")
humanPlayer2.setName("Player 2")
ttt.start(board, humanPlayer1, humanPlayer2)
restart = raw_input("Do you want to try again (Y or N) ?")
if ( not restart.lower().startswith('y')):
break
|
3f1a4882b6869c9d181d632d20f4aafebdd90014
|
Pavan-443/Python-Crash-course-Practice-Files
|
/chapter 3&4 - lists/chap_4_lists/cubes_4-8.py
| 147 | 4.125 | 4 |
cubes = []
numbers = list(range(1,11))
for num in numbers:
cube = f'Cube of {num} is {num**3}'
cubes.append(cube)
for cube in cubes:
print(cube)
|
9a7c3fdaff845673cac16ebc3926419b24c027cb
|
vipin-t/py-samples
|
/listings.py
| 1,058 | 4.28125 | 4 |
# print ("to work on lists")
a_list = [7,1,5,8,4,2,6]
b_list = ['f', 'g', 'a', 'd', 'b', 'e', 'c']
c_list = [a_list, b_list]
b_list.
## list commands
# a_list.sort()
# a_list.reverse()
# b_list.sort()
print ( a_list )
print(b_list)
print ('\n')
print ( c_list )
#print ( b_list.pop(2) )
# print ( len(a_list) )
# print ( a_list + b_list )
## using dictionary. This uses key:value pair and used when we dont have any ordering or indexing.. Just retrieves the value based on the key
print ("to work on Dictionary")
new_dictionary = {'apples': 20, 'mango': 40, 'orange': 10, 'banana': 80}
my_dictionary = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}
print (new_dictionary)
print (my_dictionary['key3'][2])
## tuple similar to list.. but not immutable.. i.e., the values are fixed and cannot be changed after they are defined.
## tuple(*,*,*) ... list[*,*,*]... dictionary {key:value, key:value, key:value}
_tuple1 = ('phy', 'chem', 'bio', 'math')
print (_tuple1)
print (_tuple1.count('phy'))
|
1fc653ac58a75e91199d0f726edd90c3e0caf11a
|
kylemaa/Hackerrank
|
/LeetCode/find-first-and-last-position-of-element-in-sorted-array.py
| 1,674 | 3.921875 | 4 |
# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
# Because the array is already sorted, we can use binary search tree for solve for logarithmic time.
class Solution:
# returns leftmost (or rightmost) index at which `target` should be inserted in sorted
# array arr via binary search.
def getRange(self, arr, target):
first = self.binarySearch(arr, 0, len(arr)-1, target, True)
last = self.binarySearch(arr, 0, len(arr)-1, target, False)
return [first, last]
# this is a helper function
def binarySearch(self, arr,low, high, target, findFirst):
# findFirst is for whether we're looking for the first index
if high < low:
return -1
mid = low + (high -low)// 2
# first index case
if findFirst:
if (mid == 0 or target > arr[mid-1]) and arr[mid] == target:
return mid
if target > arr[mid]:
return self.binarySearch(arr, mid + 1, high, target, findFirst)
else:
return self.binarySearch(arr, low, mid -1, target, findFirst)
# last index case
else:
if (mid == len(arr)-1 or target < arr[mid + 1]) and arr[mid] == target:
return mid
elif target < arr[mid]:
return self.binarySearch(arr, low, mid - 1, target, findFirst)
else:
return self.binarySearch(arr, mid + 1, high, target, findFirst)
arr = [1, 3, 3, 5, 7, 8, 9, 9, 9, 15]
x = 9
print(Solution().getRange(arr, 9))
|
bc37dad623ce7e411d1ddbb12e0b504891c28c5a
|
vitalyvj/python
|
/HW3_3.py
| 278 | 3.859375 | 4 |
def my_func(a, b, c):
d = min(a, b, c)
return a + b + c - d
a = float(input('Введите первое число: '))
b = float(input('Введите второе число: '))
c = float(input('Введите третье число: '))
print(my_func(a, b, c))
|
f409dd577aaf6baf462ee31c5cde435570831cd8
|
yinchuandong/python_algorithm
|
/leetcode/add_two_numbers.py
| 1,250 | 3.890625 | 4 |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = rlist = ListNode(0)
s = 0
while l1 is not None or l2 is not None:
s /= 10
if l1 is not None:
s += l1.val
l1 = l1.next
if l2 is not None:
s += l2.val
l2 = l2.next
reminder = s % 10
head.next = ListNode(reminder)
head = head.next
if s / 10 == 1:
head.next = ListNode(1)
return rlist.next
def printList(ln):
arr = []
while ln is not None:
arr.append(ln.val)
ln = ln.next
print arr
if __name__ == '__main__':
ln11 = ListNode(9)
ln12 = ListNode(9)
# ln13 = ListNode(3)
ln11.next = ln12
# ln12.next = ln13
ln21 = ListNode(1)
# ln22 = ListNode(6)
# ln23 = ListNode(4)
# ln21.next = ln22
# ln22.next = ln23
s = Solution()
rlist = s.addTwoNumbers(ln11, ln21)
printList(rlist)
|
81e1c7ffebfcd8feacae0a3d63457ebfadeb07b0
|
alexkorep/udacity-deep-learning
|
/softmax.py
| 381 | 3.53125 | 4 |
import numpy as np
def softmax(input):
sum = np.sum(np.exp(input), 0)
if not sum.any():
return input
return np.exp(input)/sum
scores = [1.0, 2.0, 3.0]
print softmax(scores)
scores = [100.0, 101.0, 102.0]
print softmax(scores)
"""
scores = np.array([[1, 2, 3, 6],
[2, 4, 5, 6],
[3, 8, 7, 6]])
print softmax(scores)
"""
|
d3019d9627a03af5aeef2d44102053b35f9a5f53
|
wandsen/PythonNotes
|
/JavaClasses/Abstract_Class_2.py
| 497 | 3.984375 | 4 |
from abc import ABCMeta, abstractmethod
import abc
class AbstractOperation(object):
__metaclass__ = abc.ABCMeta
def __init__(self, operand_a, operand_b):
self.operand_a = operand_a
self.operand_b = operand_b
super(AbstractOperation, self).__init__ #This is an explicit declaration. If not written, it is still executed implicitly.
'''
note that __meta__class is for python 2
class name(metaclass=ABCMeta) is for python 3
class name(ABC) is for python 3.7
'''
|
b768c36a0857d704bc90a8b19bed0d48c3563a6b
|
supragub/python-codecool
|
/18-Pairprogramming/Fizzbuzz/fizzbuzz_module.py
| 353 | 3.765625 | 4 |
def fizzbuzz(number):
text = number
if int(number) % 15 == 0:
text = "FizzBuzz"
elif int(number) % 3 == 0:
text = "Fizz"
elif int(number) % 5 == 0:
text = "Buzz"
return text
def main():
for i in range(1, 101):
print(fizzbuzz(i))
fizzbuzz(i)
return
if __name__ == '__main__':
main()
|
bb82660c60a1ac8bf2ae9f7dba5306b325f3dfa0
|
sagar8080/Algorithms
|
/Search/Interpolation_Search.py
| 774 | 4.03125 | 4 |
# Implement interpolation search
def interpolation_search(input_sequence, key):
start = 0
end = len(input_sequence) - 1
while input_sequence[end] != input_sequence[start] and key >= input_sequence[start] and key <= input_sequence[end]:
mid = int(
start + ((key - input_sequence[start]) * (end - start) / (input_sequence[end] - input_sequence[start])))
if input_sequence[mid] == key:
return mid
elif input_sequence[mid] < key:
start = mid + 1
else:
end = mid - 1
return -1
# Driver function
if __name__ == '__main__':
input_sequence = list(map(int, input("enter input ").split(" ")))
key = int(input("Enter a key "))
print (interpolation_search(input_sequence, key))
|
9963c2ba41bf2eaafac35445565557c7889feec6
|
wwd605075811/CS5014_MachineLearning
|
/P1_logistic_regression/practise/bc.py
| 940 | 3.6875 | 4 |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
def one_bezier_curve(a, b, t):
return (1 - t) * a + t * b
# xs表示原始数据
# n表示阶数
# k表示索引
def n_bezier_curve(xs, n, k, t):
if n == 1:
return one_bezier_curve(xs[k], xs[k + 1], t)
else:
return (1 - t) * n_bezier_curve(xs, n - 1, k, t) + t * n_bezier_curve(xs, n - 1, k + 1, t)
def bezier_curve(xs, ys, num, b_xs, b_ys):
n = len(xs) - 1
t_step = 1.0 / (num - 1)
t = np.arange(0.0, 1 + t_step, t_step)
for each in t:
b_xs.append(n_bezier_curve(xs, n, 0, each))
b_ys.append(n_bezier_curve(ys, n, 0, each))
def main():
xs = [0, 2, 5, 10, 15, 20]
ys = [0, 6, 10, 0, 5, 5]
num = 100
b_xs = []
b_ys = []
bezier_curve(xs, ys, num, b_xs, b_ys)
plt.figure()
plt.plot(b_xs, b_ys)
plt.plot(xs, ys)
plt.show()
if __name__ == "__main__":
main()
|
3a877aca5369408bbd17c0d4838a9c537e0d751d
|
zbarton88/Python-Physics-Euler-Problems
|
/Euler 49.py
| 720 | 3.703125 | 4 |
def sieve(n):
answer = []
notprimes = []
primes = []
for i in range(2,10000):
if i not in notprimes:
primes.append(i)
for k in range(i**2,10000,i):
notprimes.append(k)
for i in range(3,len(primes)):
n1 = primes[i]
n2 = primes[i]+3330
n3 = primes[i]+6660
if n2 in primes and n3 in primes:
str1 = str(n1)
str2 = str(n2)
str3 = str(n3)
if len(str1)==len(str2)==len(str3) and sorted(str1)==sorted(str2)==sorted(str3):
answer.append(n1)
answer.append(n2)
answer.append(n3)
print(answer)
sieve(100)
|
f45532bdc3d09be187c77ae63a85200aa75a0875
|
Invalid-coder/Data-Structures-and-algorithms
|
/Graphs/Unweighted_graphs/Tasks/eolymp(2401).py
| 863 | 3.625 | 4 |
#https://www.e-olymp.com/uk/submissions/7692873
class Graph:
def __init__(self, matrix):
self.adjacentMatrix = matrix
def wave(self, start, end):
queue = [start]
distances = {start:0}
while len(queue) > 0:
current = queue.pop(0)
if current == end:
return distances[current]
for neighbor, edge in enumerate(self.adjacentMatrix[current]):
if edge == 1 and not neighbor in distances:
queue.append(neighbor)
distances[neighbor] = distances[current] + 1
return 0
if __name__ == '__main__':
n, s, f = map(int, input().split())
matrix = []
for i in range(n):
row = list(map(int, input().split()))
matrix.append(row)
graph = Graph(matrix)
print(graph.wave(s - 1, f - 1))
|
330c7adb265619579a7977d492cc955e93a49d33
|
0siris7/vjcet-python
|
/program42.py
| 169 | 4.03125 | 4 |
list1=input("enter list:")
minimum=list1[0]
for i in range(1,len(list1)):
if(list1[i]<minimum):
minimum=list1[i]
print "the minimum is:",minimum
|
95f34a50d7e799de0cde93ebf7306f6622ad1f04
|
Joey-Hu/pythonbasic
|
/100day&Project/train_project/geekcomputers/koch curve/koch curve.py
| 954 | 3.5625 | 4 |
#!/usr/bin/env python
# encoding: utf-8
# @author: huhao
# @Software : PyCharm
# @file: koch curve.py
# @time: 2019/6/28 15:04
# @Ducument:https://www.python.org/doc/
# @desc:
from turtle import *
def snowflake(lengthSide,levels):
if levels == 0:
forward(lengthSide) #向右绘制
return
lengthSide /= 3.0
snowflake(lengthSide, levels-1)
left(60)
snowflake(lengthSide, levels-1)
right(120)
snowflake(lengthSide, levels-1)
left(60)
snowflake(lengthSide, levels-1)
if __name__ == '__main__':
speed(0) #defining the speed of the turtle
length = 300.0
penup() # Pull the pen up – no drawing when moving.
backward(length / 2.0)
pendown()
for i in range(3):
# Pull the pen down – drawing when moving.
snowflake(length, 2)
right(120)
# To control the closing windows of the turtle
mainloop()
|
85977cdd81750694446d29c0de981b5ab982e107
|
sandeepkabir/python-project
|
/assingment2.py
| 326 | 3.796875 | 4 |
#Q1
print("my name is sandeep")
#Q2
print("sandeep" +"kabir")
#Q3
x=input("enter any number")
y=input("enter any number")
z=input("enter any number")
print(x,y,z)
#Q4
print("let\'s get started")
#Q5
s="acadview"
course="python"
fees=5000
print("%s %s %d" %(s,course,fees))
print (s + " " + course + " " + str(fees))
|
6233cc7838eca4c21fd29f495106beef40795f43
|
Darioxa20/Toapanta
|
/semana2/import math.py
| 192 | 3.578125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 26 12:40:21 2019
@author: 1-26-PB-L2-13
"""
from math import pi,radians,degrees,sin,cos,tan,asin
ad=90
ar=radians(ad)
print(ar)
|
fe9c910ccf39ba6cd2b15e0847ea18cd5bace87a
|
ttungl/Coding-Interview-Challenge
|
/source-code/Positions of Large Groups 830.py
| 1,491 | 3.796875 | 4 |
# 830. Positions of Large Groups
# In a string S of lowercase letters, these letters form consecutive groups of the same character.
# For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".
# Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
# The final answer should be in lexicographic order.
# Example 1:
# Input: "abbxxxxzzy"
# Output: [[3,6]]
# Explanation: "xxxx" is the single large group with starting 3 and ending positions 6.
# Example 2:
# Input: "abc"
# Output: []
# Explanation: We have "a","b" and "c" but no large group.
# Example 3:
# Input: "abcdddeeeeaabbbcd"
# Output: [[3,5],[6,9],[12,14]]
class Solution(object):
def largeGroupPositions(self, S):
"""
:type S: str
:rtype: List[List[int]]
"""
# sol 1:
# time O(n^2) space O(n)
# runtime: 70ms
res, n = [], len(S)
i = j = 0
while i < n:
while j < n and S[i]==S[j]: j += 1
if j - i >= 3: res.append([i,j-1])
i = j
return res
# sol 2:
# time O(n^2) space O(n)
# runtime: 75ms
res, j, s = [], 0, S + '.'
for i in range(len(s)):
if s[i] != s[j]:
if i-j >= 3: res.append([j, i-1])
j = i
return res
|
1253792585fdf668d346671ca672e190706495f2
|
rishavhack/Data-Structure-in-Python
|
/String/String Template.py
| 289 | 3.609375 | 4 |
from string import Template
#Create template that has placeholder for value of x
t = Template('x is $x')
print t.substitute({'x':1})
student=[('Rishav',88),('Ankit',78),('Bob',92)]
t = Template('Hi $name,you got $marks marks')
for i in student:
print t.substitute(name = i[0],marks=i[1])
|
124d75fb8167d9c709b64f757b846a805a59675f
|
MaximKuba/python_labs
|
/lab5/lab5.1.py
| 356 | 3.59375 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 21:47:33 2018
@author: maximkuba
"""
import numpy as np
M = 208
N = 12
array = np.zeros((M,N))
array.size
a = np.array([1, 2, 3])
key = int(input('Enter key:'))
print(key)
def find_nearest(z, A):
id = (np.abs(A-z)).argmin()
return A[id]
find_nearest(key,a)
|
0711bf826050419d69c4c78f2c19b3ccd2e5252d
|
HeywoodKing/mytest
|
/MyPractice/fib3.py
| 308 | 3.59375 | 4 |
# -*- coding utf-8 -*-
L = ['adam', 'LISA', 'barT']
def normalize(name):
return name.capitalize()
res = list(map(normalize, L))
print(res)
L1 = [1,2,3,4,5]
from functools import reduce
def multi(x, y):
return x * y
def prod(l):
return reduce(multi,l)
print(prod(L1))
|
84be8ce106db4d9c3d97cc7d07ea06734f0f8f04
|
sudhanvalalit/Koonin-Problems
|
/Koonin/Chapter1/Exercises/chap1c.py
| 669 | 3.78125 | 4 |
"""
The following FORTRAN program finds the positive root of the function
..math::
f(x) = x^2 - 5, x_0 = 5^{1/2} = 2.236068
to a tolerance of 10^{-6} using x = 1 as an initial guess and an initial step size of 0.5:
"""
import numpy as np
# tolerance
tolx = 1e-6
def func(x):
return x*x - 5.0
def main():
x = 1.0
fold = func(x)
dx = 0.5
it = 0
while abs(dx) > tolx:
it += 1
x += dx
diff = np.sqrt(5.0) - x
print("Iteration: {}, x: {:.7f}, Error: {:.5E}".format(
it, x, diff))
if fold*func(x) < 0:
x -= dx
dx /= 2
if __name__ == "__main__":
main()
|
61b170a04191b0de444bed073640f63dab941bfb
|
cjetter/practicefiles
|
/Coursera/Python for Everyone/PythonCode/Ch8Ex5.py
| 792 | 3.84375 | 4 |
'''Ch10Ex1: Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line.
Count the number of messages from each person using a dictionary. After all the data has been read, print the person with the
most commits by creating a list of (count, email) tuples from the dictionary.
Then sort the list in reverse order and print out the person who has the most commits.
'''
fhand = open('mbox-short.txt')
d = dict()
for line in fhand:
if line.startswith('From ') is False: continue
else:
line = line.rstrip()
words = line.split()
email = words[1]
d[email]=d.get(email,0)+1
lst = list()
for key,val in list(d.items()):
lst.append((val,key))
lst.sort(reverse=True)
val,key = lst[0]
print key, val
|
9bf9bd16ac955622202eac70d66f40b9658c8715
|
Erin-hua/python-study
|
/three_chapter/list_3_8.py
| 294 | 3.8125 | 4 |
places=["Yunlan","Beijing","Xinjiang","Qinghai","Xian","Nanjing"]
print(places)
print(sorted(places))
print(places)
print(sorted(places,reverse=True))
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse=True)
print(places)
|
d90a7b450e6ba6a3b1da578577bfb90c095ecc8c
|
saurabhsharma21/PythonTraining
|
/Task 1/Task1.py
| 1,583 | 3.859375 | 4 |
#Code
#>>> a = 1; b = 3.3; c = 'String'
#>>> c
#'String'
#>>> b
#3.3
#>>> a
#1
########################
#>>> x = 1 + 2j
#>>> a = 3
#>>> a = x
#>>> a
#(1+2j)
#########################
#>>> a = 2
#>>> b = 3
#>>> result = a
#>>> a = b
#>>> b = result
#>>> a
#3
#>>> b
#2
#>>> a = 5
#>>> b = 7
#>>> a, b = b, a
#>>> a
#7
#>>> b
#5
#######################
Python 3.7.3 (default, Jun 2 2020, 19:48:59)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = eval(input('Enter a value'))
Enter a value10
>>> a
10
Python 2.7.16 (default, Feb 29 2020, 01:55:37)
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = eval(raw_input('Enter a value'))
Enter a value0
>>> a
0
#############################
a = int(input("Input number 1"))
b = int(input("Input number 2"))
z = a + b + 30
print("Sum total is ", + z)
##############################
>>> a = 'Saurabh'
>>> print("the imput value data type is: ", type(a))
the imput value data type is: <class 'str'>
>>> print("the input value data type is: ",type(a))
the input value data type is: <class 'str'>
########################
typeOfVariable = 1 #lowerCamel
TypeOfVariable2 = 'Saurabh' #LadderCamel
TYPEOFVARIABLE3 = 10.98 #UPPERCASE
#####################################
Yes!This is possible due to the fact that the data types are dynamically typed in python.
>>> a= 10
>>> type(a)
<type 'int'>
>>> a= 'Hello'
>>> type(a)
<type 'str'>
|
4b27099442e351a591145e9e400c8cce3561b7d9
|
brendonericlucas/project-euler
|
/archive-problems/problem7/problem7a.py
| 740 | 3.71875 | 4 |
import math
from itertools import compress
def sieve_of_eratosthenes(n):
"""
implements the sieve_of
eratosthenes; compare
the time complexity of
this function to the
function using trial
division in sol 3a
"""
is_prime = [True]*(n + 1)
is_prime[0] = False
is_prime[1] = False
bound = int(math.floor(math.sqrt(n)))
for i in range(2, bound + 1):
if is_prime[i] == True:
for j in range(i**2, n + 1, i):
is_prime[j] = False
return list(compress(range(len(is_prime)), is_prime))
def bound_nth_prime(n):
return math.ceil( n * ( math.log(n) + math.log(math.log(n)) ) )
print((sieve_of_eratosthenes(bound_nth_prime(10001))[10000]))
|
19a0b25920b206ea008ee041405eec09dbe4f2dc
|
Araym51/DZ_Algoritm
|
/Ostroumov_DZ_5/Ostroumov_DZ_5-2.py
| 3,497 | 4.03125 | 4 |
"""
2. Написать программу сложения и умножения двух шестнадцатеричных чисел.
При этом каждое число представляется как массив, элементы которого это цифры числа.
Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно.
Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’].
"""
a = input('введите первое шестнадцатеричное число')
b = input('введите второе шестнадцатеричное число')
def sixteen_to_ten(x):
"""
Функция принимает строку, формирует из неё массив символов,
сверяет символы со словарем hexnumber и возращает число в десятичной системе
эквивалентное ранее заданному шестнадцеричному
:param x: строка символов шестнадцеричного числа
:return: число в десятиричной системе счисления эквивалентное введенному шестнадцеричному
"""
hexnumber = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
z = 0
arr = []
for item in x: # формируем массив из введенных пользователем символов
arr.append(item.upper())
i = len(arr) - 1
for item2 in arr: # просматриваем символы
for k, v in hexnumber.items(): # сверяемся с символами в словаре
if k == item2:
x = hexnumber[k]
y = x * (16 ** i)
z += y
i -= 1
return z
def ten_to_sixteen(result): # использование функции hex тут не является читерством?
"""
Функция принимает число в десятиричной форме, преобразовывает его в шестнадцеричный формат
и возвращает массив из полученных символов
:param result: исло в десятиричной форме
:return: массив из символов шестнадцеричных чисел
"""
arr = []
temp = hex(result)
for item in temp[2:]:
arr.append(item.upper())
return arr
result_sum = sixteen_to_ten(a) + sixteen_to_ten(b)
result_multiplication = sixteen_to_ten(a) * sixteen_to_ten(b)
print(f'результат сложения {a} и {b}:\n{ten_to_sixteen(result_sum)}')
print(f'результат умножения {a} и {b}:\n{ten_to_sixteen(result_multiplication)}')
# сверка с параметрами из задачи:
c = ['A', '2']
d = ['C', '4', 'F']
result_sum = sixteen_to_ten(c) + sixteen_to_ten(d)
result_multiplication = sixteen_to_ten(c) * sixteen_to_ten(c)
print(f'результат сложения {c} и {d}:\n{ten_to_sixteen(result_sum)}')
print(f'результат умножения {c} и {d}:\n{ten_to_sixteen(result_multiplication)}')
|
353046578d02f9bb00200c28cb23599a84fb3884
|
destructor0/destructor0
|
/is_primenumber.py
| 484 | 4.21875 | 4 |
while True:
a = int(input("Enter a number you want to check is prime number or not: \n"))
def is_prime(a):
if a%a==0 and a<10 and a/4!=1 and a/6!=1 and a/9!=1 and a/8!=1:
print(f"{a} is a prime number")
elif a%a==0 and a%2!=0 and a%3!=0 and a%4!=0 and a%5!=0 and a%6!=0 and a%7!=0 and a%8!=0 and a%9!=0:
print(f"{a} is a prime number")
else:
print(f"{a} is not a prime number")
is_prime(a)
|
24119635301ba517509b11b9f8320b6ce6c37694
|
gksheethalkumar/Python_Practice
|
/beersong.py
| 366 | 3.953125 | 4 |
word = "bottles"
for num in range(99,0,-1):
print(num, word, "of beer on the wall")
print(num, word, "of beer")
print("take one down")
print("pass it worund")
if num == 1:
print("no more bottles")
else:
num -= 1
if num == 1:
word = "bottle"
print(num, word, " of beer on the wall")
print()
|
ace6e8569c9636fc12f49423a8746cc11b7e3036
|
2324593236/MyPython
|
/练习项目/逢7拍桌子.py
| 780 | 4.28125 | 4 |
# _*_ coding utf-8 _*_
# 开发团队:HS黄舍
# 开发人员:Administrator
# 开发项目:Python Study
# 开发时间:日期:2020/11/27 时间:19:48
# 文件名称:逢7拍桌子.py
# 开发工具:PyCharm
i = range(1,100)#建立1-99数字
count = 0
for x in i :
if x%7 == 0:#遍历到7的倍数时
print("啪")
count +=1#拍桌子次数加一
continue#跳出本次小循环,进入下一次循环
elif str(x).startswith("7"):#遍历到开头是7的数时
print("啪")
count +=1
continue
elif str(x).endswith("7"):#遍历到结尾是7的数时
print("啪")
count +=1
continue
else:
print(x)
continue
print("拍桌子的次数为:",count)
|
d146faf4ec2432c8b9db0e814ba6407a440b22db
|
AnastasioNieves/Python-
|
/Cursos/Mastermind/Cualestuedad.py
| 395 | 3.75 | 4 |
edad = int(input("¿ Que edad tiene? "))
tipo_carnet = input("digame su tipo de carnet (E para estudiante / P pensionista / F familia numerosa / N para ninguno) " )
if (edad <= 35 and edad >= 25 and tipo_carnet == "E") or edad < 10 or (edad > 65 and tipo_carnet == "P") or (tipo_carnet == "F"):
print("se te ha aplicado el descuento")
else:
print("no se te aplica el descuento")
|
fcae6eab4a894859eb4fb987f69f3bfbc35c8f1b
|
bottleling/scratches
|
/IsTreeSymmetric.py
| 3,024 | 3.71875 | 4 |
class Tree(object):
def __init__(self, x):
self.value = x
self.left = None
self.right = None
def buildtree(treedict):
if treedict is None:
return None
keys = treedict.keys()
tree = Tree(treedict["value"])
tree.left = None
tree.right = None
if "left" in keys:
tree.left = buildtree(treedict["left"])
if "right" in keys:
tree.right = buildtree(treedict["right"])
return tree
## Non-recursive
def isTreeSymmetric_nonrec(t):
if t == None:
return True
storage = []
storage.append((t.left, t.right))
while storage:
a, b = storage.pop()
if (a == None and b != None) or (a != None and b == None):
return False
if not (a == None and b == None):
if a.value != b.value:
return False
storage.append((a.left, b.right))
storage.append((a.right, b.left))
return True
def isLeaf(a):
return a.left is None and a.right is None
def isTreeSymmetric(t):
if isLeaf(t):
return True
return isMirror(t.left, t.right)
def isMirror(a,b):
if a is None and b is None:
return True
elif (a is None) != (b is None) :
return False
if a.value != b.value:
return False
return isMirror(a.left, b.right) and isMirror(a.right, b.left)
def main():
d1 = {
"value": 1,
"left": {
"value": 2,
"left": {
"value": 3,
"left": None,
"right": None
},
"right": {
"value": 4,
"left": None,
"right": None
}
},
"right": {
"value": 2,
"left": {
"value": 4,
"left": None,
"right": None
},
"right": {
"value": 3,
"left": None,
"right": None
}
}
}
d2 = {
"value": 1,
"left": {
"value": 2,
"left": None,
"right": {
"value": 3,
"left": None,
"right": None
}
},
"right": {
"value": 2,
"left": None,
"right": {
"value": 3,
"left": None,
"right": None
}
}
}
d3 = {
"value": 1,
"left": {
"value": 2,
"left": {
"value": 3,
"left": None,
"right": None
},
"right": {
"value": 4,
"left": None,
"right": None
}
},
"right": {
"value": 2,
"left": {
"value": 4,
"left": None,
"right": None
},
"right": {
"value": 3,
"left": None,
"right": None
}
}
}
# test1 = buildtree(d1)
# print(isTreeSymmetric(test1))
test2 = buildtree(d2)
print(isTreeSymmetric(test2))
test3 = buildtree(d3)
print(isTreeSymmetric(test3))
if __name__ == '__main__':
main()
|
4452dae5d2de7395735227d9515de3b45ff09654
|
MorhaliukOL/python_workout
|
/ex_1.py
| 938 | 4.125 | 4 |
import random
def get_int_input() -> int:
"""
Take input from user and convert it to integer.
If user input cannot be converted to int, ask user to try again
"""
# Fix 'int '-like inputs (with trailing spaces) !!!
num_str = input('>')
try:
num = int(num_str)
return num
except ValueError:
print(f'Please enter number, not {num_str}.')
get_int_input()
def guessing_game():
"""
Ask user to guess random number from 0 to 100
"""
number = random.randint(0, 100)
print('Enter number from 0 to 100 (inclusive)')
while True:
guess = get_int_input()
if guess == number:
print(f'Congratulation your guess is correct -- {number}')
input()
break
elif guess < number:
print('Too low')
else:
print('Too high')
if __name__ == '__main__':
guessing_game()
|
06cfeba0d268f8408d7475bb135dd98143871c15
|
IsseW/Python-Problem-Losning
|
/Uppgifter/3/3.15.py
| 772 | 4.21875 | 4 |
"""
Övning 3.15 - Omvänd uppslagning
Skriv en funktion reverse_lookup(dictionary, value) som tar in en dictionary och ett värde som argument och returnerar en sorterad lista med alla
nycklar som är associerade med det värdet. Funktionen ska returnera en tom lista om man inte får någon träff.
>>> reverse_lookup({'a':1, 'b':2, 'c':2}, 1)
['a']
>>> reverse_lookup({'a':1, 'b':2, 'c':2}, 2)
['b', 'c']
>>> reverse_lookup({'a':1, 'b':2, 'c':2}, 3)
[]
"""
def reverse_lookup(dictionary, value):
l = []
for k in dictionary:
if dictionary[k] == value:
l.append(k)
return l
print(reverse_lookup({"a": 1, "b": 2, "c": 2}, 1))
print(reverse_lookup({"a": 1, "b": 2, "c": 2}, 2))
print(reverse_lookup({"a": 1, "b": 2, "c": 2}, 3))
|
9189af8da8a59718f850591c46559b3d06ad5208
|
rahdirs11/Geekster
|
/Contests/28Feb/goodPairs6.py
| 675 | 3.671875 | 4 |
'''
Given an array of integers nums.
A pair (i,j) is called good if nums[i] == nums[j] and i < j.
Find the number of good pairs.
Input Format
first line contain N, no of elements in nums arrays. Second line contain Array elements
Constraints
1<=N<=1000 1<=Ai<=1000
Output Format
Print desired output
Sample Input 0
6
1 2 3 1 1 3
Sample Output 0
4
'''
from typing import List
def goodPairs(array: List[int]) -> int:
pairs = 0
for i in range(len(array)):
for j in range(i + 1, len(array)):
if array[i] == array[j]:
pairs += 1
return pairs
if __name__ == '__main__':
n = int(input())
array = [int(x) for x in input().split()]
print(goodPairs(array))
|
7aa00b18bbb5d693187b09532cd35aec6aa692c2
|
Amazinggggg/-
|
/性格分析.py
| 8,735 | 3.78125 | 4 |
# /usr/bin/python
# coding: utf-8
from tkinter import *
import math
# 按键返回函数
def call(num):
global content2
if num == 'A型':
content = display.get() + num
content2 = content2 + '+3'
display.set(content)
elif num == 'B型':
content = display.get() + num
content2 = content2 + '+5'
display.set(content)
elif num == 'AB型':
content = display.get() + num
content2 = content2 + '+7'
display.set(content)
elif num == 'O型':
content = display.get() + num
content2 = content2 + '+11'
display.set(content)
elif num == '1':
content = display.get() + num
content2 = content2 + '1'
display.set(content)
elif num == '2':
content = display.get() + num
content2 = content2 + '2'
display.set(content)
else:
content = display.get() + num
content2 = content2 + '+'+ num
display.set(content)
# 使用eval 函数计算
def calculate():
global content2
content = display.get()
result = eval(content2)
n = result % 9
if n == 0:
content3 = '坚持原则。做事有自己的一套方式,不轻易受人影响,' + '\n' +\
'不会随波逐流。有个人风格是件好事,尤其是懂得择善' + '\n' +\
'固执更能减少出错,不过适当时候选一些适当的事情与' + '\n' +\
'人协调,增进一下人际关系也无妨呀!'
display.set(content + '的分析结果:\n' + content3)
elif n == 1:
content3 = '重情重义。你价值观通常以人为先,认为人与人之间的' + '\n' +\
'和谐关系和感情是最重要的,平日也乐于助人,许多事' + '\n' +\
'都没所谓,给人随和易相处的感觉。要小心别感情用事' + '\n' +\
'否则就会令处事上有不公正的盲点。'
display.set(content + '的分析结果:\n' + content3)
elif n == 2:
content3 = '决断洒脱。做事话一就一,拖泥带水犹豫不决不是你的' + '\n' +\
'作风,面对工作或感情事的时候都一样。你自己决断的' + '\n' +\
'同时,也难忍受别人拖拉,看见别人迟疑不决,你会忍' + '\n' +\
'不住爽快地替他作决定。'
display.set(content + '的分析结果:\n' + content3)
elif n == 3:
content3 = '随和顺人。由于你甚么都没所谓,所以很少会与人起冲' + '\n' +\
'突,而随和的个性亦为你带来许多好朋友,并且深得他' + '\n' +\
'们喜爱。不过有时过分迁就他人可能会失去自己个性,' + '\n' +\
'如果能够适当地保留一点自我就更完美啦!'
display.set(content + '的分析结果:\n' + content3)
elif n == 4:
content3 = '喜当领导。你工作无疑会很努力,但待人处世则少不免' + '\n' +\
'带点支配欲,有时更可能为了一份凌驾他人的优越感而' + '\n' +\
'好胜逞强。事业上的攀升固然重要,但与人相处之道亦' + '\n' +\
'不可忽略,尝试在个人提升及人际关系间稍作平衡吧。'
display.set(content + '的分析结果:\n' + content3)
elif n == 5:
content3 = '心坚志毅。你意志坚定不移,做事一旦确立了目标,从' + '\n' +\
'不会因小阻滞而半途而废,不达终点不会放弃。每次忘' + '\n' +\
'我地完成手上工作后,不妨找些乐事让自己轻松一下,' + '\n' +\
'不要待薄自己呀!'
display.set(content + '的分析结果:\n' + content3)
elif n == 6:
content3 = '自强不息。你是个很低调、默默耕耘的人。别人眼中可' + '\n' +\
'能看不见你的成功,但成就不是为他人而干亦不是做给' + '\n' +\
'人看,即使无高职要位和金钱权力,充实的生活和自强' + '\n' +\
'不息就是你最好的财富和最大的成功。'
display.set(content + '的分析结果:\n' + content3)
elif n == 7:
content3 = '乐天知命。你可说是进取心不太强的人,凡事抱平常心' + '\n' +\
'看待,很少强求些甚么,对许多事情都不会执着。随遇' + '\n' +\
'而安是你的生活态度你大部分时间生活得颇开心。乐天' + '\n' +\
'知命当然令人活得轻松,但也不要容许自己太散漫呀!'
display.set(content + '的分析结果:\n' + content3)
elif n == 8:
content3 = '吊儿郎当。不过因为你个性比较「坐唔定」,三分钟热' + '\n' +\
'度经常要转换口味,所以所涉猎的知识虽广却不精。做' + '\n' +\
'事如果能够对某个项目专心发展,成绩或许会更好,不' + '\n' +\
'过知识广博始终对工作及生活方面有很大帮'
display.set(content + '的分析结果:\n' + content3)
else:
display.set('输入有错!请重新输入')
# 清空内容栏
def clear():
display.set('')
global content2
content2 = ''
# 删除前一个字符
def backspace():
display.set(str(display.get()[:-1]))
global content2
content2 = str(content2[:-1])
def main():
# 定义主窗口
global content2
content2 = ''
root = Tk()
root.title('性格分析器')
root.geometry('400x300+300+300')
# 将display定义成global,main() 函数外的call, calculate等可以调用
global display
display = StringVar()
# 设置内容显示栏,使用label,anchor是靠右,默认居中
label = Label(root, relief='sunken', borderwidth=3, anchor=SW)
label.config(font=14,bg='white', width=49, height=5)
label['textvariable'] = display
label.grid(row=1, column=0, columnspan=6)
label1 = Label(root, text='请按 年月日血型 输入,如 19970101A型 ')
label1.config(font=16,bg='grey', width=50, height=1)
label1.grid(row=0, column=0, columnspan=6)
# text = Text(root, relief = 'sunken', borderwidth = 3)
# text.insert(INSERT, str(display))
# text.grid(row = 0, column = 0, columnspan = 4)
# 添加各个按钮,并绑定行为,使用lambda很方便,是用的是grid布局
Button(root, text='C', fg='#EF7321', width=3, padx=16, pady=16, command=lambda: clear()).grid(row=2, column=5)
Button(root, text='DEL', width=3, padx=16, pady=16, command=lambda: backspace()).grid(row=3, column=5)
Button(root, text='7', width=3, padx=16, pady=16, command=lambda: call('7')).grid(row=3, column=1)
Button(root, text='8', width=3, padx=16, pady=16, command=lambda: call('8')).grid(row=3, column=2)
Button(root, text='9', width=3, padx=16, pady=16, command=lambda: call('9')).grid(row=3, column=3)
Button(root, text='4', width=3, padx=16, pady=16, command=lambda: call('4')).grid(row=2, column=3)
Button(root, text='5', width=3, padx=16, pady=16, command=lambda: call('5')).grid(row=2, column=4)
Button(root, text='6', width=3, padx=16, pady=16, command=lambda: call('6')).grid(row=3, column=0)
Button(root, text='1', width=3, padx=16, pady=16, command=lambda: call('1')).grid(row=2, column=0)
Button(root, text='2', width=3, padx=16, pady=16, command=lambda: call('2')).grid(row=2, column=1)
Button(root, text='3', width=3, padx=16, pady=16, command=lambda: call('3')).grid(row=2, column=2)
Button(root, text='A型', width=3, padx=16, pady=16, command=lambda: call('A型')).grid(row=4, column=0)
Button(root, text='B型', width=3, padx=16, pady=16, command=lambda: call('B型')).grid(row=4, column=1)
Button(root, text='AB型', width=3, padx=16, pady=16, command=lambda: call('AB型')).grid(row=4, column=2)
Button(root, text='O型', width=3, padx=16, pady=16, command=lambda: call('O型')).grid(row=4, column=3)
Button(root, text='=', width=12, bg='#EF7321', padx=16, pady=16, command=lambda: calculate()).grid(row=4, column=4, columnspan=2)
Button(root, text='0', width=3, padx=16, pady=16, command=lambda: call('0')).grid(row=3, column=4)
root.mainloop()
if __name__ == '__main__':
main()
|
d52d53973e9d61efbf4b2939cd7f3c3f7e081a67
|
VioletZhdanova/backend_python
|
/task2.py
| 471 | 3.9375 | 4 |
import re
#Регулярное выражение
pattern = r"[АВЕКМНОРСТУХ]\d{3}[АВЕКМНОРСТУХ]{2}\d{2,3}"
#Пример для теста (Важно, что перечислены русские буквы)
numbers = ["А123АА11", "А222АА123", "А12АА123", "А123СС1234", "АА123А12","О123ОО59","а123аа59"]
answer = list()
for i in numbers:
if re.fullmatch(pattern, i):
answer.append(i)
print(answer)
|
c60e305dce1f7659a7037a686120e8af58d03fc8
|
TUdayKiranReddy/Voice_Controlled_bot
|
/data_set/codes/rename.py
| 392 | 3.71875 | 4 |
# Pythono3 code to rename multiple
# files in a directory or folder
# importing os module
import os
# Function to rename multiple files
path = '/media/solomon/Apps/AI and ML/Audio_Dataset/right'
files = os.listdir(path)
print(enumerate(files))
for index, file in enumerate(files):
os.rename(os.path.join(path, file), os.path.join(path, ''.join(['right'+str(index+1), '.wav'])))
|
12cfb12e447c948514226443fd6c0fafb238e6ed
|
shubhamagrawal7/ViolentPython
|
/UnixPasswordCracker.py
| 1,690 | 3.609375 | 4 |
import argparse
import crypt
class UnixPwdCrack:
def __init__(self):
# Parsing Shadow file
open_shadow = open('shadow.txt', 'r')
self.shadow_file = {}
for line in open_shadow:
comps = line.split(":")
self.shadow_file[comps[0]] = comps[1]
def parse_password(self, args):
# Parsing password for the asked username
if args.username in self.shadow_file:
password = self.shadow_file[args.username].split('$')
if password[1] == '*' or password[1] == 'x' or password[1] == '!':
print('No password found')
exit(0)
wordlist = open(args.wordlist, 'r')
for word in wordlist:
cryptpass = crypt.crypt(word, f"${password[1]}${password[2]}$")
if cryptpass == self.shadow_file[args.username]:
print(f"Password Found: {word}")
exit(0)
else:
print("The requested username was not found in the system. Please try another username !!")
exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='This tool helps in cracking Unix Passwords. '
'Do note to run this tool you need to be a root user because shadow '
'file cannot be accessed from a normal user')
parser.add_argument('-u', '--username', dest='user', help='Enter the username to crack')
parser.add_argument('-w', '--wordlist', help='Enter the wordlist file name')
args = parser.parse_args()
cracker = UnixPwdCrack()
cracker.crack(args)
|
301c421ef05c3554b6934fb7fee0fcbc3cd98a8c
|
tina8860035/yzu_python
|
/Lesson02/case08.py
| 113 | 4.0625 | 4 |
# -*- coding:UTF-8 -*-
n = int(input("請輸入數字"))
odd = n % 2 ==0
print('%d是偶數嗎? %s' % (n, odd))
|
d23a1e54efcb3fdb1f47c55d83ba5bcdaccd264a
|
mestre204os/Python-Curso_em_video
|
/LIções/010.py
| 847 | 3.703125 | 4 |
from random import randint
import time
itens = ('Pedra', 'Papel', 'Tesoura')
jogador = int(input('''Qual é a sua jogada?
[0] Pedra
[1] Papel
[2] Tesoura
'''))
time.sleep(1)
print('JO')
time.sleep(1)
print('KEN')
time.sleep(1)
print('PÕ')
computador = randint(0,2)
print('-=-' * 11)
print('Computador escolheu {}'.format(itens[computador]))
print('-=-' * 11)
if computador == 0:
if jogador == 0:
print('Empate')
elif jogador == 1:
print('Você venceu.')
else:
print('Você perdeu.')
elif computador == 1:
if jogador == 1:
print('Empate')
elif jogador == 2:
print('Você venceu.')
else:
print('Você perdeu.')
elif computador == 2:
if jogador == 2:
print('Empate')
elif jogador == 0:
print('Você venceu.')
else:
print('Você perdeu.')
|
d596a10eb0d923153348bc3bf318ce21d1ed41bf
|
yooseungju/TIL
|
/Algorithm_class02/IM/sort.py
| 1,847 | 3.609375 | 4 |
import sys
sys.stdin =open('input.txt')
# 버블정렬: n**2시간 복잡도, 원하는 갯수만큼 정렬하고 싶다면 회전수를 정하면됨
def bubbleSort(x):
#정렬할 대상과 회전수
for i in range(len(x)-1):
#비교 대상들
for j in range(i+1, len(x)):
if x[i] > x[j]:
x[i], x[j] = x[i] , x[j]
# #이차정렬일 경우 안에다가 하나 넣어주면됨
# if x[i] == x[j]:
#퀵정렬: nlogn , 최악 n**2-절렬이 잘되어 있을경우
# pivot: 기준 , left 비교대상, target:교환할 대상
# 정렬대상의 시작과 끝이 필요
def quickSort(start, end, x):
if start >= end:
return
else:
pivot = end
target = start
for left in range(start, end):
if x[left] < x[pivot]:
x[target] , x[left] = x[left], x[target]
target += 1
x[target] , x[pivot] = x[pivot], x[target]
quickSort(start, target-1, x)
quickSort(target+1, end, x)
# 머지정렬: nlogn, 메모리를 N만큼 필요
def mergeSort(start, end, x):
if start >= end:
return
else:
mid = (start+end)//2
mergeSort(start, mid,x)
mergeSort(mid+1,end, x)
L, R, T = start, mid+1, start
while L <= mid and R <=end :
if x[L] < x[R]:
tmp[T] = x[L]
T+=1
L +=1
else:
tmp[T] = x[R]
T+=1
R +=1
while L <= mid:
tmp[T] = x[L]
T += 1
L += 1
while R <=end:
tmp[T] = x[R]
T += 1
R += 1
N = int(input())
x = list(map(int, input().split()))
quickSort(0,len(x)-1, x)
tmp = [0] * len(x)
for i in x:
print(i )
|
0551d706c9ce7ffbd7393a32ffd344241b9796dd
|
maguas01/hackerRank
|
/pStuff/SortingBubbleSort.py
| 1,057 | 4.1875 | 4 |
#!/bin/python
'''
Given an n element array A = a0, a1,...,a(n-1) fo distint elements, sort array A in ascending order using the
Bubble Sort algorithm above. Once sorted, print the following three line:
1. Arrays is sorted in numSwaps swaps, where numSwaps is the number of swaps that took place
2. First Element: firstElement, where firstElement is the first element in the sorted array
3. Last Element: lastElement, where lastElement is the last element in the sorted array
'''
import sys
def bubbleSort(a) :
numberOfSwaps = 0
for i in range(1, len(a)) :
for j in range(1, len(a)) :
if( a[j-1] > a[j] ) :
a[j-1], a[j] = a[j], a[j -1]
numberOfSwaps += 1
return numberOfSwaps
def main() :
n = int(raw_input().strip())
a = map(int, raw_input().strip().split(' '))
numberOfSwaps = bubbleSort(a)
print "Array is sorted in %d swaps." % numberOfSwaps
print "First Element: %d" % a[0]
print "Last Element: %d" % a[n-1]
if __name__ == "__main__" :
main()
|
e1e4520e7a382c4c4d244a19274f9216ed32c430
|
cloud0606/summer_semester
|
/Cloud/LearnPython/test/hello.py
| 1,012 | 4.28125 | 4 |
print('hello,world')
print('hello','python')
print("waht\'s your name?")
# 这是第一个python程序的注释
print('打印一个浮点:')
a = 6.6e6
print(a)
print("打印字符串:")
a = "穿着长衫"+","+"站着喝酒"+'。'
print(a)
print(r'他说"要一碟茴香豆"')
print(r'''
今天天气不错啊!
你看起来像一条"小鱼"
谢谢!^-^''')
print("2017 + 0x11 = ",2017 + 0x11)
print('\nlist的使用:')
friend = [1,'wzy',2,'xm',3,'xh']
print(friend)
print (friend[0],friend[1])
print (friend[-6],friend[-5])
friend.append(4)#默认在尾部插入
friend.append("xx")
print(friend)
friend.insert(0,"cloud")#添加索引插入
friend.insert(0, 0)
print(friend)
#frined.pop(2)
friend.pop()#尾部删除
friend.pop()
print(friend)
print('\ntuple的使用:')
#元组一旦创建,就不能修改
t = ('xh','xw')
print(t)
print(t[0])
t = (66,)#定义单元素的tuple
print(t)
print(t[0])
t = ('xh','xw',[66,33])
print(t)
t[2][0] = 33#元组一旦创建,指向不能修改
t[2][1] = 66
print(t)
|
5069af05ee55a5f14ba74370bf09fbdb71a8aebd
|
kecarrillo/monopoly
|
/Monopoly/Pawn.py
| 15,855 | 3.796875 | 4 |
import random
from Monopoly.Auction import Auction
from Monopoly.Owner import Owner
class Pawn(Owner):
"""
This class represents the avatar of the players.
"""
def __init__(self, name, money):
"""This method is the constructor of the class.
:param form: Form of the pawn.
:type form: string
:return: create a pawn.
:rtype: string
"""
super().__init__(name, money)
print(f'{self.form} créé.')
self.form = name
self.position = 0
self.turn = 0
self.money = money
self.jail_time = 0
self.free_card = 0
self.double = 0
self.debt = 0
self.possessions = []
self.possession = None
def __del__(self):
"""This method is the destructor of the class.
:return: String
:rtype: void
"""
print(f"Suppression de {self.form}.")
def salary(self):
"""
Method to get salary.
:return: void
.. todo:: Adding money limits
"""
# Bank.money = Bank.money - 20_000
self.money = self.money + 20_000
def roll_dice(self): # Roll dices
"""This method rolls 2 dices.
:return: Roll dices.
:rtype: void
"""
dice_1 = random.randrange(1, 6)
dice_2 = random.randrange(1, 6)
if self.jail_time < 1:
if dice_1 == dice_2:
self.double += 1
if self.double == 3:
self.go_to_jail()
else:
self.position = self.position + dice_1 * 2
if self.position > 39:
self.salary()
self.position = self.position - 40
self.roll_dice()
else:
self.position = self.position + dice_1 + dice_2
if self.position > 39:
self.salary()
self.position = self.position - 40
else:
self.is_jailed(dice_1, dice_2)
self.jail_time += 1
self.turn += 1
def get_money(self, amount):
"""This method allows the pawn to receive money.
:param amount: Money to receipt.
:type amount: integer
:return: Receipt money.
:rtype: void
"""
self.money = self.money + amount
def give_money(self, amount, owner):
"""This method allows the pawn to spend money.
:param amount: Money to give.
:type amount: integer
:param owner: Owner of the payment.
:type owner: Owner
:return: Give money.
:rtype: void
"""
self.money = self.money - amount
owner.money = owner.money + amount
def go_to_jail(self):
"""This method is used when a pawn go to jail.
:return: Buying ownership.
:rtype: void
"""
self.position = 10
if self.free_card > 0:
self.free_card -= 1
self.turn += 1
else:
self.jail_time = 1
self.turn += 1
def freed_from_jail(self):
"""This method is used when the pawn is freed from jail.
:return: ... .
:rtype: void
"""
self.jail_time = 0
def is_jailed(self, dice_1, dice_2):
"""This method allows the pawn to make some action in jail.
.. todo:: declarer la banque.
:return: Buying ownership.
:rtype: void
"""
bank = ...
if dice_1 == dice_2:
self.position = self.position + dice_1 * 2
self.jail_time = 0
self.roll_dice()
if self.give_money(5_000, bank):
self.jail_time = 0
self.roll_dice()
def is_penniless(self, creditor, give_up=False):
"""This method is used when the money's pawn is below 0.
:param creditor: The creditor of the pawn.
:type creditor: Owner
:param buildables: The Buildable of the player
:type list
:param give_up: If the pawn give up the game.
:type give_up: boolean
:return: Message.
:rtype: string
"""
amount = 0
for buildable in self.possessions:
if buildable.nb_hotel > 0:
amount += (buildable.hotel_price / 2) + \
((buildable.house_price / 2) * 4)
if buildable.nb_house > 0:
amount += (buildable.house_price / 2) * buildable.nb_house
amount += buildable.mortgage_price
amount += self.money
if amount < 0:
print(f'{self.form} est ruiné!')
self.give_money(amount, creditor)
elif give_up is True:
print(f'{self.form} abandonne!')
self.give_money(amount, creditor)
else:
print("Rien n'est joué!")
def give_up(self, creditor):
"""This method is used when a player wants to give up the game.
:return: End of the game for the player
:rtype: string
"""
self.is_penniless(creditor, self.possessions, True)
def buy_ownership(self, ownership, owner):
"""This method allows the pawn to buy an ownership.
:param owner: The owner of the ownership.
:type owner: Owner
:param ownership: The ownership.
:type ownership: Ownership
:return: Buying ownership.
:rtype: void
"""
amount = ownership.price
self.give_money(amount, owner)
ownership.owner = self.form
self.possessions.append(ownership)
def buy_house(self, bank):
"""This method allows the pawn to buy a house.
:param owner: The bank.
:type owner: Owner
:param color: Color object which organize the ownerships.
:type buildable: Color
:param buildable: Ownership with a price.
:type buildable: Buildable
:return: Buying house.
:rtype: void
"""
self.choose_possession()
if self.possession.color is "colorless":
print("Ce terrain ne peut pas possèder de maison!")
else:
nb_same_color = len(
self.possession.groups[self.possession.color])
nb_total_house = 0
for ownership in self.possessions:
if ownership.color == self.possession.color:
nb_total_house += ownership.nb_house
if self.possession.owner is not self.form:
print("Vous devez être le propriétaire du terrain pour acheter"
" des maisons!")
self.possession = None
else:
max_house = round(nb_same_color/nb_total_house) + 1
if max_house < self.possession.nb_house:
amount = self.possession.house_price
self.give_money(amount, bank)
self.possession.nb_house += 1
self.possession = None
elif self.possession.nb_house == 4:
print("Nombre maximal de maison atteinte!")
self.possession = None
else:
print("Le nombre de maison sur les terrains de même "
"couleurs doivent être identiques!")
self.possession = None
def buy_hotel(self, bank):
"""This method allows the pawn to buy a hotel.
:param owner: The bank.
:type owner: Owner
:param color: Color object which organize the ownerships.
:type buildable: Color
:param buildable: Ownership with a price.
:type buildable: Buildable
:return: Buying hotel.
:rtype: void
"""
self.choose_possession()
if self.possession.color is "colorless":
print("Vous ne pouvez pas bâtir d'hôtel sur ce terrain.")
self.possession = None
elif self.possession.owner is not self.form:
print("Vous devez être le propriétaire du terrain pour acheter"
" un hotel!")
self.possession = None
else:
nb_same_color = len(
self.possession.groups[self.possession.color] )
if self.possession.nb_house == nb_same_color * 4 \
and self.possession.nb_hotel < 1:
amount = self.possession.hotel_price
self.give_money(amount, bank)
self.possession.nb_hotel += 1
self.possession.nb_house = 0
self.possession = None
elif self.possession.nb_house == 4 \
and self.possession.nb_hotel > 0:
print("Vous ne pouvez construire qu'un seul hotel par "
"terrain!")
self.possession = None
else:
print("Vous ne possèdez pas le nombre de maisons requises!")
self.possession = None
def sell_hotel(self):
"""This method allows the pawn to sell a hotel he possess.
:param buildable: Ownership with a price.
:type buildable: Buildable
:return: Selling hotel.
:rtype: void
"""
self.choose_possession()
if self.possession.owner is not self.form:
print("Vous devez être le propriétaire du terrain pour vendre"
" un hotel!")
self.possession = None
else:
if self.possession.nb_hotel == 1:
amount = (self.possession.hotel_price / 2) + \
((self.possession.house_price / 2) * 4)
self.get_money(amount)
self.possession.nb_hotel = 0
self.possession = None
else:
print("Vous ne pouvez vendre que si vous possèdez un hotel!")
self.possession = None
def sell_house(self):
"""This method allows the pawn to sell a house he possess.
:param color: Color object which organize the ownerships.
:type buildable: Color
:param buildable: Ownership with a price.
:type buildable: Buildable
:return: Selling house.
:rtype: void
"""
self.choose_possession()
if self.possession.owner is not self.form:
print("Vous devez être le propriétaire du terrain pour vendre"
" des maisons!")
self.possession = None
else:
nb_same_color = len(
self.possession.groups[self.possession.color] )
nb_total_house = 0
for ownership in self.possessions:
if ownership.color == self.possession.color:
nb_total_house += ownership.nb_house
max_house = round(nb_same_color/nb_total_house) + 1
if max_house == self.possession.nb_house:
amount = self.possession.house_price / 2
self.get_money(amount)
self.possession.nb_house -= 1
self.possession = None
elif self.possession.nb_house == 0:
print("Nombre maximal de maison vendues atteinte pour ce "
"terrain!")
self.possession = None
else:
print("Le nombre de maison sur les terrains de même "
"couleurs doivent être identiques!")
self.possession = None
def make_mortgage(self):
"""This method is used to make mortgage.
It permits the pawn to mortgage his ownership and to contract a debt.
:param ownership: The ownership of the pawn.
:type ownership: Ownership
:return: Make the mortgage.
:rtype: void
"""
self.choose_possession()
amount = self.possession.mortgage_price
self.get_money(amount)
self.possession.is_mortgaged = True
self.debt += amount
self.possession = None
def refund_mortgage(self, owner):
"""This method is used for the refund of mortgage.
It permits the pawn to catch back his ownership and be free of a debt.
:param ownership: The ownership of the pawn.
:type ownership: Ownership
:param owner: The bank.
:type owner: Owner
:return: Refund the mortgage.
:rtype: void
"""
self.choose_possession()
amount = self.possession.mortgage_price + \
self.possession.mortgage_price * 0.1
self.give_money(amount, owner)
self.possession.is_mortgaged = False
self.debt -= self.possession.mortgage_price
self.possession = None
def draw_card(self, deck, retry=False):
"""This method allows the pawn to draw a card.
:param deck: Instance of Card.
:type deck: Card
:param retry: When you choose to draw a card instead of paying.
:type retry: boolean
:return: Action of the drawn card.
:rtype: void
"""
community_fund_cells = [2, 17, 33]
if self.position in community_fund_cells and retry is False:
draw_card = deck.community_fund_cards.pop(0)
draw_card.action()
if draw_card.name is not "free_card":
deck.community_fund_cards.append(draw_card)
else:
draw_card.owner = self.form
self.free_card += 1
elif self.position in community_fund_cells and retry is True:
draw_card = deck.chance_cards.pop(0)
draw_card.action()
if draw_card.name is not "free_card":
deck.chance_cards.append(draw_card)
else:
draw_card.owner = self.form
self.free_card += 1
else:
draw_card = deck.chance_cards.pop(0)
draw_card.action()
if draw_card.name is not "free_card":
deck.chance_cards.append(draw_card)
else:
draw_card.owner = self.form
self.free_card += 1
def auction_sale(self):
"""This method allows the pawn to create an auction sale.
:param possession: The possession of the pawn.
:type possession: Object
:return: Alert.
:rtype: string
"""
if self.possession is not None:
if self.possession.owner == self.form:
print(f"{self.form} vend {self.possession} au plus offrant!")
min_bid = int(input("Quel est le prix minimum attendu?"))
if min_bid < 0:
print("Erreur: l'enchère minimum ne peut pas être "
"négative!")
else:
self.auction = Auction(self.possession, self.form, min_bid)
self.possession = None
else:
print("Vous devez être propriétaire du bien pour le mettre "
"aux enchères!")
self.possession = None
else:
print("Une enchère doit mettre en jeu une possession!")
def auction_bid(self, amount):
""" This method allows the pawn to make a bid in an auction sale.
:param amount:
:param possession:
:return:
"""
print(f"{self.form} enchérit à {amount}F!")
def choose_possession(self):
"""
This method allows the pawn to choose one of his possession.
:return: Choice of a possession.
:rtype: void
"""
possession = input(f'Choisissez une de vos possessions parmi \n'
f'{self.possessions}')
if possession.owner == self.form:
self.possession = possession
else:
self.choose_possession()
|
883d99978fe304f98203f1d0a633127cfe7bdd21
|
iknowed/units-convert
|
/node.py
| 1,303 | 4.09375 | 4 |
class Node(object):
"""
This module implements the Node class as a container
for edges to neighbor nodes.
"""
def __init__(self, name):
""" initialize node and set name """
self.name = name
self._edges = []
def _set_name(self, name):
self.name = name
def _number_of_edges(self):
""" return number of edges in this node """
if self._edges is None:
return 0
return len(self._edges)
def edges(self):
""" return edges for this node """
return self._edges
def neighbors(self):
""" return neighbors for this node """
return [e.name for e in self.edges()]
def add_edge(self, node):
""" adds an edge between this node and another node """
self._edges.append(node)
def remove_edge(self, name):
""" removes an edge from a node """
for edge in self._edges:
if edge.name == name:
self._edges.remove(edge)
def __str__(self):
res = ""
for edge in self._edges:
try:
res = res + edge
res = res + "{0}, {1}".format(edge.name, edge.edges())
except Exception as exception:
exception = None
return res
|
bc4011ac60e86b1dd19772eca0793dcc723415a2
|
EJChavez/challenges
|
/Exercises/SuperList.py
| 273 | 3.96875 | 4 |
class SuperList(list): # this is how you use inheritance to get all the stuff from the object class
def __len__(self):
return 1000
super_list1 = SuperList()
print(len(super_list1))
super_list1.append(5)
print(super_list1[0])
print(issubclass(SuperList, list))
|
cb4afefeba1f69736a6c1e3b7f6bbafbb2d43e9c
|
tawrahim/Taaye_Kahinde
|
/Kahinde/chp5/repython/additionprogram.py
| 353 | 3.9375 | 4 |
print"I will ask you to type in 2 numbers so I can add them together for you."
addend=int(raw_input("What is your first addend?"))
second=int(raw_input("What is your second addend?"))
print "You entered,",addend,"for your first addend."
print "And you entered,",second,"for your second addend."
answer=addend+second
print "The answer is,",answer
|
ef7868cf2ce1f3dbb22bfa65b2e5454bd94daa25
|
berlyncast/python3
|
/ejercicios_progra/ejer8.py
| 837 | 3.578125 | 4 |
#escriba un algoritmo que dada la cantidad de monedas de 5-10-12-,5-25-50 cent
#y bolivar, dega la cantidad de dinero que se tiene en total
monedas1 = 0
monedas2 = 0
monedas3 = 0
monedas4 = 0
monedas5 = 0
monedas6 = 0
tot1 = 0
tot2 = 0
tot3 = 0
tot4 = 0
tot5 = 0
tot6 = 0
total = 0
monedas1 = int(input("ingrese monedas de 5:."))
tot1 = monedas1 * 0.05
monedas2 = int(input("ingrese monedas de 10:."))
tot2 = monedas2 * 0.10
monedas3 = int(input("ingrese monedas de 12,5:."))
tot3 = monedas3 * 0.125
monedas4 = int(input("ingrese monedas de 25:."))
tot4 = monedas4 * 0.25
monedas5 = int(input("ingrese monedas de 50:."))
tot5 = monedas5 * 0.50
monedas6 = int(input("ingrese monedas de 1 bolivar:."))
tot6 = monedas6 * 1
total = tot1 + tot2 + tot3 + tot4 + tot5 + tot6
print("la cantidad total de dinero que se tiene es de:.",total)
|
9101dbb722c7dcfacc2dfe3103ac052074484ed9
|
swcide/algorithm
|
/week_1/01_01_find_max_num.py
| 731 | 4 | 4 |
input = [3, 5, 2, 3, 4, 6, 1, 2, 4]
def find_max_num(array):
a = max(array)
for i in array:
for j in array:
'''
i의 값이 j보다 작다면 break
j의 값이 더 크다면 계속해 반복.
for else.
if 문 안의 값이 break가 아닐 시 else를 출력함.
'''
if i < j:
print(i, ": i", j, ":j")
'''
3 : i 5 :j
5 : i 6 :j
2 : i 3 :j
3 : i 5 :j
4 : i 5 :j
'''
break
else:
print(i, "else")
return i
result = find_max_num(input)
print(result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.