blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
2ab5420425027c8709ac61acbe154185a0654117
pcarvalhor/SCRIPTS-DE-ESTUDO
/SCRIPTS DE ESTUDO/casadecambio.py
625
3.578125
4
print('\033[1;34mSeja bem-vindo ao Carvalho Cambios\033[m') S = float(input('\033[1;31mQuantos reais voce tem?\033[m')) Z = str(input('\033[1;32mQual moeda voce quer comprar?\033[m')).lower() if Z == 'dolar': D = float(5.22) if Z == 'euro': D = float(5.67) if Z == 'libra': D = float(6.52) T = S / D if D == 5.22: print('\033[1;31mVoce pode comprar {:.0f} dolares'.format(T)) if D == 5.67: print('Voce pode comprar {:.0f} euros'.format(T)) if D == 6.52: print('Voce pode comprar {:.0f} libras\033[m'.format(T)) print('\033[1;34mobrigado por comprar na carvalho cambios\033[m')
511caa6a153064077476e4c38bd590d51c362789
MarvinVoV/algorithm-python
/sort/selection_sort.py
334
3.765625
4
def selection_sort(a): """ Selection sort :param a: list :return: list """ if not a or len(a) <= 1: return for i in range(len(a)): p = i for j in range(i + 1, len(a)): if a[j] < a[p]: p = j a[p], a[i] = a[i], a[p] # swap a[p], a[i] return a
9fb7143527edda33e84be4a2d044a61431c8789d
SajedNahian/SoftDev2
/listcomp.py
1,254
3.78125
4
UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" LOWERCASE = UPPERCASE.lower() DIGITS = [str(i) for i in range(10)] SPECIAL = "*.!?&#,;:-_" def threshold_checker(password): upper = [char for char in password if char in UPPERCASE] lower = [char for char in password if char in LOWERCASE] numbers = [char for char in password if char in DIGITS] specials = [char for char in password if char in SPECIAL] return len(upper) > 1 and len(lower) > 1 and len(numbers) > 1 def strength_checker(password): strength = 1 if threshold_checker(password): p_length = len(password) if p_length > 10: strength += 4 else: strength += p_length - 4 numbers = [char for char in password if char in DIGITS] upper = [char for char in password if char in UPPERCASE] lower = [char for char in password if char in LOWERCASE] specials = [char for char in password if char in SPECIAL] if len(specials) > 0: strength += 1 if len(specials) > 2: strength += 1 if len(numbers) > 2: strength += 1 if len(upper) > 2: strength +=1 if len(lower) > 2: strength +=1 return strength
f6a8f87d5beb592f564d16ea02a21022d86b9b39
vincenttian/Backtesting_Platform
/strategy_random500.py
2,138
3.71875
4
import sqlite3 import math from pprint import pprint import random from security_data import SecurityData from account_manager import AccountManager from account_metrics import AccountMetrics ''' This file sets up a new account for the following trading strategy: Invest a fixed amount (e.g. 100) of fund into 500 randomly chosen securities. At the end of each month, replace the entire holdings in the account by investing the fixed amount of fund to a new set of 500 randomly selected stocks. ''' if __name__=='__main__': con = sqlite3.connect('qse_test.db') security_data = SecurityData(con) account_manager = AccountManager(con) account_metrics = AccountMetrics(con) dates = security_data.get_dates() stock_ids=security_data.get_security() if len(stock_ids)<=500: print "There are insufficient number of securities in the database for this trading strategy." exit(1) new_id=account_manager.new_account() #print new_id rows=[] for d in dates: my_ids=random.sample(stock_ids, 500) for id in my_ids: row=[new_id, id, 100, d] rows.append(row) account_manager.add_holdings(rows) account_manager.add_account(new_id,0,"Invest 100 each month in 500 randomly chosen stocks") all_acct=account_manager.get_accounts() print "... All Accounts ..." pprint(all_acct) print ''' stocks_071231=account_manager.get_holdings(new_id,"2007-12-31") num=len(stocks_071231) print("The number of stocks in the account %s is %s on 2007-12-31" %(new_id,num)) ''' #### Show performance metrics for the new account #### rslt=account_metrics.all_returns(new_id) total=sum(rslt) up_months = 0 down_months = 0 for result in rslt: if result > 0: up_months += 1 else: down_months += 1 print("Account %s Monthly Returns: " %new_id) print rslt print("Cumulative Returns: %s" %total) account_metrics.show_stats(rslt) print("No. Up Months: %s" %up_months) print("No. Down Months: %s" %down_months)
1f15e174430ce0d8cc48bfa57fa75e5ba33588a0
vincenttian/Backtesting_Platform
/account_manager.py
3,516
3.953125
4
import sqlite3 import math from pprint import pprint import random ''' The class AccountManager contains functions to update information in the account and holding table in the database. It supports creation of accounts for new trading strategies. Each entry in the account table represents a stock trading account implementing a trading strategy. Each entry in the holding table represents a stock holding at a given time in an account. ''' class AccountManager: def __init__(self,con): self.con=con def get_accounts(self): '''Return a list of accounts''' sql='select * from account' return [r for r in self.con.execute(sql)] def get_holdings(self, account_id, as_of_date): '''Return a list of (security, amount) in an account at a given date acount_id: an integer representing an account id as_of_date: 'YYYY-MM-DD' text formatted date ''' sql='select security_id,amount from holding where account_id=? AND as_of_date=?' return [r for r in self.con.execute(sql,(account_id,as_of_date))] def new_account(self): account_id=None accounts=self.get_accounts() ids=[r[0] for r in accounts] account_id=max(ids)+1 return account_id def add_stock(self, acct, date, security_id, amount): row=[acct, security_id, amount, date] sql='insert into holding(account_id,security_id,amount,as_of_date) values (?,?,?,?)' self.con.execute(sql,row) self.con.commit() def delete_stock(self, acct, date, security_id): '''Remove a stock in the holding table for an account at a given date ''' sql="DELETE FROM holding WHERE account_id=? AND security_id=? AND as_of_date=?" self.con.execute(sql,(acct,security_id,date)) self.con.commit() def add_stocks(self, acct, date, stock_rows): '''The stock_rows is a list of (security_id, amount) tuples ''' sql='insert into holding(account_id,security_id,amount,as_of_date) values (?,?,?,?)' for stock in stock_rows: row=[acct, stock[0], stock[1], date] self.con.execute(sql,row) self.con.commit() def add_holdings(self, holding_rows): '''The holding_rows is a list of (account_id, security_id, amount, date) tuples ''' sql='insert into holding(account_id,security_id,amount,as_of_date) values (?,?,?,?)' self.con.executemany(sql,holding_rows) self.con.commit() def add_account(self, account_id, rating, desc): sql='insert into account(account_id,rating,desc) values(?,?,?)' account_row=[account_id, rating, desc] self.con.execute(sql,account_row) self.con.commit() ## This function needs further testing def update_rating(self, account_id, rating): sql='update account set rating=? where account_id=?' self.con.execute(sql,(rating,account_id)) self.con.commit() if __name__=='__main__': con = sqlite3.connect('qse_test.db') account_manager = AccountManager(con) accounts=account_manager.get_accounts() id=account_manager.new_account() holding_1=account_manager.get_holdings(1, "2008-01-31") #account_manager.add_stock(1,"2009-01-31",782,1) print "...The account Id of a newly created account will be..." print id print "...All accounts ..." pprint(accounts) print print "...Holding at one date..." pprint(holding_1) print
70e15b366634efea90e939c6c169181510818fdb
Sushantghorpade72/100-days-of-coding-with-python
/Day-03/Day3.4_PizzaOrderCalculator.py
881
4.15625
4
''' Project Name: Pizza Order Author: Sushant Tasks: 1. Ask customer for size of pizza 2. Do they want to add pepperoni? 3. Do they want extra cheese? Given data: Small piza: $15 Medium pizza: $20 Large pizza: $ 25 Pepperoni for Small Pizza: +$2 Pepperoni for medium & large pizza: +$3 Extra cheese for any size pizza: +$1 ''' print("Welcome to python pizza deliveries!!!") size = input("What size pizza do you want? S,M or L? ") add_pep = input("Do you want pepperoni? Y or N: ") extra_cheese = input("Do you want extra cheese? Y or N: ") #Price size wise: bill = 0 if size == "S": bill += 15 elif size == "M": bill += 20 else: bill += 25 if add_pep == "Y": if size == "S": bill += 2 else: bill += 3 if extra_cheese == "Y": bill += 1 print(f"Your final bill is ${bill}")
049365f444a456bc954e511b09ca6a7c8a2c6868
Sushantghorpade72/100-days-of-coding-with-python
/Day-04-Randomization- and-python-lists/Day4.2_Bank_Roulette.py
278
3.84375
4
''' Project Name: Bank roulette Author: Sushant ''' import random name_str = input("Give me everybody's name, seprated by a comma. ") names = name_str.split(",") person_who_pays = random.choice(names) print(f'{person_who_pays} is going to pay for everyone')
6b07d6ae31b51c376a52628ad09e0c25da64a32b
PCvdScheer/Codewars
/Python/factorial/Kata.py
330
3.9375
4
def factorial(n): if n>12 or 0>n: raise ValueError('Provided value not within set limit (0 to 12)') elif n == 0: return 1 else: mylist = [] for i in range(1,n+1): mylist.append(i) value = 1 for x in mylist: value = value * x return value
962bfd875ae5f4e16a8ce4cbf154d9936fcba550
PCvdScheer/Codewars
/Python/Reverse every other word in the string/Kata.py
307
3.796875
4
import re def reverse_alternate(string): temp = re.sub (' +', ' ', string) temp = temp.split(' ') out = [] for i in range(len(temp)): if (i+1) %2==0: out.append(temp[i][::-1]) else: out.append(temp[i]) out1 = ' '.join(out) return out1.strip()
68eadbb2dd36110990c732586cf67b27067c4084
Long0Amateur/Self-learnPython
/Chapter 3 Numbers/A program that prints out the sine and cosine of the angles ranging from 0 to 345 degrees in 15 degrees increment.py
401
3.9375
4
# A program that prints out the sine and cosine of the angles ranging from 0 to 345 degree in # 15 degrees increments. Each result should be rounded to 4 decimal places. from math import sin, cos, pi for i in range(0,360,15): x = sin((i*pi)/180) # To convert degree to radian, multiplying by pi divided by 180 y = cos((i*pi)/180) print(i, '---',round(x,4),round(y,4))
0d5f545e7bacef8184a4224ad8e9816989ab6e2e
Long0Amateur/Self-learnPython
/Chapter 2 Loops/Chapter 2 (loops).py
633
4.46875
4
# Example 1 for i in range(5): print('i') print(sep='') #Example 2 print('A') print('B') for i in range (5): print('C') print('D') print('E') print(sep='') #Example 3 print('A') print('B') for i in range (5): print('C') for i in range (5): print('D') print('E') print(sep='') #Example 4 for i in range(3): print(i+1,'--Hello') print(sep='') #Example 5 for i in range(5,0,-1): print(i, end='') print('Blast off!!!') print(sep='') #Example 6 for i in range(4): print('*'*6) print(sep='') #Example 7 for i in range(4): print('*'*(i+1))
8cb56ab0d210e9f3b146f0c9a778ae33b25d614a
Long0Amateur/Self-learnPython
/Chapter 7 Lists/A programs prints a list of 50 random numbers between 1 and 100 .py
180
3.828125
4
# A program generates a list L of 50 random numbers between 1 and 100 from random import randint L = [] for i in range(50): L.append(randint(1,100)) print(L)
71669b68018642dbf531b2bef3f36e8a677a6634
Long0Amateur/Self-learnPython
/Chapter 8 More with Lists/A program picks 1 name from a list of names (choice).py
168
3.90625
4
# A program picks a name from a list of names from random import choice names = ['Joe','Bob','Sue','Sally'] current_player = choice(names) print(current_player)
ca8c79b60d0858891c593e9bdb34e1b784266715
Long0Amateur/Self-learnPython
/Chapter 4 If statement/Leap year 2.0.py
280
4.03125
4
# Leap year x = eval(input('Enter a year:')) if (x%4) == 0: if(x%100) ==0: if (x%400) == 0: print(x,'Leap year') else: print(x,'Not leap year') else: print(x,'Leap year') else: print(x,'Not leap year')
59b46979b7ed16dbb116246773fa8d75e3d139de
Long0Amateur/Self-learnPython
/Chapter 5 Miscellaneous/review/summing.py
111
3.703125
4
# A program adds up the number from 1 to 100 s = 0 for i in range(1,51): s = s + i print(s)
2f081564ba6182d99df8f9c9d51025eae805ff37
Long0Amateur/Self-learnPython
/Chapter 8 More with Lists/list comprehension/List comprehension IV (join).py
189
3.734375
4
# A program creates a random assortment of 100 letters from random import choice alphabet = 'abcdefghijklmnopqrstuvwxyz' s = ''.join( choice(alphabet) for i in range(100) ) print(s)
db25f02be10a08b3d484a4d7731055f74a62a4aa
Long0Amateur/Self-learnPython
/Chapter 3 Numbers/A program that asks the user to enter an angle in degrees and prints out the sine of that angle.py
200
4.34375
4
# A program that asks the user to enter an angle in degrees and prints out the sine of that angle from math import sin, pi x = eval(input('Enter an angle in degrees:')) print(sin((x*pi)/180))
bfd27b9e904038ac5e7dd11294d61b48f9f5c181
Long0Amateur/Self-learnPython
/Chapter 5 Miscellaneous/review/flag, prime.py
211
3.953125
4
# flag, prime numbers x = eval(input('Enter number:')) flag = 0 for i in range (2,x): if x%i == 0: flag = 1 if flag == 1: print(x,'is not prime') else: print (x,'is prime')
9b4a03cec322c2c28438a0c1df52d36f1dfce769
Long0Amateur/Self-learnPython
/Chapter 5 Miscellaneous/swapping.py
297
4.21875
4
# A program swaps the values of 3 variables # x gets value of y, y gets value of z, and z gets value of x x = 1 y = 2 z = 3 hold = x x = y y = hold hold = y y = z z = hold hold = z z = x z = hold print('Value of x =',x) print('Value of y =',y) print('Value of z =',z)
ce86a8409845bf69ba15d483e589531407b64a91
Long0Amateur/Self-learnPython
/Chapter 7 Lists/problem/6. A program modifies a given list using for loop.py
768
3.96875
4
# A program creating list using a for loop import string # A list consisting of the integers 0 through 49 L = [] for i in range(50): L.append(i) print('A list consisting of the integers 0 through 49:\n',L,'\n') # A list containing the squares of the integers 1 through 50 N = [] for j in range(1,51): N.append(j**2) print('A list containing the squares of the integers 1 through 50:\n',N,'\n') # The list['a','bb','ccc','dddd',...] that ends with 26 copies of the letter z s = string.ascii_lowercase print('Via enumerate method:') print([(i+1)*char for i, char in enumerate(s)]) print('\n') print('Via for loop method:') M = [] length = len(s) for z in range(0,length): c = s[z]*(z+1) M.append(c) print(M)
4af78f23eafc7a91c42c743535ddffaa8d427d01
Long0Amateur/Self-learnPython
/Chapter 7 Lists/A program prints out two highest and lowest scores in the list.py
397
4.03125
4
# A programs prints out the two largest and two smallest elements of a list # called scores from random import randint scores = [] for i in range(10): scores.append(randint(0,10)) scores.sort() print(scores) print('Two lowest scores:',scores[0],scores[1]) print('Two highest scores:',scores[-1],scores[-2]) print('Average:',sum(scores)/len(scores))
8ab960a90654477984660a75a051cd02b87e0be5
Long0Amateur/Self-learnPython
/Chapter 3 Numbers/A program that generates and prints 50 randoms integers, each between 3 and 6.py
178
4.15625
4
# A program that generates and prints 50 random integers, each between 3 and 6 from random import randint for i in range (0,50): x = randint(3,6) print(x,end=' ')
a5391be6c639c900c6f7be8e584d515d5d7b56c4
Long0Amateur/Self-learnPython
/Chapter 5 Miscellaneous/Natural logarithm.py
281
3.984375
4
# A program asks user to enter a value n, then compute ln(n) import math e = 2.718 x = eval(input('Enter a number:')) s = 0 for i in range(1,x+1): s = s + 1/i print('The natural logarithm of',x,'is',s) y = math.log(x,e) print('ln(',x,') is',round(y,3))
a70f14120ac4fd6df74ec36b96e55257cad237dc
JayantiTA/UDP-clients-server
/clients.py
1,303
3.515625
4
import socket import sys import threading # function send_message() to send message to the server def send_message(clientSock): # input client's username as identity username = input("Input username: ") # input message and send it to the server while True: message = input() message_send = username + ': ' + message clientSock.sendto(message_send.encode("utf-8"), (UDP_IP_ADDRESS, UDP_PORT_NO)) # to delete message input sys.stdout.write("\033[F") # declare ip address and port UDP_IP_ADDRESS = '0.0.0.0' UDP_PORT_NO = 2410 # create socket clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # allows sockets to bind() to the same IP:port clientSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # allows broadcast UDP packets to be sent and received clientSock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # bind the socket to address clientSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO)) # print additional message print("\nWelcome to WhatsUDP Messenger!") # create object Thread clientThread = threading.Thread(target=send_message, args=(clientSock,)) clientThread.start() # receive broadcast message from server and print it while True: data, addr = clientSock.recvfrom(1024) print(data.decode("utf-8"))
c5107058ef2aebfe562e200daceb118484c4cad9
Carbon2015/Python-002
/week01/Week01_Task01.py
2,608
3.5
4
# 作业一: # 安装并使用 requests、bs4 库,爬取猫眼电影()的前 10 个电影名称、电影类型和上映时间,并以 UTF-8 字符集保存到 csv 格式的文件中。 # 猫眼电影网址: https://maoyan.com/films?showType=3 import requests from bs4 import BeautifulSoup as bs import pandas as pd targetUrl = "https://maoyan.com/films?showType=3" # 增加cookie字段,否则可能去到”验证中心“页面。 header = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36", "cookie": "uuid=33119590CC2811EA989D8534BBE132DAE1777F37D0574C959B3EB84DE37B0413;"} # 使用requests获取目标页面response response = requests.get(targetUrl, headers=header) # 使用BeautifulSoup来parse response为“BeautifulSoup”对象。参见https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ parsedData = bs(response.text, "html.parser") # 最总结果的List,为pandas输出做准备 resultList = [] # 找到指定class的div标签,limit可以限制返回个数。 for movie in parsedData.find_all("div", class_="channel-detail movie-item-title", limit=10): # 存储每个电影的名称,类型,上映时间为list tempResult = [movie["title"]] # 获取每个电影的链接后,拼接url,打开下层页面。 response_L2 = requests.get(str("https://maoyan.com" + movie.find("a")["href"]), headers=header) parsedData_L2 = bs(response_L2.text, "html.parser") # 因为电影类型数量不固定,需要for in遍历所有类型。 for movieType in parsedData_L2.find("div", class_="movie-brief-container").find("ul").find("li").find_all("a"): # 记录电影类型到list tempResult.append(movieType.get_text().strip()) # 记录电影上映时间到list # 多次find找到目标的唯一路径。 # .find_all("li")[2] 让我们直接找第三个li而不用遍历。 # .contents[0] 是因为find_all返回的是tag的list。tag的 .contents 属性可以将tag的子节点内容以列表的方式输出。或者使用get_text()也一样。 tempResult.append( parsedData_L2.find("div", class_="movie-brief-container").find("ul").find_all("li")[2].contents[0][0:10]) # 记录电影信息到最终result列表 resultList.append(tempResult) # 把list转为pandas的DataFrame movieFile = pd.DataFrame(data=resultList) # 写DataFrame为csv文件。中文系统使用GBK编码,英文可以使用utf-8 movieFile.to_csv("./movies_work01.csv", encoding="GBK", index=False, header=False)
8f42e52832e46d28c857ee3d84cd19ae49f00b72
LakshayNagpal/Data-Analyst-Nanodegree
/P6: Intro to Hadoop and MapReduce/reducer_wordcount.py
739
3.546875
4
#!/usr/bin/python import sys current_count = 0 current_word = None # Loop around the data # It will be in the format key\tval # Where key is the store name, val is the sale amount # # All the sales for a particular store will be presented, # then the key will change and we'll be dealing with the next store for line in sys.stdin: data_mapped = line.strip().split("\t") if len(data_mapped) != 2: # Something has gone wrong. Skip this line. continue word, count = data_mapped try: count = int(count) except ValueError : continue if current_word == word: current_count +=1 else: if current_word: print current_word , "\t" , current_count current_word = word current_count = count
e93d8b3bc8ceb3d66066bc1e4585e4e82bd001fd
morrislab/plos-medicine-joint-patterns
/scripts/co_occurrences/summarize_deltas.py
1,179
3.53125
4
""" Summarizes deltas. """ import pandas as pd from click import * from logging import * @command() @option('--input', required=True, help='the CSV file to read deltas from') @option('--output', required=True, help='the CSV file to write summaries to') def main(input, output): basicConfig( level=INFO, handlers=[ StreamHandler(), FileHandler( '{}.log'.format(output), mode='w') ]) # Load the data. info('Loading data') data = pd.read_csv(input) info('Result: {}'.format(data.shape)) # Calculate summaries. info('Calculating summaries') mean_offdiagonal = data.query( 'reference_site_root != co_occurring_site_root')['delta'].mean() mean_diagonal = data.query( 'reference_site_root == co_occurring_site_root')['delta'].mean() # Compile the summaries. info('Compiling summaries') summary = pd.DataFrame({ 'diagonal': ['off_diagonal', 'on_diagonal'], 'mean': [mean_offdiagonal, mean_diagonal] }) # Write the output. info('Writing output') summary.to_csv(output, index=False) if __name__ == '__main__': main()
6760ca99d0f6ddf708a15c4b409074372558db40
morrislab/plos-medicine-joint-patterns
/scripts/localizations/get_optimal_partial_threshold.py
1,021
3.59375
4
""" Obtains optimal thresholds for partial localization. This threshold is determined by where the most negative slope occurs. """ import pandas as pd from click import * from logging import * @command() @option('--input', required=True, help='the CSV file to read stats from') @option( '--output', required=True, help='the text file to output the optimal threshold to') def main(input: str, output: str): basicConfig(level=DEBUG) info('Loading stats') stats = pd.read_csv(input) stats.set_index('threshold', drop=False, inplace=True) debug(f'Result: {stats.shape}') info('Calculating slopes') rises = stats['mean'].shift(-1) - stats['mean'].shift(1) runs = stats['threshold'].shift(-1) - stats['threshold'].shift(1) slopes = rises / runs info('Determining optimal threshold') threshold = slopes.argmin() info('Writing output') with open(output, 'w') as handle: handle.write(str(threshold)) if __name__ == '__main__': main()
2db6ef3327edb52ccd1074d7a2f2b3a46aec8c5d
morrislab/plos-medicine-joint-patterns
/scripts/crosstalk/make_data.py
6,289
3.8125
4
""" Generates data for analyzing distributions of scores among patient groups. Normalizes scores by patient. The end result is that for each patient, scores will be in the range [0, 1] with the highest-scoring factor having a normalized score of 1. """ from click import * from logging import * import janitor as jn import pandas as pd import string def get_threshold(ctx, param, value): """ Obtains a threshold from the given parameter. """ if value is not None: try: return int(value) except ValueError: if value not in ['cohort', 'cluster']: raise ValueError('must be a number, "cohort", or "cluster"') return value return 0 def normalize(X: pd.DataFrame) -> pd.DataFrame: """ Normalizes scores to the range [0, 1] for a single patient. Args: X: data frame containing patient factor scores for a single patient Returns: normalized patient factor scores """ Y = X.set_index(['factor'])[['score']] Y['score'] /= Y['score'].max() return Y def z_transform(x: pd.Series) -> pd.Series: """ Z-transforms scores. Args: x: values to Z-transform Returns: Z-transformed scores """ return (x - x.mean()) / x.std() @command() @option( '--score-input', required=True, help='the CSV file to read scores from') @option( '--localization-input', required=True, help='the CSV file to read localization data from') @option('--output', required=True, help='the Feather file to write output to') @option( '--letters/--no-letters', default=False, help='whether to use letters for factor names') @option('--count-input', help='the CSV file to read joint counts from') @option( '--threshold', callback=get_threshold, help=( 'the joint count to calculate to set as a minimum inclusion threshold; ' '"cohort": calculate a global median threshold from the cohort; ' '"cluster": calculate a per-cluster median threshold')) def main(score_input, localization_input, output, letters, count_input, threshold): basicConfig(level=DEBUG) if threshold == 'none' and not count_input: raise Exception( '--count-input must be defined if --threshold is not "none"') # Load data. info('Loading scores') scores = pd.read_csv(score_input) debug(f'Result: {scores.shape}') info('Loading localizations') localizations = pd.read_csv( localization_input, index_col='subject_id').drop( 'threshold', axis=1) debug(f'Result: {localizations.shape}') # Filter the data if needed. if threshold != 0: info('Loading joint counts') counts = pd.read_csv(count_input, index_col=0) debug(f'Result: {counts.shape}') if isinstance(threshold, int): info('Filtering scores') filtered_counts = counts.query('count >= @threshold') scores = scores.set_index('subject_id').loc[ filtered_counts.index].reset_index() debug(f'Result: {scores.shape}') elif threshold == 'cohort': info('Calculating median count') median_count = counts['count'].median() debug(f'Median: {median_count} joints') info('Filtering scores') filtered_counts = counts.query('count >= @median_count') scores = scores.set_index('subject_id').loc[ filtered_counts.index].reset_index() debug(f'Result: {scores.shape}') else: info('Joining joint counts with classifications') joined_counts = counts.join(localizations[['classification']]) debug(f'Result: {joined_counts.shape}') before_n_patients = joined_counts['classification'].value_counts() for k, v in before_n_patients.iteritems(): debug(f'- {k}: {v} patients') info('Calculating median counts') median_counts = pd.Series( joined_counts.groupby('classification')['count'].median(), name='median') debug(f'Result: {median_counts.shape}') for k, v in median_counts.iteritems(): debug(f'- {k}: {v} joints') info('Filtering scores') joined_medians = joined_counts.reset_index( ).set_index('classification').join( median_counts.to_frame()).reset_index().set_index('subject_id') to_retain = joined_medians['count'] >= joined_medians['median'] scores = scores.set_index('subject_id').loc[ to_retain].reset_index() after_n_patients = scores.set_index('subject_id').join( localizations['classification']).reset_index()[ 'classification'].value_counts() for k, v in after_n_patients.iteritems(): debug(f'- {k}: {v} patients') debug(f'Result: {scores.shape}') # Melt data. info('Melting scores') scores = scores.melt( id_vars='subject_id', var_name='factor', value_name='score') scores['factor'] = scores['factor'].astype(int) debug(f'Result: {scores.shape}') # Patient-normalize patient factor scores. info('Patient-normalizing scores') scores = scores.groupby('subject_id').apply(normalize).reset_index() debug(f'Result: {scores.shape}') # Calculate Z-scores. info('Calculating Z-scores') scores['z_score'] = scores.groupby('factor')['score'].apply(z_transform) debug(f'Result: {scores.shape}') # Rename factors. info('Renaming factors') scores['factor'] = [ f'<{string.ascii_uppercase[x - 1]}>' for x in scores['factor'] ] if letters else [f'<{x:02d}>' for x in scores['factor']] # Join data. info('Joining data') joined = scores.set_index('subject_id').join(localizations) debug(f'Result: {joined.shape}') # Write output. info('Writing output') joined = joined.pipe( jn.encode_categorical, columns=['classification', 'localization']) joined.reset_index().to_feather(output) if __name__ == '__main__': main()
fafa60fcff780a161c7889d5d763ecae8dab8849
consbio/parserutils
/parserutils/numbers.py
414
4.03125
4
from math import isnan, isinf def is_number(num, if_bool=False): """ :return: True if num is either an actual number, or an object that converts to one """ if isinstance(num, bool): return if_bool elif isinstance(num, int): return True try: number = float(num) return not (isnan(number) or isinf(number)) except (TypeError, ValueError): return False
29251cbc397c958ab2bb023038dca2a6c58aea9a
sabk18/CS_555_GEDCOM
/src/sprint2/story25.py
2,455
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 2 14:00:42 2020 @author: sabkhalid """ #story 25: Unique first names in Family #No more than one child with the same name and birth date should appear in the family #step 1: for each row of FAM, chk for children id. for every unique children id, chk for their birth date in INDI. if unique then show that in #family table. import unittest class Unique_birthDate_firstName(unittest.TestCase): def test_unique_childIDs_true(self): result = unique_childID(['xyz', 'abc','123']) self.assertTrue(result, 'True') def test_unique_childIDs_equal(self): result1 = unique_childID(['xyz', 'abc','123']) result2 = unique_childID(['xyz', 'abc','123']) self.assertEqual(result1, result2) def test_true_unique_FirstName_BirthDate(self): result = name_birth(['Meredith - 9th Feb 1995', 'Alex - 30th Jan 1998', 'Christina - 26th July 1990']) self.assertTrue(result, 'True') def test_false_unique_FirstName_BirthDate(self): result= name_birth(['Meredith - 9th Feb 1995', 'Alex - 30th Jan 1998', 'Meredith - 9th Feb 1995']) self.assertFalse(result, 'False') def unique_childID(children): if len(children) == len(set(children)): #chk if unique return True else: return False def name_birth(data): if len(data) == len(set(data)): return True else: return False def s25test(info, file): for fam in info['FAM']: if 'CHIL' in info['FAM'][fam]: children_ids = info['FAM'][fam]['CHIL'] if unique_childID(children_ids): uniqueChild = [] for child in children_ids: children_name = info['INDI'][child]['NAME'] name_split = children_name.split('/') first_name = name_split[0] #print (first_name) date_of_birth = info['INDI'][child]['BIRT'] #print (date_of_birth) child = first_name + ' - ' + date_of_birth uniqueChild.append(child) if not name_birth(uniqueChild): file.write("\nError: For Family ID {}, there should be unique child first name and birth date".format(fam)) return file if __name__ == '__main__': unittest.main()
e480e4a53659ad7983b6be14b4c06dba1fb00c50
sabk18/CS_555_GEDCOM
/src/sprint3/story41.py
1,532
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 7 22:18:31 2020 @author: sabkhalid """ #story41: include partial dates. 'Only Year ' from datetime import * def partial_date(date): try: date_dt = datetime.strptime(date, '%d %b %Y') #change to datetime Year = date_dt.year except: False return Year def s41test(info, file): for indiv in info['INDI']: if 'BIRT' in info['INDI'][indiv]: birth_date= info['INDI'][indiv]['BIRT'] birth_date = partial_date(birth_date) print("\nINDI: {} ".format(indiv) , "Partial Birth Date: {}".format(birth_date)) if 'DEAT' in info['INDI'][indiv]: death_date = info['INDI'][indiv]['DEAT'] death_date = partial_date(death_date) print("\nINDI: {} ".format(indiv) , "Partial Death Date: {}".format(death_date)) for fam in info['FAM']: if 'MARR' in info['FAM'][fam]: marriage_date= info['FAM'][fam]['MARR'] marriage_date = partial_date(marriage_date) print("\nINDI: {} ".format(indiv) , "Partial Marriage Date: {}".format(marriage_date)) if 'DIV'in info ['FAM'][fam]: divorce_date= info['FAM'][fam]['DIV'] divorce_date =partial_date(divorce_date) print("\nINDI: {} ".format(indiv) , "Partial Divorce Date: {}".format(divorce_date)) return file
23094db9ffde4fff11f92010efe854558bb732de
haraldyy/teaching_turtles
/retangulos_e_quadrados.py
432
3.84375
4
from turtle import * shape("turtle") #Isso vai desenhar uma estrela cinza clara em um fundo azul escuro color("WhiteSmoke") bgcolor("MidnightBlue") def quadrado(): for i in range(4): forward(100) right(90) def retangulo(): for i in range(2): right(90) forward(150) right(90) forward(90) quadrado() penup() backward(250) pendown() left(90) retangulo()
0e41bd56ce0c6b4761aa3bf3f86b181ea7b70697
Tuman1/Web-Lessons
/Python Tutorial_String Formatting.py
1,874
4.28125
4
# Python Tutorial: String Formatting - Advanced Operations for Dicts, Lists, Numbers, and Dates person = {'name':'Jenn', 'age': 23} # WRONG example # Sentence = 'My name is ' + person['name'] + ' and i am ' + str(person['age']) + ' years old.' # print(Sentence) # Sentence = 'My name is {} and i am {} years old.'.format(person['name'], person['age']) # print(Sentence) # Sentence = 'My name is {1} and i am {0} years old.'.format(person['name'], person['age']) # print(Sentence) # tag = "h1" # text = "This is a headline" # # Sentence = '<{0}><{1}></{0}>'.format(tag, text) # print(Sentence) # Sentence = 'My name is {1[name]} and i am {0[age]} years old.'.format(person, person) # print(Sentence) # class Person(): # def __init__(self, name, age): # self.name = name # self.age = age # # p1 = Person('Jack', '33') # # Sentence = 'My name is {0.name} and i am {0.age} years old.'.format(p1) # print(Sentence) # Sentence = 'My name is {name} and i am {age} years old.'.format(name = "Garold", age = "33") # print(Sentence) #One of the most convinient way to print dictionary # Sentence = 'My name is {name} and i am {age} years old.'.format(**person) # print(Sentence) #Formatting number # for x in range(1, 11): # sentence = "The value is {:03}".format(x) # print(sentence) # pi = 3.14159265 # # sentence = 'Pi is equal to {:.2f}'.format(pi) # print(sentence) # sentence = '1 Mb is equal to {:,.2f} bytes'.format(1000**2) # print(sentence) import datetime my_date = datetime.datetime(2016,9,24,12,30,45) # print(my_date) # Example what we need -> March 01 2016 # sentence = '{:%B %d, %Y}'.format(my_date) # print(sentence) # Example what we need -> March 01, 2016 fell on a Tuesday and was the 061 day of the year. sentence = '{0:%B %d, %Y} fell on a {0:%A} and was the {0:%j} day of the year.'.format(my_date) print(sentence)
949f77b98a5e36ce0b38ba07937cf73a17120097
dahea-moon/Algorithm
/leetcode/345_Reverse Vowels of a String.py
852
3.671875
4
from unittest import TestCase from typing import List class Solution: def reverseVowels(self, s: str) -> str: vowels = ['a', 'e', 'i', 'o', 'u'] s = list(s) vowel_index = [(idx, char) for idx, char in enumerate(s) if char.lower() in vowels] j = 0 for i in range(len(vowel_index)-1, -1, -1): vowel_idx = vowel_index[i][0] s[vowel_idx] = vowel_index[j][1] j += 1 return ''.join(s) class Test(TestCase): def setUp(self) -> None: self.solution = Solution() def test_testcases(self): test_cases = [ ("hello", "holle"), ("leetcode","leotcede") ] for test_case in test_cases: answer = self.solution.reverseVowels(test_case[0]) self.assertEqual(answer, test_case[1])
5fa5335a5f6a44d3546c47db3b2718cc4a9634ff
dahea-moon/Algorithm
/leetcode/605_Can Place Flowers.py
1,867
3.703125
4
from unittest import TestCase from typing import List class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: idx = 0 planted = 0 for i in range(n): while idx < len(flowerbed): if flowerbed[idx]: idx += 1 elif not flowerbed[idx]: if idx == len(flowerbed)-1 and not flowerbed[idx-1]: flowerbed[idx] = 1 planted += 1 break elif idx == 0 and not flowerbed[idx+1]: flowerbed[idx] = 1 planted += 1 break elif not flowerbed[idx-1] and not flowerbed[idx+1]: flowerbed[idx] = 1 planted += 1 break else: idx += 1 if planted == n: return True return False def fastest(self, flowerbed: List[int], n: int) -> bool: cnt, beds = 1, 0 for bed in flowerbed: if bed: cnt = 0 else: cnt += 1 if cnt == 3: cnt = 1 beds += 1 if not flowerbed[-1]: cnt += 1 if cnt == 3: beds += 1 return beds >= n class Test(TestCase): def setUp(self) -> None: self.solution = Solution() def test_testcases(self): test_cases = [ ([1,0,0,0,1], 1, True), ([1,0,0,0,1], 2, False), ([1,0,1,0,1,0,1], 1, False) ] for test_case in test_cases: answer = self.solution.canPlaceFlowers(test_case[0], test_case[1]) self.assertEqual(answer, test_case[2])
9153885112141bce545f746c8f1aab591766dae1
Invirent/Tugas-Pertemuan-12
/code_penulisan_angka.py
2,031
3.546875
4
import os kata = ['','one ','two ','three ','four ','five ','six ','seven ','eight ','nine '] belasan = ['','eleven ','twelve ','thirteen ','fourteen ','fifthteen ','sixteen ','seventeen ','eighteen ','nineteen '] puluhan = ['','ten ','twenty ','thirty ','fourty ','fifty ','sixty ','seventy ','eighty ','ninety '] def perhitungan(n): if n <10: return kata[n] elif n>=1_000_000_000: return perhitungan(n//1_000_000_000)+"billion "+(perhitungan(n%1_000_000_000)if n%1_000_000_000 != 0 else '') elif n>=1_000_000: return perhitungan(n//1_000_000)+"million "+(perhitungan(n%1_000_000)if n%1_000_000 != 0 else '') elif n>=1_000: return perhitungan(n//1000)+"thousand "+(perhitungan(n%1000)if n%1000 != 0 else '') elif n ==100: return perhitungan(n//100)+"hundred "+(perhitungan(n%100)if n%100 != 0 else '') elif n >100: return perhitungan(n//100)+"hundred and "+(perhitungan(n%100)if n%100 != 0 else '') else: if n%10 == 0: return puluhan[n//10] elif n<20 and n>10: return belasan[n//10] else: return puluhan[n//10]+ (perhitungan(n%10) if n%10!=0 else ' ') while True: os.system("cls") err=0 print ("Program Angka ke Huruf ") print ('=======================================') try: nomor= int(input('Number? ')) print (perhitungan(nomor)) os.system("pause") retry=input('Apakah Program ingin Diulang?(Y/N) ') while True: if retry.lower() in ['y','n']: break if retry.lower() =='n': break except ValueError: print ('Input harus angka') err+=1 except Exception as e: print(f'Error Type {e}') if err == 1: retry=input('Apakah Program ingin Diulang?(Y/N) ') while True: if retry.lower() in ['y','n']: break if retry.lower() =='n': break
39603555694c8d7f1f7bf47daee88f06ec297e99
SusyVenta/Chess
/Utils.py
1,545
3.546875
4
class Utils: def get_current_letter(self, tag_position): return tag_position[0] def get_current_number(self, tag_position): return tag_position[1] def letter_to_number(self, letter): letters_and_numbers = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8} return letters_and_numbers[letter] def number_to_letter(self, number): numbers_and_letters = {1: "a", 2: "b", 3: "c", 4: "d", 5: "e", 6: "f", 7: "g", 8: "h"} return numbers_and_letters[number] def all_numbers_except_current_list(self, current_number): all_numbers = [1, 2, 3, 4, 5, 6, 7, 8] all_numbers.remove(current_number) return all_numbers def all_letters_except_current_list(self, current_letter): all_letters = ["a", "b", "c", "d", "e", "f", "g", "h"] all_letters.remove(current_letter) return all_letters def end_position_is_free(self, end_coordinates, pieces_position): if end_coordinates in pieces_position.keys(): return False return True def end_position_contains_opponent_piece(self, piece_moved, end_coordinates, pieces_position): if end_coordinates in pieces_position.keys(): if (piece_moved.islower() and pieces_position[end_coordinates].isupper()) or ( piece_moved.isupper() and pieces_position[end_coordinates].islower()): return True return False def is_white_moving(self, piece_moved): return piece_moved.isupper()
16fc93b40eb0ad8b1b35774e0172315d67b4e46b
koushikd9/Mini_Projects
/Python/RollADice.py
210
3.90625
4
import random while True: choice=input("Do you want to Roll Dice or exit:Y/N").capitalize() if choice=="Y": print(random.randint(1,6)) elif choice=="N": print("Bye") break
b7439c8d91988f6652f6dccf2886ac650db178db
yu5shi8/AtCoder
/ABC_A/ABC171A.py
183
3.65625
4
# -*- coding: utf-8 -*- # A - αlphabet # https://atcoder.jp/contests/abc171/tasks/abc171_a S = input() if S.isupper(): print('A') else: print('a') # 21:00 - 21:02(AC)
aaaaf1539dfaf12e1991144d05f3096958bc19d5
yu5shi8/AtCoder
/ABC_A/ABC046A.py
200
3.515625
4
# -*- coding: utf-8 -*- # A - AtCoDeerくんとペンキ # https://atcoder.jp/contests/abc046/tasks/abc046_a abc = list(map(int, input().split())) count = (len(abc) + len(set(abc))) - 3 print(count)
cc483e1488b21a6666c72989ad9f3be348da652d
yu5shi8/AtCoder
/ABC_A/ABC018A.py
347
3.65625
4
# -*- coding: utf-8 -*- # A - 豆まき # https://atcoder.jp/contests/abc018/tasks/abc018_1 a = [1] + [int(input())] b = [2] + [int(input())] c = [3] + [int(input())] rank = [a, b, c] rank.sort(key=lambda x:-x[1]) for i in range(3): rank[i].append(i+1) rank.sort(key=lambda x:x[0]) for i in range(3): print(rank[i][2]) # 10:09 - 10:18
ef83c6b7cebd3095bcd5171043eaa45a7f2baa78
yu5shi8/AtCoder
/ABC_A/ABC006A.py
210
3.71875
4
# -*- coding: utf-8 -*- # A - 世界のFizzBuzz # https://atcoder.jp/contests/abc006/tasks/abc006_1 n = input() if n.count('3') > 0 or int(n) % 3 == 0: print('YES') else: print('NO') # 11:03 - 11:07
5418ae94592bff2e401f03d295adc3c4aaf2bfa1
yu5shi8/AtCoder
/ABC_A/ABC092A.py
431
3.5625
4
# -*- coding: utf-8 -*- # A - Traveling Budget # https://atcoder.jp/contests/abc092/tasks/abc092_a a = int(input()) b = int(input()) c = int(input()) d = int(input()) if a >= b and c >= d: print(b + d) elif a >= b and c < d: print(b + c) elif a < b and c >= d: print(a + d) else: print(a + c) # min() で比較するとスマートになります # if min(a, b) and min(c, d): # print(min(a, b) + min(c, d))
bd44ffbfac8714c373eec4a6bb907cf6f32f4aa3
yu5shi8/AtCoder
/ABC_A/ABC073A.py
257
3.96875
4
# -*- coding: utf-8 -*- # A - September 9 # https://atcoder.jp/contests/abc073/tasks/abc073_a n = input() if n[0] == '9' or n[1] == '9': print('Yes') else: print('No') # if n[0] == '9' or n[1] == '9': # ↓ スマートにできる # if '9' in n:
489caf71a3730eb7897cc16629a39715db58022f
yu5shi8/AtCoder
/ARC_A/ARC003A.py
401
3.5625
4
# -*- coding: utf-8 -*- # A - GPA計算 # https://atcoder.jp/contests/arc003/tasks/arc003_1 N = int(input()) r = input() cnt = 0 for i in range(N): if r[i] == 'A': cnt += 4 elif r[i] == 'B': cnt += 3 elif r[i] == 'C': cnt += 2 elif r[i] == 'D': cnt += 1 else: cnt += 0 gpa = cnt / N print('{:.12f}'.format(gpa)) # 15:10 - 15:14(AC)
5f024e8fbf88acb26502a5e6e26b16b1b6a10673
yu5shi8/AtCoder
/ABC_A/ABC088A.py
200
3.5625
4
# -*- coding: utf-8 -*- # A - Infinite Coins # https://atcoder.jp/contests/abc088/tasks/abc088_a n = int(input()) a = int(input()) ans = n % 500 if ans <= a: print('Yes') else: print('No')
f65400b3a60dd75d0674a81523e6cc3eebc9bb2d
JoLartey/data
/app.py
249
3.875
4
print('Hello Notitia-AI C2 Fellow') # The greet function requests the name of the fellow and then welcomes them to the fellowship. def greet(): name = input("Please enter your name\n") print("Welcome to Notitia-AI" + "" + name) greet()
efdccd8d87863e0aaa75ef8c76c9b761bb2dd275
clkadem/Goruntu-Isleme
/intensity_inverse_example.py
1,811
3.515625
4
# intensity transformation # intensity inverse example # gamma correction import os import matplotlib.pyplot as plt import numpy as np print(os.getcwd()) path = "C:\\Users\\Adem\\PycharmProjects\\GörüntüIsleme" file_name_with_path = path + "\pic_1.jpg" print(file_name_with_path) img_0 = plt.imread(file_name_with_path) plt.imshow(img_0) plt.show() print(img_0.ndim,img_0.shape) print(np.min(img_0),np.max(img_0)) def convert_rgb_to_gray_level(im_1): m=im_1.shape[0] n=im_1.shape[1] im_2=np.zeros((m,n)) for i in range(m): for j in range(n): im_2[i,j]=get_distance(im_1[i,j,:]) return im_2 def get_distance(v,w=[1/3,1/3,1/3]): a,b,c=v[0],v[1],v[2] w1,w2,w3=w[0],w[1],w[2] d=((a**2)*w1+(b**2)*w2+(c**2)*w3)*5 return d def my_f_1(a,b): assert a>=0;"intensity pozitive","error intensity not pozitive" if(a<=255-b): return a+b else: return 255 def my_f_2(a): return int(255-a) img_1 = convert_rgb_to_gray_level(img_0) plt.imshow(img_1,cmap='gray') plt.show() m,n=img_1.shape img_2 = np.zeros((m,n),dtype="uint8") for i in range(m): for j in range(n): intensity = img_1[i,j] #increment = 50 img_2[i,j] = my_f_2(intensity) plt.subplot(1,2,1) plt.imshow(img_1,cmap='gray') plt.subplot(1,2,2) plt.imshow(img_2,cmap='gray') plt.show() x = np.array(list(range(100))) y1 = np.power(x/float(np.max(x)),1) y2 = np.power(x/float(np.max(x)),10) y3 = np.power(x/float(np.max(x)),1/10) plt.plot(x,y1) plt.plot(x,y2) plt.plot(x,y3) plt.show() def my_f_3(image_001,gamma): return np.power(image_001/float(np.max(image_001)),gamma) x = img_0 img_100 = np.power(x/float(np.max(x)),1) plt.imshow(img_100) plt.show()
5e1f4a6ef075b0ada1c5e5517f4048f1a259307d
glassnotes/Balthasar
/src/balthasar/curve.py
5,452
3.59375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # # curve.py: A class for curves over finite fields in discrete phase space. # # © 2016 Olivia Di Matteo ([email protected]) # # This file is part of the project Balthasar. # Licensed under BSD-3-Clause # from pynitefields import * class Curve(): """ Class to hold all points in a curve. Curves are sets of points of the form :math:`(\\alpha, c(\\alpha)` for all :math:`\\alpha` in a specified GaloisField, where .. math:: c(\\alpha) = c_0 + c_1 \\alpha + c_2 \\alpha^2 + ... They are constructed by passing in a list of coefficients in the form :math:`[c_0, c_1, c_2, \ldots]`. Args: coefs (list): The coefficients of the curve. field (GaloisField): The field over which the curve is defined. Attributes: field (GaloisField): The finite field in which is curve is defined coefs (list): The coefficients :math:`[c_0, c_1, \ldots]`. form (string): "beta" or "alpha", tells whether to do the curve as :math:`beta = f(alpha) or alpha = f(beta). By default, we use the beta form, beta = f(alpha). is_ray (bool): A Boolean which indicates whether the curve passes through the point (0, 0) or not points (list): A list of tuples of field elements which are the points of this curve over the field. """ def __init__(self, coefs, field, form="beta"): self.field = field self.coefs = coefs self.form = form # Default curve in form beta (alpha) self.is_ray = False # Does it pass through 0, 0 self.points = [] # List of points as tuples # Determine if the curve is a ray by checking the constant term if type(coefs[0]) is int: if coefs[0] == 0: self.is_ray = True else: if coefs[0] == self.field[0]: self.is_ray = True # Compute all the points on the curve for el in field: if self.form == "beta": self.points.append( (el, field.evaluate(coefs, el)) ) elif self.form == "alpha": self.points.append( (field.evaluate(coefs, el), el) ) def __getitem__(self, index): """ Get a point on the curve. Args: index (int): The index at which we would like to find the value on the curve. Expressed as a power of the primitive element of the field. Returns: The tuple (index, value of the curve at index). """ if index < len(self.points) and index >= 0: return self.points[index] else: print("Error, element out of bounds.") def __iter__(self): """ Allow the user to iterate over the curve point by point """ return iter(self.points) def print(self, as_points = False): """ Print the curve. Args: as_points (bool): If True is passed, will print the list of points on the curve as tuples. By default, prints the curves as a polynomial. """ if as_points == True: # Print the curve as a list of points for point in self.points: print(str(point[0].prim_power) + ", " + str(point[1].prim_power), end = "\t") else: # Print the curve as a polynomial print(self.form + "(x) = ", end = "") for i in range(len(self.coefs)): if type(self.coefs[i]) == int: # Integers if self.coefs[i] == 0: # Ignore 0 terms unless the curve is 0 continue if self.coefs[i] == 1 and i == 0: # Only print 1 if it's the constant print(str(self.coefs[i]), end="") continue print(str(self.coefs[i]), end="") else: # Field elements if self.coefs[i] == self.field[0]: # Ignore 0 terms unless curve is 0 continue if (self.coefs[i].prim_power == 1): if self.field.n > 1: print("s", end="") else: if self.field.n > 1: print("s" + str(self.coefs[i].prim_power), end="") else: print(str(self.coefs[i].prim_power), end="") if i > 0: if i == 1: print(" x", end="") else: print(" x" + str(i), end="") if i != len(self.coefs) - 1: print(" + ", end = "") print("")
f79f39bfe901c87ae8fdfbaa1b24cbf76bfc20bd
Ngyg520/python--class
/预科/7-12/夜晚作业/字符串方法练习.py
218
3.671875
4
f=open('zfc.txt','r',encoding='utf-8') for line in f: list1=line.split('"') for x in list1: res=x.startswith('h') if res==True: print(x) else: continue f.close()
a90ed1ca6f1dd7e673b8b804b655e510da0dbd87
Ngyg520/python--class
/预科/7-23/函数的参数.py
1,664
3.859375
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:预科 @author:Mr.Yang @file:函数的参数.PY @ide:PyCharm @time:2018-07-23 09:45:55 """ #1,必备参数(位置参数),实参和形参数量上必须要保持一致 def sum(a,b): c=a+b print(c) sum(1,6) #2,命名关键字参数:通过定义关键字来获取实参的值,与形参的顺序无关. def show(name,age): print('姓名是:%s-年龄是:%s'%(name,age)) show(age=20,name='张三') #3.默认参数 #使用场景:数据库连接,地址和端口可以设置默认 #使用默认参数的时候,如果给形参传递了实参,则会接受实参的值.如果没有给这个形参传递实参,则形参会采用默认值 def show_one(user='zhangsan',password='123456789'): print('账号是%s'%user) print('密码是%s'%password) show_one('李四','54554') #4,可变参数(不定长参数)(包括位置参数和关键字参数) #4-1:位置参数 #形参的数据会根据形参的数量的变换而变化 #*args:接收N个位置参数转化成元组的形式 def show_two(*args): print(type(args)) print(args) show_two(1) show_two(1,2,3) show_two('曹森') #4-2:关键字参数 #**kwargs:把N个关键字参数,转化成了字典. def show_three(**kwargs): print(type(kwargs)) print(kwargs) show_three(name='张三',age='20',sex='男') #尝试写一个函数:把以上所有参数填写进去 def show_all(name,*args,age=20,mother,**kwargs): print('----',name) print('===',args) print('\\\\',age) print('---',mother) print('====',kwargs) show_all('张三',*(10,20),age=34,mother='啊实打实',**{'sex':'女','father':'马云'})
1da35e52a93c7f856043ad7dd3cfed3741169d14
Ngyg520/python--class
/正课/7-25/高阶函数之filter函数.py
1,253
3.734375
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:正课 @author:Mr.Yang @file:高阶函数之filter函数.PY @ide:PyCharm @time:2018-07-25 09:22:58 """ #filter():用于对一个序列进行过滤或者筛选. #两个参数:第一个参数:函数,用于设置过滤的内容的逻辑,第二个参数:序列 #返回值也是一个迭代器 #定义一个函数,用于过滤奇偶数 def filter_function(number): return number%2==1 #filter函数会将序列中每一个元素都传递到函数中执行,在函数中返回True或者false的结果,fileter()函数会根据返回的结果,保留True的元素,过滤掉False的元素 result=filter(filter_function,[1,2,3,4,5,6]) print(result) for res in result: print(res,end=',') #将字符串中的大写的字符过滤掉 #定义一个过滤函数 def filter_upper_char(string): return string.islower() result_1=filter(filter_upper_char,'AffgwadfAFS') print(result_1) for res in result_1: print(res,end='.') #使用lambda函数改造: result_3=filter(lambda number:number%2==1,[1,2,3,4,5]) print(result_3) for res in result_3: print(res,end='-') result_4=filter(lambda string:string.islower(),'AbcDefG') print(result_4) for res in result_4: print(res,end=',')
280d6a67ced86fdb7c8f4004bb891ee7087ad18c
Ngyg520/python--class
/正课第二周/7-30/(重点理解)self对象.py
1,556
4.21875
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:正课第二周 @author:Mr.Yang @file:self对象.PY @ide:PyCharm @time:2018-07-30 14:04:03 """ class Student(object): def __init__(self,name,age): self.name=name self.age=age # print('self=',self) def show(self): print('调用了show函数') # print('self=',self) #self其实本身指代的就是一个对象,这个对象是Student类类型的,self具体指代的是Student哪一个对象,是由Student中的哪一个对象在使用属性或者函数(方法)来决定的 print(Student('张三','20')) #对象调用中间不能有其他语句,要不每调用一次,就是重新声明,重新声明就是重新分配内存地址 stu =Student('张三','20') stu.show() stu_1=stu print(stu) print(stu_1) # stu.show() stu_one=Student('李四','22') # stu_one.show() #对象的内存具有唯一性,两个不同的对象内存是不一样的 #stu和Student('张三','20')之间的关系: #第一步:当Student('张三','20')执行完毕的时候,实际上已经实例化出来了一个对象,与此同时对象在内存当中已经产生 #第二步:将内存中已经产生的这个对象赋值给了stu这个变量(指针),使用这个变量(指针)来代替Student('张三','20')这个对象来执行函数的调用,属性的调用 #指针是用于指向一个对象的内存地址,方便去操作对象,管理对象. #一个对象的内存地址可以由多个指针进行指向,但是一个指针只能指向一个对象的内存地址.
23b0fbe3cba25c9ef37ddbad2bb345086e63e6be
Ngyg520/python--class
/正课第二周/7-31/对象属性的保护.py
2,251
4.21875
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:正课第二周 @author:Mr.Yang @file:对象属性的保护.PY @ide:PyCharm @time:2018-07-31 09:26:31 """ #如果有一个对象,当需要对其属性进行修改的时候,有两种方法: #1.对象名.属性名=属性值------------------>直接修改(不安全) #2.对象名.方法名( )--------------------->间接修改 #为了更好的保护属性的安全,也就是不让属性被随意的修改,一般的处理方式: #1,将属性定义为私有属性 #2.添加一个可以调用的方法(函数),通过调用方法来修改属性(还可以在方法中设置一些属性的条件) class People(object): #私有属性 def __init__(self,name,age,weight): #python设置私有属性,需要在属性前加两个_ self.__name=name self.__age=age self._weight=weight #由于私有属性只能在类的内部使用,想要在外部获取私有属性的值,可以通过定义函数来完成 def get_name(self): return self.__name #添加修改属性 def set_name(self,name): if isinstance(name,str):#(属性,限制) self.__name=name else: raise ValueError('name is not"str"type!') p1=People('张三','20','180') name=p1.get_name() print(name)#打印出私有属性 # print(p1.__name)#私有属性无法直接调用 p1.set_name('李四') print(p1.get_name())#对私有属性进行修改,并且要满足限制"str" #一般也将_weight这种视为私有属性,不会再类的外部进行访问 print(p1._weight) #面试题: #python单_和双_的区别? #1.__方法名__:内建方法,用户不能这样定义.例如:__init__ #2.__变量名(属性名):全私有属性(变量)/全保护属性(变量).只有类对象自己能访问,子类并不能访问这个属性 #3._变量名(属性名):半保护属性(变量),只有类对象和子类对象能访问到这些变量 #虽然从意义上讲单下划线和双下划线的变量(属性)都属于私有变量(属性),理论上外界不能访问的,但是Python并没有那么严格,仍然是可以强制访问的,因此python的私有仅仅是意义上的私有,只是种规范,可以不遵守 print('强制访问:',p1._People__name)
cf28d90ba946d4968a7ed1dc0dc538a93d32dc44
Ngyg520/python--class
/预科/7-11/字典.py
3,791
3.546875
4
#author:yang #字典:也是 python中内置的一种容器类型.字典是可变的,可以对字典进行增删改查的操作. #字典有以下特点: #1,字典是以"键-值"结构来存储数据的,字典照片那个没有索引这个概念,'键':相对于列表中的索引.可以通过键对一个数据进行增删改查. #2,列表中的索引值是唯一的,键也是唯一的,都不允许重复. #3,字典是无序的,'键-值'对的存储没有先后顺序,只需要一个键对应一个值. #声明一个空字典 dict1={} #声明一个非空字典 #键:adc,辅助,打野,中单,上单 #值:uzi,ming,mlxg,小虎,letme dict2={'adc':'uzi','辅助':'ming','打野':'mlxg','中单':'xiaohu','上单':'letme'} #计算内存中,True-1,False-0.1和True,0和False不能同时为字典中的键,同时存在会产生冲突 #列表和字典都不能当键,元组可以,是因为通常情况下,键不可变,而列表可变,元组不可变. dict3={True:'true',(1,2,3):'(1,2,3)'} print(dict3) #------------------------------添加数据------------------------------ #数据的时候,要指定一个键,并且要给该键赋一个值. dict2['替补']='karsa' print(dict2) #-----------------------------查询数据------------------------------- name=dict2 ['adc'] print(name) name1=dict2['辅助'] print(name1) #------------------------------常用的函数----------------------------------- dict4={'name':"张三",'age':20,'sex':'男'} #P.get():根据键获取对应的值,如果字典中不存在这个键,则默认采用后面的默认值.如果存在该键,则直接取字典中的值 #get()函数:第一个参数:键 第二个参数:默认值 res=dict4 .get('name','李四') print('----',res) res1=dict4.get('height','170') print(res1) #2,items():将字典中的每一个键值对设置成元组的形式,并且存储在列表之中 res2=dict4.items() print(res2) #字典第一种遍历方式 for key,value in dict4 .items(): print(key,value) #字典第二种遍历方式,只取键,不取值.相当于遍历键(name,age,sex) for key,value in enumerate(dict4): print('====',key,value) #3.keys()取出字典中的所有的键并存放在列表中. res3=dict4.keys() print(res3) #4.values:取出字典中所有的值并存放在列表中. res4=dict4.values() print(res4) #5,pop():根据键删除字典中的值,返回的结果是删除的这个键对应的值 res5=dict4.pop('sex') print(res5) #6.setdefault():根据键获取对应的值,如果存在该键,则直接获取字典中的值.如果字典中不存在这个键,则采取后面默认的值.并且将该键与值加入到原始字典中. dict5={'name':'麻子','age':21,'sex':'女'} res6=dict5.setdefault('name','王二') print('-----',res6) res7=dict5.setdefault('height',180) print('====',res7) print(dict5) #7.popitem():随机返回并删除字典中的一对键值对(一般会删除末尾的键值对),返回值是一个被删除的键值对组成的元组 res8=dict5.popitem() print('被删除的',res8) print(dict5) #8.fromkeys():生成一个字典,第一个函数是键,第二个参数是值,如果第一个参数填写的是可迭代对象,则会将对象中的每一个元素拆分成一个元素当做键,并且对应的值都为第二个参数 dict6=dict.fromkeys('12',[1,2]) print(dict6) dict7=dict.fromkeys('1','hhh') print(dict7)#老师说10年用不上一次 #9.update():用于将一个字典添加到另一个字典中. dict8={'射手':'iboy','辅助':'meiko'} dict9={'打野':'7酱','中单':'scount','上单':'ray'} dict8.update(dict9) #10.判断一个键是否在一个字典中 if '射手' in dict8 : print('存在射手这个键') #11.clear():清除所有键值对 dict8.clear() print(dict8) #12.del:根据键删除字典中的值 dict10={'name':'张三'} del dict10 ['name'] print(dict10)
a62a4f8dfa911c1f3bde259e14efe019c5b7ddc1
Ngyg520/python--class
/预科/7-23/生成器函数.py
1,580
4.125
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:预科 @author:Mr.Yang @file:生成器函数.PY @ide:PyCharm @time:2018-07-23 14:34:00 """ #生成器函数:当一个函数带有yieid关键字的时候,那么他将不再是一个普通的函数,而是一个生成器generator #yieid和return;这俩个关键字十分的相似,yieid每次只返回一个值,而return则会把最终的结果一次返回 #每当代码执行到yieid的时候就会直接将yieid后面的值返回出,下一次迭代的时候,会从上一次遇到yieid之后的代码开始执行 def test(): list1=[] for x in range (1,10): list1.append(x) return list1 res=test() print(res) def test_1(): for x in range (1,10): yield x generator=test_1() print(generator) print(next(generator)) print(next(generator)) print(next(generator)) #生成器函数的例子:母鸡下蛋 #1,一次性把所有的鸡蛋全部下下来. #如果一次把所有的鸡蛋全部下下来,一是十分占地方,而是容易坏掉. def chicken_lay_eggs(): #鸡蛋筐列表 basket=[] for egg in range (1,101): basket.append(egg) return basket eggs =chicken_lay_eggs() print('一筐鸡蛋:',eggs) #这样做的好处:第一是省地方,第二是下一个吃一个,不会坏掉 def chicken_lay_eggs_1(): for egg in range(1,101): print('战斗母鸡正在下第{}个蛋'.format(egg)) yield egg print('我把第{}个蛋给吃了!'.format(egg)) eggs_1=chicken_lay_eggs_1() print(next(eggs_1)) print(next(eggs_1)) print(next(eggs_1))
d5a6aea9ce496970111d058fa130c14d4d318c31
Ngyg520/python--class
/预科/7-11/晚间复习.py
3,317
4.03125
4
#列表,元组,字典 list=[] tuple=(20,1,3,5) dict={} set1=set() #-----------添加数据------------- list.append('李四') print(list) list.insert(0,'张三') print(list) dict['A']='阿罗多姿' print(dict) set1.add(1) print(set1) #---------查询数据------------ name=list[0:2] print(name) name1=list[:] print(name1) name2=list[-1] print(name2) for x in list: print('---',x) for y in range (0,len(list)): print('==',list[y]) for y in range (0,len(list)): print('==',y) #枚举函数 for index,value in enumerate(list): print(index,value) a = tuple[0]#按索引查询 print(a) b= tuple [0:1] print(b) for z in range(0,len(tuple)):#按索引值列举所有 print(tuple[z]) for e in tuple:#直接列举所有 print(e) for index,value in enumerate(tuple):#枚举列举 print(index,value) name= dict['A']#按键查询 print(name) #-------------------------修改数据------------------ list[0]='王五'#根据索引修改列表的值 print(list) dict[1]='wangbadan'#字典添加键值对 print(dict) res2=dict.pop('A')#根据键删除数据 print('---',dict) tuple1=('多','来','米','发',[('锁','拉')],'西')#元组无法对一级值进行修改添加,可对二级进行 res=tuple1[4][0] print(res) tuple1[4][0]=('王八蛋')#对元组进行修改 print(tuple1) #-----------------------常用函数------------------- num=list.count('李四')#统计值出现的次数 print(num) num1=list.index('王五')#显示值的索引 print(num1) list.reverse()#将列表进行反转 print(list) list1=['武器','安妮'] list.extend(list1)#合并列表 print(list) list.clear()#清空列表所有值 print(list) while len(list):#使用循环删除列表中所有的元素 del list[0] print('---',list) list2=['剑圣','剑姬','巨人','剑魔'] del list2[0]#根据索引值删除值 print(list2) list2.pop(1)#根据索引值删除值 print(list2) list2.pop()#默认删除最后的值 print(list2) list2.remove('剑姬')#直接删除填写的元素,如果存在多个,则默认删除第一个符合条件的 print(list2) sex=tuple.count(20)#统计次数 print(sex) sex1=tuple.index(20)#打印列表元素的索引值,存在多个,则默认打印第一个元素的索引值 print(sex1) dict2={'name':"张三",'age':20,'sex':'男'} #get():根据键获取对应的值,如果字典中不存在这个键,则默认采用后面的默认值.如果存在该键,则直接取字典中的值 sex2=dict2.get('name','李四') print(sex2) sex3=dict2.get('height',150) print(sex3) #items():将字典中的每一个键值对设置成元组的形式,并且存储在列表之中 sex4=dict.items() print(sex4) #字典第一种遍历 for key, value in dict2.items(): print(key,value) #第二种遍历 for key ,value in enumerate(dict2): print(key,value) #打印出来的是删除的键对应的值 sex5=dict2.pop('name') print(sex5) #setdefault():根据键获取对应的值,如果存在该键,则直接获取字典中的值.如果字典中不存在这个键,则采取后面默认的值.并且将该键与值加入到原始字典中. sex6=dict2.setdefault('age','19') print(sex6) #fromkeys():生成一个字典,第一个函数是键,第二个参数是值 dict3=dict.fromkeys('1',[3]) print(dict3) print(dict2) #update():用于将一个字典添加到另一个字典中 dict2.update(dict3)
a7b4bb3d047da001a63dbc9560a84a4542d2a8ea
Ngyg520/python--class
/正课第二周/7-31/类的多继承.py
659
3.734375
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:正课第二周 @author:Mr.Yang @file:类的多继承.PY @ide:PyCharm @time:2018-07-31 16:10:38 """ #定义一个A类 class A(object): def print_test(self): print('A类') class B(object): def print_test(self): print('B类') class C(A,B): def print_test(self): print('C类') #面试题: #在上面多继承的例子中,如果父类A,B都有一个同名的方法,name通过子类调用的时候,会调用哪一个? obj_c=C() obj_c.print_test() #先调用自己的类,再调用父类 print(C.__mro__)#可以查看C类的对象搜索方法时的先后顺序
27f8780f3f00118b1d34db5b2c593f2bc802b28f
Ngyg520/python--class
/正课第二周/7-31/类的单继承.py
2,148
3.96875
4
""" 座右铭:路漫漫其修远兮,吾将上下而求索 @project:正课第二周 @author:Mr.Yang @file:类的单继承.PY @ide:PyCharm @time:2018-07-31 15:43:05 """ #面向对象编程的三个基本特征:封装,继承,多态 #函数是封装的最基本单位,而类和对象属于更高级的封装形态,在类中封装用于保存数据,也可以在类中封装函数用于操作数据,不同的功能和逻辑又可以封装成不同的函数 #继承: #继承的优势:可以更好的实现代码的重用 #1.子类可以继承父类,子类会拥有父类中所有的属性,子类不需要重复声明,父类的对象是不能够调用子类的属性和方法的,这种继承属于单项继承 #2.当父类当中的属性和函数不符合子类需求的时候,子类可以重写父类的属性和方法,或者自定义一些新的方法 #object是所有类的父类(根类,基类) #Animal类是object的子类,object是Animal的父类 #如果一个类没有特别指定父类,一般都是继承于object class Animal(object): def __init__(self,name,age,sex): self.name=name self.age=age self.__sex=sex def run(self): print('跑') def eat(self): print('吃') def __sleep(self): print('睡') #声明一个狗类继承于Animal class Dog(Animal): def wangwang(self): print('叫') an=Animal('gou','20','公') print(an.name) print(an.age) # print(an._Animal__sex) an.run() an.eat() # an.wangwang() #Dog类中,虽然并没有声明__init__这个初始化函数,但是由于Dog类继承于Animal类,所以,Dog类中的对象也去执行了Animal的初始化函数,才创建Dog类对象的时候,必须指定__init__函数中的实参 dog=Dog('藏獒','8','母') print(dog.name) print(dog.age) dog.run() dog.eat() # print(dog._dog__sex) #dog._Dog__sleep() #总结: #1.私有属性,不能通过对象直接访问,但是可以通过设置方法(函数)访问 #2.父类中的私有属性,私有方法,不会被子类继承,也不能被访问(可以强制访问) #3.一般情况下,私有属性还有私有方法,是不可以被外部所访问的(强制访问除外)
b8a2c3747c37ee4d7ad47a35a006009c65639132
Abhishek-Bajpai/hackerrank
/exepy.py
120
3.5625
4
def gcd(a,b): while( b!=0): temp = a a = b b = temp % b return a print(gcd(60, 96))
4aa5b7924d8f7d10a1ec7f7c7b1c1a41a9996665
Lyndondshelton/Cryptographic-System
/Encoder.py
4,935
3.59375
4
import math import numpy as np # # Initialization of the encryption and decryption dictionaries. alpha_encrypt will return the value of a letter, # alpha_decrypt will return the letter associated with a value. # alpha_encrypt = {' ': 0, 'A': 3, 'B': 6, 'C': 9, 'D': 12, 'E': 15, 'F': 18, 'G': 21, 'H': 24, 'I': 27, 'J': 30, 'K': 33, 'L': 36, 'M': 39, 'N': 42, 'O': 45, 'P': 48, 'Q': 51, 'R': 54, 'S': 57, 'T': 60, 'U': 63, 'V': 66, 'W': 69, 'X': 72, 'Y': 75, 'Z': 78, ',': 81, '.': 84, '?': 87, '!': 90, "'": 93, '-': 96, '0': 99, '1': 102, '2': 105, '3': 108, '4': 111, '5': 114, '6': 117, '7': 120, '8': 123, '9': 126} alpha_decrypt = {0: ' ', 3: 'A', 6: 'B', 9: 'C', 12: 'D', 15: 'E', 18: 'F', 21: 'G', 24: 'H', 27: 'I', 30: 'J', 33: 'K', 36: 'L', 39: 'M', 42: 'N', 45: 'O', 48: 'P', 51: 'Q', 54: 'R', 57: 'S', 60: 'T', 63: 'U', 66: 'V', 69: 'W', 72: 'X', 75: 'Y', 78: 'Z', 81: ',', 84: '.', 87: '?', 90: '!', 93: "'", 96: '-', 99: '0', 102: '1', 105: '2', 108: '3', 111: '4', 114: '5', 117: '6', 120: '7', 123: '8', 126: '9'} # # Initialization of the Matrix encryption key. MATRIX_KEY is final and should not be changed. # MATRIX_KEY = [ [2, 3, 6, 7], [1, 4, 5, 2], [6, 7, 3, 2], [9, 10, 2, 3] ] # # Initialization of the empty matrices. # Y = [] # The encryption matrix that will hold the values of the message ENC = [] # The encrypted matrix. ENC = Y * MATRIX_KEY DEC = [] # The decrypted matrix. DEC = ENC * inv_matrix_key string = input("Enter a message: ").upper() # Get the message as input from the user # # Row and Column configuration. # x_rows = len(MATRIX_KEY) # The number of rows in MATRIX_KEY x_cols = len(MATRIX_KEY[0]) # The number of columns in MATRIX_KEY y_rows = math.ceil(len(string) / x_rows) # The number of rows needed for matrix Y to fit the length of the string y_cols = x_rows # The number of columns in matrix Y needs to be equal to the number of rows in MATRIX_KEY entries_in_y = y_rows * x_cols # The number of total entries in matrix Y CAESAR_KEY = x_rows * (alpha_encrypt['B'] - alpha_encrypt['A']) # The key used for the caesar cipher. CAESAR_KEY is final and should not be changed. max_value = alpha_encrypt['9'] + CAESAR_KEY # The largest possible value of a character in the alphabet # # Encrypt the message by using the caesar cipher then the encryption matrix Y # # return ENC # def encryption(s): # Caesar cypher initialization. Increment the values of alpha_encrypt by 3, creating a caesar cipher. for x in alpha_encrypt: alpha_encrypt[x] = (alpha_encrypt[x] + CAESAR_KEY) % max_value # While the number of characters in s is less than the number of entries in ENC, create spaces to fill the gaps. while len(s) < entries_in_y: s = s + ' ' # For the number of characters in s, place the value of each character in their proper places in Y. char_count = 0 for i in range(y_rows): Y.append([]) for j in range(y_cols): Y[i].append(alpha_encrypt[s[char_count]]) char_count += 1 # Matrix multiplication on Y * MATRIX_KEY = ENC for i in range(len(Y)): ENC.append([]) for j in range(len(MATRIX_KEY[0])): e = 0 for c in range(len(MATRIX_KEY)): e += Y[i][c] * MATRIX_KEY[c][j] ENC[i].append(e) return ENC # # Decrypt the message from the ENC matrix, using the INV_MATRIX_KEY and the caesar_key. # # return decrypted_message # def decryption(enc_mat): # Initialization of the MATRIX_KEY inverse inv_matrix_key = np.linalg.inv(MATRIX_KEY) # Initialization of the decrypted message decrypted_message = '' # Matrix multiplication on enc_mat * INV_MATRIX_KEY = D for i in range(len(enc_mat)): DEC.append([]) for j in range(len(inv_matrix_key[0])): d = 0 for c in range(len(inv_matrix_key)): d += enc_mat[i][c] * inv_matrix_key[c][j] DEC[i].append(round(d)) # For each of the values in DEC, use the caesar_key to find the original values and decrypt the message for i in range(len(DEC)): for j in range(len(DEC[0])): DEC[i][j] = (DEC[i][j] - CAESAR_KEY) % max_value decrypted_message += alpha_decrypt[DEC[i][j]] return decrypted_message # The following lines will encrypt the string and print the encrypted matrix ENC to the screen, then decrypt ENC and # print the decrypted matrix DEC and the original message to the screen. print("\nThe Encrypted Matrix(ENC): {}\n".format(encryption(string))) message = decryption(ENC) print("The Decrypted Matrix(DEC): {}".format(DEC)) print("The decrypted message: {}".format(message))
9e57dbd5a0eb34bd3ed3567b5c83fd2cfed10ebc
Psami-wondah/shiiiiii
/atm shii.py
1,383
3.78125
4
from datetime import datetime now = datetime.now() currentDt = now.strftime("%d/%m/%Y %H:%M:%S") allowedUsers = ['Seyi', 'Sam', 'Love'] allowedPassword = ['passwordSeyi', 'passwordSam', 'passwordLove'] Balance = 0 name = input('What is your name? \n') if name in allowedUsers: password = input('Your password \n') userId = allowedUsers.index(name) if password == allowedPassword[userId]: print(currentDt) print('Welcome ', name) print('These are the available options:') print('1. Withdrawal') print('2. Cash Deposit') print('3. Complaint') selectedOption = int(input('Please select an option \n')) if selectedOption == 1: withdrawalAmount = int(input('How much would you like to withdraw? \n')) print('Take your cash') elif selectedOption == 2: depositAmount = int(input('How much would you like to deposit \n')) Balance = Balance + depositAmount print('Your balance is:', Balance) elif selectedOption == 3: issue = input('What issue will you like to report? \n') print('Thank you for contacting us') else: print('Invalid option selected, please try again') else: print('Password incorrect please try again') else: print("Name not found please try again")
607d083c65f3d595701c5b185fa55e87f4f78cc5
Prasannarajmallipudi/Python_ToT_2019
/gcdnumber.py
314
3.890625
4
#from math import gcd #print(gcd(20, 8)) a = int(input('Please input the First Number:')) b = int(input('Please input the Second Number:')) while b != 0: gcd = b b = a % b a = gcd print(gcd) ''' for i in range(1,b+1): if a % i == 0 and b % i == 0: gcd = i print(gcd)'''
9a303764d51699ab237fe658e66a4e498b57df8c
greg-dry/BlackJack
/blackjack.py
4,943
3.796875
4
import random import math suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Ace','Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King') values = {'Ace': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10} class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit self.value = values[rank] def __str__(self): return f'{self.rank} of {self.suit}' class Deck(Card): def __init__(self): self.all_cards = [] for suit in suits: for rank in ranks: self.all_cards.append(Card(rank, suit)) def shuffle(self): random.shuffle(self.all_cards) def remove_card(self): return self.all_cards.pop(0) class Player(Deck, Card): def __init__(self, balance): self.balance = balance self.my_cards = [] self.values = [] def __str__(self): return f"You have ${self.balance}." def player_hit(self, new_card): self.my_cards.append(new_card) self.values.append(new_card.value) def make_a_bet(self): print(myplayer) while True: try: bet = int(input('Make a bet: ')) except: print('invalid input') else: if bet > self.balance: print('You do not have the funds in your balance to make that bet') else: new_balance = self.balance - bet print(f"You now have ${new_balance}") break class Dealer(Deck): def __init__(self): self.dealer_cards = [] self.dealer_values = [] def dealer_hit(self, new_card): self.dealer_cards.append(new_card) self.dealer_values.append(new_card.value) mydeck = Deck() myplayer = Player(balance = 100) mydealer = Dealer() print('Welcome to BlackJack') while True: try: play_choice = int(input("do you want to play? Enter 1 for Yes, 2 for No: ")) except: print('Invalid answer') else: break if play_choice == 1: print("Ok let's play!") game_on = True else: print("Goodbye") game_on = False mydeck.shuffle() top_card = mydeck.remove_card() myplayer.player_hit(top_card) def game_play(): while game_on == True: myplayer.make_a_bet() break print(f"Your card is {myplayer.my_cards[0]}") players_turn = True while players_turn == True: try: hit_choice = int(input("Would you like to hit? Enter 1 for Yes, 2 for No: ")) except: print('invalid answer') else: if hit_choice == 1: top_card = mydeck.remove_card() myplayer.player_hit(top_card) print(f"Your card is {myplayer.my_cards[-1]}") player_current_value = sum(myplayer.values) print('your current hand value is ' + str(player_current_value)) if player_current_value > 21: print('You went over 21, game over') break elif player_current_value == 21: print('you won!') break else: pass else: player_current_value = sum(myplayer.values) print('your current hand value is ' + str(player_current_value)) print('It is now the dealers turn') top_card = mydeck.remove_card() mydealer.dealer_hit(top_card) print(f"The dealer's card is {mydealer.dealer_cards[0]}") dealer_wins = False while dealer_wins == False: top_card = mydeck.remove_card() mydealer.dealer_hit(top_card) print(f"The dealer's card is {mydealer.dealer_cards[-1]}") dealer_current_value = sum(mydealer.dealer_values) print('Dealers current hand value is ' + str(dealer_current_value)) if dealer_current_value > 21: print('Dealer went over 21, you win!') dealer_wins = True players_turn = False elif dealer_current_value > player_current_value and dealer_current_value <= 21: print('dealer has higher hand, you lose.') dealer_wins = True players_turn = False else: pass game_play()
524b33b034b850a6ef1a8bcc9c5f6c321bb76ccb
skydeamon/Pre-Bootcamp-Coding-Challenge
/Task3.py
345
3.765625
4
""" Created on 11/04/2020 @author: SkyCharmingDeamon _Umuzi_ Pre-bootcamp challenges tast 3: functions A function that takes 2 numbers as input. If either of the numbers is 65, OR if the sum of the numbers is 65 then return true. Otherwise return false, """ def function(a,b): return (a == 65 or b == 65 or (a + b) == 65)
f2f85ec9808c7dedfb4d7d11215aa37e3a5c0de4
AnikaitSahota/Naive-Bayes-classifiers
/Codes/Matrix.py
3,918
4.1875
4
""" Author : Anikait Sahota Status : no error Dated : 21 March 2019 """ def matrix_multiplication(a,b): """ function to multiply matrix a with matrix b -> aXb Arguments: a and b are two dimensional matrices """ if len(a[0])!=len(b): # if number of columns of matrix a == number of rows of matrix b return(False) # these matrices can't be multiplied hence False tmp_k=len(b) m_a=len(a) #number of rows n_b=len(b[0]) #number of columns result=[[None for i in range (n_b)] for i in range (m_a)] #creating matrix with dimensions of resultanst matrix for i in range (m_a): for j in range (n_b): sum=0 for k in range (tmp_k): sum+=a[i][k]*b[k][j] result[i][j]=float(sum) return(result) def transpose(a): """ function to return transpose of 'a' matrix Arguments: a is the input matrix """ m = len(a) # numner of rows in given matrix n = len(a[0]) # number of columns in given matrix result = [[None for i in range (m)] for j in range (n)] #creating a matrix while swaping the number of rows with number of columns for i in range(m) : # for loop to assign values to result matrix for j in range(n): result[j][i] = a[i][j] return(result) # returning the matrix def determinent(a): """ function to return determinent of the given matrix a using the recursiion Argument: a is the input square matrix to find determinent""" n = len(a) if(n == 1): # base case for 1X1 square matric return a[0][0] ; elif(n == 2): # base case for 2X2 square matrix return(a[0][0]*a[1][1] - a[0][1]*a[1][0]) else: # for all cases above 2X2 result = 0 # resultant determinent tmp_matrix = [[None for i in range (n-1)]for j in range (n-1)] # matrix with (n-1)X(n-1) dimensions for recursion for i in range (n): for j in range (n): # loop for assigning the value to (n-1)X(n-1) square matrix temp_index = 0 for k in range (n): if(k != i and temp_index < n and j>0): tmp_matrix[j-1][temp_index] = a[j][k] temp_index += 1 result += ((-1)**(i))*(a[0][i])*determinent(tmp_matrix) # calculating the determinent return result # returning the determinent value def Adjoint(a): """ fuction to find adjoint of a matrix and return it Argument: a is the input matrix""" n = len(a) # number of columns and rows of square matrix result = [[None for i in range (n)]for j in range(n)] if(n == 1): # base case for 1X1 matrix result[0][0] = 1 elif(n == 2): # base case for 2X2 matrix result[0][0] = a[1][1] result[0][1] = -1*a[0][1] result[1][0] = -1*a[1][0] result[1][1] = a[0][0] """ it converts matrix | a b | --> | d -b | | c d | | -c a | """ else: tmp_matrix = [[None for i in range (n-1)]for j in range (n-1)] # tempararory matrix for finding determinent for i in range (n): # for loop for result matrix for j in range (n): # for loop for result matrix tmp_i = 0 for k in range (n): # for loop for formig determinent matrix tmp_j = 0 for l in range (n): # for loop for forming determinent matrix if(k != i and l != j): tmp_matrix[tmp_i][tmp_j] = a[k][l] tmp_j += 1 if(tmp_j == n-1): tmp_i += 1 result[j][i] = ((-1)**(i+j))*determinent(tmp_matrix) # used (j,i) instead of (i,j) to form transpose return result # returning the Adjoint matrix of a def inverse(a) : """ function to find inverse of a matrix return inverse of matrix if possible othervise Fasle Arguments: a is the input matrix """ det = determinent(a) # finding determinent of matrix 'a' if(det == 0): # if det == 0 hence it is singular matrix , inverse not possible return False Adj = Adjoint(a) # finding Adjoint of matrix if(det != 1): for i in range (len(a)): # for loop Adj(a)/det(a) for j in range (len(a)): Adj[i][j] /= det return Adj # returning the inverse of matrix 'a' a = [['Ab','Cd'],['Ef','Gh']] #print(transpose(a))
a86010ff291698cf14382ff1bfd77c3a1aaf3617
kkyoung28/Programming-Python-
/Function2.py
3,547
3.6875
4
#p107~109 import random # def rolling_dice(): # n=random.randint(1, 6) # print("6면 주사위 굴린 결과 : ",n) #1<=n<=6 랜덤수 # def rolling_dice(pip): # n=random.randint(1,pip) # print(pip, "면 주사위 굴린 결과 : ",n) #1<=n<=pip 랜덤 def rolling_dice(pip, repeat): for r in range(1, repeat+1): n = random.randint(1,pip) print(pip, "면 주사위 굴린 결과 ",r, ":" ,n) #1<=n<=pip 랜덤 rolling_dice(6, 1) rolling_dice(6, 2) rolling_dice(12, 0) rolling_dice(20, -3) #p109 def star(): print("*****") star() #***** star() #***** star() #***** #p113 print("핱") print("핱","읖") print("핱","읖","큷") print("핱","읖","큷","슾") print("핱","읖","큷","슾","별") #p114 # def p(*args): # string="" # for a in args: # string += a # print(string) # p("핱") # p("핱","읖") # p("핱","읖","큷","슾") #p114 def p(space, space_num,*args): string=args[0] for i in range(1, len(args)): string +=(space * space_num)+args[i] print(string) p(",",3,"핱","읖") p("별",2,"핱","읖","큷") p("_",3,"핱","읖","큷","슾") #p115 def star2(ch, *nums): for i in range(len(nums)): print(ch * nums[i]) star2("읖", 3) #읖읖읖 star2("핱",1,2,3) #핱 #핱핱 #핱핱핱 #p116 def fn(a,b,c,d,e): print(a,b,c,d,e) fn(1,2,3,4,5) fn(10,20,30,40,50) fn(5,6,7,8,9) fn(a=1, b=2,c=3,d=4,e=5) fn(e=5, d=4, c=3, b=2, a=1) fn(1, 2, c=3, e=5, d=4) #fn(d=4, e=5, 1, 2, 3) #에러 #p118 #***__*** #***__*** #***__*** def star3(mark, repeat, space, space_repeat, line): for _ in range(line): string= (mark*repeat)+(space*space_repeat)+(mark*repeat) print(string) star3("*", 3, "_", 2, 3) #p119 def hello(msg="안녕하세요"): print(msg+"!") hello("하이") hello("hi") hello() #p120 def hello2(name, msg="안녕하세요"): print(name+"님, "+msg+"!") hello2("김가영", "오랜만이에요") hello2("김선옥") #hello2() #에러 name 인자 없음 def fn2(a, b=[]): b.append(a) print(b) fn2(3) #[].append(3) => [3] fn2(5) #[].append(5) => [5]:x [3,5]:o fn2(10) #[3, 5, 10] fn2(7, [1]) #[3, 5, 10, 1, 7]:x vs [1, 7]:o #fn2(a=7, b=[1]): #print([1].append(7)) #p123 def gugudan(dan=2): #1~9 i for i in range(1, 9+1): #print(dan, "X",i, "=", dan*i) print(str(dan)+"x"+str(i)+"="+str(dan*i)) gugudan(3) #3단 출력 gugudan(2) #2단 출력 gugudan() #2단 출력 #p125 def sum(*numbers): sum_value=0 for number in numbers: sum_value += number return sum_value print("1 + 3 =", sum(1, 3)) print("1 + 3 + 5 + 7=", sum(1, 3, 5, 7)) def min(*numbers): min_value=numbers[0] for number in numbers: if min_value > number: min_value = number return min_value print("min(3, 6, -2)=", min(3, 6, -2)) def max(*numbers): max_value=numbers[0] for number in numbers: if max_value < number: max_value = number return max_value print("max(8, 1, -1, 12) =", max(8, 1, -1, 12)) def multi_num(multi, start, end): result = [] for n in range(start, end): if n % multi == 0: result.append(n) return result print("multi_num(17, 1, 200)=",multi_num(17, 1, 200)) print("multi_num(3, 1, 100)=",multi_num(3, 1, 100)) def min_max(*args): min_value = args[0] max_value = args[0] for a in args: if min_value > a: min_value = a if max_value < a: max_value = a return min_value, max_value min, max = min_max(52, -3, 23, 89, -21) print("최솟값", min, "최댓값:", max)
85012bb061be955cb0e30489928b014f2b3f1053
RussH-code/Forest-Fire-Simulation
/sims.py
19,935
3.53125
4
""" This module contains: simulation(), simulation_combine() and sim_plot(). The simulation and simulation_combine functions run the forest fire simulation. The simulation function only changes one parameter at a time, this is useful for studying the effect of one parameter on the function. The simulation_combine function can take values to change both the lightning and new tree growth probabilities, this is useful for looking at the effect of changing both these parameters. The sim_plot is used for creating graphs of these simulations: a line graph showing the changing proportion of trees on fire and alive trees, and a dynamic bar chart representing the number of cells in the grid that are empty, on fire or alive. """ #Import all the needed modules from animation import animate, animate_with_rain from setup import initialise, init, reset, initialise_with_rain import config import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from IPython.display import HTML def simulation(parameter, sim_values, times = 1, GRID_HEIGHT = config.GRID_HEIGHT, GRID_WIDTH = config.GRID_WIDTH, lightning = config.lightning, tree_growth = config.tree_growth, frame_num = config.frame, cloud_th = config.cloud_th, rain = False): """ Runs forest fire simulation for a parameter over the specified values for specified number of times. Note: the parameters that are not changed will be run as specified in config.py so this should be checked before running Args: parameter : (int) the parameter to be changed in the simulation 0 = tree_growth 1 = lightning 2 = GRID_HEIGHT and GRID_WIDTH 3 = rain sim_values : (numpy ndarray) a 1D array corresponding to the probabilities/values of the parameter(s) to be used in simulation times : (int) number of times to repeat the simulation, defaults to 10 GRID_HEIGHT (int): The grid height, default value set in the config GRID_WIDTH (int): The grid width, default value set in the config lightning (float): The probability that lightning, default value set in the config tree_growth (float): The probability that a new tree, default value set in the config frame_num (int): The number of frames to run the simulation rain (boolean): If true, the simulation will be run with the effect of rain, defaults to false Returns: mean_remaining_trees : (list) a list of floats containing the mean values of the remaining number of trees one mean value is returned for each value in sim_values mean_last_frame : (list) a list of floats containing the mean values of the last frame number one mean value is returned for each value in sim_values Raises: ValueError: If any of the arguments are of the correct type but not a valid value TypeError: If any of the arguments are not of the correct data type """ #Checks the number of the times argument is above 0 if times <= 0: raise ValueError("Number of times must be at least 1!") #Checks the simulation values are stored in a numpy array elif (type(sim_values) != np.ndarray): raise TypeError("Invalid simulation value type, only accepts 1D numpy array!") #Checks there is at least one value in the values for the testing elif (sim_values.size <= 0 ): raise ValueError("Must have at least one value in simualation values!") #Checks the paramater value is valid (either 0, 1, 2 or 3) elif (parameter > 3 or parameter < 0): raise ValueError("Invalid parameter values, see documentation.") #Check the grid height and width are positive and probabilities of lightning and tree growth are between 0 and 1. elif (GRID_HEIGHT <= 0 or GRID_WIDTH <= 0 or lightning > 1 or lightning < 0 or tree_growth > 1 or tree_growth < 0): raise ValueError("Invalid values!") #If parameter is 3 (simulating rain) and rain is false, raises an error, elif (parameter == 3 and rain == False): raise ValueError("Conflicting rain argument!") #If the frame number is smaller than 1, raise an error elif(frame_num < 1): raise ValueError("Invalid frame number, frame number must be at least 1!") #Creates two empty arrays #This first array will store the proportion of the grid that are still alive trees for each value in the parameter. A mean is taken for #each value. mean_remaining_trees = [] #This array will store the value of the last frame. This is either the frame the simulation has burnt out at or the max frame number as #previously set. A mean is taken for each value. mean_last_frame = [] #Iterate over each value in the simulation values so each one is tested. for param in list(sim_values): #Set empty list for this value #This array will store the proportion of the grid that are still trees in each simulation for one value when the simulation has #ended. This can either be ending by the grid burning out or the max number of frames is reached. remaining_trees_per_sim = [] #This array will store the number of the last frame that the simulation ends on. This can either be when the simulation burns out #or when the max number of frames has ended. last_frame_per_sim = [] #Repeat this simulation the number of times set as specified in the "times" argument for time in range(times): #Reset the variables in config.py reset() #Change the frame number and last_frame in config.py config.frame = frame_num config.last_frame = frame_num #If rain effect is not activated if(rain == False): #Checks which parameter is to be tested and sets the appropriate parameter. #If it is 0: in the initialize function set tree growth to be the value in the list if (parameter == 0): fig = initialise(tree_growth = param, GRID_HEIGHT = GRID_HEIGHT, GRID_WIDTH = GRID_WIDTH, lightning = lightning) #If it is 1: in the initialize function set to lightning to be the value in the list elif (parameter == 1): fig = initialise(lightning = param, GRID_HEIGHT = GRID_HEIGHT, GRID_WIDTH = GRID_WIDTH, tree_growth = tree_growth) #If it is 2: in the initialize function set it to grid height and width #Note: as this grid is a square only one value is used for both grid height, grid width elif (parameter == 2): fig = initialise(GRID_HEIGHT = param, GRID_WIDTH = param, lightning = lightning, tree_growth = tree_growth) #Run the FuncAnimation function from the MatPlot Library (see packages imported) using the appropriate parameters #Fig makes sure the output is placed in a figure #animate_with_rain calls the animate_with_rain function (see modules imported) #the number of frames is set to the value declared in the config module #Interval of 1 to proceed through the animation faster #The init function (see the init module) is called first to set up the plot. anim = FuncAnimation(fig, animate, frames=config.frame, interval=1, init_func = init) #Display this in HTML HTML(anim.to_jshtml()) #If rain is in effect else: #Checks which parameter is to be tested and sets the appropriate parameter. #If it is 0: in the initialize function set tree growth to be the value in the list if (parameter == 0): fig = initialise_with_rain(tree_growth = param, GRID_HEIGHT = GRID_HEIGHT, GRID_WIDTH = GRID_WIDTH, lightning = lightning, cloud_th = cloud_th) #If it is 1: in the initialize function set to lightning to be the value in the list elif (parameter == 1): fig = initialise_with_rain(lightning = param, GRID_HEIGHT = GRID_HEIGHT, GRID_WIDTH = GRID_WIDTH, tree_growth = tree_growth, cloud_th = cloud_th) #If it is 2: in the initialize function set it to grid height and width #Note: as this grid is a square only one value is used for both grid height, grid width elif (parameter == 2): fig = initialise_with_rain(GRID_HEIGHT = param, GRID_WIDTH = param, lightning = lightning, tree_growth = tree_growth, cloud_th = cloud_th) #If it is 3 set it to cloud threshold elif (parameter == 3): fig = initialise_with_rain(cloud_th = 1-param, GRID_HEIGHT = GRID_HEIGHT, GRID_WIDTH = GRID_WIDTH, lightning = lightning, tree_growth = tree_growth) # we do 1 minus the cloud threshold so we can plot the rain probability and the trend is easier to interoperate #Run the FuncAnimation function from the MatPlot Library (see packages imported) using the appropriate parameters #Fig makes sure the output is placed in a figure #animate calls the animate function (see modules imported) #the number of frames is set to the value declared in the config module #Interval of 1 to proceed through the animation faster #The init function (see the init module) is called first to set up the plot. anim = FuncAnimation(fig, animate_with_rain, frames=config.frame, interval=1, init_func = init) #Display this in HTML HTML(anim.to_jshtml()) #Set the remaining trees to be the proportion of alive trees in the last frame. This value is appended to the array storing the #number of remaining trees in the simulations remaining_trees_per_sim.append(config.prop_of_trees[-1]) #Set the last frame in a simulation and add this to the array storing number of the last frames. last_frame_per_sim.append(config.last_frame) #There is now an array for one value in the parameter list. A mean of each list is then taken to find the mean number of trees #remaining and mean value for the last frame. This value is then appended to the arrays containing the mean for each value. mean_remaining_trees.append(np.mean(np.array(remaining_trees_per_sim))) mean_last_frame.append(np.mean(np.array(last_frame_per_sim))) #Return the mean remaining tree number and mean last frame lists. return mean_remaining_trees, mean_last_frame def simulation_combine(light_values, tree_values, times = 1, frame_num = config.frame): """ Runs forest fire simulation over specified values for the specified number of times. Each lightning probability is tested against each new tree value for the number of times specified. Args: light_values : (numpy ndarray) a 1D array corresponding to the probabilities/values of lightning to be used in the simulation tree_values : (numpy ndarray) a 1D array corresponding to the probabilities/values of new tree growth to be used in the simulation times : (int) number of times to repeat the simulation, defaults to 10 frame_num (int): The number of frames to run simulation Returns: mean_remaining_trees : (list) a list of floats containing the mean values of the remaining number of trees one mean value is returned for each value combination of lightning values and new tree values mean_last_frame : (list) a list of floats containing the mean values of the last frame number one mean value is returned for each value combination of lightning values and new tree values condition: (list) a list of pairs of values representing the lightning and new tree probabilities used as (lightning, new tree) Raises: ValueError: If any of the arguments are of the correct type but not a valid value TypeError: If any of the arguments are not of the correct data type """ #Checks the number of the times argument is above 0 if times <= 0: raise ValueError("Number of times must be at least 1!") #Checks the simulation values are stored in a numpy array elif (type(light_values) != np.ndarray): raise TypeError("Invalid simulation value type, only accepts 1D numpy array!") #Checks there is at least one value in the values for the testing elif (light_values.size <= 0 ): raise ValueError("Must have at least one value in simualation values!") #Checks the simulation values are stored in a numpy array elif (type(tree_values) != np.ndarray): raise TypeError("Invalid simulation value type, only accepts 1D numpy array!") #Checks there is at least one value in the values for the testing elif (tree_values.size <= 0 ): raise ValueError("Must have at least one value in simualation values!") #If the frame number is smaller than 1, raise an error elif(frame_num < 1): raise ValueError("Invalid frame number, frame number must be at least 1!") #Creates two empty arrays #This first array will store the proportion of the grid that are still alive trees for each value in parameter. A mean is taken for #each value. mean_remaining_trees = [] #This array will store the value of the last frame. This is either the frame the simulation has burnt out at or the max frame number as #previously set. A mean is taken for each value. mean_last_frame = [] #This array will store each condition for tabulating and visualising the data. condition = [] #Iterate over each value in the simulation values so each one is tested. for lightning_value in list(light_values): #for each value in the lightning list iterate over the new tree probability list and test each one. for tree_value in list(tree_values): #Set empty list for this value remaining_trees_per_sim = [] last_frame_per_sim = [] #Repeat this simulation the number of times set as specified in the "times" argument for time in range(times): #Reset the variables in config.py reset() #Change the frame number in config.py config.frame = frame_num config.last_frame = frame_num #Set the probabilities of new tree growth and lightning to be the values specified in the lists using the initialize #function (see the initialize module) fig = initialise(tree_growth = tree_value, lightning = lightning_value) #Run the FuncAnimation function from the MatPlot Library (see packages imported) using the appropriate parameters #Fig makes sure the output is placed in a figure #animate calls the animate function (see modules imported) #the number of frames is set to the value declared in config module #Interval of 1 to proceed through the animation faster #The init function (see the init module) is called first to set up the plot. anim = FuncAnimation(fig, animate, frames=config.frame, interval=1, init_func = init) #Display this in HTML so can be displayed in a Jupiter Notebook HTML(anim.to_jshtml()) #Set the remaining trees to be the proportion of alive trees in the last frame. This value is appended to the array storing #the number of remaining of trees in the simulations remaining_trees_per_sim.append(config.prop_of_trees[-1]) #Set the last frame in a simulation and add this to the array storing number of the last frames. last_frame_per_sim.append(config.last_frame) #There is now an array for set of conditions. A mean of each list is then taken to find the mean number of trees #remaining and mean value for the last frame. This value is then appended to the arrays containing the mean for each value. mean_remaining_trees.append(np.mean(np.array(remaining_trees_per_sim))) mean_last_frame.append(np.mean(np.array(last_frame_per_sim))) #The condition tested is then appended to the list of conditions condition.append((lightning_value, tree_value)) #Return the mean remaining tree number, mean last frame and conditions return mean_remaining_trees, mean_last_frame, condition def sim_plot(sim_values, rem_trees, last_frame, x_axis): """ This function plots the proportion of trees in the last frame and the number of frames in the simulation and is used after the simulation function to visualise the results. Args: sim_values: (numpy ndarray) a 1D array corresponding to the probabilities/values of the parameter(s) to be used in simulation rem_trees: (list) a list of floats containing the mean values of the remaining number of trees last_frame: (list) a list of floats containing the mean values of the last frame number x_axis: (string) label for the x axis of the plot Raises: Type Error: An incorrect data type is passed into the parameters, simulation values must be added as a numpy array. Value Error: The lists or array are not the same length and so could not be plotted together. """ #Checks that the simulation values are in a numpy array if (type(sim_values) != np.ndarray): raise TypeError("Invalid simulation value type, only accepts 1D numpy array!") #Checks all arguments are of the same length and so can be plotted together elif (sim_values.size != len(rem_trees) or sim_values.size != len(last_frame)): raise ValueError("Arguments are of differen size/lengths!") #Creates two subplots and sets the figure size to be 12x5 size_sim, axes = plt.subplots(1, 2, sharex = True, figsize = (12, 5)) #For the first plot: #Plot the simulation values against the list of values contaning the remaining trees axes[0].plot(list(sim_values), rem_trees) #Add a title to the plot axes[0].set_title("No. of remaining trees in last frame") #Set the y axis label axes[0].set_ylabel("Proportion of trees") #For the second plot: #Plot the simulation values against the list of values containing the last frame numbers axes[1].plot(list(sim_values), last_frame) #Add a title to the plot axes[1].set_title("No. of frames in simulation") #Set the y axis label axes[1].set_ylabel("Frame number") #Add an x axis label for the simulation values and set this at the bottom of the plot in the center size_sim.text(0.5, 0.04, x_axis, ha='center') #Display the plot plt.show()
4724c8dead863938ccb4c7ce4c65a31f29f2363f
LeonKennedy/DataStructureAlgorithm
/Knapsack.py
2,136
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: Knapsack.py # @Author: olenji - [email protected] # @Description: 0-1 背包问题 # @Create: 2019-07-10 22:48 # @Last Modified: 2019-07-10 22:48 from copy import copy from typing import List class Knapsack: def __init__(self): self.maxW = 9 self.items = [2, 2, 4, 6, 3] self.values = [3, 4, 8, 9, 6] print(f"item weight: {self.items}") def backtracking(self, i, bag): if i >= len(self.items): yield bag else: negative_bag = copy(bag) yield from self.backtracking(i + 1, negative_bag) if sum(bag) + self.items[i] > self.maxW: yield bag else: sub_bag = copy(bag) sub_bag.append(self.items[i]) yield from self.backtracking(i + 1, sub_bag) def dynamic(self): states = [-1] * (self.maxW + 1) states[0] = 0 n = len(states) for i, item in enumerate(self.items): for j in range(n-1, -1, -1): # 这里的倒叙是关键, 不然会覆盖之后的值 if states[j] >= 0 and j + item < n and states[j + item] < states[j] + self.values[i]: states[j + item] = self.values[i] + states[j] return states def find_combine(self, states) -> List: # 打印组合 max_value = max(states) max_weight = states.index(max_value) print(f"max value: {max_value} max weight: {max_weight}") output = list() for i, item in enumerate(self.items): if states[max_weight - item] == max_value - self.values[i]: output.append(i) max_value -= self.values[i] max_weight -= item return output if __name__ == "__main__": k = Knapsack() max_bag = [] print('---- backtracking --- ') for bag in k.backtracking(0, []): if sum(bag) > sum(max_bag): max_bag = bag print(max_bag) print('---- dynamic --- ') states = k.dynamic() output = k.find_combine(states) print(output)
7b98b8dd7e3a060af3ed6f3f7a7769fbb65af04e
LeonKennedy/DataStructureAlgorithm
/leetcode/MergeSortedLists.py
1,536
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: MergeSortedLists.py # @Author: olenji - [email protected] # @Description: 合并多个有序列表 # https://leetcode.com/problems/merge-k-sorted-lists/ # @Create: 2019-07-20 17:24 # @Last Modified: 2019-07-20 17:24 from typing import List from queue import PriorityQueue import sys class ListNode: __slots__ = 'val', 'next' def __init__(self, x): self.val = x self.next = None def __lt__(self, other): return self.val < other.val class MergeSortedLists: def mergeKLists(self, lists: List[ListNode]) -> ListNode: head = ListNode(None) tail = head q = PriorityQueue() for node in lists: if node: q.put(node) while q.qsize() > 0: tail.next = q.get() tail = tail.next if tail.next: q.put(tail.next) return head.next def print_list(data): if data is None: return p = data while p.next is not None: print(p.val, end='->') p = p.next print(p.val) if __name__ == "__main__": data = [ [5, 4, 1], [4, 3, 1], [6, 2] ] input = list() for l in data: head = ListNode(None) for d in l: t = ListNode(d) t.next = head.next head.next = t input.append(head.next) for l in input: print_list(l) m = MergeSortedLists() # input = [None, None] output = m.mergeKLists(input) print_list(output)
2cb2346e70db90645b00a7e910c0bf85c691dfff
LeonKennedy/DataStructureAlgorithm
/graph/TopologicalSort.py
1,217
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: TopologicalSort.py # @Author: olenji - [email protected] # @Description: # @Create: 2019-08-16 15:39 # @Last Modified: 2019-08-16 15:39 from Graph import AdjacencyMap def topological_sort(graph: AdjacencyMap): incount = dict() queue = list() for vertex in graph.vertices: incount[vertex] = graph.degree(vertex, False) walk = None while len(incount): if walk == incount: break walk = incount.copy() for k,v in walk.items(): if v == 0: queue.append(k) for e in graph.incident_edges(k): incount[e.destination] -= 1 del incount[k] return queue if __name__ == '__main__': dg = AdjacencyMap(is_directed=True) dg.insert_edges(1, 2) dg.insert_edges(1, 3) dg.insert_edges(4, 3) dg.insert_edges(3, 5) dg.insert_edges(3, 6) dg.insert_edges(4, 6) dg.insert_edges(5, 7) dg.insert_edges(1, 7) dg.insert_edges(7, 8) dg.insert_edges(2, 8) # dg.insert_edges(5, 1) # 如果有环 就退出 # dg.insert_edges(9, 8) # dg.insert_edges(8, 9) print(topological_sort(dg))
5840829e5f7c53e2d6416bba1d77ca793d8d62be
LeonKennedy/DataStructureAlgorithm
/leetcode/nqueue.py
2,528
3.78125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Filename: nqueue.py # @Author: olenji - [email protected] # @Description: 51. N-Queens # The n-queens puzzle is the problem of # placing n queens on an n×n chessboard # such that no two queens attack each other. # Given an integer n, return all distinct solutions to the n-queens puzzle. # # Each solution contains a distinct board configuration of the n-queens' placement, # where 'Q' and '.' both indicate a queen and an empty space respectively. # Input: 4 # Output: [ # [".Q..", // Solution 1 # "...Q", # "Q...", # "..Q."], # # ["..Q.", // Solution 2 # "Q...", # "...Q", # ".Q.."] # ] # @Create: 2019-07-10 11:00 # @Last Modified: 2019-07-10 11:00 from typing import List from array import array import copy class NQueue: def solveNQueens(self, n: int) -> List[List[str]]: chessboard = [array('u', '.' * n) for i in range(n)] output = list() for complete_chessboard in self.assign(chessboard, 0): solution = list() for row in complete_chessboard: solution.append(''.join(['Q' if i == 'Q' else '.' for i in row])) output.append(solution) return output def totalNQueens(self, n: int) -> int: chessboard = [array('u', '.' * n) for i in range(n)] num = 0 for complete_chessboard in self.assign(chessboard, 0): num += 1 return num def assign(self, chessboard: List[List[str]], layer: int) -> List[List[str]]: for column, cell in enumerate(chessboard[layer]): if cell != '.': continue sub_chessboard = copy.deepcopy(chessboard) sub_chessboard[layer][column] = 'Q' if layer == len(chessboard) - 1: yield sub_chessboard else: self.fill(sub_chessboard, layer, column) for output in self.assign(sub_chessboard, layer+1): yield output def fill(self, chessboard, layer, column): for row in chessboard: row[column] = '+' chessboard[layer][column] = 'Q' length = len(chessboard) i = layer + 1 while i < length: left = column - i + layer if left >= 0: chessboard[i][left] = '+' right = column + i - layer if right < length: chessboard[i][right] = '+' i += 1 if __name__ == "__main__": q = NQueue() print(q.solveNQueens(4))
ce6179fc4574abb0e25669192dad041088c0ea7b
JustCreature/Py_practice
/practice.py
10,814
4.09375
4
"""This is the list of my practical work of learning OOP. (Uncomment he part of code you want to run)""" """Class and object creation""" # # import random # # class Warrior: # def __init__(self, name): # self.name = name # self.hp = 100 # # def gotHurt(self): # self.hp -= 20 # # # first = Warrior('first') # second = Warrior('second') # # while first.hp > 0 and second.hp > 0: # turn = random.randint(0, 1) # if turn == 0: # whoAt = first # whoHurt = second # else: # whoAt = second # whoHurt = first # whoHurt.gotHurt() # txt = f"The {whoAt.name} attaced the {whoHurt.name}\n" \ # f"The {whoHurt.name} has {whoHurt.hp} lives" # print(txt) # # print("The first won") if first.hp > 0 else print("The second won") ################### ################### """Constructor __init__""" # import random # class Employee: # def __init__(self, name, last_name, quall=1): # self.name = name # self.last_name = last_name # self.quall = quall # # def info(self): # return self.name + self.last_name + self.quall # # def __del__(self): # return print(f"Goodbye Mr.{self.name} {self.last_name}") # # # person1 = Employee('Ivan', 'Ivanov', random.randint(1, 5)) # person2 = Employee('Nikolay', 'Nikolayev') # person3 = Employee('Sergey', 'Sergeyev', random.randint(1, 5)) # # emps = [] # emps.append(person1) # emps.append(person2) # emps.append(person3) # # arr = [] # arr.append(person1.quall) # arr.append(person2.quall) # arr.append(person3.quall) # weak = arr.index(min(arr)) # # emps[weak].__del__() # # input() ################# ################# """Inheritance""" # import random # # # class Person: # def __init__(self, id, team): # self.id = id # self.team = team # # # class Hero(Person): # def __init__(self, id, team): # Person.__init__(self, id, team) # self.level = 0 # # def level_up(self): # self.level += 1 # # class Soldier(Person): # def follow_hero(self, my_hero): # pass # # # hero1 = Hero(1, 1) # hero2 = Hero(2, 2) # # sold1 = [] # sold2 = [] # # i = 0 # # while i < random.randint(10, 15): # check = random.randint(1, 2) # if check == 1: # sold = Soldier(i, 1) # sold1.append(sold) # else: # sold = Soldier(i, 2) # sold2.append(sold) # # i += 1 # # hero1.level_up() if len(sold1) > len(sold2) else hero2.level_up() # # x = sold1[random.randint(0, len(sold1))] # x.follow_hero(hero1) # # print(f"Hero 1 level is {hero1.level}") # print(f"Hero 2 level is {hero2.level}") # # print(f"Soldier {x.id} is following hero {hero1.id}") ############################ ############################ """Polimorphism""" # # class Thing: # def __init__(self, material): # self.material = material # # def __add__(self, other): # if self.material == other.material: # return f"The room furniture is made of {self.material}" # else: # return "The room furniture is made of different materials" # # # class Table(Thing): # def somethig(self): # pass # # # class Chair(Thing): # def anything(self): # pass # # # table = Table(str(input("Enter material of table...\n"))) # chair = Chair(str(input("Enter material of chair...\n"))) # # print(table + chair) # ############################### ############################### """Encapsulation""" # # class Calculate: # __usage = 0 # # def __init__(self, a, b): # self.val = Calculate.__calk(a, b) # # def __setattr__(self, attr, value): # if attr == 'val': # self.__dict__[attr] = value # else: # raise AttributeError # # def __calk(a, b): # return a * b / 2 * b # # def get_val(self): # return self.val # # def set_usage(n): # Calculate.__usage = n # # def get_usage(): # return Calculate.__usage # # q = Calculate(5, 5) # print(q.get_val()) # # q.val = 5 # print(q.get_val()) # # i = 0 # # while i != '': # i += 1 # q = input("First number\n") # if q == 'exit': # print(f"Goodbye. You used the function {Calculate.get_usage()} times") # break # w = input("Second number\n") # if w == 'exit': # print(f"Goodbye. You used the function {Calculate.get_usage()} times") # break # q = int(q) # w = int(w) # print(Calculate(q, w).get_val()) # Calculate.set_usage(i) # ################################### ################################### """Composition""" # import math # import sys # # class Room: # def __init__(self, width, length, height): # self.set_sides(width, length, height) # self.wd = [] # # def getRolls(self, l, w): # self.__rolls = math.ceil(self.get_work_surface() / (l * w)) # # def set_sides(self, width, length, height): # self.__width = width # self.__length = length # self.__height = height # # def lastDel(self): # self.wd.pop() # # def clearWD(self): # self.wd.clear() # # def addWD(self, w = 1, h = 1): # self.wd.append(WinDoor(w, h)) # # def get_work_surface(self): # self.__work_surf = self.get_square() # if len(self.wd) > 0: # for i in self.wd: # self.__work_surf -= i.get_sq() # return self.__work_surf # # def get_square(self): # self.__square = 2 * self.__height * (self.__length + self.__width) # return self.__square # # # class WinDoor: # def __init__(self, x, y): # self.__square = x * y # # def get_sq(self): # return self.__square # # # ask = 0 # # while ask != 'exit': # try: # l = float(input("Enter your room width\n")) # w = float(input("Enter your room length\n")) # h = float(input("Enter your room height\n")) # r1 = Room(l, w, h) # except ValueError: # print("Incorrect input") # break # # while ask != exit: # ask = input("\nWhat do you want? Choose ONE!!!\n1 - Count square, 2 - Count the amount of rolls, " # "3 - Add window-door,\n4 - delete last added window-door, 5 - Count work surface, " # "6 - New room parametrs,\nexit - stop the program\n") # if not str(ask).isdigit() and ask != 'exit' or ask == ' ' or ask == '': # print("Incorrect input") # sys.exit() # if ask == 'exit': # sys.exit() # ask = int(ask) # if ask == 1: # print(f"\nThe square is {r1.get_square()}\n") # elif ask == 2: # l = float(input("The length of your roll:\n")) # w = float(input("The width of your roll:\n")) # print(f"\nYou'll need {r1.getRolls(l, w)} rolls\n") # elif ask == 3: # try: # l = float(input("The length of your window-door(or leave it empty):\n")) # w = float(input("The width of your window-door(or leave it empty):\n")) # r1.addWD(l, w) # except ValueError: # pass # r1.addWD() # elif ask == 4: # r1.lastDel() # elif ask == 5: # print(f"\nThe work surface is {r1.get_work_surface()}\n") # elif ask == 6: # break # print("GoodBye") ########################## ########################## """Operator overload""" # # class Snow: # def __init__(self, q): # self.q = q # # def __add__(self, other): # return self.q - other.q # # def __sub__(self, other): # return self.q + other.q # # def __mul__(self, other): # return self.q / other.q # # def __truediv__(self, other): # return self.q // other.q # # def __call__(self, ar): # self.q = ar # # def makeSnow(self, row_quant): # self.qw = self.q / row_quant # i = 0 # row = '' # while i < self.qw: # row += row_quant * "*" + "\n" # i += 1 # return row # # # s1 = Snow(20) # s2 = Snow(50) # x = s1 + s2 # print(x) # print(s1.makeSnow(5)) # s1(10) # print(s1.makeSnow(5)) # ##################################### ##################################### """Modules and packages""" # # import geometry # from geometry import planimetry as pl, stereometry as st # # b = st.Ball(5) # a = pl.Circle(5) # # print(a.length(), b.V()) # # print(geometry.stereometry.__doc__) # ######################## ######################## """Just prog""" # # import random # # # class Data: # def __init__(self, *info): # self.info = info # # def __getitem__(self, item): # return self.info[item] # # # class Teacher: # def teach(self, info, *pupil): # for i in pupil: # i.take(info) # # # class Pupil: # def __init__(self): # self.knowledge = [] # # def take(self, info): # self.knowledge.append(info) # self.knowledge = set(self.knowledge) # self.knowledge = list(self.knowledge) # # def forget(self): # self.out = random.randint(0, len(self.knowledge) - 1) # self.knowledge.pop(self.out) # # # lesson = Data('class', 'object', 'inheritance', 'polimorphism', 'encapsulation') # marIvanna = Teacher() # vasya = Pupil() # petya = Pupil() # # marIvanna.teach(lesson[2], vasya, petya) # marIvanna.teach(lesson[0], petya) # # print(f"Vasya knows {vasya.knowledge}") # print(f"Petya knows {petya.knowledge}") # # i = 0 # for i in range(3): # selfEd = random.randint(0, len(lesson.info) - 1) # petya.take(lesson[selfEd]) # vasya.take(lesson[selfEd]) # # petya.forget() # # print(f"Vasya knows {vasya.knowledge}") # print(f"Petya knows {petya.knowledge}") # ##################### ##################### """Static methods""" # # from math import pi # # class Cylinder: # @staticmethod # def __make_area(d, h): # circle = pi * d ** 2 / 4 # side = pi * d * h # return round(circle*2 + side, 2) # # def __init__(self, diametr, hight): # self.diametr = diametr # self.hight = hight # self.__count_area() # # def __count_area(self): # self.__area = self.__make_area(self.diametr, self.hight) # # def __setattr__(self, key, value): # if key != 'diametr' or key != 'hight': # self.__dict__[key] = value # else: # raise AttributeError # # def get_area(self): # self.__count_area() # return self.__area # # # a = Cylinder(1, 2) # print(a.get_area()) # # print(a._Cylinder__make_area(2, 2)) # # a.diametr = 2 # # print(a.get_area()) # ######################## ########################
5d78a0925d11a2978b91d75f298730931692a4cd
nschalla/GUVI_Home
/333.py
120
3.875
4
n=int(input("enter the number")) sum = 0 while (num > 0): sum += int(n % 10) n = int(n / 10) print(sum)
d1771a309ef434261340ad20b2937d96dedd188f
nschalla/GUVI_Home
/555.py
62
3.90625
4
'''reverse the given number''' n=int(input()[::-1]) print(n)
42b32eeaa42d5962f29f4d1235951a38e014dd77
gabrielsgradinar/exercicios-hacker-rank
/introduction/if-else.py
458
3.859375
4
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) def is_even(n): if n % 2 == 0: return True return False if not is_even(n): print("Weird") if is_even(n) and n in range(2, 6): print("Not Weird") if is_even(n) and n in range(6, 21): print("Weird") if is_even(n) and n > 20: print("Not Weird")
5470b091b9bd46530850873c488b5598249d3a0b
roger2399/python-practice
/loop_traversal.py
145
3.765625
4
fruit = "banana" index = 0 while len(fruit) > index: letter = fruit[index] print (letter) index += 1
ed6d0b6d1f7240a0e3caba4092c71d7d42b2b8ac
vanman247/Stat-GUI
/Tests/pearson_Coor1.py
1,483
3.59375
4
from scipy.stats import pearsonr from tkinter import * from tkinter import filedialog def main(url = "adult.csv", data1="age", data2="y"): direc="C:/Users/Ammon Van/Desktop/Fun Projects/Statistic Analysis/Tests" filetypes = (("CSV", "*.CSV"), ("All Files", "*.*")) url = filedialog.askopenfilename(initialdir=direc, title="Open File", filetypes=filetypes) url = open(url, "r") stuff = url.read() text1.insert(END, stuff) url.close() ## data1 = ## data2 = try: print("Pearson’s Correlation Coefficient \n \n \n") print("_____ASSUMPTIONS______") print(" 1. Observations in each sample are independent and identically distributed") print(" 2. Observations in each sample are normally distributed") print(" 3. Observations in each sample have the same variance \n") pearson(url = url, data1=data1, data2=data2) except ValueError: print(ValueError) print("Passed") return def pearson(url = "adult.csv", data1="age", data2="y"): df = pd.read_csv(url) df = df.select_dtypes(include=["float64", "int64"]) stat, p = pearsonr(df["{}".format(data1)], df["{}".format(data2)]) print('stat=%.4f, p=%.4f' % (stat, p), "\n") if p > 0.05: print('H0: the two samples are probably independent. \n \n \n') else: print('H1: there is probably a dependency between the samples \n \n \n') if __name__ == "__main__": main()
266db82f465a561b52a117fa38cb97ee80aa0d4d
dsssssssss9/pimoroni-pico
/micropython/examples/pico_display/buttons.py
1,998
3.5
4
# This example shows you a simple, non-interrupt way of reading Pico Display's buttons with a loop that checks to see if buttons are pressed. import picodisplay as display import utime # Initialise display with a bytearray display buffer buf = bytearray(display.get_width() * display.get_height() * 2) display.init(buf) display.set_backlight(0.5) # sets up a handy function we can call to clear the screen def clear(): display.set_pen(0, 0, 0) display.clear() display.update() while True: if display.is_pressed(display.BUTTON_A): # if a button press is detected then... clear() # clear to black display.set_pen(255, 255, 255) # change the pen colour display.text("Button A pressed", 10, 10, 240, 4) # display some text on the screen display.update() # update the display utime.sleep(1) # pause for a sec clear() # clear to black again elif display.is_pressed(display.BUTTON_B): clear() display.set_pen(0, 255, 255) display.text("Button B pressed", 10, 10, 240, 4) display.update() utime.sleep(1) clear() elif display.is_pressed(display.BUTTON_X): clear() display.set_pen(255, 0, 255) display.text("Button X pressed", 10, 10, 240, 4) display.update() utime.sleep(1) clear() elif display.is_pressed(display.BUTTON_Y): clear() display.set_pen(255, 255, 0) display.text("Button Y pressed", 10, 10, 240, 4) display.update() utime.sleep(1) clear() else: display.set_pen(255, 0, 0) display.text("Press any button!", 10, 10, 240, 4) display.update() utime.sleep(0.1) # this number is how frequently the Pico checks for button presses
1b81f53332ac9ed7f14bd9d1146d309f92eb3573
seilcho7/algorithm-practice
/algo_3.py
2,075
3.65625
4
# movie theater problem # nCols = 16 # nRows = 11 # col = 5 # row = 3 # affected_column = nCols - (col -1) # affected_rows = nRows - row # affected_peeps = affected_column * affected_rows # print(affected_peeps) # elevator problem # left_elevator = "left" # right_elevator = 'right' # def elevator(left, right, call): # if abs((call-left)) < abs((call-right)): # print(left_elevator) # elif abs((call-left)) > abs((call-right)): # print(right_elevator) # elif abs((call-left)) == abs((call-right)): # print(right_elevator) # elevator(0, 1, 0) # elevator(0, 1, 1) # elevator(0, 1, 2) # elevator(0, 0, 0) # elevator(0, 2, 1) # def checklists(list_a, list_b): # result = [] # counter = 0 # if len(list_a) == len(list_b): # for num in list_a: # while counter < len(list_b): # if num == list_b[counter]: # result.append(list_b.pop(counter)) # counter += 1 # break # else: # counter += 1 # counter = 0 # else: # print('false') # print(result) # if len(result) == len(list_a): # print('true') # else: # print('false') # checklists([1,2,3,4], [1,2,3,4]) # checklists([1,2,3,4], [1,4,5,6]) # checklists([1,2,3,4], [1,4,4,2]) # checklists([1,2,3,4], [1,4,3,2]) # checklists([1,2,3,4,5], [1,2,3,4]) # checklists([1,1,1,1], [1,1,1,2]) # checklists([1,1,2,2], [2,2,2,1]) # better way def are_they_the_same(a, b): counter = {} counter2 = {} for i in a: counter[i] = 0 for i in a: counter[i] += 1 for i in b: counter2[i] = 0 for i in b: counter2[i] += 1 resultFalse = 0 for key in counter.keys(): if key in counter2.keys(): if counter[key] == counter2[key]: pass else: resultFalse = 1 if resultFalse == 1: return False else: return True print(are_they_the_same([1,2,3,4], [1,2,3,4]))
c4c6d1dfddde4594f435a910147ee36b107e87b9
Pakizer/PragmatechFoundationProject
/tasks/7.py
303
4.15625
4
link[https://www.hackerrank.com/challenges/py-if-else/problem] n = input('Bir eded daxil edin :') n=int(n) if n%2==0 and n>0: if n in range(2,5): print('Not Weird') if n in range(6,20): print ('Weird') else: print('Not Weird') else: print('Weird')
f7e9b67df56874a72f9b38844b2e0ced43313850
tothricsaj/dataStructures
/LinkedList/simply/python/main.py
348
3.515625
4
import LinkedList as ll if __name__ == '__main__': print('Hello LinkedList!!!\n') llist = ll.LinkedList() llist.add(1) llist.add(2) llist.add(3) llist.add('What the bloody horse lungs....????') # llist.printAll() llist.shift(0) llist.shift(-1) llist.shift(-2) llist.shift(-3) llist.printAll()
3f95d9eb38c10dedc759e9d59c6337dec412f6b0
jjauzion/salesman_problem
/src/population.py
4,710
3.859375
4
# -*-coding:Utf-8 -* import random from src.city import City from src.individual import Individual import src.param as param class Population(): """Class population is a set of Individual""" count = 0 final = 0 def __init__(self, city2travel=None, population_size=None): """Constructor of Population. Requires list of cities and pop size""" self.list = [] self.size = 0 self.generation = Population.count Population.count += 1 def __getitem__(self, index): return self.list[index] def __setitem__(self, index, value): if isinstance(value, list): for item in value: if not isinstance(item, Individual): raise TypeError("value contains {} item and should only\ contains Individual elements".format(type(value))) elif not isinstance(value, Individual): raise TypeError("value is {} and should be a Individual element"\ .format(type(value))) self.list[index] = value def __add__(self, new): """Add a new individual to the population""" if not isinstance(new, Individual): raise TypeError("Type {} can't be added to the population,\ must be an Individual".format(type(new))) self.list.append(new) self.size += 1 return self def __iter__(self): for i in self.list: yield i def __repr__(self): return "Generation {}: av fitness = {:.1f} ; best fitness = {:.1f} ; nb individual = {}"\ .format(self.generation, self.av_fitness, self.best_performer.fitness, self.size) def random_population(self, city2travel, population_size): """Generate a random population""" self.size = population_size for i in range(self.size): self.list.append(Individual(city_list=city2travel)) self.compute_stats() self.compute_breed_probability() def compute_stats(self): """Compute statistics of the population: self.worse_performer : worse individual performer self.best_performer : best individual performer self.av_fitness : average fitness of the entire population """ self.worse_performer = self.list[0] self.best_performer = self.list[0] self.av_fitness = 0 for i in self.list: self.av_fitness += i.fitness if i.fitness < self.best_performer.fitness: self.best_performer = i elif i.fitness > self.worse_performer.fitness: self.worse_performer = i self.av_fitness = self.av_fitness / self.size def compute_breed_probability(self): """Compute the breed probability of every individual. The probability is higher for individual with high performance """ self.best_performer.adjusted_fitness = (self.best_performer.fitness -\ self.worse_performer.fitness) * -1 if self.best_performer.adjusted_fitness == 0: Population.final = 1 for i in self.list: i.adjusted_fitness =\ (i.fitness - self.worse_performer.fitness) * -1 if Population.final: i.breed_proba = 100 else: i.breed_proba =\ i.adjusted_fitness * 100 / self.best_performer.fitness def pick_parents(self): """Pick randomly two parents from the indivduals pool. Indivdual with high breed propability have higher chances to be picked. Return a tuple of two Individuals. """ parent = [] while len(parent) < 2: element = random.choice(self.list) if element.breed_proba >= random.randrange(101): if len(parent) >= 1 and element != parent[0]: parent.append(element) elif len(parent) < 1: parent.append(element) return (parent[0], parent[1]) def next_generation(self): """Generate the next generation based on the current population The next generation's individuals are sons of the current population. The function return a new instance of a Population class. """ next_gen = Population() i = 0 while i < self.size: father, mother = self.pick_parents() next_gen = next_gen + Individual(father=father, mother=mother) i += 1 next_gen.compute_stats() next_gen.compute_breed_probability() return next_gen
19e9415ff1883e29e995c0bea242524a1f9bb625
himashugit/python_dsa
/string/List/module/forloop/range.py
230
4.03125
4
# 5 is the stop value and o is the start value print(list(range(5))) # we use list to conver the result in the list format in python3 print(list(range(0,20,2))) # result will be 0,2,4,6..18 so 20-2 will be last number to print
7481502d696c2d5a78261dd7becc48f8a849ca6f
himashugit/python_dsa
/string/join_Center_zerofill.py
204
3.640625
4
x="hello" print("-".join(x)) # center my_str="python" my_Strn1="scripting" my_Str2="lang" print(f'{my_str.center(12)}\n{my_Strn1.center(20)}\n{my_Str2.center(20)}') zero="python" print(zero.zfill(10))
06badb56fb645ab46abc58aae9871c5f913a4bbc
himashugit/python_dsa
/string/List/module/forloop/read_string_printwith_indexvalue.py
994
3.859375
4
''' usr_strng= input("Enter your string: ") index=0 # index var is defined for each_char in usr_strng: print(f' {each_char} -->{index}') index=index+1 # we're increasing index value by 1 ''' import os req_path= input("Enter your dir path: ") if os.path.isfile(req_path): print(f' the {req_path} is a file pls provide dir ') else: all_f_ds= os.listdir(req_path) if len(all_f_ds)==0: print(f" the given path {req_path} is empty") else: req_ex=input("Enter the req file extention .py/.sh/.log/.txt: ") req_files=[] for each_file in all_f_ds: if each_file.endswith(req_ex): req_files.append(each_file) if len(req_files)==0: print(f'There are no {req_ex} files in the location of {req_path}') else: print(f'There are {len(req_files)} files in the loc of {req_path} with an extention of {req_ex}') print(f'the reuired files are: {req_files}')
3a57aa31606b198a76d98cff001fec94613a18e4
himashugit/python_dsa
/variables/var.py
99
4.0625
4
x = 3 # x is var to store value here y = 5 print(x) myname="himanshu" print(myname,type(myname))
edfd81e4cbd96b77f1666534f7532b0886f8ec4e
himashugit/python_dsa
/func_with_Arg_returnvalues.py
617
4.15625
4
''' def addition(a,b): result = a+b return result # this value we're sending back to main func to print def main(): a = eval(input("Enter your number: ")) b = eval(input("Enter your 2ndnumber: ")) result = addition(a,b) # calling addition func & argument value and storing in result print(f' "the addition of {a} and {b} is {result}"') main() # calling main func ''' def multiply_num_10(value): #result = value*10 #return result return value*10 def main(): num=eval(input("Enter a number:")) result=multiply_num_10(num) print("The value is: ", result) main()
38c8fc1d0c52d8d25cb810d8e272961831471ccf
chrisjdavie/compsci_basics
/number_theory/primality_test/naive.py
634
3.578125
4
from math import sqrt from parameterized import parameterized import unittest class Test(unittest.TestCase): @parameterized.expand([ (11, True), (15, False), (1, False), (5, True), (4, False), (49, False) ]) def test(self, target, is_prime_expected): self.assertEqual(is_prime(target), is_prime_expected) def is_prime(target): if target < 2: return False if not target%2 or not target%3: return False for i in range(5, int(sqrt(target)) + 1, 6): if not target%i or not target%(i+2): return False return True
2d92ff696bd8fb26b608b6c50ce5681c12f972bd
chrisjdavie/compsci_basics
/stacks/next_greater_element/heap.py
1,089
3.8125
4
""" Given an array A [ ] having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. If no such element exists, output -1. https://practice.geeksforgeeks.org/problems/next-larger-element/0 """ from heapq import heappush, heappop from parameterized import parameterized import unittest class Test(unittest.TestCase): @parameterized.expand([ ("provided example 0", [1, 3, 2, 4], [3, 4, 4, -1]), ("provided example 1", [4, 5, 2, 25], [5, 25, 25, -1]), ("provided example 2", [7, 8, 1, 4], [8, -1, 4, -1]) ]) def test(self, _, input_arr, expected_output): self.assertEqual(next_greater_element(input_arr), expected_output) def next_greater_element(arr): value_heap = [] next_greater = [-1]*len(arr) for ind, value in enumerate(arr): while value_heap and value_heap[0][0] < value: _, lower_ind = heappop(value_heap) next_greater[lower_ind] = value heappush(value_heap, (value, ind)) return next_greater
78fbd0e815c8cf689d089a7abcd84576aab9fe32
chrisjdavie/compsci_basics
/dynamic_programming/partition_problem/playing.py
557
3.765625
4
from copy import copy def _rec(arr, n, m): if n < 1: return yield from _rec(arr, n-1, m) for i in range(1,m): arr_loop = copy(arr) arr_loop[n-1] = i yield arr_loop yield from _rec(arr_loop, n-1, m) def main(n, m): arr = [0]*n yield arr yield from _rec(arr, n-1, m) for i in range(1,m): arr_loop = copy(arr) arr_loop[n-1] = i yield arr_loop yield from _rec(arr_loop, n-1, m) if __name__ == "__main__": for arr in main(4, 3): print(arr)
d0d3c2a049951c3c8b4d57ada259ceefd6fd79b4
chrisjdavie/compsci_basics
/dynamic_programming/pick_from_top_or_bottom/memoization.py
1,794
3.609375
4
import unittest from parameterized import parameterized class Test(unittest.TestCase): @parameterized.expand([ ("provided example 0", [5, 3, 7, 10], 15), ("provided example 1", [8, 15, 3, 7], 22), ("one number", [1], 1), ("two numbers highest", [1, 2], 2), ("three numbers", [1, 2, 3], 4), ("four numbers out of order", [3, 15, 2, 1], 16) ]) def test(self, _, stack, expected_winnings): self.assertEqual(pick_from_top_or_bottom(stack), expected_winnings) def cache(func): prev_vals = None def cached_func(stack, n_lhs, n_rhs): nonlocal prev_vals key = (n_lhs, n_rhs) if key == (0, len(stack)-1): prev_vals = {} if key not in prev_vals: prev_vals[key] = func(stack, n_lhs, n_rhs) return prev_vals[key] return cached_func @cache def _pick_from_top_or_bottom(stack, n_lhs, n_rhs): if n_lhs == n_rhs: return stack[n_lhs], 0 best_other_l, best_mine_l = _pick_from_top_or_bottom(stack, n_lhs+1, n_rhs) best_mine_l += stack[n_lhs] best_other_r, best_mine_r = _pick_from_top_or_bottom(stack, n_lhs, n_rhs-1) best_mine_r += stack[n_rhs] if best_mine_l > best_mine_r: return best_mine_l, best_other_l return best_mine_r, best_other_r def pick_from_top_or_bottom(stack): """Consider a row of n coins of values v1 . . . vn, where n is even. We play a game against an opponent by alternating turns. In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first.""" return _pick_from_top_or_bottom(stack, 0, len(stack)-1)[0]
f9fea5999edbcad89bc88a0c6ab3d38f238a699f
chrisjdavie/compsci_basics
/sorting_and_searching/key_pair/solve.py
911
3.609375
4
"""Given an array A[] of n numbers and another number x, determine whether or not there exist two elements in A whose sum is exactly x.""" from parameterized import parameterized import unittest class Test(unittest.TestCase): @parameterized.expand([ (16, [1, 4, 45, 6, 10, 8], True), (10, [1, 2, 4, 3, 6], True), (1, [1, 0], True), (2, [0, 1], False), (5, [0, 2, 1], False), (3, [0, 2, 1], True) ]) def test(self, target, arr, expected_result): self.assertEqual(sum_values_match_target(target, arr), expected_result) def sum_values_match_target(target, arr): arr.sort() i_lhs = 0 i_rhs = len(arr) - 1 while i_lhs < i_rhs: summ = arr[i_lhs] + arr[i_rhs] if summ == target: return True elif summ > target: i_rhs -= 1 else: i_lhs += 1 return False
011660b420866fac9fbfd80c72f0924bff71f8c4
chrisjdavie/compsci_basics
/dynamic_programming/subset_sum/recursive.py
785
3.546875
4
import unittest from parameterized import parameterized class Test(unittest.TestCase): @parameterized.expand([ ("provided example", [3, 34, 4, 12, 5, 2], 9, True), ("single value true", [1], 1, True), ("single value false", [1], 2, False), ("three values true", [1, 2, 3], 5, True), ("three values false", [2, 4, 6], 5, False) ]) def test(self, _, arr, target, expected_result): self.assertIs(subset_sum(arr, target), expected_result) def _subset_sum(arr, target, n): if n < 0 or target < 0: return False if target == 0: return True return _subset_sum(arr, target - arr[n-1], n-1) or _subset_sum(arr, target, n-1) def subset_sum(arr, target): return _subset_sum(arr, target, len(arr))
575f4c1f07957af2be9b688ce5b5333c25d4b441
samcoh/Data-Manipulation
/SQL/hw9_ec1.py
1,379
3.84375
4
import sqlite3 as sqlite import datetime conn = sqlite.connect('Northwind_small.sqlite') cur = conn.cursor() def extra_credit(): statement = 'SELECT CustomerId,OrderDate ' statement += 'FROM [Order] ' statement += 'ORDER BY CustomerId' row = cur.execute(statement) ids = [] print('CustomerID, '+'Order Date, '+ 'Previous Order Date, '+'Days Passed') for x in row: if x[0] not in ids: ids.append(x[0]) previous_date = x[1] list_ = previous_date.split('-') year = int(list_[0]) month = int(list_[1]) date = int(list_[2]) continue else: order = x[1] order_date_list = order.split('-') year_order = int(order_date_list[0]) month_order = int(order_date_list[1]) date_order = int(order_date_list[2]) new_order = datetime.date(year_order, month_order, date_order) old_order = datetime.date(year, month, date) subtract = new_order - old_order days_passed = subtract.days print(x[0]+',' + str(x[1])+"," + previous_date + ","+ str(days_passed)) previous_date = x[1] list_= previous_date.split('-') year = int(list_[0]) month = int(list_[1]) date = int(list_[2]) extra_credit()
08f6dcabed5205513d36aae8ce1bb1f7dbe7baff
egoetz/clustering-analysis
/k_means.py
6,690
3.6875
4
# E Goetz # Basic implementation of the k-means clustering algorithm from clusteringalgorithm import ClusteringAlgorithm from random import uniform from numpy import ndarray, zeros, array_equal class KMeans(ClusteringAlgorithm): def __init__(self, data, answer_key, dimension_minimums=None, dimension_maximums=None, verbose=False): """ Cluster data using the k-means algorithm. :param data: the data set to be clustered :param answer_key: the expected clusters :param dimension_minimums: the smallest values of each dimension in the data set :param dimension_maximums: the largest values of each dimension in the data set :param verbose: whether to print progress messages """ self.verboseprint(verbose, "Calling KMeans") self.answer_key = answer_key self.generated_samples = data self.cluster_membership = None self.dimension_minimums = dimension_minimums self.dimension_maximums = dimension_maximums # get minimums and maximums for each dimension if self.dimension_minimums is None or self.dimension_maximums is None: if self.dimension_minimums is None: self.dimension_minimums = self.generated_samples[0].copy() if self.dimension_maximums is None: self.dimension_maximums = self.generated_samples[0].copy() for point in self.generated_samples: for ith_dimension in range(len(point)): if point[ith_dimension] < self.dimension_minimums[ ith_dimension]: self.dimension_minimums[ith_dimension] = point[ ith_dimension] elif point[ith_dimension] > self.dimension_maximums[ ith_dimension]: self.dimension_maximums[ith_dimension] = point[ ith_dimension] self.verboseprint(verbose, "Found the minimal value for each data " "point dimension: {}".format( self.dimension_minimums)) self.verboseprint(verbose, "Found the maximum value for each data " "point dimension: {}".format( self.dimension_maximums)) self.get_k(verbose) def get_k(self, verbose): """ Get the number of clusters or k that has the smallest percent error. :param verbose: whether to print progress messages :return: None :side effect: self.k, self.cluster_membership, and self.percent_error are set to the k, cluster_membership, and percent_error values of the clustering attempt with the smallest percent error. """ self.percent_error = None for k in range(1, len(self.generated_samples)): self.verboseprint(verbose, "Setting k to {}".format(k)) means = self.initialize(k) old_means = None clusters = None while old_means is None or not array_equal(means, old_means): clusters = self.assign(means) old_means = means.copy() means = self.update(k, clusters, old_means) current_error = self.get_percent_error(clusters, self.answer_key) if self.percent_error is None or self.percent_error > \ current_error: self.verboseprint(verbose, "\tNew Percent error: {}".format( current_error)) self.percent_error = current_error self.cluster_membership = clusters self.k = k if self.percent_error == 0: return def initialize(self, k): """ Initialize the k means to random values that are inclusively within the maximum range of the data points for every dimension. :return: An ndarray holding k random points with the same number of dimensions as the points in self.generated_samples """ means = ndarray((k, len(self.generated_samples[0]))) for cluster_k in range(k): for dimension in range(len(self.generated_samples[0])): means[cluster_k][dimension] = uniform(self.dimension_minimums[ dimension], self. dimension_maximums[dimension]) return means def assign(self, means): """ Assign all data points in the class to the closest mean. :return: An ndarray holding a number representing cluster membership for every point. """ cluster_membership = ndarray((len(self.generated_samples),), dtype= int) for point_index in range(len(self.generated_samples)): minimum_distance = None cluster = None for mean_index in range(len(means)): distance = 0 for i in range(len(self.generated_samples[point_index])): distance += (means[mean_index][i] - self. generated_samples[point_index][i])**2 distance = distance / 2 if minimum_distance is None or distance < minimum_distance: minimum_distance = distance cluster = mean_index cluster_membership[point_index] = cluster return cluster_membership def update(self, k, clusters, old_means): """ Update the k means to be the mean of the data points that are assigned to their cluster. :return: An ndarray holding k points that are the means of the k clusters """ new_means = zeros((k, len(self.generated_samples[0]))) cluster_sizes = zeros((k,)) for point_index in range(len(self.generated_samples)): mean_index = clusters[point_index] cluster_sizes[mean_index] += 1 for dimension in range(len(self.generated_samples[point_index])): new_means[mean_index][dimension] += self.generated_samples[ point_index][dimension] for mean_index in range(len(new_means)): if cluster_sizes[mean_index] != 0: new_means[mean_index] = new_means[mean_index] / cluster_sizes[ mean_index] else: new_means[mean_index] = old_means[mean_index] return new_means
ce3606b2dd45f71f61953d4e8542384584b733e0
bharathulaprasad/Sentiment-Analysis-on-US-Airlines-Twitter-data
/US Airlines Twitter Sentiment Analysis .py
11,465
3.671875
4
#!/usr/bin/env python # coding: utf-8 # ### Importing the necessary libraries # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # ### Importing the data # In[2]: data=pd.read_csv("Tweets.csv") data.columns # In[3]: data.head() # In[4]: data.tail() # ### Data Understanding and preprocessing # In[5]: data.describe(include='all') # In[6]: ### From the above descriptive statistics we could see that ### 1.airline_sentiment has most of its tweets negative ### 2.Customer Service Issue is the mostly occured negative reason ### 3.United airlines is the most appeared one among all the airlines. ### 4.Most of the tweets are from Boston MA ### 5.We can see missing values in negativereason,negativereason_confidence,airline_sentiment_gold,negativereason_gold, ### tweet_coord,tweet_location,user_timezone # In[7]: data['negativereason'].value_counts() # In[8]: data['tweet_id'] # In[9]: ## checking for null values data.isnull().sum() # In[10]: data.shape # In[11]: data['airline_sentiment'] # In[12]: data['tweet_coord'] # In[16]: data.info() # In[17]: data['airline_sentiment'].value_counts() # In[18]: data['airline_sentiment_confidence'].value_counts() # In[19]: ## number of values with airline_sentiment_confidence<=0.5 (data['airline_sentiment_confidence']<=0.5).value_counts() # ### Sentiment for each airline # #### 1.we look for total number of tweets for each airline # #### 2.Then we will calculate the number of positive,negative,nuetral tweets for each airline # #### 3.we plot those counts of sentiments for each airline # In[20]: print("total number of tweets for each airline \n",data.groupby('airline')['airline_sentiment'].count().sort_values(ascending=False)) # In[21]: #Plotting the number of tweets each airlines has received colors=sns.color_palette("husl", 10) pd.Series(data["airline"]).value_counts().plot(kind = "bar", color=colors,figsize=(8,6),fontsize=10,rot = 0, title = "Total No. of Tweets for each Airlines") plt.xlabel('Airlines', fontsize=10) plt.ylabel('No. of Tweets', fontsize=10) # In[22]: airlines=['United','US Airways','American','Southwest','Delta','Virgin America'] plt.figure(1,figsize=(15,9)) ## Represents the width and height of overall figure for i in airlines: indices=airlines.index(i) ## will return the indices 0,1,2,3,4,5 for respective values of i ## i.e. for i='United',indices=0 and so on for other values plt.subplot(2,3,indices+1) ## (x,y,z)it represents the x=height,y=width of plot and z= plot traversal towards right ## the values should be 1<=num<=6 ,where num is x,y,z new_df=data[data['airline']==i] count=new_df['airline_sentiment'].value_counts() Index=[1,2,3] plt.bar(Index,count,color=['red','grey','green']) plt.xticks(Index,['negative','nuetral','positive']) plt.ylabel("count Mood") plt.xlabel("Mood") plt.title("count of moods of"+i) # #### The above plots convey us: # ##### 1.United,US Airways and the American airlines are the ones which recieve more negative tweets # ##### 2.VirginAmerica is the airlines with most balanced tweets # In[23]: #Plotting the number of each type of sentiments colors=sns.color_palette("husl", 10) pd.Series(data["airline_sentiment"]).value_counts().plot(kind = "bar", color=colors,figsize=(8,6),rot=0, title = "Total No. of Tweets for Each Sentiment") plt.xlabel('Sentiments', fontsize=10) plt.ylabel('No. of Tweets', fontsize=10) # In[24]: colors=sns.color_palette("husl", 10) pd.Series(data["airline_sentiment"]).value_counts().plot(kind="pie",colors=colors, labels=["negative", "neutral", "positive"],explode=[0.05,0.02,0.04], shadow=True,autopct='%.2f', fontsize=12,figsize=(6, 6),title = "Total Tweets for Each Sentiment") # ### The most used words in Positive ,Negative and Neutral tweets # #### 1.wordcloud is the best way to identify the most used words # #### 2.Wordcloud is a great tool for visualizing nlp data. # #### 3.The larger the words in the wordcloud image , the more is the frequency of that word in our text data. # In[25]: from wordcloud import WordCloud ,STOPWORDS # ### wordcloud for negative sentiment of tweets # In[26]: new_df=data[data['airline_sentiment']=='negative'] words = ' '.join(new_df['text']) cleaned_word = " ".join([word for word in words.split() if 'http' not in word and not word.startswith('@') and word != 'RT' ]) wordcloud = WordCloud(stopwords=STOPWORDS, background_color='black', width=3000, height=2500 ).generate(cleaned_word) plt.figure(1,figsize=(12, 12)) plt.imshow(wordcloud) plt.axis('off') plt.show() # In[27]: ## In a wordcloud the words which are bigger are the once which occured the most in our given text ## The words which are bigger in the above negative sentiment wordcloud are the ones having more influence among ## the negative sentimnet texts. ## i.e. Customer service,late flight,cant tell,cancelled flight,plane,help,delay etc.. are most occured and influenced words for negative sentiments. # In[28]: #Plotting all the negative reasons color=sns.color_palette("husl", 10) pd.Series(data["negativereason"]).value_counts().plot(kind = "bar", color=color,figsize=(8,6),title = "Total Negative Reasons") plt.xlabel('Negative Reasons', fontsize=10) plt.ylabel('No. of Tweets', fontsize=10) # In[29]: color=sns.color_palette("husl", 10) pd.Series(data["negativereason"]).value_counts().head(5).plot(kind="pie", labels=["Customer Service Issue", "Late Flight", "Can't Tell","Cancelled Flight","Lost Luggage"], colors=color,autopct='%.2f',explode=[0.05,0,0.02,0.03,0.04],shadow=True, fontsize=12,figsize=(6, 6),title="Top 5 Negative Reasons") # ## Word cloud for positive sentiments # In[30]: new_df=data[data['airline_sentiment']=='positive'] words = ' '.join(new_df['text']) cleaned_word = " ".join([word for word in words.split() if 'http' not in word and not word.startswith('@') and word != 'RT' ]) wordcloud = WordCloud(stopwords=STOPWORDS, background_color='black', width=3000, height=2500 ).generate(cleaned_word) plt.figure(1,figsize=(12, 12)) plt.imshow(wordcloud) plt.axis('off') plt.show() # In[31]: ## The words which are bigger in the above positive sentiment wordcloud are the ones having more influence among ## the positive sentiment texts. ## i.e.thank,awesome,great,flight,trip etc.. are most occured and influenced words for positive sentiments. # ## Word cloud for neutral sentiments # In[32]: df=data[data['airline_sentiment']=='neutral'] words = ' '.join(df['text']) cleaned_word = " ".join([word for word in words.split() if 'http' not in word and not word.startswith('@') and word != 'RT']) wordcloud = WordCloud(stopwords=STOPWORDS, background_color='black', width=3000, height=2500 ).generate(cleaned_word) plt.figure(1,figsize=(12, 12)) plt.imshow(wordcloud) plt.axis('off') plt.show() # In[33]: air_senti=pd.crosstab(data.airline, data.airline_sentiment) air_senti # In[34]: percent=air_senti.apply(lambda a: a / a.sum() * 100, axis=1) percent # In[35]: pd.crosstab(index =data["airline"],columns = data["airline_sentiment"]).plot(kind='bar', figsize=(10, 6),alpha=0.5,rot=0,stacked=True,title="Airline Sentiment") # In[36]: percent.plot(kind='bar',figsize=(10, 6),alpha=0.5, rot=0,stacked=True,title="Airline Sentiment Percentage") # In[37]: data['tweet_created'] = pd.to_datetime(data['tweet_created']) data["date_created"] = data["tweet_created"].dt.date # In[38]: data["date_created"] # In[39]: df = data.groupby(['date_created','airline']) df = df.airline_sentiment.value_counts() df.unstack() # In[40]: from nltk.corpus import stopwords stop_words=stopwords.words('english') print(list(stop_words)) # In[41]: def tweet_to_words(raw_tweet): letters_only = re.sub("[^a-zA-Z]", " ",raw_tweet) words = letters_only.lower().split() stops = set(stopwords.words("english")) meaningful_words = [w for w in words if not w in stops] return( " ".join( meaningful_words )) # In[42]: def clean_tweet_length(raw_tweet): letters_only = re.sub("[^a-zA-Z]", " ",raw_tweet) words = letters_only.lower().split() stops = set(stopwords.words("english")) meaningful_words = [w for w in words if not w in stops] return(len(meaningful_words)) # In[43]: data['sentiment']=data['airline_sentiment'].apply(lambda x: 0 if x=='negative' else 1) data.sentiment.head() # In[44]: #Splitting the data into train and test data['clean_tweet']=data['text'].apply(lambda x: tweet_to_words(x)) data['Tweet_length']=data['text'].apply(lambda x: clean_tweet_length(x)) train,test = train_test_split(data,test_size=0.2,random_state=42) # In[45]: train_clean_tweet=[] for tweets in train['clean_tweet']: train_clean_tweet.append(tweets) test_clean_tweet=[] for tweets in test['clean_tweet']: test_clean_tweet.append(tweets) # In[46]: from sklearn.feature_extraction.text import CountVectorizer v = CountVectorizer(analyzer = "word") train_features= v.fit_transform(train_clean_tweet) test_features=v.transform(test_clean_tweet) # In[51]: from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC, LinearSVC, NuSVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier from sklearn.metrics import accuracy_score # In[52]: Classifiers = [ LogisticRegression(C=0.000000001,solver='liblinear',max_iter=200), KNeighborsClassifier(3), SVC(kernel="rbf", C=0.025, probability=True), DecisionTreeClassifier(), RandomForestClassifier(n_estimators=200), AdaBoostClassifier()] # In[53]: dense_features=train_features.toarray() dense_test= test_features.toarray() Accuracy=[] Model=[] for classifier in Classifiers: try: fit = classifier.fit(train_features,train['sentiment']) pred = fit.predict(test_features) except Exception: fit = classifier.fit(dense_features,train['sentiment']) pred = fit.predict(dense_test) accuracy = accuracy_score(pred,test['sentiment']) Accuracy.append(accuracy) Model.append(classifier.__class__.__name__) print('Accuracy of '+classifier.__class__.__name__+' is '+str(accuracy)) # In[55]: Index = [1,2,3,4,5,6] plt.bar(Index,Accuracy) plt.xticks(Index, Model, rotation=45) plt.ylabel('Accuracy') plt.xlabel('Model') plt.title('Accuracies of Models')
c9361ac9212e8bd0441b05a26940729dd6915861
itsMagondu/python-snippets
/fib.py
921
4.21875
4
#This checks if a certain number num is a number in the fibbonacci sequence. #It loops till the number is the sequence is either greater or equal to the number in the sequence. #Thus we validate if the number is in the fibonacci sequence. import sys tot = sys.stdin.readline().strip() try: tot = int(tot) except ValueError: pass def fibTest(f0,f1,f,num): f0 = f1 f1 = f f = f0+f1 if int(f) < int(num): f0,f1,f,num = fibTest(f0,f1,f,num) else: if f == int(num): print "IsFibo" else: print "IsNotFibo" return f0,f1,f,num def getFibnumber(f0,f1): return f0+f1 while tot: num = sys.stdin.readline().strip() f0 = 0 f1 = 1 f = getFibnumber(f0,f1) try: num = int(num) if num != 0 or num != 1: fibTest(f0,f1,f,num) tot -= 1 except ValueError: pass
389887394ef680275f708fd4e8fc0370e3aafaf2
itsMagondu/python-snippets
/utopia.py
173
3.5
4
doub = True h = 1 cyc = 10 while cyc: if doub == True: h = h*2 doub = False else: h = h+1 doub = True print h cyc = cyc -1