blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
8d91cdb6a5887f6dfa678c5bd737a2b81250b333 | KabsaA/tweet-generator | /frequency.py | 1,861 | 3.671875 | 4 | import sys
import random
import string
from numpy.random import choice
def histogram(fileName):
textFile = open(fileName, "r")
fileLines = textFile.readlines()
histogram = {}
for line in fileLines:
for word in line.split():
# strip punctuation/capitals
i = word.lower().translate(
str.maketrans('', '', string.punctuation))
if i in histogram:
histogram[i] = histogram[i] + 1
else:
histogram[i] = 1
return histogram
def unique_words(fileName):
return len(histogram(fileName))
def frequency(fileName, target):
return histogram(fileName)[target]
def sample(fileName):
return random.choice(list(histogram(fileName).keys()))
def words1(fileName, sampleCount=1):
hist = histogram(fileName)
# number of (total, not unique, words)
word_count = 0
for key in hist:
word_count += hist[key]
probability_list = []
for key in hist:
probability_list.append(hist[key]/word_count)
weighted_choice = choice(list(histogram(fileName).keys()), sampleCount,
p=probability_list)
# print(list(histogram(fileName).keys()))
# print(probability_list)
return weighted_choice
def sentence(fileName, word_count=9, sentenct_structure=True):
"""weighted sampling"""
phrase = ""
words = words1(fileName, word_count)
for word in words:
phrase += word + " "
phrase = phrase.strip()
if sentenct_structure:
phrase = phrase.capitalize()
phrase += "."
return phrase
if __name__ == '__main__':
# print(unique_words(str(sys.argv[1])))
print(frequency(str(sys.argv[1]), str(sys.argv[2])))
print(sample(str(sys.argv[1])))
print(words1(str(sys.argv[1])))
test_weight(str(sys.argv[1]), 200000)
|
35c32a0db91590633ef6e92e1f2a03c1dc14c685 | qmppz/leetcode-and-jianzhi_offer | /jianzhi-offer-斐波那契数列.py | 707 | 3.953125 | 4 | '''
jianzhi-offer 斐波那契数列
https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tqId=11160&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
'''
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
'''
递归肯定不行
f = [0,1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
return f[n]
'''
'''
方法二:节省空间法
只用两个变量
'''
if n<=1:return n
now, last=1,0
for i in range(2,n+1):
now += last
last = now - last
return now
|
39c8c9677a91de1817453085c3510e26db71302d | SuguruChhaya/python-tutorials | /Data Structures and Algorithms/mergesortiter.py | 2,970 | 4.125 | 4 | #Actual iterative merge sort code based on C++ code.
#I will first follow the C++ code completely and make tweeks of my own.
def merge(arr, arrEmpty, l, m, r, size):
#Pointers: similar to previous merging methods.
a = l
#Beginning of second subarray
b = m + 1
#Beginning of big array (very similar to previous method. )
c = l
'''
if arrEmpty[m] <= arr[m+1]:
while a < m+1:
arr[c] = arrEmpty[a]
a+=1
b+=1
c+=1
'''
while a < m+1 and b <r+1:
if arr[a] <= arr[b]:
arrEmpty[c] = arr[a]
a+=1
else:
arrEmpty[c] = arr[b]
b+=1
c+=1
while a < m+1:
arrEmpty[c] = arr[a]
a+=1
c+=1
while b < r+1:
#I am not yet accomodating for only 1 side copying.
arrEmpty[c] = arr[b]
b+=1
c+=1
def merge_pass(arr, arrEmpty, size, lenArr):
#Unlike the C++ code, I will only define 3 variables: l, m, and r
l = 0
while l + size < lenArr:
#This is the part where we figure out all the indices.
m = l + size - 1
#Don't need for low2
r = m + 1 + size - 1
if r >=lenArr:
r = lenArr-1
merge(arr, arrEmpty, l, m, r, size)
l = r+1
#All the subarrays in the original list has been merged at this point. Now we copy it back to the original. But I have no idea what is going on right here.
#I understand why the value of l will be so large. It is because it has been incremented a lot to the point that l+size<lenArr.
#Also, it's funny how when stepping through code, the stepper bases off lines and if I add comments it will get confused.
print(f"lenArr: {lenArr}")
print(f"arr: {arr}")
print(f"arrEmpty: {arrEmpty}")
print(f"l: {l}")
#The next for loop is pretty much for the case when we have an odd number of sublists and we have 1 sublist that won't
#be merged that round. The pointer l will be pointing to the beginning item of the un-merging sublist. We shouldn't do anything
#to that sublist for that round so we can just copy it from the original to the arrEmpty. This is important because we are copying
#the entire arrEmpty array into the arr next round, so we want to make sure arrEmpty has all the correct values.
for i in range(l, lenArr):
print(f"i: {i}")
arrEmpty[i] = arr[i]
print(f"lenArr: {lenArr}")
print(f"arr: {arr}")
print(f"arrEmpty: {arrEmpty}")
print(f"l: {l}")
for j in range(0, lenArr):
print(f"j: {j}")
arr[j] = arrEmpty[j]
def mergesort(arr):
#I will need a temporary list to store processes.
lenArr = len(arr)
arrEmpty = [0] * lenArr
subArraySize = 1
while subArraySize < lenArr:
merge_pass(arr, arrEmpty, subArraySize, lenArr)
subArraySize *= 2
arr = [5, 2, 4, 1, 84, 2, 5, 2]
mergesort(arr)
print(arr)
|
d365b935f9e5c39e6b2c9730df16f5e7671614c8 | cristinae/fairseq | /scripts_clean_sb/reduce_caps.py | 825 | 4.125 | 4 | """
This script lowercases sentences that are completely written in caps (don't contain 3 small letters in a row).
Acronyms and sentences only partially written in caps remain unchanged.
Lowercasing of caps sentences is important for the language detection.
Author: Damyana Gateva
"""
import os
import re
def process_file_lc(inF, outF):
pattern = re.compile('[a-zäöüß]{3,}')
patt2 = re.compile('[A-ZÄÖÜ]')
curr = 0
lower = 0
with open(inF) as f, open(outF, 'w') as fOUT:
for line in f:
curr += 1
#line = line.strip()
if (re.search(pattern, line) == None) and (re.search(patt2, line) != None):
line = line.lower()
lower +=1
fOUT.write(line)
print("Lowercased {} sentences in {}".format(lower, inF))
|
bab68d3bdcd601264e7ae3810ed41aa15cdd2e8c | Seraphineyoung/module2 | /ch09 - List_and_Tuples/ch09_seraphine.py | 2,713 | 4.15625 | 4 |
#####################Task 1 #############################
#Create a list
my_favourite_fruits = ['apple','orange','banana']
x = ['this',55,'that',my_favourite_fruits]
print(x[0])
print(x[:])
#####################Task 2 #############################
#Modify a list
x.remove(my_favourite_fruits)
x[1] = 'and'
x.append('again')
print(x)
print(x[::-1])
print(x[::1])
print(x[-3::])
#List operations
x = ['the','cat','sat']
y = ['on','the','mat']
#this prints none because the append and extend functions does not have the return key word
a = x.extend(y)
b = y.append(x)
#this merges the 2 arrays in a new array keeping its original array brackets
print(y)
#this merges the 2 arrays in a new array and removed the brackets seperating the two arrays, so one big array
print(x)
#this creates a new list with x and y in one array
z = x + y
print(z)
z = x * 3
print(z)
#set function removes duplicate values and changes the data type to dictionaries. In dictionaries the keys has to uniques
print(set(z))
############################ Task3 #################################
#Slicing a List
b = ['the','cat','sat','hair','food','skin','care']
#starts from 1 to n-1, so to 4-1 which is index 3
print(b[1:4])
print(b[3:5])
print(b[-1::-1])
print(b[-3:-1])
############################ Task4 #################################
#SORT AND SORTED
x = [5,3,8,1,6,0,1,2,5]
#SORTED DOES NOT MUTATE X
y = sorted(x)
print(y)
print(x)
##this prints none as the sort() returns nothing, but x is mutated.
print(x.sort())
#prints out the mutated version
print(x)
#REVERSE SORT
x = [5,3,8,1,6,0,1,2,5]
y= ['the','cat','sat','hair','food','skin','care']
print(sorted(x))
print(sorted(x,reverse=True))
print(sorted(y,reverse=True))
print(sorted(y,reverse=False))
print(x[::-1])
print(x[:-2])
print(x[-3::])
################################Task 5 #############################
#CREATING A TUPLES
a = (5,3,8,1,6,0,1,2,'edem')
print(a[-1][-1])
#To change a data types you can cast Tuples to List and back to Tuple
b =list(a)
#tuples cant be added to or changed.
#del a[-1]
#
#print(a)
#
#a.append('z')
print(a)
b.append('seraphine')
print(b)
#####################Task 6 #############################
######LAMBDA FUNCTION######
a = [0,1,2,3,4,5,6,7,8,9]
b = (0,1,2,3,4,5,6,7,8,9)
x = ['the','cat','sat' ,'sun','york']
myFavF = ["apple", "orange", "banana",""]
x = ["zz", "sb", "lf", "hw", "ed", "fy"]
z = ["fg", "uj", "sx", "uj", "ww", "cf"]
y = sorted(x)
x2 = [('a',3,z),('c',1,y),('b', 5,x)]
print(x2)
print()
print(sorted(x2, key=lambda s:s[2]))
print()
print(sorted(x2, key=lambda s:s[2][1]))
print()
print(sorted(x2, key=lambda s:s[2][1][0]))
|
85265deffed9b206519fac2ad87dca1d0c996e98 | rurbonas/eng89_python_collections | /Lists_Tuples.py | 914 | 4.4375 | 4 | # Create a shopping list
# Syntax [] - name_of_list = ["items in list"]
shoppingList = ["mango", "eggs", "tea", "bread", "apples", "tuna"]
print(shoppingList)
print(shoppingList.pop(3)) # Pop will remove and return the last item from the list unless an index is specified
print(shoppingList)
shoppingList = ["mango", "eggs", "tea", "bread", "apples", "tuna"]
print(shoppingList)
del shoppingList[0] # Del will remove the indexed item from the list
print(shoppingList)
shoppingList = ["mango", "eggs", "tea", "bread", "apples", "tuna"]
print(shoppingList)
shoppingList.remove("bread") # Del will remove the specified named item from the list
print(shoppingList)
# Create a shopping tuple
# Syntax () - name_of_list = ("items in list")
# Lists are MUTABLE tuples are IMMUTABLE (Unchangeable)
shoppingTuple = ("mango", "eggs", "tea", "bread", "apples", "tuna")
# print(shoppingTuple.pop(3)) will return an error |
dc40491abb549c23c5f57f441569e51147ff5121 | bpaternostro/challenge-ortex | /src/challenge_exec_2.py | 2,868 | 3.921875 | 4 | from datetime import datetime
from core import dispacher as dispa_o
'''
This task is to fix this code to write out a simple monthly report. The report should look professional.
The aim of the exercise is to:
- Ensure that the code works as specified including date formats
- Make sure the code will work correctly for any month
- Make sure the code is efficient
- Ensure adherence to PEP-8 and good coding standards for readability
- No need to add comments unless you wish to
- No need to add features to improve the output, but it should be sensible given the constraints of the exercise.
Code should display a dummy sales report
'''
### Do not change anything in the section below, it is just setting up some sample data
# test_data is a dictionary keyed on day number containing the date and sales figures for that day
month = "02"
test_data = {f"{x}": {"date": datetime.strptime(f"2021{month}{x:02d}", "%Y%m%d"),
'sales': float(x ** 2 / 7)} for x in range(1, 29)}
### Do not change anything in the section above, it is just setting up some sample data'''
# - BP - Fixing the index to something more dinamic
# start=test_data[0]
# end=test_data[27]
start = test_data[list(test_data)[0]]
end = test_data[list(test_data)[-1]]
def DateToDisplayDate(date):
# E.g. Monday 8th February, 2021
return (f"""{date.strftime("%a")} {date.strftime("%d")}th {date.strftime("%B")}, {date.strftime("%Y")}""")
#start["date"] = DateToDisplayDate(start["date"])
#end["date"] = DateToDisplayDate(end["date"])
# I created 2 variables to avoid changing the dict
aux_start = DateToDisplayDate(start["date"])
aux_end = DateToDisplayDate(end["date"])
# - BP - I did some changes in order to make more readable this lines
# print("Sales Report\nReport start date: " + start["date"] + "| Starting value: " + str(start["sales"]) + "\nReport end date: " + end["date"] + "\nTotal sales: " + str(end["sales"]) + "\n")
print("Sales Report\nReport start date: " + str(aux_start) + "| Starting value: " + str(aux_start) + "\nReport end date: " + str(aux_end) + ", total sales: " + str(aux_end) + "\n")
# - BP - changing to 0
#total=None
total=0
# - BP - fix adding method .items()
result=[]
for k, v in test_data.items():
leap_year=False
# - BP - fix - adding a value to the variable month
month=v["date"].strftime("%m")
# - BP - I've changed the operator
#if month is "2" and k is "29":
if month == "2" and k == "29":
leap_year=True # Must be displayed if data is for a leap year
aux={
"Date":DateToDisplayDate(v['date']),
"Sales":v['sales'],
"Month to date":"${t}".format(t=total),
"Total":v['sales']+total,
"Aditional-data":leap_year
}
total=v['sales']+total
result.append(aux)
dispa=dispa_o.Dispacher()
dispa.generates_report(result)
|
39f7d28e5d7b9104adc0fe468361948ab3ceb14a | udanzo-p/LABS-38 | /Optional exercise 1/radian to degree.py | 175 | 4.40625 | 4 | import math
print("Enter radian to convert into degree" )
radian=float(input())
pi=math.pi
degree=float((radian/pi)*180)
print("The conversion of radian to degree is ",degree) |
8ce7b72794b2058f12318289ec669df36cb1e848 | mtasende/airbnb-analysis | /src/visualization/visualize.py | 841 | 4.09375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def prop_vs_mean(x, y):
"""
Proportional dependency vs "taking the mean" comparison.
It is used to decide the method to imput missing data.
"""
data = pd.concat([x, y], axis=1).dropna(how='any')
x = data[x.name]
y = data[y.name]
a = (y.values / x.values).mean()
plt.scatter(x, y, label='Data')
plt.hlines(y.mean(), x.min(), x.max(), colors='r', label='Mean')
x_t = np.linspace(x.min(), x.max(), 1000)
plt.plot(x_t, a * x_t, 'g', label='Proportional')
plt.legend()
def show_data(data):
""" Shows shape, missing data, and head of a pandas DataFrame. """
print('The data has shape: {}\n'.format(data.shape))
print('There is {} missing data!\n'.format(data.isnull().sum().sum()))
print(data.head())
|
7ab5654b0af7c8dfa788a11840ef94ba90a8055d | svaccaro/codeeval | /lowercase.py | 119 | 3.5625 | 4 | #!/usr/bin/env python
from sys import argv
input = open(argv[1])
for line in input:
print line.rstrip().lower()
|
d71db487817a2fec22a537d41cae952aed2351be | elunacado/FISICA_FUERZA | /F/main.py | 1,381 | 4.21875 | 4 | def calculo():
ul = ["a = asceleracion", "m = masa", "f = fuerza"]
print(ul)
peticion=input("que quieres calcular?")
def fuerza():
m = float(input("dime el valor de la m "))
a = float(input("dime el valor de la a "))
result=m * a
print(result)
again=input("ingresa r y presiona enter si quieres realizar otra formula o presiona enter y cierra el pregrama")
if again == "r":
calculo()
def asceleracion():
f = float(input("dime el valor de la f "))
m = float(input("dime el valor de la m "))
result=f/m
print(result)
again = input("ingresa r y presiona enter si quieres realizar otra formula o presiona enter y cierra el pregrama")
if again == "r":
calculo()
def masa():
f = float(input("dime el valor de la f "))
a = float(input("dime el valor de la a "))
result=f/a
print(result)
again = input("ingresa r y presiona enter si quieres realizar otra formula o presiona enter y cierra el pregrama")
if again == "r":
calculo()
if peticion=="f":
fuerza()
elif peticion=="a":
asceleracion()
elif peticion=="m":
masa()
else:
print("not yet")
input()
calculo()
|
b389931087c438a2195463469a3a82c08b5431bf | kishorebolt03/Python-programs | /frequent char.py | 696 | 3.703125 | 4 | string=input()
liststr=list(string)
print(liststr)
liststr2=[]
list1=[]
for i in string:
if(i not in list1):
val=string.count(i)
liststr2.append(val)
keys = liststr
values = liststr2
dictionary = dict(zip(keys, values))
k=sorted(dictionary.items(),key=lambda i:i[1],reverse=True)
print(k)
dic=dict(k)
print(dic)
tup=dic.values()
print(tup)
s=set(tup)
print(s)
li=list(s)
li.sort(reverse=True)
print(li)
ans=li[1]
count=0
for key,values in dic.items():
if(ans==values):
count+=1
if count==1:
print('Yes')
elif(count==0):
print("No")
else:
print('Invalid')
|
0382004bbb13efe153b597aa847150c119555f4f | alexsoulfear/hillel_homework | /homework_task_22.py | 1,363 | 4.03125 | 4 | import random
print('What is number?')
print('_______________')
def greeting():
print()
print()
print('Try to guess, what is the number?')
print('---------')
print('Or push <<q>> to leave.')
def who_is_winner(user_number, computer_number):
result = True
if user_number == computer_number:
result = True
if not user_number == computer_number:
result = False
return result
def game():
print('Howdy folk!')
while True:
greeting()
user_number = input()
if user_number == 'q':
print('Alright bye! Newer come back again ))))')
break
valid_choise = user_number.isnumeric() and 1 <= int(user_number) <= 10
if not valid_choise:
print("Enter valid data! It's 1, 2... 10 and no more, you silly pancake )))))")
continue
user_number = int(user_number)
computer_number = random.randint(1,10)
user_winner = who_is_winner(user_number, computer_number)
if user_winner:
print('%d? You damn right! Wanna go again?' % (user_number))
if user_number > computer_number:
print('Ha! Lol no! Not even close! Your number is too big')
if user_number < computer_number:
print('A-a-and you failed! Try better next time! Your number is too small')
game() |
0da45c8f33e0efd2d614439bf0245c75f96b344b | MODYLb/python | /untitled1/assvol.py | 3,149 | 3.671875 | 4 | class Simple:
count = 0
def __init__(self, name, age, job='None', salary=0):
self.name = name
self.age = age
self.job = job
self.salary = salary
Simple.count += 1
def __del__(self):
Simple.count -= 1
def __str__(self):
return f'class: {self.__class__.__name__}, ' + ', '.join([f'{i} = {j}' for i, j in self.__dict__.items()])
# return f'class: {self.__class__.__name__}, name = {self.name}, age = {self.age}'
@staticmethod
def howmany():
print(Simple.count)
def __setattr__(self, key, value):
if __name__ != '__main__': # if key in self.__dict__.keys(): - позволяет сделать так, чтоб никто (даже я) не менял ниче
print('Not today') # pass
else: # if key in [age, job] - так можно сделать, чтоб нельзя было менять конкретные атрибуты
self.__dict__[key] = value
def upsalary(self, up=30):
self.salary *= 1 + up/100
self.salary = round(self.salary, 2) # Округлил до 2 знаков
class Developer: # Делегирование
def __init__(self, name, age, salary=0):
self.cap = Simple(name, age, job='Developer', salary=salary)
def __str__(self):
return str(self.cap)
def __getattr__(self, item):
return getattr(self.cap, item)
def upsalary(self, up=30, bonus=10):
self.cap.upsalary(up + bonus)
class Ofik(Simple):
def __init__(self, name, age, salary=0, rang='Youngster'):
Simple.__init__(self, name, age, job='Ofik', salary=salary)
self.rang = rang
def upsalary(self, up=30, bonus=3):
Simple.upsalary(self, up + bonus)
class Firma:
def __init__(self, name, *a):
self.name = name
self.spisok = list(a)
def printall(self):
for i in self: # for i in self.spisok: <--- до перегрузки оператора __getitem__
print(i)
def __getitem__(self, item): # a[item]
return self.spisok[item]
def addsub(self, *b):
self.spisok += list(b)
import shelve # позволяет хранить объекты по ключам
if __name__ == '__main__': # Тестировщик
I1 = Simple('Yarik', 22, 'Student')
I2 = Simple('Sanya', 54, 'Developer', 300000)
I2.upsalary()
Simple.howmany()
# print(I1)
# print(I2)
#
I3 = Developer('Max', 17, 10000)
# print(I3.salary)
# I3.upsalary()
# print(I3.salary)
#
I4 = Ofik('Yurik', 13, 40000)
# print(I4)
# I4.upsalary()
# print(I4.salary)
#
# for i in [I1, I2, I3, I4]:
# i.upsalary(up=10)
# print(i.salary)
# a = Firma('Uzniki', I1, I2, I3)
# print(*a.spisok, sep='\n')
# a.printall()
# print(a.spisok[0])
# print(*a[2:])
# a.printall()
# a.addsub(I4)
# print(*a)
# print(*a.spisok, sep='\n')
db = shelve.open('db')
db[I2.name] = I2
print(db['Sanya'])
db.close() |
be17965c6dead6932c305fd5a0215fa5b601f0c4 | kmorozkin/euler-solutions | /src/problem47.py | 1,120 | 3.5625 | 4 | '''
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
'''
from math import sqrt
def factors(num):
results = set()
# sieve until the number is odd
while int(num) & 1 == 0:
num /= 2
results.add(2)
# loop through evens; even non-primes are filtered by their lesser prime factors
for factor in range(3, int(sqrt(num)) + 1, 2):
while num % factor == 0:
results.add(factor)
num /= factor
if num > 2:
results.add(num)
return results
def consecutive(num, count=4):
length = len(factors(num))
if length != count:
return False
for other in range(num + 1, num + count):
if len(factors(other)) != length:
return False
return True
x = 2*3*5*7
while not consecutive(x, 4):
x += 1
print(x) |
f25177555f6f1cf75857e592d82b03cfdd33720a | Kathy961225/My_LeetCode_Practice | /130.py | 1,150 | 3.5625 | 4 | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return
rows=len(board)
cols=len(board[0])
queue=[]
visited=set()
for i in range(rows):
for j in range(cols):
if (i==0 or i==rows-1 or j==0 or j==cols-1) and board[i][j]=='O':
queue.append((i,j))
visited.add((i,j))
while queue:
i,j = queue.pop(0)
x_change=[1,-1,0,0]
y_change=[0,0,1,-1]
for ind in range(4):
x=x_change[ind]+i
y=y_change[ind]+j
if x<0 or y<0 or x>=rows or y>=cols or (x,y) in visited or board[x][y]=='X':
continue
queue.append((x,y))
visited.add((x,y))
for i in range(rows):
for j in range(cols):
if board[i][j]=='O' and not (i,j) in visited:
board[i][j]='X' |
3e349af3ceb07fc0087c58edf4d3dbf2061a82e4 | vaniroo/intro_class | /shoplist.py | 4,248 | 4.46875 | 4 |
shopping_list_dict = {"Target": ["socks", "soap", "detergent", "sponges"],
"Safeway": ["butter", "cake", "cookies", "bread"],
# "PeterGrocery": ["apples", "oranges", "bananas", "milk"],
"JaneGrocery": ["oreos", "brownies", "soda"]}
# def user_choice():
# choice = int(raw_input("Choose a number from main menu:"))
# return int(choice)
# choice = int(raw_input("Choose a number from main menu:"))
# return int(choice)
def show_all_lists():
#show items, keys and values, in alphabetical order
print shopping_list_dict
def show_specific_list(shopping_list_dict):
#show items, all values,on a selected list
print "These are the lists:",shopping_list_dict.keys()
print shopping_list_dict[raw_input("which list would you like to see?")]
def add_new_shopping_list(key):
key = key
shopping_list = []
# add new shopping list, key has to be unique
# print shopping_list_dict[raw_input("which list would you like to add?")]
if key not in shopping_list_dict:
shopping_list_dict[key] = shopping_list
else:
print "A list with that name already exists"
def add_item(key,item):
#adding item to an existing shopping list, cannot be duplicate
#print out all items from list
#ask user for item until one is done
item = item.lower()
key = key.lower()
if key in shopping_list_dict:
shopping_list = shopping_list_dict[key]
if item not in shopping_list:
shopping_list.append(item)
print "here is your updated list", sorted_shopping_list(key)
else:
print "this item %s already exists" % (item)
else:
print "There is no list with that name."
# new_item = raw_input("what item do you want to add to your list?").lower()
# for one_list in shopping_list_dict.values():
# #for new_item in one_list:
# new_list = raw_input("where do you want to add it?")
# one_list.append(new_item)
# # print one_list
#print "%s is already in your list" % new_item
#new_item is the value
#need to specify which key new_item goes into
def remove_item(shopping_list_dict):
#remove item from existing shopping list, cannot be duplicate
#print out all items from list
# ask user for item until one is done
remove_from_list = raw_input("what do you want to remove:")
for one_list in shopping_list_dict.values():
if remove_from_list in one_list:
one_list.remove(remove_from_list)
print one_list
def remove_list_nickname(shopping_list_dict):
#remove list based on entered nickname or key
del shopping_list_dict["Target"]
print shopping_list_dict
def exit_done(shopping_list_dict):
#exit from shopping list
print "Thanks for using shopping list app!"
print "Bye-bye!"
def main():
# all functions work independently with hard coded data
# TODO: change hard coded data into raw_input data saved into variable
# TODO: pass variables into functions as arguments when being called
# TODO: give functions paramater so it can use variables from raw_input
# TODO: make a while loop that works and is not infinite
# user_choice()
choice = None
while choice != 7:
choice = main_menu()
if choice == 1:
print shopping_list_dict
elif choice == 2:
show_specific_list(shopping_list_dict)
elif choice == 3:
list_name = raw_input("which list would you like to see?")
add_new_shopping_list(list_name)
item = raw_input("please enter an item")
choice = 0
elif choice == 4:
add_item(shopping_list_dict)
elif choice == 5:
remove_item(shopping_list_dict)
elif choice == 6:
remove_list_nickname(shopping_list_dict)
else:
print "bye"
def main_menu():
while True:
#display list
print """
Choose a menu item:
0 - Main Menu:
1 - Show all lists.
2 - Show a specific list.
3 - Add a new shopping list.
4 - Add an item to a shopping list.
5 - Remove an item from a shopping list.
6 - Remove a list by nickname.
7 - Exit when you are done.
"""
choice = raw_input("--> ")
# if choice not in str(range(8)):
# print "'" + str(choice) + "' was not a menu item."
# else:
return int(choice)
if __name__ == '__main__':
main()
|
0c9b38d66b888a31f5552113987b1221f653cdfe | johnnyferreiradev/python-course-microsoft | /numbers.py | 632 | 3.984375 | 4 | # check if the type is a number
def isnumber(value):
try:
float(value)
except ValueError:
return False
return True
pi = 3.14159
print(pi)
first_number = 3
second_number = 7
print(first_number + second_number)
print(first_number ** second_number)
days_in_feb = 28
print(str(days_in_feb) + ' days in February')
first_input = input('Enter first number: ')
second_input = input('Enter second number: ')
if (not isnumber(first_input) and not isnumber(second_input)):
first_input = 0
second_input = 0
print(float(first_input) + float(second_input))
print(int(first_input) + int(second_input))
|
d034c7459f7c07c1d138f4db36a2c02540f88884 | gadjishka/pythonProg | /питончик/програмирование/cucle.py | 1,161 | 3.859375 | 4 | # print(2,4,6,8,10,12,14,16,18,20)
# i = 0
# while i <= 100:
# if i % 2 == 0:
# print(i)
# i += 1
# name = ""
# while True:
# name = input("Вы пришли на танцы.\
# Представьтесь! ")
# if name == "лукман":
# print("Здоровеньки булы," + name + \
# "Мы вас дождались")
# break
# else:
# print("Пошел вон . нам нужен только лукман. Возвращайся в свою селуху")
while True:
name = input("Вы пришли на трудоустройство.\
Представьтесь! ")
if name == "саид":
print("Я вам не верю. Введите настоящее имя")
continue
elif name == "лукман":
print("Здравствуйте лукман. Зубная щетка вас заждалась")
break
elif name == "ахмед":
print("ВЫ нам не нужны .\
Забудьте дорогу сюда,сюда")
break
print("Ничего не подошло!!")
|
421675dfdff1f65de9dbdc08568b118bec96208d | greatabel/HXDataScience | /data_process/i0csv_operation.py | 646 | 3.59375 | 4 | import os
import pickle
import pprint
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
import csv
def csv_write(filename, mylist, mode="w", directory="./"):
with open(os.path.join(directory, filename), mode, newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(mylist)
def csv_reader(filename, directory="./"):
with open(os.path.join(directory, filename), newline="") as csvfile:
reader = csv.reader(csvfile, delimiter=" ", quotechar="|")
mylist = []
for row in reader:
mylist.append(row[0].split(","))
return mylist
|
a058842fbce6a5d284851920aa93e804c451b742 | niketanrane/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python | /5_Sorting_And_Searching/Bubble_Sort_5_7.py | 943 | 4 | 4 | __author__ = "niketanrane"
def bubbleSort(aList):
for passnum in range(len(aList)-1, 0, -1):
for i in range(passnum):
if aList[i] > aList[i+1]:
aList[i], aList[i+1] = aList[i+1], aList[i]
alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)
def shortBubbleSort(aList):
#It will check if at current pass whether we have done at least one exchange, if not list is sorted. -> STOP
for passnum in range(len(aList) - 1, 0, -1):
exchanged = False
for i in range(passnum):
if aList[i] > aList[i+1]:
exchanged = True
aList[i], aList[i + 1] = aList[i + 1], aList[i]
if exchanged == False:
print(passnum)
break
aList = [54,26,93,17,77,31,44,55,20]
shortBubbleSort(aList)
print(aList)
alist=[20,30,40,90,50,60,70,80,100,110]
shortBubbleSort(alist)
print(alist)
|
4d79ff0dd991076d2b3acb878be73f04ba9172d4 | Beshkov/Python_OOP | /06-Polymorphism/polymorphism-demo.py | 3,057 | 4.09375 | 4 | from abc import ABC, abstractmethod
from math import pi
# class Animal(ABC):
# def __init__(self, name):
# self.name = name
#
# @abstractmethod
# def sound(self):
# raise NotImplementedError("Subclass must implement")
#
# class Dog(Animal):
# def __init__(self, name):
# super().__init__(name)
#
# def sound(self):
# print("Bark!")
#
#
# class Cat(Animal):
# def __init__(self, name):
# super().__init__(name)
#
# def sound(self):
# print("Meow!")
#
# cat = Cat("Willy")
# cat.sound()
# dog = Dog("Willy")
# dog.sound()
# animal = Animal("Willy")
# animal.sound()
# Problem 2
# class Solution:
# class Shape(ABC):
#
# @abstractmethod
# def calculate_area(self):
# raise NotImplementedError
#
# @abstractmethod
# def calculate_perimeter(self):
# raise NotImplementedError
#
# class Circle(Shape):
# def __init__(self, radius):
# self.radius = radius
#
# def calculate_area(self):
# return pi * (self.radius ** 2)
#
# def calculate_perimeter(self):
# return 2 * pi * self.radius
#
# class Rectangle(Shape):
# def __init__(self, height, width):
# self.height = height
# self.width = width
#
# def calculate_area(self):
# return self.height * self.width
#
# def calculate_perimeter(self):
# return 2 * (self.height + self.width)
#
# circle = Circle(5)
# print(circle.calculate_area())
# print(circle.calculate_perimeter())
#
# rectangle = Rectangle(10, 20)
# print(rectangle.calculate_area())
# print(rectangle.calculate_perimeter())
#
"""Problem 3: Execute - duck typing """
#
# def execute(func, *args):
# return func(*args)
#
# def say_hello(name,my_name):
# print(f"Hello, {name}, I am {my_name}")
#
# def say_bye(name):
# print(f"Bye, {name}")
#
# execute(say_hello, "Peter", "George")
# execute(say_bye, "Peter")
# def play_instrument(func):
# return func.play()
#
# class Guitar:
# def play(self):
# print("playing the guitar")
#
# guitar = Guitar()
# play_instrument(guitar)
#
# class Piano:
# def play(self):
# print("playing the piano")
# piano = Piano()
# play_instrument(piano)
class ImageArea:
def __init__(self, width, height):
self.width = width
self.height = height
def get_area(self):
return self.width * self.height
def __eq__(self, other):
return self.get_area() == other.get_area()
def __ge__(self, other):
return self.get_area() >= other.get_area()
def __gt__(self, other):
return self.get_area() > other.get_area()
def __lt__(self, other):
return self.get_area() < other.get_area()
def __le__(self, other):
return self.get_area() <= other.get_area()
def __ne__(self, other):
return self.get_area() != other.get_area()
a1 = ImageArea(7, 10)
a2 = ImageArea(35, 2)
a3 = ImageArea(8, 9)
print(a1 == a2)
print(a1 != a3)
print(a1 != a2)
print(a1 >= a3)
print(a1 <= a2)
print(a1 < a3)
print(a1 > a3)
|
0d1e73661230e6afc06f5cc81493ec6119f26c13 | deelm7478/CTI110 | /P4HW2_ CelsiusFahrenheit _MathewDeel.py | 506 | 3.9375 | 4 | # A table showing Celsius and Fahrenheit temperatures
# 10/16/18
# CTI-110 P4HW2 - Celsius to Fahrenheit Table
# Mathew Deel
#
def main():
#Table header is displayed
print("Celsius\tFahrenheit")
print("-------------------")
#Range of celcius temperatures is determined
for celsius in range(0,21):
#Fahrenheit is calculated
fahrenheit = int(9 / 5 * celsius + 32)
#Both temperatures are displayed
print(celsius,"\t",fahrenheit)
main()
|
cafdadffc9d0110387806a698b5ffedb76b84183 | phanhung2905/hungdeptrai | /session03/menu.py | 426 | 3.84375 | 4 | # list / array
menu = ["com", "ca", "thit bo", "ghe", "pizza", "ghe 50 kg"]
# separator
# update
menu[4] = "tom hum"
print(*menu)
# print(len(menu))
# menu.append("ghe")
# print(len(menu))
# print(menu[-1])
# for i in range(len(menu)):
# print(menu[i])
# for index, item in enumerate(menu):
# print(index + 1, item, sep = ", ")
# print ("{}. {}".format(index + 1, item))
# for item in menu:
# print(item) |
56461a7744de85a24a7531c9f11d7d3062223815 | sanamahuja/iris-flower | /app.py | 616 | 3.5 | 4 | import streamlit as st
st.title("Machine Learning - Iris")
sepal_length = st.slider('Sepal Length', 0.1, 7.9, 2.0)
sepal_width = st.slider('Sepal Width', 0.1, 7.9, 2.0)
petal_length = st.slider('Petal Length', 0.1, 7.9, 2.0)
petal_width = st.slider('Petal Width', 0.1, 7.9, 2.0)
from sklearn.datasets import load_iris
iris = load_iris()
x = iris.data
y = iris.target
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(x,y) # Training
y = model.predict([[sepal_length,sepal_width,petal_length,petal_width]])
y =iris.target_names[y[0]]
st.title(f"The flower is {y}")
|
63ff705091641d3db372ab890b7c4e1b69592f6a | IamAlexKole/python_practice | /task1.py | 1,583 | 3.953125 | 4 | import re
# Введення рядку користувачем
str = input("Введіть рядок: ")
# Знаходження чисел у заданому рядку
rd = re.findall(r'\d+', str)
str = re.sub(r"\d+", "", str, flags=re.UNICODE)
rd = [int(i) for i in rd]
# Виведення відформатного рядку
print("Рядок без чисел:\n", str, sep='')
# Функція заміни букв за умовою
def function(str):
str, result = str.title(), ""
for slovo in str.split():
result += slovo[:-1] + slovo[-1].upper() + " "
return result[:-1]
# Виведення слів після форматування
print("\nСлова змінені за вказаною умовою:\n", function(str), sep='')
# Виведення масиву чисел
print("Масив чисел з рядка:\n", rd, sep='')
# Знаходження макс. числа за умови наявності чисел у введеному рядку і вихід з програми у разі їх відсутності
if rd:
maxNum = max(rd)
index = rd.index(maxNum)
print("\nМаксимальне число:", maxNum)
if not rd:
print("Рядок не містить чисел!")
exit()
# Запис масиву чисел піднесених до степеня
arr = []
for i in range(len(rd)):
if rd[i] != max(rd):
arr.append(pow(rd[i], i))
# Виведення масиву нових чисел
print("Піднесені до степеня числа:\n", arr, sep='')
|
20deb446fd607d0cfae4c319ba7e1edb2984a5bd | stellavirginiaa/cp-solution | /HackerEarth/Algorithms/rest_in_peace_21_1.py | 237 | 3.828125 | 4 | # Contributor: Jayaku Briliantio [BIOS-Bunda Mulia]
n = int(input())
for n in range(n):
number = input()
if '21' in number or int(number) % 21 == 0:
print('The streak is broken!')
else:
print('The streak lives still in our heart!')
|
6d9e25a7836b3f81ecc45b696f322596e135ec1e | yennanliu/analysis | /DS_algorithms/map_reduce.py | 1,205 | 3.765625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
class map_reduce(object):
def __init__(self):
pass
def Load_data(self, dataset):
agg_row = []
with open(dataset) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
print (row)
agg_row.append([row[0], row[1]])
return agg_row
def Map(self, agg_row):
print (agg_row)
for row in agg_row:
print ('%s\t%s' % (row, 1))
def Reduce(self, agg_row):
word = None
word_dict = {}
for index, row in enumerate(agg_row):
word, count = row[0] + row[1], 1
#print (word, count)
if word in word_dict:
# if word already in word_list : count + 1
word_dict[word] += 1
else:
# if word is not in word_list : add it with count = 1
word_dict[word] = 1
return word_dict
if __name__ == '__main__':
mapreduce = map_reduce()
agg_row = mapreduce.Load_data('map_reduce.csv')
word_count = mapreduce.Reduce(agg_row)
print ('word_count : ', word_count)
|
9e2fafdd4286415fc947311097742af9dd4c95cb | saikrishna6415/python-problem-solving | /square.py | 302 | 3.859375 | 4 | n = int(input(" enter a number : "))
for i in range(n):
for j in range(n):
if j == 0 or j==n-1 or i == n-1 or i ==0 :
print("1 ",end="")
else:
print(" ",end="")
print()
# enter a number : 5
# 1 1 1 1 1
# 1 1
# 1 1
# 1 1
# 1 1 1 1 1 |
2914bdd66cac81f9660b078a6c1ca5667b96987b | geonwoomun/AlgorithmStudy | /codeUp100제/1025.py | 391 | 3.640625 | 4 | a = input()
for idx, value in enumerate(list(a)):
if(idx == 0) :
print('[{0:<05d}]'.format(int(value)))
elif(idx == 1) :
print('[{0:<04d}]'.format(int(value)))
elif(idx == 2) :
print('[{0:<03d}]'.format(int(value)))
elif(idx == 3) :
print('[{0:<02d}]'.format(int(value)))
elif(idx == 4) :
print('[{0:<01d}]'.format(int(value))) |
3b03afa14098dd194dc5e9808de0e717f333adb2 | Taimoor23/1st-Python | /countingWords.py | 224 | 3.984375 | 4 | intro=input("Please introduce urself:")
print(intro)
characterCount=0
wordCount=1
python
for i in intro:
characterCount=characterCount+1
if(i==' '):
wordCount=wordCount+1
print(wordCount) |
8c523a4fcbab8c6093e6bdcbcceced5c48a47979 | xilixjd/leetcode | /Math/453. 最小移动次数使数组元素相等(easy).py | 865 | 3.859375 | 4 | # -*- coding: utf-8 -*-
__author__ = 'xilixjd'
'''
给定一个长度为 n 的非空整数数组,找到让数组所有元素相等的最小移动次数。每次移动可以使 n - 1 个元素增加 1。
示例:
输入:
[1,2,3]
输出:
3
解释:
只需要3次移动(注意每次移动会增加两个元素的值):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
'''
class Solution(object):
def minMoves(self, nums):
"""
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/93817/It-is-a-math-question
m 为移动次数,sums 为 sum(nums),x 为移动后的数组中的数,n 为数组长度,min_num 为 min(nums),则有
x * n = sums + (n - 1) * m
x = min_num + m
:type nums: List[int]
:rtype: int
"""
return sum(nums) - min(nums) * len(nums)
|
3ddb28e829e8fda81802541d24413b86e550495b | brokenhedgehog/ubiquitous-waffle | /shop.py | 3,379 | 4.03125 | 4 | from collections import namedtuple
Customer = namedtuple('Customer','name loyality')
goods = {
'cabbage': 10, 'carrot': 15, 'tea': 40, 'nutella': 200
}
class LineItem:
def __init__(self,product,quantity,price):
self.product = product
self.quantity = quantity
self.price = price
def cost(self):
return int(self.quantity * self.price)
class Order:
def __init__(self,customer,foodcart,promotion = None):
self.customer = customer
self.foodcart = foodcart
self.promotion = promotion
def total(self):
return sum(item.cost() for item in self.foodcart)
def due(self):
if self.promotion is None:
discount = 0
else:
discount = self.promotion
return self.total() - discount
def different_discount(order:Order) -> float:
return order.total() * 0.05 if len([item.product for item in order.foodcart]) else 0
def loyality_discount(order) -> float:
return order.total() * 0.1 if order.customer.loyality >= 1000 else 0
def large_discount(order:Order) -> float:
discount = 0
for item in order.foodcart:
if item.quantity >= 20:
discount += item.cost() * 0.07
return discount
def shop_products() -> None:
print('| {:^10} | {:^8} |'.format('product', 'price'))
global goods
for product in goods:
print('| {:^10} | {:^8} |'.format(product, goods[product]))
return None
def idintifity() -> Customer:
name = input('enter your name:').strip()
loyality = input('enter your loyality:').strip()
try:
loyal = int(loyality)
customer = Customer(name, loyal)
except:
customer = Customer('default_customer', 0)
return customer
def creating_cart() -> Order:
order = Order(idintifity(),[])
print('please, choose products, print "stop" to stop:')
while True:
inp1 = input().strip().lower()
if inp1 != 'stop':
try:
inp2 = inp1.split()
try:
q = int(inp2[1])
except:
continue
if inp2[0] in goods and len(inp2) == 2:
order.foodcart.append(LineItem(inp2[0], q, goods[inp2[0]]))
except IndexError:
LookupError('please,enter product quantity')
else:
break
return order
def same_things(order:Order) -> Order:
d = dict()
for product in order.foodcart:
if product.product not in d:
d[product.product] = product.quantity
else:
d[product.product] += product.quantity
order.foodcart = [LineItem(product, d[product], goods[product]) for product in d]
return order
def print_check() -> None:
order = same_things(creating_cart())
print('| {:^10} | {:^10} | {:^10} | {:^10} |'.format('product','quantity','price','cost'))
for product in order.foodcart:
print('| {:^10} | {:^10} | {:^10} | {:^10} |'.format(
product.product,product.quantity,product.price,product.cost()
))
order.promotion = int(max(different_discount(order), large_discount(order), loyality_discount(order)))
print(f'{order.total()} - {order.promotion} = {order.due()}')
return None
shop_products()
print_check()
|
2e4a4fb2665cff5b8f8bcafaa69b42a4b1123e27 | praveensankar/NIT | /data structures/Tree.py | 291 | 3.578125 | 4 | class Tree:
def __init__(self,data):
self.key=data
self.left=None
self.right=None
class Traversal:
def InOrder(self,root):
if root is not None:
self.InOrder(root.left)
print(root.key)
self.InOrder(root.right)
|
12b77a90dce224d991b07d02fce2629ea12da356 | NoJeong/TID | /doit_python/02. 기초문법/부가세_출력_프로그램_만들기.py | 940 | 3.84375 | 4 | #소비자 가격 = 물건가격 * 1.1
#물건가격 = 소비자 가격 * 1 / 1.1
# 8000원짜리 점심의 부가세는?
print(8000 * 0.1/1.1)
print(round(8000 /1.1,1))
print(round(8000 /1.1))
print(round(8000 * (1/11)))
y = lambda x : 3 * x
print(y(12))
add = lambda x, y : x + y
a = add(12,45)
print(a)
a = '나는 이제 오픽을 준비해야 한다.'
short = lambda x : x[:10]
print(short(a))
# 1원이 0.00086달러
exchange = lambda x : x * 0.00086
print(exchange(10000))
###############################i########################################################################################
# 가격 받아오기
price = {'a':23,'b':40,'c':72}
def service_price():
service= input('서비스의 종류를 입력하세요, a,b,c: ')
valueAdded = input('부가세를 포함합니까? y/n: ')
if valueAdded == 'y':
print(price[service] * 1.1)
else:
print(price[service])
service_price() |
697739e94929c983b8d99e84fff3905b06b61698 | mamhamed/coding | /leetcode/297. Serialize and Deserialize Binary Tree.py | 1,791 | 3.703125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
mystr = ''
if root is None:
return ''
queue = [root]
while len(queue) > 0:
node = queue.pop(0)
if node is None:
mystr += 'None' + ' '
else:
mystr += str(node.val) + ' '
queue.append(node.left)
queue.append(node.right)
return mystr
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if data == '' or data is None:
return None
values = data.split(' ')
val = values.pop(0)
root = TreeNode(val)
parents = [root]
while len(values) > 0 and len(parents) > 0:
parent = parents.pop(0)
for i in ('left', 'right'):
val = values.pop(0)
if val == 'None':
node = None
else:
node = TreeNode(int(val))
parents.append(node)
if i == 'left':
parent.left = node
else:
parent.right = node
return root
t1 = TreeNode(1)
t2 = TreeNode(2)
t1.left = t2
t3 = TreeNode(3)
t1.right = t3
t4 = TreeNode(4)
t3.left = t4
t5 = TreeNode(5)
t3.right = t5
t6 = TreeNode(6)
t4.right = t6
t7 = TreeNode(7)
t5.left = t7
d = Codec().serialize(t1)
print d
t_hat = Codec().deserialize(d)
t_hat |
e934b7cac6f434aeebfa46679636145716e54850 | deepthimneni/LogSoftAssignment | /DictSortAssignment.py | 339 | 4 | 4 | assignment_dict = {
'hello': ['doc1'],
'my': ['doc1'],
'name': ['doc1'],
'is': ['doc1', 'doc2'],
'james': ['doc1', 'doc2'],
'a': ['doc2'],
'developer': ['doc2']
}
def sortDict(input):
result= []
for key in sorted(input):
result.append((key, sorted(input[key])))
return result
print(sortDict(assignment_dict))
|
8c3c111345b1f5215918ccaac3bf81c2834858ea | xilixjd/leetcode | /Math/441. 排列硬币(easy).py | 1,210 | 3.578125 | 4 | # -*- coding: utf-8 -*-
__author__ = 'xilixjd'
'''
你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。
给定一个数字 n,找出可形成完整阶梯行的总行数。
n 是一个非负整数,并且在32位有符号整型的范围内。
示例 1:
n = 5
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤
因为第三行不完整,所以返回2.
示例 2:
n = 8
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
因为第四行不完整,所以返回3.
'''
class Solution(object):
def arrangeCoins(self, n):
"""
递归会爆栈
:type n: int
:rtype: int
"""
def helper(n, remain, count):
# print remain, count
if remain < count + 1:
return count
else:
count += 1
return helper(n, remain - count, count)
return helper(n, n, 0)
def arrangeCoins2(self, n):
if n == 0:
return 0
count = 1
while n > count:
n -= count
count += 1
return count if count == n else count - 1
solu = Solution()
print solu.arrangeCoins2(1) |
a9b0a1d54229f67da0284a199aac5f95a02bed4c | taufderl/ProgITSec | /studienbrief1/beispiele/quelltext_1_18.py | 653 | 3.5625 | 4 | class Contact(object):
def __init__(self, first_name=None, last_name=None,
display_name=None, email=None):
self.first_name = first_name
self.last_name = last_name
self.display_name = display_name
self.email = email
def print_info(self):
print(self.display_name, "<" + self.email + ">")
def set_email(self, value):
if '@' not in value:
raise Exception(
"Dies ist keine gueltige Email-Adresse.")
self._email = value
def get_email(self):
return self._email
email = property(get_email, set_email) |
fa67fe0989a153dfe0a6aac9ca19fe9f297f2b5d | utevo/ProjectEuler-solutions | /Problem 009/script.py | 463 | 3.6875 | 4 | from math import sqrt
def isPythagoreanTriplet(a, b, c):
if a**2 + b**2 == c**2:
return True
return False
def main():
for i in range(1001):
for j in range(i + 1, 1001):
k = round(sqrt(i**2 + j**2))
if k > j:
if i**2 + j**2 == k**2:
if i + j + k == 1000:
print(i, j, k)
print(i * j * k)
if __name__ == "__main__":
main() |
589b5edf2a6c8e7d898142f4b1f6e8caf4e0e256 | wizardcapone/Basic-IT-Center-Python | /homework3/224.py | 308 | 3.640625 | 4 | def input_num(message):
try:
i = int(input(message))
return i
except:
print("mutqagreq miayn tiv")
my_arr = []
for i in range(1,5):
n = input_num('mutqagreq tiv-' + str(i) + '\n')
my_arr.append(n)
k = input_num('mutqagreq k tiv@')
for j in my_arr:
num = j**3
num = -num
if(num < k):
print(num) |
2ae4fac2caccae3a44547a292e9377418768b33d | iptq/CSCI1913 | /lab1.py | 2,973 | 3.84375 | 4 | def isInside(v, e):
if type(e) is str:
return v == e
elif type(e) is tuple:
if isInside(v, e[0]) or isInside(v, e[2]): return True
return False
def solve(v, q):
if isInside(v, q[0]): return solving(v, q)
elif isInside(v, q[2]): return solving(v, q[::-1])
else: return None
def solvingAdd(v, q):
if isInside(v, q[0][0]):
return solving(v, (q[0][0], '=', (q[2], '-', q[0][2])))
elif isInside(v, q[0][2]):
return solving(v, (q[0][2], '=', (q[2], '-', q[0][0])))
def solvingSubtract(v, q):
if isInside(v, q[0][0]):
return solving(v, (q[0][0], '=', (q[2], '+', q[0][2])))
elif isInside(v, q[0][2]):
return solving(v, (q[0][2], '=', (q[0][0], '-', q[2])))
def solvingMultiply(v, q):
if isInside(v, q[0][0]):
return solving(v, (q[0][0], '=', (q[2], '/', q[0][2])))
elif isInside(v, q[0][2]):
return solving(v, (q[0][2], '=', (q[2], '/', q[0][0])))
def solvingDivide(v, q):
if isInside(v, q[0][0]):
return solving(v, (q[0][0], '=', (q[2], '*', q[0][2])))
elif isInside(v, q[0][2]):
return solving(v, (q[0][2], '=', (q[0][0], '/', q[2])))
def solving(v, q):
assert isInside(v, q[0])
if v == q[0]:
return q
else:
return {
'+': solvingAdd,
'-': solvingSubtract,
'*': solvingMultiply,
'/': solvingDivide
}[q[0][1]](v, q)
#
# TESTS. Test the equation solver for CSci 1913 Lab 1.
#
# James B. Moen
# 12 Sep 16
#
# Each PRINT is followed by a comment that shows what must be printed if your
# program works correctly.
print(isInside('x', 'x')) # True
print(isInside('x', 'y')) # False
print(isInside('x', ('x', '+', 'y'))) # True
print(isInside('x', ('a', '+', 'b'))) # False
print(isInside('x', (('m', '*', 'x'), '+', 'b'))) # True
print(solve('x', (('a', '+', 'x'), '=', 'c'))) # ('x', '=', ('c', '-', 'a'))
print(solve('x', (('x', '+', 'b'), '=', 'c'))) # ('x', '=', ('c', '-', 'b'))
print(solve('x', (('a', '-', 'x'), '=', 'c'))) # ('x', '=', ('a', '-', 'c'))
print(solve('x', (('x', '-', 'b'), '=', 'c'))) # ('x', '=', ('c', '+', 'b'))
print(solve('x', (('a', '*', 'x'), '=', 'c'))) # ('x', '=', ('c', '/', 'a'))
print(solve('x', (('x', '*', 'b'), '=', 'c'))) # ('x', '=', ('c', '/', 'b'))
print(solve('x', (('a', '/', 'x'), '=', 'c'))) # ('x', '=', ('a', '/', 'c'))
print(solve('x', (('x', '/', 'b'), '=', 'c'))) # ('x', '=', ('c', '*', 'b'))
print(solve('x', ('y', '=', (('m', '*', 'x'), '+', 'b')))) # ('x', '=', (('y', '-', 'b'), '/', 'm')
# custom case
print(solve('x', (('a', '+', 'b'), '=', ('w', '-', ('x', '*', ('y', '/', 'z'))))))
'''
Results:
True
False
True
False
True
('x', '=', ('c', '-', 'a'))
('x', '=', ('c', '-', 'b'))
('x', '=', ('a', '-', 'c'))
('x', '=', ('c', '+', 'b'))
('x', '=', ('c', '/', 'a'))
('x', '=', ('c', '/', 'b'))
('x', '=', ('a', '/', 'c'))
('x', '=', ('c', '*', 'b'))
('x', '=', (('y', '-', 'b'), '/', 'm'))
('x', '=', (('w', '-', ('a', '+', 'b')), '/', ('y', '/', 'z')))
''' |
3556c50554e16a929bb9f137b816f5cd2f4d4f22 | ande3674/pig_game_python | /deck.py | 1,531 | 3.90625 | 4 | import random
class Deck:
suits = ["hearts", "clubs", "diamonds", "spades"]
values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
def __init__(self):
self.deck = {}
# build the dictionary that represents the deck
# we'll use the index i to create the value for each key-value pair
for i in range(len(self.values)):
# we need a card for each suit
for suit in self.suits:
# build the card string
cardString = self.values[i] + ' of ' + suit
cardValue = i + 1 # this way A = 1, 2 = 2, ..., J = 11, Q = 12, K = 13 etc
# add the card to the deck dictionary
self.deck[cardString] = cardValue
# randomize the keys of the deck dictionary
keys = list(self.deck.keys())
random.shuffle(keys)
# create randomized key-value pairs deck dictionary with randomized keys list
self.deck = {key: self.deck[key] for key in keys}
def dealCard(self):
return self.deck.popitem()
# use this method to deal a hand in the game of pig
# hand will contain 4 cards
# since the deck is in random order, it doesn't really matter if we deal the classic way,
# or if we just give 4 cards in a row to each player :)
def dealHand(self):
hand = {}
for i in range(4):
cardString, cardValue = self.dealCard()
hand[cardString] = cardValue
return hand |
8c483a20abcd8d76c1137f97ed3ca982fcd9f7cb | yjw9012/cracking-the-coding-interview | /chapter-8/8.4-power_set.py | 267 | 3.59375 | 4 | def power_set(s):
if len(s) == 0:
return [[]]
num = s.pop()
subresult = power_set(s)
other_result = [lis + [num] for lis in subresult]
return subresult + other_result
if __name__ == '__main__':
s = [1,2,3]
print(power_set(s))
|
79a6f9ed02db2376c2160b49df19878808aa3981 | owenda7/Multiple-Programing-Languages-Project | /weather.py | 1,900 | 3.71875 | 4 | # Link for PIL documentation: https://pillow.readthedocs.io/en/stable/
# Download PIL with 'pip3 install pillow'
from PIL import Image, ImageDraw, ImageFilter, ImageFont
def main():
buildBackground((getWeather("weather.csv")))
def getWeather(file):
weatherData = []
data = ""
# Open the csv file
with open(file) as inFile:
for line in inFile:
for char in line:
if char != ',':
data += char
else:
weatherData.append(data)
data = ""
weatherData.append(data[:-1])
data = ""
return weatherData
def buildBackground(weatherData):
DAYS = 7
# open background image
background = Image.open('images/background.png')
icons = []
# open icons based on user input
for i in range(0, DAYS):
icons.append(Image.open('images/'+weatherData[(3*i)]+'.png'))
# constants used for spacing icons
ICONX = 365
ICONY = 700
final = background.copy()
# paste icons onto copy of background image
for i in range(0, DAYS):
final.paste(icons[i],((i+1)*ICONX+i*5,ICONY))
# constants used for spacing text
TEMPX = 390
TEMPY = 1000
# set font and size
# NOTE: If error on ImageFont.truetype call, download below for font:
# font download link: https://github.com/JotJunior/PHP-Boleto-ZF2/blob/master/public/assets/fonts/arial.ttf
tempFont = ImageFont.truetype("arial.ttf", 170)
temps = []
# create 7 text boxes with high and low temperatures
for i in range(0, DAYS):
temps.append(ImageDraw.Draw(final))
temperatures = "" + weatherData[(1+(3*i))] + "\n" + weatherData[2+(3*i)]
temps[i].multiline_text(((i+1)*TEMPX-i*20, TEMPY),temperatures, font=tempFont)
# save final photo
final.save('exampleresult.png')
final.show()
main()
|
e281fe687064dc6e3582a72f0c17eff3d22d0b1d | fotavio16/PycharmProjects | /PythonExercicio/ex069.py | 660 | 3.734375 | 4 | total = 0
mais18 = 0
homens = 0
mulheres20 = 0
while True:
pessoa = str(input('Digite o nome da pessoa: '))
total += 1
idade = int(input('Digite a idade da pessoa: '))
if idade > 18:
mais18 += 1
sexo = str(input('Digite o sexo da pessoa (M/F: ')).upper()
if sexo == 'M':
homens += 1
elif idade < 20:
mulheres20 += 1
continua = str(input('Quer continuar (S/N)? ')).upper()
if continua == 'N':
break
print("De um total de {} pessoas, {} são pessoas maiores de 18 anos,".format(total, mais18), end='')
print(" {} são homens e {} são mulheres com menos de 20 anos.".format(homens,mulheres20))
|
ed6ba42230dbb314adfcf9efff35ae1ad37401b6 | ojhaanshu87/data_structures | /Tree_DS/reverse_alternate_node.py | 585 | 3.921875 | 4 | class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def reverse_traversal_util (root1, root2, set_val):
if root1 is None or root2 is None:
return
if (set_val %2 ==0):
root1.val, root2.val = root2.val, root1.val
reverse_traversal_util(root1.left, root2.right, set_val+1)
reverse_traversal_util(root1.right, root2.left, set_val+1)
def reverse_alternate_node(root):
reverse_traversal_util(root.left, root.right, 0)
def inorder_traversal (root):
if root:
inorder_traversal(root.left)
print root.val
inorder_traversal(root.right) |
3cbe61eab8cb8f38fec251bb0ebeffab4dbc90f0 | kritikyadav/Practise_work_python | /string/string5.py | 207 | 3.5625 | 4 | s1=str(input('enter string: '))
s2=s3=s4=''
for i in s1:
if i.isalpha():
s2=s2+i
else:
s3=s3+i
for i in sorted(s2):
s4=s4+i
for i in sorted(s3):
s4=s4+i
print(s4)
|
d84f45036b23c3c5801d3b5a6f75ee3a0db1090c | Deniz-Jasa/Python-Project-Euler | /python_project_euler_problem_20.py | 349 | 3.734375 | 4 | # Python Project Euler - Problem 20 - Deniz Jasarbasic
# Solution:
def compute_factorial(n):
if n < 1:
return 1
else:
return_number = n * compute_factorial(n-1)
return return_number
def compute_sum(n):
factorial_sum = sum(int(c) for c in str(compute_factorial(n)))
return str(factorial_sum)
print(compute_sum(100)) |
86fec61b47469a17645bbc49aa50ca20ee18a44a | FranArleynDynamicDuo/Algoritmos_2_Proyectos | /Proyecto Nº1 De Algoritmos 2/Copias/matrix_calc.py | 4,476 | 3.6875 | 4 | # Proyecto #1 Definiciones y operaciones
#
# Nombre: Arleyn Goncalves, Carnet: 10-10290
# Nombre: Francisco Sucre, Carnet: 10-10717
class Matriz():
#-----------------------------CREAR----------------------------------#
def crear(self,fi,co):
# Crea la matriz vacia, donde fi es el numero de filas y
# co es el numero de columnas y comp son los componentes que
# contiene la matriz
self.fila = fi
self.columna = co
self.comp = []
for i in range(fi):
self.comp.append([0]*co)
#-----------------------------Leer----------------------------------#
def leer(self,NombreTexto):
# Extrae una matriz de un archivo .txt y la guarda en una
# variable
data = open(NombreTexto,'r')
medidaJuntas = data.readline()
medidaSep = medidaJuntas.split()
filaT = int(medidaSep[0])
columnaT = int(medidaSep[1])
self.crear(filaT,columnaT)
print(self.fila)
print(self.columna)
iter1 = 0
for line in data:
lineas = line.split()
for iter2 in range(self.columna):
self.comp[iter1][iter2] = int(lineas[iter2])
iter1 = iter1 + 1
print(self.comp)
#------------------------------OBTENER-------------------------------#
def obtener(self,fi,co):
# Procedimiento donde entra en numero de la fila nombrado como
# fi y el numero de la columna nombrado como co, y se muestra
# que valor se encuentra en dicha posicion
valor = self.comp[fi - 1][co - 1]
print(" El valor buscado es: ", valor)
print()
return valor
#------------------------------COLOCAR-------------------------------#
def colocar(self,fi,co,ing):
# Procedimiento donde fi es la posicion de la fila y co es la
# posicion de la columna y ing es el valor que se va a ingresar
# en dicha posicion
self.comp[fi - 1][co - 1] = ing
print(" La matriz queda :", self.comp)
print()
return self
#-------------------------------SUMA---------------------------------#
def sumar(self,N,F):
# Procedimiento en donde se suman dos matrices
if (self.fila != N.fila) or (F.columna != N.columna):
print("Las dimensiones de las matrices deben ser iguales")
else:
for i in range(self.fila):
for j in range(self.columna):
self.comp[i][j] = N.comp[i][j] + F.comp[i][j]
Ms = self.comp
print(" El resultado de la suma de dos matrices", Ms)
print()
return Ms
#-------------------MULTIPLICACION DE UN ESCALAR---------------------#
def multiplicar(self,N,F):
# Procedimiento en donde se multiplican dos matrices.
Mx = Matriz()
Mx.crear(N.fila,F.columna)
for i in range(N.fila):
for j in range(F.columna):
for k in range(N.columna):
Mx.comp[i][j] = Mx.comp[i][j] + (N.comp[i][k]*F.comp[k][j])
print(" La multiplicacion de matrices es: ", Mx.comp)
print()
return Mx
#---------------------------TRASPUESTA-------------------------------#
def trasponer(self,F):
# Procedimiento donde se calcula la traspuesta de una matriz
Mt = Matriz()
Mt.crear(F.columna,F.fila)
for i in range(F.columna):
for j in range(F.fila):
Mt.comp[i][j] = F.comp[j][i]
print(" La traspuesta de la matriz es: ", Mt.comp)
print()
return Mt
#---------------------------MULTIPLICAR------------------------------#
def multiplicar(self,N,F):
# Procedimiento en donde se multiplican dos matrices.
Mx = Matriz()
Mx.crear(N.fila,F.columna)
for i in range(N.fila):
for j in range(F.columna):
for k in range(N.columna):
Mx.comp[i][j] = Mx.comp[i][j] + (N.comp[i][k]*F.comp[k][j])
print(" La multiplicacion de matrices es: ", Mx.comp)
print()
return Mx
#---------------------------Pruebas----------------------------------#
M0 = Matriz()
M1 = Matriz()
M0.crear(2,4)
M1.crear(4,2)
M0.colocar(0,0,1)
M0.colocar(0,1,1)
M0.colocar(0,2,1)
M0.colocar(0,3,1)
M0.colocar(1,0,1)
M0.colocar(1,1,1)
M0.colocar(1,2,1)
M0.colocar(1,3,1)
M1.colocar(0,0,1)
M1.colocar(0,1,1)
M1.colocar(1,0,1)
M1.colocar(1,1,1)
M1.colocar(2,0,1)
M1.colocar(2,1,1)
M1.colocar(3,0,1)
M1.colocar(3,1,1)
M0.multiplicar(M0,M1)
# Ojo: Haremos un matriz memoria que no va ha tener objetos
|
e013f1a08563620b2035e5e1eafdeeb87f5cbe68 | awslearn1/W3-Python-Tutorial-W3Schools | /01_PythonTutorial/060_SomeValuesAreFalse2.py | 288 | 3.84375 | 4 | #Some Values are False
'''One more value, or object in this case, evaluates to False,
and that is if you have an object that is made from a class with a __len__ function that returns 0 or False:'''
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj)) |
dd0f9d0de9127457285c6c64b63a705d250f172f | SavchenkoDima/python-advanced | /lesson_2/task_1.py | 2,493 | 4.34375 | 4 | """
1)
Создать класс автомобиля.
Описать общие аттрибуты.
Создать классы легкового автомобиля и грузового.
Описать в основном классе базовые аттрибуты для автомобилей.
Будет плюсом если в классах наследниках переопределите методы базового класса.
"""
class Car:
""" It is class about cars """
NUMBER_OF_WHEELS = 4
TYPE_FUEL = 'GAS'
NUMBER_OF_DOORS = 4
def __init__(self, color, engine_type, fuel):
""" description """
self._color = color
self._engine = engine_type
self._fuel = fuel
def broke_down_car(self):
""" description """
return 'Car is broke down!'
def drive(self):
""" description """
return "Car is drive!"
def set_fuel(self, value):
""" description """
self._fuel += value
def get_fuel(self):
""" description """
return self._fuel
def set_engine(self, value):
self._engine = value
""" description """
def get_engine(self):
""" description """
return self._engine
def set_color(self, value):
""" description """
self._color = value
def get_color(self):
""" description """
return self._color
class Truck(Car):
""" it is class about truck """
def __init__(self, carrying, color, engine_type, fuel):
""" description """
super().__init__(color, engine_type, fuel)
self._carrying = carrying
def set_carrying(self, value):
""" description """
self._carrying += value
def get_carrying(self):
""" description """
return self._carrying
def set_fuel(self, value):
""" description """
self._fuel += value*2
class SmallCar(Car):
""" it is class about small car """
def __init__(self, number_of_seats, color, engine_type, fuel):
""" description """
super().__init__(color, engine_type, fuel)
self._number_of_seats = number_of_seats
def set_number_of_seats(self, value):
""" description """
self._number_of_seats += value
def get_number_of_seats(self):
""" description """
return self._number_of_seats
def drive(self):
""" description """
return 'Car is driving very fast'
|
e2a695bf7c759fd6884ed022bf3619afa14d4838 | rabiaasif/Python | /stack.py | 430 | 3.78125 | 4 | class Stack:
def __init__(self):
self.stack = []
def pop(self):
self.stack = self.stack[1:]
def push(self, number):
self.stack.reverse()
self.stack.append(number)
self.stack.reverse()
def is_empty(self):
if self.stack == []:
return True
else:
return False
def display(self):
for i in self.stack:
print str(i)
|
c74253e472ca1b460b9fdb97481fb8706ed708f3 | zschuster/Udemy_AdvancedPython | /Threads/thread_using_function.py | 363 | 3.921875 | 4 | from threading import Thread
import threading
# we will print the current thread inside the function and outside the
# function to show how python uses threads.
def is_even():
print('in function: ', threading.current_thread().getName())
print(4 % 2 == 0)
t = Thread(target=is_even)
t.start()
print('in main script: ', threading.current_thread().getName())
|
0456c225bd75a055d1b71f671c3e8782dc208b24 | HussainAther/physics | /mech/pendulum.py | 2,671 | 4.03125 | 4 | import numpy as np
import matplotlib.pyplot as plt
"""
Runge-Kutta (runge kutta Runge Kutta) algorithm to solve for the oscillations of a simple pendulum.
"""
def delta_theta(T):
"""
return the velocity of the pendulum so that it has its own nonlinear momentum
"""
result = []
for i in range(len(T)):
if result == []:
result.append(1)
else:
result.append(i*3)
return result
def delta_delta_theta(theta, delta_theta):
"""
return the angular acceleration. with the absence of friction
and external torques, this takes the form:
d^2(theta)/dt^2 = -(delta_theta*r)^2 * sin(theta)
"""
return -(delta_theta)^2 * np.sin(theta)
def a(theta):
"""
Acceleration due to gravity.
"""
return -(m*g*r/I) * np.sin(theta)
def pendulum():
m = 3.0 # mass
g = 9.8 # acceleration due to gravity
r = 2.0 # radius (length)
I = 12.0 # moment of Inertia
dt = .0025 # step size
l = 2.0
c = 10 # number of cycles
t = np.range(0, c, dt) # range of iterations for each step size
n = len(t) # number of iterations
y = np.zeros(n) # y coordinates
v = np.zeros(n) # velocity values
theta0 = 90 # initial angle
# delta_theta(T) # velocity across the time interval. Still working on this
for i in range(0, n-1):
"""
Calculate Runge-Kutta formulations for each time point (step)
"""
k1y = h*v[i]
k1v = h*a(y[i])
k2y = h*(v[i] + .5*k1v)
k2v = h*a(y[i] + .5*k1y)
k3y = h*(v[i] + .5*k2v)
k3v = h*a(y[i] + .5*k2y)
k4y = h*(v[i] + k3v)
k4v = h*a(y[i] + k4y)
y[i+1] = y[i] + (k1y + 2 * k2y + 2 * k3y + k4y) / 6.0
v[i+1] = v[i] + (k1v + 2 * k2v + 2 * k3v + k4v) / 6.0
t = np.range(0, c, dt)
y[0] = np.radians(theta0)
v[0] = np.radians(0)
pendulum()
plt.plot(t, y)
plt.title("Pendulum Motion with Runge-Kutta method:")
plt.xlabel("time (s)")
plt.ylabel("angle (rad)")
plt.grid(True)
plt.show()
"""
Now solve the pendulum using Euler method.
"""
def euler(dt, yi, theta):
"""
Euler step uses -sin(theta) to solve differential equations
"""
dtheta = dt * yi
dy = dt * (-np.sin(theta))
yi += dy
theta += dtheta
return yi
# initial positions
theta = .5
y = [] # list of y coordinates
y0 = 0 # initial y coordinate
c = 10 # number of cycles
dt = .05 # time step (interval)
t = np.range(0, c, dt)
for i in t:
(y0, theta) = euler(dt, y0, theta)
y.append(y0)
plt.plot(t, y)
plt.title("Pendulum Motion with Euler method:")
plt.xlabel("time (s)")
plt.ylabel("angle (rad)")
plt.grid(True)
plt.show()
|
f6071e3d9b8eeaeb2a3ca25527bb8f045404ee2f | wmechem/python_samples | /challenges/roman_cls_pep8.py | 4,988 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 3 19:59:11 2016
@author: will
Write a method that converts its argument from integer to roman numeral i
f a numeric value is passed, or from roman numeral to an integer
if a roman numeral is passed.
Your solution should rely on the parameter's class to determine its type
and if a non-roman numeral character is passed (i.e. 'M3I',)
the method should raise a BadRomanNumeral exception.
The solution should be a single method that accepts
a single argument and return the converted value.
Additionally, your solution should demonstrate your mastery of
Python's exception handling capabilities.
Include unit tests to verify correct conversion of both types of input,
and verify exception output with bad input.
Convert to and from Roman numerals
Adapted from:
Mark Pilgrim
version 1.4
date 8 August 2001
pylint 5/26/2016
flake8 5/26/2016
"""
import re
import unittest
#Define exceptions
class RomanError(Exception):
""" Roman error. """
pass
class OutOfRangeError(RomanError):
""" Out of range error. """
pass
class NotIntegerError(RomanError):
""" Not integer error. """
pass
class BadRomanNumeralError(RomanError):
""" Bad Roman numeral error. """
pass
#Define digit mapping
ROMAN_NUMERAL_MAP = (('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1))
#Define pattern to detect valid Roman numerals
ROMAN_NUMERAL_PATTERN = re.compile("""
^ # beginning of string
M{0,4} # thousands - 0 to 4 M's
(CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
# or 500-800 (D, followed by 0 to 3 C's)
(XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
# or 50-80 (L, followed by 0 to 3 X's)
(IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
# or 5-8 (V, followed by 0 to 3 I's)
$ # end of string
""", re.VERBOSE)
class SwapRoman(object):
# pylint: disable=too-few-public-methods
""" Convert to and from Roman numerals. """
def __init__(self):
self.in_string = None
self.num = None
def convert(self, in_string=''):
""" Convert in_string to and from Roman numerals. """
self.in_string = in_string
if not self.in_string:
raise BadRomanNumeralError('Input can not be blank')
if isinstance(self.in_string, int):
self.num = in_string
if not 0 < self.num < 5000:
raise OutOfRangeError("number out of range (must be 1..4999)")
if int(self.num) != self.num:
raise NotIntegerError("decimals can not be converted")
result = ""
for numeral, integer in ROMAN_NUMERAL_MAP:
while self.num >= integer:
result += numeral
self.num -= integer
return result
else:
if not ROMAN_NUMERAL_PATTERN.search(self.in_string):
raise BadRomanNumeralError('Invalid Roman numeral: %s'
% self.in_string)
result = 0
index = 0
for numeral, integer in ROMAN_NUMERAL_MAP:
while self.in_string[index:index + len(numeral)] == numeral:
result += integer
index += len(numeral)
return result
def test_conversion(test):
""" Test function. Create instance and execute method. """
temp = SwapRoman()
return temp.convert(test)
class TestToRoman(unittest.TestCase):
# pylint: disable=R0904
""" Test from int to Roman assert equal. """
def setUp(self):
self.test = 1963
self.results = 'MCMLXIII'
def test_converts(self):
""" Test from int to Roman assert equal. """
self.assertEqual(self.results, test_conversion(self.test))
class TestToInteger(unittest.TestCase):
# pylint: disable=R0904
""" Test from Roman to int assert equal. """
def setUp(self):
self.test = 'MCMLXIII'
self.results = 1963
def test_converts(self):
""" Test from Roman to int assert equal. """
self.assertEqual(self.results, test_conversion(self.test))
class TestBadRoman(unittest.TestCase):
# pylint: disable=R0904
""" Test invalid Roman numeral. """
def setUp(self):
self.test = 'MMXM'
def test_bad_roman(self):
""" Test invalid Roman numeral. """
self.assertRaises(BadRomanNumeralError, test_conversion, self.test)
if __name__ == '__main__':
unittest.main()
|
ea945115905d6870cf4ed0bbb82f35783a226e00 | Vagacoder/Codesignal | /python/Arcade/Python/P18CompetitiveEating.py | 2,158 | 4.03125 | 4 | #
# * Python 18, Competitve Eating
# * Easy
# * The track of players' time will be kept by a float number. It will be displayed
# * on the board with the set precision precision with center alignment, and it
# * is guaranteed that it will fit in the screen. Your task is to test the billboard.
# * Given the time t, the width of the screen and the precision with which the time
# * should be displayed, return a string that should be shown on the billboard.
# * Example
# For t = 3.1415, width = 10, and precision = 2,
# the output should be
# competitiveEating(t, width, precision) = " 3.14 "
# * Input/Output
# [execution time limit] 4 seconds (py3)
# [input] float t
# The time to be displayed on the billboard. It is guaranteed that t has at most 5 digits after the decimal point.
# Guaranteed constraints:
# 0 ≤ t < 1000.
# [input] integer width
# The width of the billboard. It is guaranteed that it's big enough to display the time t with the desired precision.
# In case it's impossible to align the time perfectly in the center, left padding should be 1 whitespace character shorter than right padding.
# Guaranteed constraints:
# 3 ≤ width ≤ 20.
# [input] integer precision
# Precision with which the number should be displayed.
# Guaranteed constraints:
# 0 ≤ precision ≤ 10.
# [output] string
# A string of length width representing the time t as it will be displayed on the billboard.
#%%
# * Solution 1
# ! string.center()
def competitiveEating1(t:float, width:int, precision:int)-> str:
return ('{' + ':0.{}f'.format(precision) + '}').format(t).center(width)
# * Solution 2
# ! string format with order number
def competitiveEating2(t:float, width:int, precision:int)-> str:
return '{0:.{1}f}'.format(t, precision).center(width)
a1 = 3.1415
a2 = 10
a3 = 2
e1 = ' 3.14 '
r1 = competitiveEating2(a1, a2, a3)
print('For {}, expected: {}, result: \'{}\''.format(a1, e1, r1))
a1 = 29.8245
a2 = 10
a3 = 0
e1 = ' 30 '
r1 = competitiveEating2(a1, a2, a3)
print('For {}, expected: {}, result: \'{}\''.format(a1, e1, r1))
# %%
|
43122830b903ea4dd33b70c3988ff94a2c655435 | KNTU-Algorithm-Design-Spring-2021/individual-project-3-am-paydar | /atash_neshan_ha.py | 2,031 | 3.921875 | 4 | from turtle import *
from time import *
def number_to_point(n):
x = (n % 5 * 50 + 25) - 125
y = (n // 5 * 50) - 125
return x, y
def point_to_number(x, y):
row = (y + 125) // 50
col = (x + 125) // 50
n = int(row * 5 + col)
def show_number(n):
lt(90)
fd(12.5)
write(n)
bk(12.5)
rt(90)
def draw_circle(n):
if n != 1:
pensize(2)
color("purple")
pendown()
else:
pu()
goto(number_to_point(n))
pensize(6)
color("black")
pu()
show_number(n)
pendown()
circle(18)
penup()
def graphic_routing(result):
draw_circle(1)
for i in result:
draw_circle(i)
def get_data():
data = [[False for i in range(21)]
for j in range(21)]
visited = [False for i in range(21)]
visited[1] = True
end_point = int(input())
while True:
a, b = input().split()
a = int(a)
b = int(b)
if a == 0 and b == 0:
break
data[a][b] = True
data[b][a] = True
return data, end_point, visited
def reach_end_point(begin_point, end_point):
if begin_point == end_point:
print("1 ", end="")
print(*result, sep=" ")
graphic_routing(result)
sleep(5)
clear()
return
for source in range(1, 21):
# print(data[begin_point][source])
# print("***********************")
if way[begin_point][source] and (not visited[source]):
result.append(source)
visited[source] = True
# print("Append")
# print(*result)
reach_end_point(source, end_point)
result.remove(source)
visited[source] = False
# print("Remove")
# print(*result)
def main():
pu()
speed(10)
pensize(6)
global way, visited, result
while True:
way, end_point, visited = get_data()
result = []
reach_end_point(1, end_point)
if __name__ == "__main__":
main()
|
b5033c6fe3b5c3ea0dbe4763470d34ea29e55f09 | pacciulli/myRepo | /Python_Course/NetworkTasks/ipFileValid.py | 727 | 3.6875 | 4 | import os.path
import sys
#Verify if the IP file exists and return the list of IPs
def ipFileValid():
filePath = input("\n# Enter IP file path and name (e.g D:\\my\\IP\\file.txt): ")
#Check if file exist or not
if os.path.isfile(filePath):
print("\n** IP file is valid **\n")
else:
print("\n** File {} does not exist. Please check and try again! **\n".format(filePath))
sys.exit()
ipFile = open(filePath, 'r')
#To guarantee that the cursor is in the start of the file
ipFile.seek(0)
ipList = ipFile.readlines()
for x in range(0,len(ipList)):
ipList[x] = ipList[x].rstrip('\n')
ipFile.close()
return ipList |
e78c5354fb8992f28cb32e1e4b06aea3a18ec49e | kcpedrosa/Python-exercises | /ex036.py | 515 | 3.859375 | 4 | #o programa é uma calculadora de emprestimo imob. e diz se este foi aprovado
vc = float(input('Qual o valor da casa?: '))
salario = float(input('Digite aqui seu salario: '))
tempo = int(input('Digite em quantos anos ira pagar o débito: '))
prestação = vc / (tempo * 12)
print('Para pagar uma casa de R$ {:.2f} em {} ano(s) a prestação será de R$ {:.2f}'.format(vc, tempo, prestação))
if prestação > (salario * 0.3):
print('O financiamento FOI NEGADO')
else:
print('O financiamento FOI APROVADO')
|
ff431448d53bf6826ad6e5ceeda581bb08be4bc9 | AnthonyDiTomo/hw-4 | /problem4.py | 505 | 4.0625 | 4 | num1 = int(input("Please enter number 1 "))
num2 = int(input("Please enter number 2 "))
operator = input("What calculation would you like to do? (add, sub, mult, div) ")
if operator == "add":
print(num1 + num2)
elif operator == "sub":
print(num1 - num2)
elif operator == "mult":
print(num1 * num2)
elif operator == "div":
print(num1 / num2)
# answer = "9"
# guess = input("pick a number: ")
# while guess != answer:
# guess = input("Nope! Try again: ")
# print("WINNER!!") |
cf23830ad6768dd3f5ece3a6a22cb30a05a4a2bf | nd-cse-34872-su21/cse-34872-su21-examples | /lecture05/permutations.py | 110 | 4.09375 | 4 | #!/usr/bin/env python3
import itertools
s = 'ABC'
for p in itertools.permutations(s):
print(''.join(p))
|
b67a8cbca23de093b756a95576e879a1d4524032 | c4ristian/collatz | /misc/pitfalls.py | 3,746 | 3.71875 | 4 | """
Dieses Skript beschreibt verschiedene Pitfalls im Umgang mit mathematischen Berechnungen
in Python.
"""
# Imports
import time
import pandas as pd
"""
1.) Rechnen mit grossen Ganzzahlen in Python:
Python ist für die mathematische Forschung praedistintiert, da es
beliebig große Ganzzahlen verarbeiten kann. Hierzu muss man einige Pitfalls vermeiden.
"""
# Falsch: Anwendung einer Division mit nur einem Schraegstrich. Bei dieser Operation wird
# die Zahl in den Datentyp "float" konvertiert. Hierbei kommt es zu einem
# Genauigkeitsverlust. Nur der Datentyp "int" kann beliebig grosse Zahlen speichern
# und verarbeiten.
valid = 5**205 == (5**205 / 5) * 5
print("Division (Falsch):", valid)
# Richtig: Anwendung einer ganzzahligen Division mit zwei Schraegstrichen. Bei dieser Operation
# bleibt die Genauigkeit erhalten. Voraussetzung für die Korrektheit: Anwendbarkeit der ganzzahligen
# Division (nicht fuer Fliesskommazahlen geeignet).
valid = 5**205 == (5**205 // 5) * 5
print("Division (Richtig):", valid)
# Falsch: Berechnungen mit einem "float", anstatt mit einer Ganzzahl. Auch hier kommt es zu
# einer Typkonversion mit Genauigkeitsverlust.
valid = 5**205 + 1 == 5**205 + 1.0
print("Weitere Berechnungen (Falsch):", valid)
# Richtig: Berechnungen mit Ganzzahlen ohne Komma.
valid = 5**205 + 1 == 5 ** 205 + 1
print("Weitere Berechnungen (Richtig):", valid)
"""
2.) Umgang mit grossen Ganzzahlen in Pandas:
Auch in Pandas kann man mit beliebig großen Ganzzahlen arbeiten. Hier die Pitfalls:
"""
# Falsch: Berechnen grosser Zahlen direkt in einer Series oder einem DataFrame.
# Der intern verwendete Pandas Datentyp "int64" ist in seiner Genauigkeit begrenzt.
my_numbers = pd.Series([5, 6])
my_exponents = pd.Series([205, 206])
my_powers = my_numbers ** my_exponents
valid = list(my_powers) == [5**205, 6**206]
print("Berechnung in Pandas (Falsch):", valid)
print("Datatype:", my_powers.dtype)
# Richtig (Alternative 1): Berechnen der großen Zahlen ausserhalb der Series oder
# des DataFrames. Werden die Zahlen extern berechnet, werden sie bei der Erzeugung der
# der Series / des DataFrames im Datentyp "object" gespeichert. Die Genauigkeit
# bleibt erhalten.
my_powers = pd.Series([5**205, 6**206])
valid = list(my_powers) == [5**205, 6**206]
print("Berechnung in Pandas (Alternative 1):", valid)
print("Datatype:", my_powers.dtype)
# Richtig (Alternative 2): Berechnung der Zahlen mit Hilfe einer Lambda-Funktion
# im DataFrame.
my_numbers = pd.Series([5, 6])
my_exponents = pd.Series([205, 206])
my_frame = pd.DataFrame({
"number": my_numbers, "exponent": my_exponents})
my_frame["power"] = my_frame.apply(
lambda x: int(x["number"]) ** int(x["exponent"]), axis=1)
valid = list(my_frame["power"]) == [5**205, 6**206]
print("Berechnung in Pandas (Alternative 2):", valid)
print("Datatype:", my_frame["power"].dtype)
"""
3.) Pandas DataFrames koennen mit relativ vielen Zahlen umgehen. Um eine effiziente
Verarbeitung zu gewahrleisten, muss folgendes beachtet werden.
"""
# Langsam: Iteratives Einfuegen einzelner Zahlen.
print("Einfuegen (Falsch) Start:", time.asctime())
my_numbers = pd.DataFrame({
"number": []
})
for i in range(10000):
my_numbers = my_numbers.append(pd.DataFrame({"number": [i]}), ignore_index=True)
my_numbers.reset_index(drop=True)
print("Einfuegen (Falsch) Ende:", time.asctime())
print(my_numbers.head())
# Schnell: Iteratives Einfuegen der Zahlen zunächst in eine Python-Liste. Dann gesammelte
# Erzeugung eines DataFrames.
print("Einfuegen (Richtig) Start:", time.asctime())
my_list = []
for i in range(10000):
my_list.append(i)
my_numbers = pd.DataFrame({
"number": my_list
})
print("Einfuegen (Richtig) Ende:", time.asctime())
print(my_numbers.head())
|
89154c746da6e15aaef9f763e4c2cd146dfe0164 | daniel-reich/turbo-robot | /trPQbGEb9p2yjMAWb_22.py | 1,018 | 4.1875 | 4 | """
In this challenge, you have to verify that every, or some, of the given
variables, pass a given test condition. There are seven parameters:
* `test`: A string being the condition to verify.
* `val`: A string with two possible values:
* `everybody` if **every** variable has to pass the test;
* `somebody` if **at least one** of the variables has to pass the test.
* `a`, `b`, `c`, `d`, `e`: The variables being integers or booleans.
Create a function that returns `True` or `False`, depending on the result of
the test applied to the variables.
### Examples
every_some(">= 1", "everybody", 1, 1, -1, 1, 1) ➞ False
# Is every variable >= 1?
every_some(">= 1", "somebody", -1, -1, -1, -1, 1) ➞ True
# Is some variable >= 1?
every_some("< 4 / 2", "everybody", 1, 2, 1, 0, -10) ➞ False
# Is every variable < 2?
### Notes
N/A
"""
def every_some(test, val, *args):
l = [eval(str(i)+test) for i in args]
return all(l) if val=="everybody" else any(l)
|
f1e08e0469a26512bf5f20150d51f0267d18d9d0 | sohn0356-git/TIL | /PyStudy/day07/class_ex1.py | 652 | 3.8125 | 4 | class Car:
count = 0
def __init__(self, name):
self.name = name
Car.count += 1
@classmethod
def outcount(cls):
print(cls.count)
@staticmethod
def hello():
print("오늘도 안전운전하세요")
Car.hello()
pride = Car("프라이드")
korando = Car("코란도")
Car.outcount()
print(Car.count)
class Date:
def __init__(self, month):
self.__month = month;
@property
def month(self):
return self.__month
@month.setter
def month(self, month):
if 1 <= month <= 12:
self.__month = month
today = Date(8)
today.month = 15
print(today.month) |
ffd4c8d55c62cfd0f73ac2b58baf623368297248 | josenriagu/fluffy-fiesta | /_dcomp/checkNums.py | 223 | 3.84375 | 4 | def checkNums(num1, num2):
if num2 > num1:
return "true"
elif num1 > num2:
return "false"
else:
return "equal"
print(checkNums(5, 8))
print(checkNums(3, 3))
print(checkNums(100, -100))
|
2035a73761aaea1786a3f888242df8f476b48b4a | Lain928/MachineLearning | /sklearn学习/sklearn_xgboost.py | 1,370 | 3.53125 | 4 | # -*- coding: utf-8 -*-
### load module
from sklearn import datasets
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
### 1 加载数据load datasets
# 手写数字识别数据集
digits = datasets.load_digits()
### 2 数据分析 data analysis
print(digits.data.shape) # 输入空间维度
print(digits.target.shape) # 输出空间维度
### 3 数据集切分data split
x_train,x_test,y_train,y_test = train_test_split(digits.data,
digits.target,
test_size = 0.3,
random_state = 33)
### 4 训练模型 fit model for train data
### 模型的参数设置
model = XGBClassifier()
model.fit(x_train,y_train)
### 5 测试集预测 make prediction for test data
y_pred = model.predict(x_test)
### 6 模型评价 model evaluate 使用sklearn自带的评价效果估计准确率
accuracy = accuracy_score(y_test,y_pred)
print("accuarcy: %.2f%%" % (accuracy*100.0))
### 7 可视化结果 用于分类的
### 特征重要性 特征值越大 表明该特征越重要
import matplotlib.pyplot as plt
from xgboost import plot_importance
fig,ax = plt.subplots(figsize=(10,15))
plot_importance(model,height=0.5,max_num_features=64,ax=ax)
plt.show() |
1acdb1e7e7ee5df6c97affeea7f4611d814c605b | CableX88/Projects | /Python projects/Exam 1 Problem1.py | 611 | 4 | 4 | ##Test Program 1
##David Brown
taxable_income = float(input('Enter your income:$'))
tax_owed = 0
#calc
if taxable_income > 0 and taxable_income < 9325.0:
tax_owed = taxable_income*0.1
elif taxable_income >= 9325.0 and taxable_income < 37950:
tax_owed = (taxable_income*0.15)+932.50
else:
tax_owed = (taxable_income*0.25)+5226.25
print('your taxes owed:$',tax_owed)
'''
Enter your income:$5100
your taxes owed: $510.0
Enter your income:$10050.50
your taxes owed: $2440.075
Enter your income:38012.75
your taxes owed: $14729.4375
>>>
Enter your income:$5000
your taxes owed:$ 500.0
>>>
'''
|
c7040fc150a0a581f056c3b2a0109fee92e884c8 | atronk/python | /low-level/types/test_list2.py | 532 | 4.125 | 4 | list1 = [1, 2, 3, 'a', 'b', 'c']
print("we got list: ", list1)
print(list1[0:3])
print(list1[2:5])
print(list1[2:])
print(list1[:])
print(list1[::2])
print(list1[1::2])
my_list = [22, 109, 'Apple', 11.2, 'Orange', 'Cherry', (10, 20, 30), [], False, 72, 'Kiwi', 0.0]
x = my_list[6:8]
print(x)
my_list = [10, 'x', 20.02, 'y', 30j, 'z', False]
my_list.append("Python 3")
print(my_list)
my_list = [10, 'x', 20.02, 'y', 30j, 'z', False]
my_list.pop(1)
print(my_list)
my_list = [10, -5, 20.02, 2018, 999]
my_list.sort()
print(my_list) |
95544c56c40675c178538ea3cba21c31b2e9b841 | dreaminkv/project | /dz.py | 5,008 | 3.953125 | 4 | # Написать функцию num_translate(), переводящую числительные от 0 до 10 c
# английского на русский язык. Например:
# >>> num_translate("one")
# "один"
# >>> num_translate("eight")
# "восемь"
# Если перевод сделать невозможно, вернуть None. Подумайте, как и где
# лучше хранить информацию, необходимую для перевода: какой тип данных выбрать,
# в теле функции или снаружи.
# def num_translate(number):
# numbers = {'zero': 'ноль', 'one': 'один', 'two': 'два', 'three': 'три', 'four': 'четыре',
# 'five': 'пять', 'six': 'шесть', 'seven': 'семь', 'eight': 'восемь', 'nine': 'девять',
# 'ten': 'десять'}
# if number in numbers:
# print(numbers[number])
# else:
# return None
#
#
#
#
# num_translate('zero')
def num_translate(number):
numbers = {'zero': 'ноль', 'one': 'один', 'two': 'два', 'three': 'три', 'four': 'четыре',
'five': 'пять', 'six': 'шесть', 'seven': 'семь', 'eight': 'восемь', 'nine': 'девять',
'ten': 'десять', 'Zero': 'Ноль', 'One': 'Один', 'Two': 'Два', 'Three': 'Три',
'Four': 'Четыре', 'Five': 'Пять', 'Six': 'Шесть', 'Seven': 'Семь', 'Eight': 'Восемь',
'Nine': 'Девять', 'Ten': 'Десять'}
if number in numbers:
print(numbers[number])
else:
return None
num_translate('Ten')
#####################################################################################################################################
# Написать функцию thesaurus(), принимающую в качестве аргументов имена сотрудников и возвращающую словарь,
# в котором ключи — первые буквы имён, а значения — списки,
# содержащие имена, начинающиеся с соответствующей буквы. Например:
# >>> thesaurus("Иван", "Мария", "Петр", "Илья")
# {
# "И": [],
# "М": [], "П": []
# }
# Подумайте: полезен ли будет вам оператор распаковки? Как поступить, если потребуется сортировка по ключам? Можно ли использовать словарь в этом случае?
def works_lis(*args):
works_dict = {}
works_dict_sort = []
for i in sorted(args):
alphabetic = i[0]
if alphabetic in works_dict:
works_dict[alphabetic].append(i)
else:
works_dict[alphabetic] = [i]
print(works_dict)
works_lis('Иван', 'Ирина', 'Инга', 'Вадим', 'Николай', 'Евгений', 'Елена', 'Анатолий', 'Валерий')
#####################################################################################################################################
# Реализовать функцию get_jokes(), возвращающую n шуток, сформированных
# из трех случайных слов, взятых из трёх списков (по одному из каждого):
#
# Например:
# >>> get_jokes(2)
# ["лес завтра зеленый", "город вчера веселый"]
#
#
# Документировать код функции.
# Сможете ли вы добавить еще один аргумент — флаг, разрешающий или запрещающий
# повторы слов в шутках (когда каждое слово можно использовать только в одной шутке)?
# Сможете ли вы сделать аргументы именованными?
# Задачи со * предназначены для продвинутых учеников, которым мало сделать обычное задание
import random
def get_jokes(number_of_jokes=0, nuko=False):
nouns = ["автомобиль", "лес", "огонь", "город", "дом"]
adverbs = ["сегодня", "вчера", "завтра", "позавчера", "ночью"]
adjectives = ["веселый", "яркий", "зеленый", "утопичный", "мягкий"]
ready_made_jokes = []
for i in range(0, number_of_jokes):
collect_jokes = random.choice(nouns), random.choice(adverbs), random.choice(adjectives)
if nuko:
nouns.remove(collect_jokes[0])
adverbs.remove(collect_jokes[1])
adjectives.remove(collect_jokes[2])
ready_made_jokes.append((' '.join(collect_jokes)))
print(ready_made_jokes)
get_jokes(5, False)
|
aae55092aacae6be1d6975fdb5b2acb8c4f4998d | Waffenfliege/MLProject-UnknownData | /Hakan Notebook/MLDL Projekt - HARB/notebook/data_and_visualization.py | 3,763 | 3.5 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from random import randint
class Data:
def __init__(self, file):
self.file = file
self.raw_data = self.read_dataset()
def printData(self):
print(self.file)
#Read data from csv
def read_dataset(self):
data = pd.read_csv(self.file)
return(data)
#Get the data, its features and labels
def get_data_features_labels(self):
data = self.raw_data.copy()
#Get the data labels/classes
labels = data['class']
#Delete feature - class
data.pop('class')
data.pop('Person')
data.pop('NA')
#Get the data features
features = data.columns.values
return(data, features, labels)
#Create random blind test set in 30 chunks and drop it from train test set
def create_blind_test_set(self, no_of_datarecords=3, path="../data/processed/"):
reduced_dataset = self.raw_data.copy()
blind_dataset = self.raw_data[0:0]
selected_data_records = []
no_data_records = len(self.raw_data)/30
for i in range(no_of_datarecords):
random_no = randint(1,no_data_records)
if random_no not in selected_data_records:
selected_data_records.append(random_no)
selected_data_records= sorted(selected_data_records, reverse=True)
for i in selected_data_records:
no_row = (i-1)*30
blind_dataset = blind_dataset.append(self.raw_data.iloc[no_row:(no_row+30)])
reduced_dataset = reduced_dataset.drop(reduced_dataset.index[no_row:(no_row+30)])
blind_dataset.to_csv(path_or_buf=path+"blind_dataset.csv", index=False)
reduced_dataset.to_csv(path_or_buf=path+"train_dataset.csv", index=False)
return(reduced_dataset, blind_dataset)
def get_min_max_mean(self):
#Check if there are empty entries
emtpy_values = self.raw_data.isnull().any().sum()
#Get the min and max values of each features
min_values = self.raw_data.min()
max_values = self.raw_data.max()
mean_values = self.raw_data.mean()
#Get the min and max of the complete dataset
min_value = min_values.min()
max_value = max_values.max()
mean_value = mean_values.mean()
print('No. of empty values: ' + str(emtpy_values))
print('Max value of Dataset: ' + max_values.idxmax() +' '+ str(max_value)) #=> DH69 Highest Value of Dataset
print('Min value of Dataset: ' + min_values.idxmin() +' '+ str(min_value)) #=> T15 lowest Value of Dataset
print('Mean value of Dataset: ' + str(mean_value))
def plot_mean_values(self):
self.raw_data.mean().plot()
plt.title("Mean value of each feature")
plt.show()
def plot_min_values(self):
self.raw_data.min().plot()
plt.title("Minimum value of each feature")
plt.show()
def plot_max_values(self):
self.raw_data.max().plot()
plt.title("Maximum value of each feature")
plt.show()
def plot_number_entries_for_class(self):
#Visualize a number of entries of the respective class
data, features, labels = self.get_data_features_labels()
count_labels = labels.value_counts().sort_index()
print(count_labels)
count_labels.plot(kind = 'bar', rot=0)
plt.title("Distribution of the entries to the classes")
plt.xticks(range(4), count_labels.index)
plt.xlabel("Class")
plt.ylabel("Entries")
plt.show()
|
d1b5be35af5de8c946b92c9ab8b54ddc1c710618 | KnightZhang625/Stanford_Algorithm | /Course_1/Week_03/1_naive_quick_sort.py | 567 | 4.1875 | 4 | def partition(array, start, end):
pivot = array[start]
while start < end:
while start < end and array[end] >= pivot:
end -=1
array[start] = array[end]
while start < end and array[start] <= pivot:
start +=1
array[end] = array[start]
array[start] = pivot
return start
def quickSort(array, left, right):
if left < right:
i = partition(array, left, right)
quickSort(array, left, i-1)
quickSort(array, i+1, right)
if __name__ == '__main__':
array = [3, 8, 2, 5, 1, 4, 7, 6, 9]
quickSort(array, 0, len(array) - 1)
print(array)
|
fc03975c0014cc3ae8b574596495e1c4e97e3beb | AlexWilliam/PythonUdemy | /excript/app-comerciais-kivy/aulas/aula73.py | 259 | 4.125 | 4 | lista = ['Alex', 'William', 'Heitor', 'Carlos', 'Joao']
print(lista)
# Inverte os itens da lista
lista.reverse()
# Ordenar de forma ascendente
lista.sort()
# Ordenando com parametros, com ordenacao reversa(Ordenacao descendente)
lista.sort(reverse=True)
|
dbc033d3f580832472f68fa5752a24cee1a29168 | Dharm3438/Problem-Solving | /3.Codeforces/next_round.py | 302 | 3.671875 | 4 | arr = input().split()
scores = input().split()
participant = int(arr[1])
count=0
check_score = int(scores[participant-1])
for item in scores:
if(int(item) >= check_score and (int(item)!=0 or check_score!=0 )):
count = count+1
elif(int(item)<check_score):
break
print(count)
|
ea79a87a0a3ffdf9d2d3a0e48aad73ef0be7f61e | yao12310/fodinha | /utils/card.py | 3,131 | 3.921875 | 4 | '''
Util file for Card-related classes.
'''
import itertools
import random
from utils.constants import Gameplay
'''
Class for data structure representing collection of cards, used for decks, player hands, and lists of shown cards
CardCollection houses a list of Card objects, and provides methods for shuffling and dealing cards
'''
class CardCollection:
def __init__(self, cardRange = None, cards = []):
if cards:
self.cards = cards
elif cardRange:
self.cards = [
Card(num, suit) for (num, suit) in
list(itertools.product(range(cardRange), CardInfo.SUITS))
]
elif not cardRange and not cards:
self.cards = []
def deal(self, numCards, numHands):
return [
CardCollection(cards = self.cards[(i * numCards):((i + 1) * numCards)]) for i in range(numHands)
]
def shuffle(self):
random.shuffle(self.cards)
def slice(self, start, end):
return CardCollection(cards = self.cards[start:end])
def get(self, index):
return self.cards[index]
def append(self, card):
self.cards.append(card)
def pop(self, index = -1):
return self.cards.pop(index)
def copy(self):
return CardCollection(cards = list(self.cards))
def __str__(self):
return str([str(card) for card in self.cards])
def __len__(self):
return len(self.cards)
def __iter__(self):
yield from self.cards
'''
Class for representing cards
Each card stores a number and a suit, as well as a string-translated rank
'''
class Card:
def __init__(self, num, suit):
self.num = num
self.suit = suit
self.rank = CardInfo.RANKS[num]
def __str__(self):
return self.rank + " of " + self.suit
def __eq__(self, other):
if not isinstance(other, Card):
return False
return (self.num == other.num) and (self.suit == other.suit)
def __hash__(self):
return hash((self.num, self.suit))
def __contains__(self, item):
return any([item == card for card in self.cards])
'''
Static class for card information
Stores information on suits, ranks, and comparison
'''
class CardInfo:
SPADES = "Spades"
HEARTS = "Hearts"
CLUBS = "Clubs"
DIAMONDS = "Diamonds"
SUITS = [DIAMONDS, CLUBS, HEARTS, SPADES]
SUIT_RANKS = {SPADES: 3, HEARTS: 2, CLUBS: 1, DIAMONDS: 0}
RANKS = [
"A", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "J", "Q", "K"
]
'''
Static class for card utils
Stores methods for ranking cards and joining collections
'''
class CardUtils:
def cardRankerGen(power, cardRange):
def cardRanker(card):
if not card:
return -1
if card == Gameplay.CANCELLED:
return -1
if card.num != power:
return card.num
return cardRange + CardInfo.SUIT_RANKS[card.suit]
return cardRanker
def joinCollections(collect1, collect2):
return CardCollection(collect1.cards + collect2.cards) |
997a891a81d2ec3aca2b040027a2ce478685a000 | henrymrrtt67/bookProject | /mainF.py | 714 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 8 12:12:23 2019
@author: Henry
"""
#importing a language package in order to tokenize the words
import nltk
#Defining the main and letting it be able to be called and must go through this every time
def main():
# downloads data, reads the data and places this sentence into a variable, then placing it into the tokenizer
data = load_data()
data = data.read()
tokens = tokenize(data)
#opens the file and downloads the file
def load_data():
return open("test.txt","r")
#tokenizes the sentece with word tokenizer and returns these individual tokens in an array.
def tokenize(data):
tokens = nltk.word_tokenize(data)
return tokens
main() |
c11a7e365f61ac3dc569b7528b6d19999f949a70 | LeoTheMighty/beginner_python_exercises | /NumberGuesser.py | 1,449 | 4.0625 | 4 | def find_yes_or_no(boolString):
s = boolString.lower()
if s == "no" or s == "nah" or s == "n":
return False
elif s == "yes" or s == "yeah" or s == "y":
return True
else:
return -1
guessString = "lower"
bottom, top = 0, 1
ifFirstSection = True
ifSecondSection = False
ifPositive = True
ifGuessing = True
# find top with just positive
while ifFirstSection:
if find_yes_or_no(input("Is your number " + guessString + " than " + str(top) + "?\n")):
if top is 1:
ifPositive = False
bottom = -1
top = 0
ifSecondSection = True
guessString = "higher"
ifFirstSection = False
else:
bottom = top
top *= 10
# top is set find negative side
while ifSecondSection:
if find_yes_or_no(input("Is your number " + guessString + " than " + str(bottom) + "?\n")):
ifSecondSection = False
else:
top = bottom
bottom *= 10
# top and bottom are set
while ifGuessing:
guess = int((top + bottom) / 2)
answer = find_yes_or_no(input("Is your number " + guessString + " than " + str(guess) + "?\n"))
interestNum = 0
if answer != ifPositive:
interestNum = bottom
bottom = guess
else:
interestNum = top
top = guess
if guess == interestNum and not answer:
ifGuessing = False
print("Your number is " + str(guess) + "! I guessed it!")
|
d9a30bfb7ffd46fa6ee75eb0c4ada2e7debf838c | RioRocker97/DistractMyselfFrom_Crypto | /Python/String_index2.py | 531 | 4.09375 | 4 | name = "chang" #String in a LIST
print(name[0:2]) #Use n:n as a substring
print(name[:3]) # use :n as a substring AT 0 to n point
print(name[3:]) # use n: as a substring AT n point to last
print(name[::2]) # use ::n to return a string at every n index
print(name[::-2])
print(name[:-2])
for n in name[2:]: #Finally , LOOP for
print(n)
for n in name: #Finally , LOOP for
a = 1
print(a,n)
a+=1
a = len(name)
print(a)
print(name.count('1'))
print(name.find('h',0)) #return index of that character or -1 if not found |
58094a7cad022095eb3e48dae7753e78c4f5e665 | PlayPurEo/Python-Leetcode | /Leetcode/code146.py | 2,455 | 3.828125 | 4 | # author : 'wangzhong';
# date: 05/12/2020 23:53
"""
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
"""
class Node:
def __init__(self, key, val, next=None, prev=None):
self.key = key
self.val = val
self.next = next
self.prev = prev
class douleList:
def __init__(self):
# 伪头结点和伪尾节点
self.head = Node(-1, -1)
self.tail = Node(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def addFirst(self, node: Node):
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
self.size += 1
def remove(self, node: Node):
node.next.prev = node.prev
node.prev.next = node.next
self.size -= 1
def removeLast(self) -> Node:
lastNode = self.tail.prev
self.remove(lastNode)
return lastNode
def getSize(self) -> int:
return self.size
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
# 用作哈希
self.hashMap = dict()
# 双向链表,构成哈希双向链表
self.cache = douleList()
def get(self, key: int) -> int:
if key not in self.hashMap:
return -1
node = self.hashMap[key]
self.put(key, node.val)
return node.val
def put(self, key: int, value: int) -> None:
newNode = Node(key, value)
if key in self.hashMap:
self.cache.remove(self.hashMap[key])
self.cache.addFirst(newNode)
self.hashMap[key] = newNode
else:
if self.cap == self.cache.getSize():
lastNode = self.cache.removeLast()
self.hashMap.pop(lastNode.key)
self.cache.addFirst(newNode)
self.hashMap[key] = newNode
|
c56f4d26e0bf7e2c3dd72df449f7e021df042568 | pgrubacc/codility_tasks | /maximum_slice/max_slice_algorithm.py | 327 | 3.703125 | 4 | def max_subarray(numbers):
best_sum = None # or: float('-inf')
current_sum = 0
for x in numbers:
current_sum = max(0, current_sum + x)
best_sum = max(best_sum, current_sum)
return best_sum
assert (max_subarray([-1, 0, 3, -2, 5, 6])) == 12
assert (max_subarray([-1, 0, 3, -4, 5, 6])) == 12
|
995a3f70b660f17d62a22fbe8b24c2e372b11249 | lzj322/leetcode | /twenty_four.py | 635 | 3.59375 | 4 | def list_result(l):
if len(l) == 1:
return [l]
all_result = []
for index,item in enumerate(l):
r = list_result(l[0:index] + l[index+1:])
print (l[0:index] + l[index+1:])
# map(lambda x : x.append(item),r)
# all_result.extend(r)
return all_result
def func(x):
return x*x
if __name__ == '__main__':
l=[1,2,3]
t=[4]
index=2
r=l[0:index] + l[index+1:]
print (r)
#print (l[0:index] + l[index+1:])
map(lambda x:x.append(t),l)
print (l)
# r=map(func,l)
# print (l)
# print (list(r))
#print (list_result(s)) |
3e080ed9c6fd21f48c92a0432d74d327482e673d | svineet/MarkovLanguageModel | /trigram.py | 2,893 | 3.5625 | 4 | import random
from time import time
from collections import defaultdict
STARTCHAR = "<s>"
ENDCHAR = "</s>"
def generate_ngrams():
bigram = defaultdict(int)
# Stores bigram -> occurences
trigram = defaultdict(int)
# Stores trigram -> occurences
vocab = set()
brown = open("data/browncorpus.txt", "r")
for line in brown:
line_words = line.split()
if len(line_words) < 3:
continue
for (i, word) in enumerate(line_words):
vocab.add(word)
if i == 0:
bigram[(STARTCHAR, word)] += 1
trigram[(STARTCHAR, STARTCHAR, word)] += 1
elif i == 1:
bigram[(line_words[i-1], word)] += 1
trigram[(STARTCHAR, line_words[i-1], word)] += 1
else:
bigram[(line_words[i-1], word)] += 1
trigram[(line_words[i-2], line_words[i-1], word)] += 1
bigram[(line_words[-1], ENDCHAR)] += 1
trigram[(line_words[-2], line_words[-1], ENDCHAR)] += 1
trigram[(line_words[-1], ENDCHAR, ENDCHAR)] += 1
return (bigram, trigram, vocab)
def main(bigram, trigram, vocab):
print(len(vocab))
def dfs(word1, word2, word3, bigram, trigram, vocab):
print (word3, sep=" ", end=" ", flush=True)
if (word3 == ENDCHAR): return ["."]
# if (word1 == STARTCHAR and word2 == STARTCHAR):
# triple = (STARTCHAR, STARTCHAR, word2)
# for (i, word) in enumerate(vocab):
# for word_ in vocab:
# print (i, flush=True)
# if trigram[(word, word_, word3)] > trigram[triple]:
# triple = (word, word_, word3)
# word1, word2, word3 = triple
# print (triple)
if (word1 == STARTCHAR and word2 == STARTCHAR):
for word in vocab:
if (bigram[word, word3] > 0):
word2 = word
sm = 0
for word in vocab:
occ = trigram[(word2, word3, word)]
if (occ == 0):
continue
else:
sm += occ
choice = int(random.uniform(0, sm))
acc = 0
for word in vocab:
occ = trigram[(word2, word3, word)]
if (occ == 0): continue
if acc <= choice and choice <= acc+occ:
return [word3]+dfs(word2, word3, word, bigram, trigram, vocab)
acc += occ
if (sm == 0): return []
if __name__ == '__main__':
print ("This uses the trigram model on "
"the brown corpus to generate random "
"sentences.")
t = time()
bigram, trigram, vocab = generate_ngrams()
print(time()-t)
random.seed(time())
main(bigram, trigram, vocab)
s = input()
while (s != "stfu"):
if (s not in vocab):
print("no pls change idk.")
else:
dfs(STARTCHAR, STARTCHAR, s, bigram, trigram, vocab)
print()
s = input()
|
ec1e34574dd6d60377542a895b583cf904060025 | Jianshu-Hu/dairlab | /data_process/data_process_find_boundary/plot_normalized_landscape.py | 4,645 | 3.734375 | 4 | """
This function is used for plotting normalized cost landscape.
Considering we search along several directions, we process the data along those directions
1.
For each direction, we compare the cost at each point on the searching line both in cost landscape 1 and
cost landscape and set the value of reasonable point with the normalized cost.
2.
For those points which exist in the cost landscape we want to normalize but not in the nominal cost landscape,
we set the value of this point 0.5.
"""
import matplotlib.pyplot as plt
import numpy as np
import os
import math
robot_option = 1
file_dir = '/Users/jason-hu/'
if robot_option == 1:
robot = 'cassie/'
else:
robot = 'five_link/'
dir1 = file_dir + 'dairlib_data/find_boundary/' + robot + '2D_rom/2D_task_space/' + 'robot_' + str(robot_option) + \
'_large_iter100/'
dir2 = file_dir + 'dairlib_data/find_boundary/' + robot + '2D_rom/2D_task_space/' + 'robot_' + str(robot_option) + \
'_small_iter200/'
# number of searching directions
n_direction = 16
# optimization range
min1 = 0.2775
max1 = 0.3075
min2 = -0.1875
max2 = 0.0625
plot_optimization_range = 0
# Note:decide which column of the task to plot according to the task dimensions
# Eg. column index 0 corresponds to stride length
task_name = ['Stride length', 'Ground incline', 'Velocity', 'Turning rate']
task_1_idx = 0
task_2_idx = 1
def process_data_from_direction(i, dir1, dir_nominal):
# need to add central point on the points list
task0 = np.genfromtxt(dir1 + str(0) + '_' + str(0) + '_gamma.csv', delimiter=",")
x = [task0[task_1_idx]]
y = [task0[task_2_idx]]
cost1 = float(np.genfromtxt(dir1 + str(0) + '_' + str(0) + '_c.csv', delimiter=","))
cost2 = float(np.genfromtxt(dir_nominal + str(0) + '_' + str(0) + '_c.csv', delimiter=","))
z = [cost1 / cost2]
data_dir1 = np.genfromtxt(dir1 + str(int(i+1)) + '_cost_list.csv', delimiter=",")
data_dir2 = np.genfromtxt(dir_nominal + str(int(i+1)) + '_cost_list.csv', delimiter=",")
if data_dir1.shape[0] >= data_dir2.shape[0]:
num_small = data_dir2.shape[0]
num_large = data_dir1.shape[0]
else:
num_small = data_dir1.shape[0]
num_large = data_dir2.shape[0]
# process the points on the line
# set the value for intersected parts
for j in range(num_small):
cost1 = data_dir1[j, 1]
cost2 = data_dir2[j, 1]
# we only append reasonable point
if (cost1 < 35) & (cost2 < 35) & (cost1/cost2<2):
task = np.genfromtxt(dir1 + str(int(data_dir1[j, 0])) + '_' + str(0) + '_gamma.csv', delimiter=",")
x.append(task[task_1_idx])
y.append(task[task_2_idx])
z.append(cost1/cost2)
for j in range(num_small, num_large):
if data_dir1.shape[0] >= data_dir2.shape[0]:
# extended range
task = np.genfromtxt(dir1 + str(int(data_dir1[j, 0])) + '_' + str(0) + '_gamma.csv', delimiter=",")
x.append(task[task_1_idx])
y.append(task[task_2_idx])
z.append(0)
return x, y, z
def generateplot(dir1, dir_nominal, adj_index, levels, ticks):
total_max = 0
for i in range(n_direction):
# process data on one line
x1, y1, z1 = process_data_from_direction(i, dir1, dir_nominal)
# process data on adjacent line
x2, y2, z2 = process_data_from_direction(adj_index[i], dir1,dir_nominal)
# plot
x = x1+x2
y = y1+y2
z = z1+z2
surf = ax.tricontourf(x, y, z, levels=levels)
if max(z) > total_max:
total_max = max(z)
print('max', total_max)
fig.colorbar(surf, shrink=0.9, aspect=10, spacing='proportional', ticks=ticks)
# continuous color map
# plt.rcParams.update({'font.size': 28})
# fig, ax = plt.subplots(figsize=(11,5.5))
fig, ax = plt.subplots()
# ceil = int(math.ceil(max(z)))
# print('ceil:', ceil)
levels = [0.0, 0.5, 1, 1.5, 2] # manual specify level sets
ticks = [0.0, 0.5, 1, 1.5, 2] # manual specify ticker values (it seems 0 is ignored)
print(levels)
adjacent = np.genfromtxt('adjacent.csv', delimiter=",")
generateplot(dir1,dir2, adjacent, levels, ticks)
ax.set_xlabel(task_name[task_1_idx])
ax.set_ylabel(task_name[task_2_idx])
ax.set_title('Normalized cost landscape')
if plot_optimization_range == 1:
x_line = np.array([min1, max1, max1, min1, min1])
y_line = np.array([min2, min2, max2, max2, min2])
ax.plot(x_line, y_line, 'black', linewidth=3)
# so that the label is not cut off by the window
# plt.tight_layout()
# plt.gcf().subplots_adjust(bottom=0.18)
# plt.gcf().subplots_adjust(left=0.15)
plt.show() |
b11dc4672e1477c26541a2b59d181655735c100b | ParkinWu/leetcode | /python/leetcode/496.py | 2,039 | 3.84375 | 4 | # 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
#
# nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
#
# 示例 1:
#
# 输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
# 输出: [-1,3,-1]
# 解释:
# 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
# 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
# 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
# 示例 2:
#
# 输入: nums1 = [2,4], nums2 = [1,2,3,4].
# 输出: [3,-1]
# 解释:
# 对于num1中的数字2,第二个数组中的下一个较大数字是3。
# 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
# 注意:
#
# nums1和nums2中所有元素是唯一的。
# nums1和nums2 的数组大小都不超过1000。
#
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/next-greater-element-i
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
from typing import List
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
map = {}
res = [-1] * len(nums2)
for i, v in enumerate(nums2):
map[v] = i
if stack:
while stack and nums2[stack[-1]] < v:
res[stack[-1]] = v
stack.pop(-1)
stack.append(i)
ans = [-1] * len(nums1)
for i, v in enumerate(nums1):
if res[map[v]] >= 0:
ans[i] = res[map[v]]
return ans
if __name__ == '__main__':
s = Solution()
print(s.nextGreaterElement([4, 1, 2], [1, 3, 4, 2 ]))
|
19abe9ba5b5e0a314abb1cd6c8b93663c8bb07cf | python-ops-org/python-ops | /dates/26-08-2020-local/regex/p01.py | 808 | 4.09375 | 4 |
import pandas as pd
import numpy as np
"""
#Example-1
#create a series from ndarray
#index taken by default
d = np.array(['Aws', 'Azure', 'GCP', 'OPENSTACK' ])
s = pd.Series(d)
print(s)
"""
"""
#Example-2
#index will be passed
d = np.array(['AWS', 'AZURE', 'GCP', 'OPENSTACK'])
s = pd.Series(d,index=[100,101,102,103])
print(s)
"""
"""
d = {'cloud1': "aws", 'cloud2': 'azure'}
s = pd.Series(d)
print(s)
"""
"""
d = {'1': "aws", '2': 'azure'}
s = pd.Series(d, index=['1', '2','3'])
print(s)
"""
"""
#Retrieve multiple elements using a list of index label values.
s = pd.Series([1,2,3],index = ['a','b','c'])
#retrieve multiple elements
print(s[['a','b','c']])
"""
"""
#Accessing Data from Series with Position
import pandas as pd
s = pd.Series([1,2,3],index = ['a','b','c'])
print(s[2])
"""
|
1cf59d26b276c17df43848c8e73736589f5b37b8 | VamsiKrishnaRachamadugu/python_solutions | /practice/class_and_static_variables.py | 331 | 3.5625 | 4 | class Parent():
name = 'vamsi'
def display():
print('self keyword')
p = Parent()
p.display()
# Parent.display()
# def __init__(self, name, age, gender):
# self.age = age
# self.gender = gender
# self.name = name
# p = Parent('venu', 22, 'M')
# print(p.name)
# print(p.age, p.gender)
|
df0723c1d21c75618e329ae9de09be1b74b9b5c4 | barisulusoy/GlobalAIHubPythonCourse | /Homeworks/HW1.py | 3,451 | 4.21875 | 4 | """
HOMEWORK1
BARIŞ ULUSOY
baris.ulusy@gmail.com
"""
print("######################################################################")
print("############################## 1. KISIM ##############################")
print("######################################################################")
##=> Dizinin oluşturulması ve terminal'e yazdırılması
###############################################################################
my_array = [1, 8, 3, 13, 97, 128, 6, 88, 91, 2021]
print("Oluşturulan Dizi:", my_array)
##=> Dizinin kaça bölüneceğinin belirlenmesi
###############################################################################
number = 2
average = len(my_array) / float(number)
last_number = 0.0
##=> Bölünmüş dizinin tutulacağı dizinin oluşturulması
###############################################################################
out_array = []
##=> Dizinin bölünmesi işlemi
###############################################################################
while last_number < len(my_array):
out_array.append(my_array[int(last_number):int(last_number + average)])
last_number = last_number + average
##=> Bölünen dizinin iki farklı dizide saklanması
###############################################################################
first_half = out_array[0]
second_half = out_array[1]
##=> Oluşturulan dizinin tüm elemanlarının silinmesi
###############################################################################
for i in range(len(my_array)):
my_array.pop()
##=> Dizinin istenilen formatta yeniden oluşturulması
###############################################################################
for i in range(len(second_half)):
my_array.append(second_half[i])
for i in range(len(first_half)):
my_array.append(first_half[i])
##=> Oluşturulan yeni diznin ekranda gösterilmesi
###############################################################################
print("Değiştirilen Dizi:", my_array)
print("######################################################################")
print("############################## 2. KISIM ##############################")
print("######################################################################")
##=> Sonsuz döngü sayesinde kullanıcı hatalı giriş yaparsa, uyarılır
##=> ve yeniden değer girmesi sağlanır:
###############################################################################
while True:
##=> Kullanıcının değer girmesi işlemi
n = (input("Tek basamaklı bir tamsayı giriniz!:"))
try:
##=> Kullanıcı 0 veya tek basamaklı pozitif tam sayı girmiş ise:
if len(str(n)) == 1 and int(n) >= 0:
even_numbers = []
for i in range(0, int(n)+1, 1):
if i % 2 == 0:
even_numbers.append(i)
print(str(n)+"'e kadar olan çift sayılar:", even_numbers)
break
##=> Kullanıcı tek basamaklı negatif tam sayı girmiş ise:
elif len(str(n)) == 2 and int(n) < 0:
even_numbers = []
for i in range(0, int(n)-1, -1):
if i%2 == 0:
even_numbers.append(i)
print(str(n)+"'e kadar olan çift sayılar:", even_numbers)
break
##=> Kullanıcı hatalı bir giriş yapmış ise:
else:
print("Lütfen tek basamaklı bir tam sayı giriniz!")
except:
print("Lütfen tek basamaklı bir tam sayı giriniz!") |
fb94ab9f709310379c9f6d354ae9f00a340c2846 | Templario17/componentes_vector | /componentes_vector.py | 404 | 3.65625 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# componentes para un vector
import math
dist = 200
grados = 30
def magnitud(dist, grados):
g = math.radians(grados)
i = dist * math.cos(g)
j = dist * math.sin(g)
mag = math.sqrt(i ** 2+ j ** 2)
print "las componentes del vector ({} i),({} j) ".format(i,j)
print "la magnitud del vector es :\n{}".format(mag)
magnitud(dist,grados)
|
796d2aaf132ae7bc024513cf1bbee78f8c01d191 | jgates5/python_learning | /nested_lists_for_storing_datatypes.py | 550 | 3.703125 | 4 | """users = ['Kristine', 'Tiffany', 'Jordan', 'Leann']
ids = [1, 2, 3, 4]
mixed_list = [42, 10.3, 'Altuve', users]
print(mixed_list)
user_list = mixed_list.pop()
print(user_list)
print(mixed_list)
nested_lists = [[123], [234], 345]] most basic list possible
teams = [
{
'astros': {
'2B': 'Altuve',
'SS': 'Correa',
'3B': 'Bregman',
}
},
{
'angels': {
'OF': 'Trout',
'DH': 'Pujols',
}
}
]
# print(teams[0])
angels = teams[1].get('angels', 'Team not found')
print(list(angels.values())[1])""" |
ea5d260dc905da9bbf418d22b76f8581e0456b0e | andrewminai24/COMSC-122-Luis | /Hw06/Luis-Hwrk6.py | 1,480 | 3.9375 | 4 | #Luis Mejia
#A Coffee File Management Program
import LastnameFirstInitial_coffee_records
#Here's ehere we import the module that we just made.
ADD_COFFEE_CHOICE=1 #define global constants for all the choices
SHOW_COFFEE_CHOICE=2
SEARCH_COFFEE_CHOICE=3
MODIFY_COFFEE_CHOICE=4
DELETE_COFFEE_CHOICE=5
QUIT_CHOICE=6
#Which includes the choice to quit
def main():
choice=0
while choice != QUIT_CHOICE:
display_menu()
choice=int(input("Enter your choice: "))
if choice==ADD_COFFEE_CHOICE:
LastnameFirstInitial_coffee_records.add_coffee() #We call the function
elif choice==SHOW_COFFEE_CHOICE:
LastnameFirstInitial_coffee_records.show_coffee()
elif choice==SEARCH_COFFEE_CHOICE:
LastnameFirstInitial_coffee_records.search_coffee()
elif choice == MODIFY_COFFEE_CHOICE:
LastnameFirstInitial_coffee_records.modify_coffee()
elif choice==DELETE_COFFEE_CHOICE:
LastnameFirstInitial_coffee_records.delete_coffee()
elif choice==QUIT_CHOICE:
print("Exiting the program...")
else:
print("Error: invalid selection.")
def display_menu():
print("\nJUAN VALDEZ COFFEE MANAGEMENT MENU")
print("1) Add more Coffee Choices to List")
print("2) Display all the Coffee Choices")
print("3) Search Coffee Choices")
print("4) Modify coffee Choices")
print("5) Delete a Coffee Choice")
print("6) Quit")
main() |
d44f65afb80e8e48e76377ea40b33f738e340794 | juliosimply/Aulas-Python-Guanabara | /Exercicio 027.py | 225 | 3.921875 | 4 | # Exercicio 027 primeiro e ultimo no de uma pessoa
n = str(input('Digite o nome complet')).strip()
nome = n.split()
print('Seu primeiro nome é {} '.format(nome[0]))
print('e seu ultimo nome é {}'.format(nome[len(nome)-1])) |
98c0d82c8927782341b6b40aeac12dbfc074b030 | pomadka/Learn_basics_of_Python | /conditions/boolean_operators.py | 291 | 4.1875 | 4 | x = 3
print (x == 3)
print (x == 45)
print (x < 70)
name = "Vlada"
age = 20
if name == "Vlada" and age == 19:
print ("Your name is Vlada, and your age is 19.")
else:
print ("Youre wrong..")
if name == "Vlada" or name == "Roma":
print ("Your name is either Vlada or Roma. ")
|
64aca29e06cc36201ed62c5fac6df5f389a610da | gaowenhao/PythonAlgorithm | /sort/insert_sort.py | 609 | 3.90625 | 4 | # -*- coding: utf-8 -*-
from utility import array_utility as au
# 插入排序相对冒泡排序和选择排序,减少了一定的对比次数,但是交换次数并没有减少 时间复杂度 同为O(n²)
def select_sort(array):
for outer in range(1, len(array)):
inner = outer
temp = array[inner]
while inner > 0 and array[inner-1] > temp:
array[inner] = array[inner - 1]
inner -= 1
array[inner] = temp
if __name__ == "__main__":
temp_array = au.generate_array()
print(temp_array)
select_sort(temp_array)
print(temp_array)
|
fb741b85b2e846bef8517e11ff9ab4f0e53fbfab | BickChen/python_Study | /python面向对象编程/test.py | 810 | 3.859375 | 4 | #
# class Person:
# sex = "男"
#
# def __init__(self,name,age,introduce):
# self.name = name
# self.age = age
# self.introduce = introduce
#
# def output(self):
# a = print(self.name)
# return a
# a = Person('小明',10,'上山去砍柴')
# print(a.output())
# class Stu(object):
# __stu_num = 0
# def __init__(self,name):
# self.name = name
# self.abc()
#
# def abc(self):
# self.__stu_num += 1
# print("成功", self.__stu_num)
#
# a1 = Stu('Alex')
# a2 = Stu("Yasin")
class Flight(object):
def __init__(self,name):
self.name = name
def filght_status(self,age):
print("name : a",self.name,age)
def name(self):
print(self.name)
f = Flight("Alex")
setattr(Flight, 'n', name)
f.n() |
7d9da91f256e506448ffbe18c7c99b6b8ddb9f87 | abbsmile/Python-base | /BaseForm/file_input_output/open/open.py | 251 | 3.515625 | 4 |
file_open = open("foo.txt", "wb")
print "the file's name is:", file_open.name
print "close or open? :", file_open.closed
print "access_mode:", file_open.mode
print "have to add space in the end:", file_open.softspace # confusing ?
file_open.closed |
190cc79b3bfe90ed50d15e5d7082b99d9c18728f | SabastianMugazambi/Word-Counter | /act_regex1.py | 1,457 | 4.46875 | 4 | # Regular expressions activity I
# Learning about regular expressions (patterns).
# The import statement below tells Python to load a
# set of 'regular expression' functions. If you use
# regular expressions in your programs, you NEED
# to have this line.
import re
def main():
name = raw_input("What's your first name? ")
poem = bananaFana(name.strip())
print "\n" + poem
print "\n (This poem has %d characters in it)" % len(poem)
def bananaFana(name):
'''Given a name (string), returns a rhyme (string).'''
name = name.lower()
first_letter = name[0]
if isVowelRegEx(first_letter):
suffix = name
else:
suffix = name[1:len(name)]
rhyme = name + ' ' + name + ' bo-b' + suffix + '\n'
rhyme = rhyme + 'banana-fana fo-f' + suffix + ' ---\n'
rhyme = rhyme + 'me my mo m' + suffix + '\n'
rhyme = rhyme + name + '!'
return rhyme
def isVowel(character):
'''Returns True if character is a lowercase vowel and False otherwise.'''
if ((character == 'a') or
(character == 'e') or
(character == 'i') or
(character == 'o') or
(character == 'u')):
return True
return False
def isVowelRegEx(character):
'''Returns True if character is a lowercase vowel and False otherwise.'''
# re.match(pattern, string) returns None if no match is found
if re.match('^[aeiou]$', character) == None:
return False
return True
main()
|
190fbccda37f2c383cceb352a97b1fd5e3350b23 | lunarkitteh/LearningPythonSyntax | /if.py | 739 | 4.21875 | 4 | import math
x = int(input("Please enter your first number:"))
y = int(input("Please enter your second number:"))
z = int(input("Please enter your third number:"))
print("The sum of those 3 number is "+ str(x+y+z)) # cast x+y into string
print("the square root of those 3 numbers is "+str(math.sqrt(x+y+z)))
# NOTE :
#%s - String (or any object with a string representation, like numbers)
#%d - Integers
#%f - Floating point numbers
#%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
#%x/%X - Integers in hex representation (lowercase/uppercase)
#if x > 10:
# Don't forget to indent
#print('you entered a number greater than 10')
#else:
#print('you entered a number less than 10.')
|
87bf6c2c114d48d2f2c5ff6de63871a067789b4a | fruizpace/romanos | /romanos.py | 4,099 | 3.859375 | 4 | simbolos = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X' : 10, 'V': 5, 'I': 1}
def simbolo_a_entero(simbolo):
if isinstance(simbolo, str) and simbolo.upper() in simbolos: # así compruebo si romano es string y mayúscula está en el diccionario símbolos
return simbolos[simbolo.upper()]
elif isinstance(simbolo, str):
raise ValueError(f"simbolo {simbolo} no permitido")
else:
raise ValueError(f"parámetro {simbolo} debe ser un string") # raise: lanza una excepción
def cuentaSimbolos(romano):
frecuencias = dict() # diccionario vacio
for caracter in romano:
if caracter in frecuencias: # si el caracter está en el diccionario
frecuencias[caracter] += 1 # suma uno
else: # si no está
frecuencias[caracter] = 1
return frecuencias # diccionario con la frecuencia de los simbolos
def romano_a_entero(romano):
tipo1 = ['I', 'X', 'C', 'M']
tipo5 = ['V', 'L', 'D']
listaTemp = []
acumulador = 0
if not isinstance(romano, str): # si metemos un número dará error
raise ValueError(f"parámetro {romano} debe ser un string")
for simbolo in romano:
entero = simbolo_a_entero(simbolo) # da su valor arábigo
listaTemp.append(entero) # lista validada de valores arábigos
if len(listaTemp)>1: # comprobación de tipos de resta
for i in range(1, len(listaTemp)):
if listaTemp[i-1] < listaTemp[i] and listaTemp[i-1] in (5, 50, 500):
raise OverflowError(f"Hay un valor {listaTemp[i-1]} (tipo 5) a la izquierda de uno mayor")
elif listaTemp[i-1] < listaTemp[i] and listaTemp[i-2] == listaTemp[i-1] and listaTemp[i-1] in (1, 10, 100, 1000):
raise OverflowError(f"Hay un valor {listaTemp[i-1]} (tipo 1) restando y repetido a la izquierda")
for i in range(1, len(listaTemp)):
if listaTemp[i-1] < listaTemp[i] and not ((listaTemp[i-1] == 1 and listaTemp[i] in (10, 5)) or (listaTemp[i-1] == 10 and listaTemp[i] in (100, 50)) or (listaTemp[i-1] == 100 and listaTemp[i] in (1000, 500))):
raise OverflowError(f"Hay una resta no aceptada")
elif listaTemp[i-1] < listaTemp[i] and (listaTemp[i-1] == 1 and listaTemp[i] in (10, 5)) or (listaTemp[i-1] == 10 and listaTemp[i] in (100, 50)) or (listaTemp[i-1] == 100 and listaTemp[i] in (1000, 500)):
listaTemp[i-1] = listaTemp[i-1] * -1
frecuenciaSimbolos = cuentaSimbolos(romano) # diccionario con frecuencia de símbolos
for i in frecuenciaSimbolos: # comprobamos repeticiones de símbolos
if i in tipo5 and frecuenciaSimbolos[i] >= 2:
raise OverflowError(f"Más de dos símbolos tipo 5")
elif i in tipo1 and frecuenciaSimbolos[i] > 3:
raise OverflowError(f"Más de tres símbolos tipo 10")
for i in range(len(listaTemp)): # Suma (y resta) los valores validados
acumulador += listaTemp[i]
return acumulador
def descomponer(numero):
if not isinstance(numero, int):
raise SyntaxError(f"{numero} no es un número natural")
l = []
for d in str(numero):
l.append(int(d))
return l
#return [int(d) for d in str(numero)] # es lo mismo que arriba
unidades = ('I','V', 'X')
decenas = ('X','L', 'C')
centenas = ('C','D', 'M')
millares = ('M',) # tupla con esa coma
lista_ordenes = [unidades, decenas, centenas, millares]
def convertir(ordenes_magnitud):
resultado = []
contador = 0
for orden in ordenes_magnitud[::-1]:
resultado.append(procesar_simbolo(orden, lista_ordenes[contador]))
contador += 1
#resultado.reverse() # esta función no devuelve nada así que hay que cogerla con join.
return ''.join(reversed(resultado))
def procesar_simbolo(s, clave):
if s== 9:
return clave[0] + clave[2]
elif s >= 5:
return clave[1] + clave[0]*(s-5)
elif s == 4:
return clave[0] + clave[1]
else:
return clave[0]*s
print(descomponer(1983))
print(convertir([1, 9, 8, 3])) |
c8d6d12f5d80ff35a2099a6f904a54d3a990fd90 | doytsujin/term-1 | /termbrowser/vector.py | 347 | 3.625 | 4 | class Vec:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def add(self, x: int, y: int):
self.x += x
self.y += y
def cloneVec(vec: Vec) -> Vec:
return Vec(vec.x, vec.y)
def addVec(v1: Vec, v2: Vec) -> Vec:
return Vec(v1.x + v2.x, v1.y + v2.y)
def equalsVec(v1: Vec, v2: Vec) -> bool:
return v1.x == v2.x and v1.y == v2.y |
3381c0ad1b9d8d8ce34ac8d46dd8270c72edf7a0 | Kjartanl/TestingPython | /TestingPython/CoreFunctionality/numbers.py | 394 | 4.03125 | 4 |
sum = 12 + 34
print(f"sum was: {sum}")
print(f'Note the difference when dividing with a non-integer as a result: {23/4}')
remainder = 23 % 5
print(f"Remainder of 23 % 5 was: {remainder}")
# NB: Notice the double // to get the whole number (here, '4'):
dividend_or_whatever_it_is_called = 23 // 5
print(f"The divident (is that the correct term?) was: {dividend_or_whatever_it_is_called}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.