blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
f4f309ec92fa0e71675d0d184b576b84483a1b56
wbddxyz/python_sutff
/ex25_find_maximum_tb.py
1,029
4.375
4
''' ex25_find_maximum.py Tom Bain 27/10/20 J27C76 Software Design and Development Standard Algorithms - Find Maximum ''' def get_max_value(data): ''' Returns the largest element/value within the data array/list. Assumes at least one entry in the data. Assumes no duplicates. Assumes no sorting ''' max_value = data[0] for x in range(1, len(data)): if data[x] > max_value: max_value = data[x] return max_value def get_max_index(data): max_index = 0 max_value = data[0] for x in range(1, len(data)): if data[x] > max_value: max_value = data[x] max_index = x return max_index def main(): scores = [63, 43, 82, 69, 99, 4, 89, 142, 60, 76] max_value = get_max_value(scores) # 142 print(f'The maximum value in the array/list is {max_value}.') index_max_value = get_max_index(scores) # 7 print(f'The maximum value in the array is at index {index_max_value}.') if __name__ == "__main__": main()
c8b448e3af70822f57a6d0826cff6f18e56a19b3
kongjingchun/PyTest
/test01/test01_05_03/package_enmerate.py
228
3.515625
4
# coding:utf-8 # @Create time: 2021/3/22 8:14 下午 # @Author: KongJingchun # @remark: 枚举函数 # 枚举打印列表 names = ['孔敬淳', '王野', '卢晓倩'] for index, item in enumerate(names): print(index, item)
1bb577fef924beda2d45dc2fe8ba2f3f617f8ecc
beardbytes/python
/methods.py
981
3.78125
4
import datetime class Employee: def __init__(self, first, last, pay) -> None: self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) @classmethod def set_raise_amount(cls, amount): cls.raise_amt = amount @classmethod def from_string(cls, emp_str): # methods starting with 'from' are constructors first, last, pay = emp_str.split('-') return cls(first, last, pay) # Static methods don't take self and cls as first arguments @staticmethod def is_worday(day) -> bool: if day.weekday() == 5 or day.weekday() == 6: return False return True emp_str_1 = 'John-Doe-40000' new_emp = Employee.from_string(emp_str_1) print(new_emp.email) print(new_emp.pay) # static methods my_date = datetime.date(2021, 6, 24) print(Employee.is_worday(my_date))
69519c585882c2314a62df89ece85b5eef866849
JayVeezy1/adventofcode
/Day_11.py
1,836
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 16 20:09:39 2020 @author: Jakob """ import itertools def count_seated(seats): return list(itertools.chain(*seats)).count('#') def count_adjacent_seats(row_id, col_id, seats): counter = 0 adjacent = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] # adjacent = [(i, j) for i, j in itertools.product(range(-1, 2, 1), repeat = 2) if i != 0 or j != 0] for off_i, off_j in adjacent: if 0 <= row_id + off_i < len(seats) and 0 <= col_id + off_j < len(seats[row_id + off_i]) and seats[row_id + off_i][col_id + off_j] == "#": counter += 1 return counter def simulate(seats): previous = [] while previous != seats: previous = seats[:] seats = [] for row_id, row in enumerate(previous): new_row = "" for col_id, col in enumerate(row): if col == ".": new_row += col elif col == "L": if count_adjacent_seats(row_id, col_id, previous) == 0: new_row += "#" else: new_row += "L" elif col == "#": if count_adjacent_seats(row_id, col_id, previous) >= 4: new_row += "L" else: new_row += "#" else: new_row += col seats.append(new_row) assert len(previous) == len(seats) assert len(previous[0]) == len(seats[0]) return previous with open(r'C:\Users\vanek\Desktop\AdventOfCode\data\data_11.txt') as file: seats = file.read().splitlines() waiting_room = simulate(seats) print(count_seated(waiting_room))
5af8df5a47f434b4a26e3748b47d65edb675b338
dengl11/Leetcode
/problems/split_linked_list_in_parts/solution.py
826
3.5
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]: l = 0 curr = root while curr: l += 1 curr = curr.next g, r = divmod(l, k) groups = [g] * k for i in range(r): groups[i] += 1 gi = 0 ans = [] while root: l = 1 head = root while l < groups[gi]: root = root.next l += 1 n = root.next root.next = None ans.append(head) root = n gi += 1 return ans + [None] * (k - len(ans))
7d9695e9e4cc482b2694ef1ceb20f0f9a9f8661b
albertogarcia13/PY-Exercices
/Exercise6.py
330
3.859375
4
lista1 = [1,2,3,4] lista2 = [5,6,7,8] lista1 += lista2 print(lista1) tupla1 = (1,2,3,4) tupla2 = (5,6,7,8) tuplaf = tupla1 + tupla2 print(tuplaf) diccionario1 = {"item1": 1, "item2": 2, "item3": 3, "item4": 4} diccionario2 = {"item5": 5, "item6": 6, "item7": 7, "item8": 8} diccionario1.update(diccionario2) print(diccionario1)
e77f629d64cbd0f930e06cd64b1b51998cb86bb8
josephmachado1991/edd
/EDD.py
6,964
3.515625
4
#!/usr/bin/python import sys import os import csv import operator def create_var_dict( data_type_file ): # initialize variable dictionary and open data type file var_dict = {} f = open(data_type_file, 'r' ) csvf = csv.reader(f) # loop over each line and load variable, data_type into var_dict for line in csvf: if line != '\n': var_dict[ line[0] ] = line[1].strip() return var_dict def process_numeric( variable_file ): # initialize variables count = 0 unfilled = 0 filled = 0 the_sum = 0 the_min = 999999999. # just shy of 1 billion the_max = -999999999. # just shy of -1 billion with open( variable_file ) as row: next(row) # skip header row # actions to do for each record for number in row: count += 1 if number == '' or number == '\n': # check to see if no data is present unfilled += 1 else: # data present --> process filled += 1 number = float(number) the_sum = the_sum + number # update min and max if number < the_min: the_min = number if number > the_max: the_max = number # sanity check: determine whether # filled + # unfilled = count if filled + unfilled != count: sys.exit("There is an error: # filled + # unfilled does not equal the count!") # calculations fill_rate = round( 100 * ( float(filled) / count ), 1) mean = round( float(the_sum) / filled, 1) # print outputs print "Filled: %d" % filled print "Unfilled: %d" % unfilled print "Count: %d" % count print "Fill rate: %0.1f" % fill_rate print "Sum: %d" % the_sum print "Mean: %0.1f" % mean print "Min: %d" % the_min print "Max: %d" % the_max return count, filled, unfilled, fill_rate, the_sum, mean, the_min, the_max def process_factor( variable_file ): # initialize variables keys = {} count = 0 unfilled = 0 filled = 0 with open( variable_file ) as row: next(row) # skip header row # actions to do for each record for factor in row: count += 1 factor = factor.strip() # removes whitespace and \n if factor == '': # check to see if no data is present unfilled += 1 else: # data present --> process filled += 1 if factor in keys: keys[factor] += 1 else: keys[factor] = 1 # sanity check: determine whether # filled + # unfilled = count if filled + unfilled != count: sys.exit("There is an error: # filled + # unfilled does not equal the count (# records)!") # calculations fill_rate = round( 100 * ( float(filled) / count ), 1) factors = keys.keys() num_factors = len(factors) # determine top 10 factors sorted_factors = sorted( keys.items(), key=operator.itemgetter(1), reverse=True ) if len(sorted_factors) >= 10: top_factors_temp = sorted_factors[:10] else: top_factors_temp = sorted_factors # format top factors list top_factors = [] for kv in top_factors_temp: the_factor = kv[0] the_freq = kv[1] the_frac = 100 * ( float(the_freq) / filled ) final_form = '%s : %d : %0.1f' % ( the_factor, the_freq, the_frac ) top_factors.append( final_form ) # print outputs print "Count: %d" % count print "Filled: %d" % filled print "Unfilled: %d" % unfilled print "Fill rate: %0.1f" % fill_rate print "Number of unique factors: %d" % num_factors print "Top 10 unique factors: %s" % top_factors return count, filled, unfilled, fill_rate, num_factors, top_factors def main(): args = sys.argv[1:] in_data_types_file = args[0] # variable_name, data_type column_file = args[1] # file with variable name and associated column # out_data_types_file = args[2] # blank file var_dict = create_var_dict( in_data_types_file ) # process column according to data type f = open( column_file ) contents = f.readlines() header = contents[0].strip() var_data_type = var_dict[header] print "This column is of type: %s" % ( var_data_type ) ######################################################################################################### ## Process variable according to data type, add characterization to FINAL output file ######################################################################################################### infile = open( in_data_types_file, 'r' ) outfile = open( 'data_types_FINAL.csv', 'ab' ) reader = csv.reader( infile ) writer = csv.writer( outfile ) ############################### ## NUMERIC ############################### if var_data_type == 'NUMERIC': count, filled, unfilled, fill_rate, the_sum, mean, the_min, the_max = process_numeric( column_file ) # write variable characterization to file for line in reader: var_name = line[0] data_type = line[1] num_factors = '' # not defined for numeric columns top_factors = '' # not defined for numeric columns if var_name == header: new_row = [var_name, data_type, count, filled, unfilled, fill_rate, the_min, the_max, the_sum, mean, num_factors, top_factors] writer.writerow( new_row ) infile.close() outfile.close() ############################### ## FACTOR ############################### if var_data_type == 'FACTOR' or var_data_type == 'DATE' or var_data_type == 'STRING': count, filled, unfilled, fill_rate, num_factors, top_factors = process_factor( column_file ) # write variable characterization to file for line in reader: var_name = line[0] data_type = line[1] the_min = '' # not defined for factor columns the_max = '' # not defined for factor columns the_sum = '' # not defined for factor columns mean = '' # not defined for factor columns if var_name == header: new_row = [var_name, data_type, count, filled, unfilled, fill_rate, the_min, the_max, the_sum, mean, num_factors, top_factors] writer.writerow( new_row ) infile.close() outfile.close() f.close() if __name__ == '__main__': main()
baa1b359e797c3382d05f8b3f91dc114890a8ca7
KevinAS28/Python-Neutron-Brain-Server-Web-Server-Project
/changeanyindir.py
1,030
3.75
4
#!/usr/bin/python3 import os import re import sys print("Change anything in dir, file name, dir name, inside text") startdir = input("start directory: ") if (startdir=="" or (os.access(startdir, os.W_OK)==False)): startdir = os.getcwd() print("Startdir: %s"%(startdir)) dari = input("What you want to replace (Using regex)? ") ke = input("you wish replace %s become: "%(dari)) for root, dirs, files in os.walk(top=startdir, topdown=False): for i in files: try: try: with open(os.path.join(root, i), "rb") as reader: baca = reader.read() os.remove(os.path.join(root, i)) with open(os.path.join(root, re.sub(dari, ke, i)), "wb") as writer: writer.write(re.sub(dari.encode("utf-8"), ke.encode("utf-8"), baca)) except Exception as err: print(str(err)) os.rename(os.path.join(root, i), os.path.join(root, re.sub(dari, ke, i))) except: pass for i in dirs: try: os.rename(os.path.join(root, i), os.path.join(root, re.sub(dari, ke, i))) except: pass
75a2eec052641721a7d7ac621282627d07100e3a
ezequiasOR/Exercicios-LP1
/unidade3/selecao.py
522
3.53125
4
# coding: utf-8 #UFCG - Programação I - 2018.1 #Aluno: Ezequias Rocha #Questão: Seleção Projeto - Unidade 3 cre = float(raw_input()) meses = int(raw_input()) entrevista = int(raw_input()) if cre < 7 and meses < 6: print 'Candidato eliminado. CRE e experiência abaixo do limite.' elif cre < 7: print 'Candidato eliminado. CRE abaixo do limite.' elif meses < 6: print 'Candidato eliminado. Experiência abaixo do limite.' else: if entrevista <= 3: print 'Candidato classificado.' else: print 'Candidato aprovado.'
cfdcd3b00702bdc5e3845c528924c6caa8ef3d60
Aasthaengg/IBMdataset
/Python_codes/p03252/s643598565.py
376
3.5625
4
from collections import Counter s = input() t = input() #文字の順番入れ替えは可能 #文字の個数は増やせない #結局はaabbbなら2,3になる #abcdbならa:1,b:2,c:1,d:1 s_dict = Counter(s) t_dict = Counter(t) s_val = list(s_dict.values()) t_val = list(t_dict.values()) s_val.sort() t_val.sort() if s_val == t_val: print('Yes') else: print('No')
667ea109da8fd9f5a9eee543cbffb8e7fb4a0e6d
naeimsalib/Sorting_Algorithms_Python
/SelectionSort.py
536
4.125
4
#Time O(N^2) time | O(1) Space def SelectionSort(array): current = 0 while current < len(array) - 1: smallest = current for i in range (current + 1, len(array)): if array[smallest] > array[i]: smallest = i swap(current, smallest, array) current += 1 return array def swap(i, j, array): array[i], array[j] = array[j], array[i] array = [1,3,10,9,8,23,0,1,2,4] print("Array Before Sorting" , array); SelectionSort(array) print("Array After Sorting " , array)
4ae9cd754bc4614960af729ce3ddd5e779b87f89
divyamodi128/Python-Practice
/Sorting_Algo/FindRepeatingchar.py
768
3.734375
4
def findrepeats(str): for i in range(len(str)): count = 0 for j in range(i,len(str)): print(str[i], str[j]) if str[i] == str[j]: count += 1 if count >= 3: print(str[i] * count) str = str.replace(str[i] * count, '') print('Final String', str) import re def findrepeats1(str): setstr = set(str) for s in setstr: l = len(re.findall(s, str)) if l >= 3 and re.findall(s * l, str): print('Removing:', s * l) str = str.replace(s * l, '') return str print(findrepeats('abbbccdeeeef')) print(findrepeats1('abbcccddeeeefdd')) """ Input 1 : 'abbbccdeeeef' Output 1 : 'acdf' Input 2 : 'aaabcdefffffgggh' Output 2 : 'bcdeh' """
8f0900c3c3500728fd8d112f7c470fd97974f808
FreddyManston/Misc
/PythonPrograms/PyGame/PyGameTutorial/PGBasics.py
3,689
3.65625
4
import pygame import time def start_up(): """ Set up the game and run the main game loop """ pygame.init() # prepare the pygame module for use main_surface = pygame.display.set_mode((480, 480)) # Create surface of (width, height). my_text = pygame.font.SysFont("Comic Sans", 17).render("Click this block for Batman", False, (100, 0, 105)) # Setting up text to blit to main_surface. # set up some data to describe a small rectangle and its color small_rect = (300, 200, 150, 90) some_color = (255, 0, 0) # A color is a mix of (Red, Green, Blue) while True: ev = pygame.event.poll() # look for any event from keyboard, mouse, joystick, etc. if ev.type != pygame.NOEVENT: #} Print all occuring events which are print ev #} recognised from the poll. if ev.type == pygame.MOUSEBUTTONDOWN: # Check if mouse button was clicked. posn_of_click = ev.dict["pos"] # Get the coordinates of the click from dictionary using key 'pos' print posn_of_click x_coord = posn_of_click [0] #} Split the coordinate into a y_coord = posn_of_click [1] #} x and y position if x_coord >= 39 and x_coord <= 189 and y_coord >= 215 and y_coord <= 275: showBatman() #... start the new window if ev.type == pygame.QUIT: # window close button clicked? break # Stop program # Completely redraw everything from scratch on each frame. main_surface.fill((0, 200, 255)) # Fill everything with the background color. main_surface.fill(some_color, small_rect) # Overpaint a smaller rectangle on the main surface. main_surface.fill((255, 100, 0), (40, 215, 150, 60)) # Overpaint an even smaller rectangle onto main_surface. main_surface.blit(my_text, (44, 240)) # Now that everything is drawn, put it on display! pygame.display.flip() pygame.quit() # once we leave the loop, close the window. def showBatman(): pygame.init() # initialiase pygame again (prep module) main_surface = pygame.display.set_mode((600, 600)) batman = pygame.image.load("I'm Batman.png") # instantiate a picture of Batman. my_font = pygame.font.SysFont('freesansbold.ttf', 16) # instantiate 16 point Courier font to draw text. the_text = my_font.render("I'm Batman!", True, (150, 50, 150)) # .render(text phrase, smooth edges, text colour) count = 1 while True: print(count) #} A count to bring to attention how count += 1 #} many times the loop has ran, during the program ev = pygame.event.poll() if ev.type == pygame.QUIT: frameRatesEtc() break main_surface.fill((200, 50, 100)) main_surface.blit(batman, (-300, -130)) # insert Batman into the frame .blit(picture, (x-coord, y-coord)) main_surface.blit(the_text, (325, 75)) # insert text into the frame .blit(text, (x-coord, y-coord)) pygame.display.flip() pygame.quit() def frameRatesEtc(): pygame.init() main_surface = pygame.display.set_mode((400, 400)) my_font = pygame.font.SysFont("Courier", 16) frame_count = 0 frame_rate = 0 t0 = time.clock() while True: ev = pygame.event.poll() if ev.type == pygame.QUIT: break # Do game logic here: Updating the frame rate every 500 frames frame_count += 1 if (frame_count % 500 == 0): t1 = time.clock() frame_rate = 500 / (t1 - t0) # Get frame rate per second t0 = t1 # Completely redraw the surface, starting with background main_surface.fill((200, 0, 200)) the_text = my_font.render("Frame = {0}, rate = {1:.2f} fps,".format(frame_count, frame_rate, 50, 66), True, (0,0,0)) # Make a new surface with an image of the text main_surface.blit(the_text, (10, 10)) # Copy the text surface to the main surface pygame.display.flip() pygame.quit() start_up()
abaa30791f89651441ff1c2282d7ab0b3874de47
DanSohn/AmazonPriceTracker
/AmazonPriceTracker.py
4,586
3.703125
4
""" A quick project where I can get a url from an amazon page, and then given credentials and a price range, it will email the user when the item falls under the price range Things to do: Get information from amazon page Get user's information Send email Do I want it running every hour? Do I need to write a script to have it turned on when computer turns on In email, sending the url as a link, not just as a string """ import requests from bs4 import BeautifulSoup import smtplib import time headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" } def check_price(URL): """ function that creates the page and returns the current price :return: the current price as a float """ # returns all the data from the URL provided page = requests.get(URL, headers = headers) # issues along the line if I use just one soup. I use two so that the soup find method will not return NoneType soup1 = BeautifulSoup(page.content, "html.parser") soup2 = BeautifulSoup(soup1.prettify(), "html.parser") # from amazon, grab the span productTitle which corresponds to the title of the item # .get_text = get rid of span tags # .strip() = return only non-whitespace string title = soup2.find(id = "productTitle").get_text().strip() # price is either priceblock_saleprice or priceblock_ourprice price = soup2.find(id = "priceblock_ourprice") if price is None: price = soup2.find(id = "priceblock_saleprice").get_text() else: price = price.get_text() """ print(converted_price, "\n") print(title) if converted_price < 150: send_mail() """ converted_price = convert_price(price) return converted_price def convert_price(price_str): """ Changes the price string of form "CDN$ 131.99" into just 131.99 as an integer :param price_str: the price from the page :return: int price """ first_digit = 0 for i in range(len(price_str)): if price_str[i].isdigit(): first_digit = i break converted_price = float(price_str[first_digit:]) return converted_price def send_mail(email, password, url): if "gmail" in email: server = smtplib.SMTP(host='smtp.gmail.com', port=587) elif "outlook" in email or "ucalgary.ca" in email: server = smtplib.SMTP(host='smtp-mail.outlook.com', port=587) else: print("Current email server not identified, or not supported. Please try again at a later date!") return # Command sent by email server to identify itself, to start process of sending email server.ehlo() server.starttls() server.ehlo() server.login(email, password) subject = 'Price has lowered for one of your items' body = 'Check the amazon link %s' % url msg = f"Subject: {subject}\n\n{body}" server.sendmail(email, "[email protected]", msg) print("Email has successfully been sent") server.quit() def get_info(): email = input("Email: ") password = input("Email password: ") url = input("Amazon URL: ") current_price = check_price(url) max_price = float(input("Current price is " + str(current_price) + ". What is your maximum price? ")) return email, password, url, max_price def main(): statement = "This program is designed to email you if the given Amazon URL's item \n" \ "becomes cheaper by a range that you set. You can keep this program\n" \ "running in the background. Currently, it only looks at one item. At a\n" \ "future date, this project may get revamped to store multiple items from\n" \ "past runs.\n" \ "Feel free to contact me at [email protected]\n" \ "-Jung Hyun Sohn" print(statement) email, password, url, max_price = get_info() print(email, password, url, max_price) check_frequency = float(input("How often do you want to check the price? (SECONDS): ")) try: print("Press <Ctrl> + <C> to stop scanning price!") while True: print("Checking price...") if check_price(url) < max_price: print("Price has dropped, sending email...") send_mail(email, password, url) break time.sleep(check_frequency) except KeyboardInterrupt: print("Thank you for trying this program! We do not keep any of your information.") if __name__ == '__main__': main()
7eaaebddb16fb1f2d66e29357787b317e52490cb
ehabosaleh/parallelism
/multiprocessing/Example_2/data_parallelism.py
533
3.515625
4
import time from multiprocessing import Pool import numpy as np def square(x): return x**2 if __name__=='__main__': numbers =np.linspace(1,10000000) p=Pool(4) t1=time.process_time() print(p.map(square,numbers)) t2=time.process_time() p.close() p.join() print("executing time when using pool is: {}".format(t2-t1)) t1=time.process_time() for number in numbers: print(square(number)) t2=time.process_time() print("executing time without Pool (serial execution) is: {}".format(t2-t1))
9d6273ad21bf217c83a3576ca32f8f93f7aadb47
ko-takahashi/college
/CS596/Homework/HW3/main_part1.py
6,144
3.71875
4
import math import numpy as np import matplotlib.pyplot as plt from getDataset import getDataSet from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report # Starting codes # Fill in the codes between "%PLACEHOLDER#start" and "PLACEHOLDER#end" # step 1: generate dataset that includes both positive and negative samples, # where each sample is described with two features. # 250 samples in total. [X, y] = getDataSet() # note that y contains only 1s and 0s, # create figure for all charts to be placed on so can be viewed together fig = plt.figure() def func_DisplayData(dataSamplesX, dataSamplesY, chartNum, titleMessage): idx1 = (dataSamplesY == 0).nonzero() # object indices for the 1st class idx2 = (dataSamplesY == 1).nonzero() ax = fig.add_subplot(1, 3, chartNum) # no more variables are needed plt.plot(dataSamplesX[idx1, 0], dataSamplesX[idx1, 1], 'r*') plt.plot(dataSamplesX[idx2, 0], dataSamplesX[idx2, 1], 'b*') # axis tight ax.set_xlabel('x_1') ax.set_ylabel('x_2') ax.set_title(titleMessage) # implementation of sigmoid function def Sigmoid(x): g = float(1.0 / float((1.0 + math.exp(-1.0*x)))) return g # Prediction function def Prediction(theta, x): z = 0 for i in range(len(theta)): z += x[i]*theta[i] return Sigmoid(z) # execute gradient updates over thetas def Gradient_Descent(X,Y,theta,m,alpha): new_theta = [] constant = alpha/m for j in range(len(theta)): deltaF = Cost_Function_Derivative(X,Y,theta,j,m,alpha) new_theta_value = theta[j] - deltaF new_theta.append(new_theta_value) return new_theta # implementation of cost functions def Cost_Function(X,Y,theta,m): sumOfErrors = 0 for i in range(m): xi = X[i] est_yi = Prediction(theta,xi) if Y[i] == 1: error = Y[i] * math.log(est_yi) elif Y[i] == 0: error = (1-Y[i]) * math.log(1-est_yi) sumOfErrors += error const = -1/m J = const * sumOfErrors #print 'cost is ', J return J # gradient components called by Gradient_Descent() def Cost_Function_Derivative(X,Y,theta,j,m,alpha): sumErrors = 0 for i in range(m): xi = X[i] xij = xi[j] hi = Prediction(theta,X[i]) error = (hi - Y[i])*xij sumErrors += error m = len(Y) constant = float(alpha)/float(m) J = constant * sumErrors return J ############# # Problem 3 # ############# from sklearn.metrics import confusion_matrix def func_calConfusionMatrix(predY, trueY): result = confusion_matrix(trueY, predY) print(result) #In [11]: y = arange(5); (y==2).nonzero()[0] #Out[11]: array([2]) # plotting all samples func_DisplayData(X, y, 1, 'All samples') # number of training samples nTrain = 120 ######################PLACEHOLDER 1#start######################### # write you own code to randomly pick up nTrain number of samples for training and use the rest for testing. maxIndex = len(X) randomTrainingSamples = np.random.choice(maxIndex, nTrain, replace=False) trainX = X[randomTrainingSamples] # training samples trainY = y[randomTrainingSamples] # labels of training samples nTrain X 1 testX = X[~randomTrainingSamples]# testing samples testY = y[~randomTrainingSamples]# labels of testing samples nTest X 1 ####################PLACEHOLDER 1#end######################### # plot the samples you have pickup for training, check to confirm that both negative # and positive samples are included. func_DisplayData(trainX, trainY, 2, 'training samples') func_DisplayData(testX, testY, 3, 'testing samples') # show all charts plt.show() # step 2: train logistic regression models ######################PLACEHOLDER2 #start######################### # in this placefolder you will need to train a logistic model using the training data: trainX, and trainY. ##################### # use sklearn class # ##################### clf = LogisticRegression() # call the function fit() to train the class instance clf.fit(trainX,trainY) ############################### # use Gradient_Descent method # ############################### theta = [0,0] #initial model parameters alpha = 0.05 # learning rates max_iteration = 1000 # maximal iterations m = len(y) # number of samples for x in range(max_iteration): # call the functions for gradient descent method new_theta = Gradient_Descent(X,y,theta,m,alpha) theta = new_theta if x % 200 == 0: # calculate the cost function with the present theta Cost_Function(X,y,theta,m) ######################PLACEHOLDER2 #end ######################### # step 3: Use the model to get class labels of testing samples. ######################PLACEHOLDER3 #start######################### # codes for making prediction, # with the learned model, apply the logistic model over testing samples # hatProb is the probability of belonging to the class 1. # y = 1/(1+exp(-Xb)) # yHat = 1./(1+exp( -[ones( size(X,1),1 ), X] * bHat )); )); predictions = [] for i in range(0, len(testX)): predictions.append(round(Prediction(theta , testX[i]))) yHat = np.array(predictions) sk_prediction = clf.predict(testX) gd_prediction = yHat ######################PLACEHOLDER 3 #end ######################### # step 4: evaluation # compare predictions yHat and and true labels testy to calculate average error and standard deviation gd_YDiff = np.abs(gd_prediction - testY) gd_avgErr = np.mean(gd_YDiff) gd_stdErr = np.std(gd_YDiff) print("\nGradient Descent: \n") print(classification_report(testY,gd_prediction)) print('Gradient Descent Average Error: {} ({})\n'.format(gd_avgErr, gd_stdErr)) print("Gradient Descent Confustion Matrix\n") func_calConfusionMatrix(gd_prediction, testY) sk_YDiff = np.abs(sk_prediction - testY) sk_avgErr = np.mean(sk_YDiff) sk_stdErr = np.std(sk_YDiff) print("\nsklearn: \n") print(classification_report(testY,sk_prediction)) print('sklearn Average Error: {} ({})\n'.format(sk_avgErr, sk_stdErr)) print("sklearn Confusion Matrix\n) func_calConfusionMatrix(sk_prediction, testY)
350653a916481644381841c1c9492e6c5c76774c
jsliacan/misc
/project-euler/p66.py
451
3.75
4
#!/usr/bin/env python # Problem 66 # won't work -- too slow! from __future__ import division from math import sqrt """ since (x-1)(x+1) = x^2-1 we have """ Dmax = 1000 Xmax = 0 dmax = 0 for d in range(2,Dmax+1): if sqrt(d).is_integer(): continue print d y = 1 x = sqrt(d*(y**2)+1) while not x.is_integer(): y += 1 x = sqrt(d*(y**2)+1) if x > Xmax: Xmax = int(x) dmax = d print Xmax
eefe89bd4b1b648369f0a34143bc0397ad686811
khadak-bogati/Introduction-to-Computer-Science-and-Programming-Using-Python
/Prblomeset2.py
3,236
3.96875
4
Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal monthlyPaymentRate - minimum monthly payment rate as a decimal For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print ======================================================= A summary of the required math is found below: Monthly interest rate= (Annual interest rate) / 12.0 Minimum monthly payment = (Minimum monthly payment rate) x (Previous balance) Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) We provide sample test cases below. We suggest you develop your code on your own machine, and make sure your code passes the sample test cases, before you paste it into the box below. ====================================================================================== set1 .................... # Test Case 1: balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 # Result Your Code Should Generate Below: Remaining balance: 31.38 # To make sure you are doing calculation correctly, this is the # remaining balance you should be getting at each month for this example Month 1 Remaining balance: 40.99 Month 2 Remaining balance: 40.01 Month 3 Remaining balance: 39.05 Month 4 Remaining balance: 38.11 Month 5 Remaining balance: 37.2 Month 6 Remaining balance: 36.3 Month 7 Remaining balance: 35.43 Month 8 Remaining balance: 34.58 Month 9 Remaining balance: 33.75 Month 10 Remaining balance: 32.94 Month 11 Remaining balance: 32.15 Month 12 Remaining balance: 31.38 solve ............................... balance = 42 annualInterestRate=0.2 monthlyInterestRate=0.04 RemainingBalance: 31.38 for i in range(12): balance = balance - (balance*monthlyInterestRate) + ((balance - (balance* monthlyInterestRate)) * (annualInterestRate/12)) print("RemainingBalance: ", round(balance, 2)) output ................................... RemainingBalance: 40.99 RemainingBalance: 40.01 RemainingBalance: 39.05 RemainingBalance: 38.11 RemainingBalance: 37.2 RemainingBalance: 36.3 RemainingBalance: 35.43 RemainingBalance: 34.58 RemainingBalance: 33.75 RemainingBalance: 32.94 RemainingBalance: 32.15 RemainingBalance: 31.38 #test case 2 balance = 482 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 for i in range(12): balance= balance-(balance*monthlyPaymentRate)+((balance-(balance*monthlyPaymentRate))*(annualInterestRate/12)) print("Remaining Balance: ", round(balance,2))
954dcdc5bb059efe07324bf84c844482b134aa56
joashdev/python-challenge
/inversion.py
3,323
3.9375
4
""" Counting Inversion #Counting Inversion traverses through a given list then counts the inversion in the list # a pair(x,y) is considered inversion when index(x) < index(y) but value(x) > value(y) #This algorithm uses Divide and Conquer recursive-approach, # specifically a modified Merge-And-Conquer algorithm #invCount() is the modified Merge-and-Conquer algorithm which accepts a list of element # then returns the sorted version of the list as well as the number of inversion that is in the list #force() is the brute-force algorithm to solve the inversion problem #use inv_input for one test-case input #use inv_test for multiple test-case input #Kent Joash A. Zamudio #CMSC 142 (lab) - Exercise 3 """ #invCount() divides the list by half (Left and Right) then process each list def invCount(arr): count = 0 #inversion count arrSort = list() #a sorted version of the list in the argument if len(arr) == 1: #if there is only 1 element in the list return arr, 0 #simply return the list and 0 since it is impossible to have a pair(x,y) else: midInd = len(arr)/2 #getting the middle index of the list LEFT = arr[:midInd] #copying the left part of the original list (from zero to middle index-1) RIGHT = arr[midInd:] #copying the right part of the original list (from middle index to last index) #sends each part to invCount() LEFT, invL = invCount(LEFT) RIGHT, invR = invCount(RIGHT) #the resulting inversion count from each side is the summed up count = invL + invR #this part is where inversions are counted leftInd = rightInd = 0 while len(LEFT) > leftInd and len(RIGHT) > rightInd: #if leftItem < rightItem, no increment in count since right elements should be greater if LEFT[leftInd] <= RIGHT[rightInd]: arrSort.append(LEFT[leftInd]) leftInd+=1 elif LEFT[leftInd] > RIGHT[rightInd]: #otherwise, there is an inversion. arrSort.append(RIGHT[rightInd]) rightInd+=1 #if we only increment 1 in the 'count', it will result to a wrong number of inversions # because in the later part of the recursion the processed list is already sorted # by subtracting the index to the length of the LEFT list, # the jumps of the elements is taken into consideration # uncomment the print statement to see jumps of element due to sorting count+= (len(LEFT)-leftInd) # print "jumps:", len(LEFT)-leftInd, "latest count:", count #if there are elements left in the left list, we copy those elements to the sorted list arrSort+= LEFT[leftInd:] arrSort+= RIGHT[rightInd:] return arrSort, count def force(arr): #brute force algorithm counterrr = 0 for item in arr: arr2 = arr[arr.index(item)+1:] for iterate in arr2: if item > iterate: counterrr+=1 print 'Brute Force Result: ',counterrr def main(): global count cases = int(raw_input()) for thisTest in range(cases): arr = [int(x) for x in raw_input().strip().split()] #for terminal use # print '=====================================' # sortedArr, count = invCount(arr) print 'input ', arr # print 'sorted ', sortedArr # force(arr) # print 'Divide and Conquer Result: ', count #for file use sortedArr, count = invCount(arr) print count main()
33aa13b512f46d66b6bba511cd975ef7aa0a91cb
savirnosaj/codingDojo
/python_stack/Python/python_fundamentals/insertionSort.py
591
4.125
4
# Insertion Sort # Execute insertion sort def insertionSort(arr): for count in range(1, len(arr)): temp = count #temp will reset through each iteration while temp > 0 and arr[temp - 1] > arr[temp]: # will have indexerror if try to go beyond 0 and checking if index before is greater arr[temp], arr[temp - 1] = arr[temp - 1], arr[temp] # then swap until index value -1 has lower value temp = temp - 1 # check all the way until first index value as long as index value is less than index-1 return arr print(insertionSort([6,5,3,1,8,7,2,4]))
37749cf214ef705f87393d877fc454c1ee92019f
sourcery-ai-bot/Python-Curso-em-Video
/python_exercicios/desafio064.py
660
3.96875
4
#Crie um programa que leia vários números inteiros pelo teclado. # O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. # No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag). n = c = s = 0 n = int(input('Digite um número [999 para parar]: ')) while n != 999: c += 1 s += n n = int(input('Digite um número [999 para parar]: ')) print('Você digitou {} números e a soma entre eles foi {}.'.format(c, s)) # Solução "Gambiarra" para tirar 1 do contador e 999 da soma #print('Você digitou {} números e a soma entre eles foi {}.'.format(c-1, s-999))
e90e39a6e609cc2a887dcb73f04f9406eb623ea5
Salishoma/My-Code-House
/src/com/python/zeroFilledSubArrays.py
863
3.875
4
''' 2348. Number of Zero-Filled Subarrays Given an integer array nums, return the number of subarrays filled with 0. A subarray is a contiguous non-empty sequence of elements within an array. Input: nums = [1,3,0,0,2,0,0,4] Output: 6 Explanation: There are 4 occurrences of [0] as a subarray. There are 2 occurrences of [0,0] as a subarray. There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6. ''' from typing import List class ZeroFilledSubArrays: def zeroFilledSubarray(self, nums: List[int]) -> int: count = 0 res = 0 for i in range(len(nums)): if nums[i] == 0: count += 1 res += count else: count = 0 return res arr = ZeroFilledSubArrays() print(arr.zeroFilledSubarray([1,3,0,0,2,0,0,4]))
8324fa28f571944426acc35ad5f1ee6b0cbd945d
Krispy2009/work_play
/sb2.py
3,672
3.515625
4
from string import ascii_lowercase import sys global finished global queue global my_words queue = [] class Node: def __init__(self, word, parent=None): self.word = word self.children = [] self.parent = parent def get_children(self): global my_words #change the word to a list to change its letters word = list(self.word) for position in range(len(word)): temp = word[:] for letter in list(ascii_lowercase): temp[position] = letter new_word = ''.join(temp) if my_words.has_key(new_word) and my_words[new_word] == 0: new_node = Node(new_word,parent=self) self.children.append(new_node) my_words[new_word] = 1 def load_words(location): f = file(location).read() return f def get_words(all_words,word_length): global my_words my_words = {} for word in all_words.split(): if len(word) is word_length: my_words[word.lower()] = 0 return my_words def process(my_words, start_node, end): global finished global queue #words reached by changing 1 letter similar_words ={} #starting temporary word top_temp = list(start_node.word) #hold parent of current node parent = start_node.parent #delete start word from list if my_words[start_node.word] == 0: my_words[start_node.word] = 1 #get the children of the current(start) node start_node.get_children() curr_children = start_node.children #for everyone of the new children, build queue for child in curr_children: #if we reach the end word we are finished if child.word == end: finished = True print 'reached end word' path = [] #print the path from the end to the start word while child.parent is not None: path.append(child.word) child = child.parent path.append(child.word) path.reverse() print path break #if current_node word is in the english dictionary then add # to similar and remove from my_words if child not in similar_words: parent = child.parent similar_words[child] = 1 #add every node from similar words into queue if it is not there for node in similar_words: if node not in queue: queue.append(node) if __name__ == '__main__': global finished args = sys.argv start_word = args[1] end_word = args[2] start_node = Node(start_word) finished = False w = load_words('/usr/share/dict/words') if len(start_word) == len(end_word): word_length = len(start_word) else: print """ Word length does not match! Make sure you are using two words of the same length """ sys.exit(0) #start the process with the start_node process(get_words(w,len(start_word)),start_node,end_word) while queue: #first node from queue first_node = queue.pop(0) #if it is in my_words delete it if first_node.word in my_words: my_words[first_node.word] = 1 #if no valid path is found, inform the user if finished == False and len(queue) == 0: print ("There is no way to reach %s from %s " "through the English dictionary") % (start_word,end_word) #if we are still looking, continue with the first node from queue if finished == False: process(my_words, first_node, end_word)
12b67cb4b2c670cf7bdb7d4c4803914a7d0760cb
mikedim/RSA-ElGamal-Demo
/rsaBob.py
424
3.90625
4
######Bob RSA###### import support print("------WELCOME BOB: RSA Encryption------") print("Enter N value received from Alice") n=input() print("Enter e value received from Alice") e=input() print("Enter integer to encrypt: ") xin=input() if xin>=n: print("Invalid input, message x must be an integer less than n") else: #encrypt message ex=support.rsaencrypt(xin,e,n) print("Ciphertext to send to Alice ") print(ex)
539506b63b232b4822fd4a2c96b89372cda29492
porrametict/learningSpace
/PythonWithChulalondkorn/for_loop2.py
454
3.71875
4
# def temperature_table(): # for celsius in range(101): # F = (celsius*9/5)+32 # print(celsius,"=",F) # temperature_table() # def mult_table(from_n,to_n): # for i in (from_n,to_n): # for j in range(1,13): # print("{} x {} = {}".format(i,j,i*j)) # print("---"*40) # mult_table(2,5) for i in range(2,4+1): for j in range(1, 13): print("{} x {} = {}".format(i, j, i * j)) print("-" * 40)
0a380297dfd81c638e2ab55e2ed77e9cf09cb7cc
Adastraea/WC-Generator
/wcgenerator.py
3,704
3.5625
4
import random from wcnaming import * from wcprofile import * def generateNameList(): while True: numnames = input("How many names to generate? ") try: numnames = int(numnames) except: print("Invalid input. Please enter a number.") continue break for x in range(0, numnames): name = generateName() print(name) def generateProfiles(): while True: numcats = input("How many cats to generate? ") numtraits = input("How many personality traits per cat? ") print() try: numcats = int(numcats) numtraits = int(numtraits) except: print("Invalid input. Please enter a number.") continue break for x in range(0, numcats): role = generateRole() name = generateName(role) gender, pronoun = generateGender(role) personality = generatePersonality(numtraits) secret = generateSecret(role) addtl = generateAdd() print(name + " is a " + gender + " " + role + ". Others describe " + pronoun + " as " + ', '.join(personality) + ".") if(secret !="" and addtl != ""): print(name + " " + secret + " and " + addtl + ".") else: if(secret != ""): print(name + " " + secret + ".") if(addtl != ""): print(name + " " + addtl + ".") print() # generate a clan's worth of characters # one leader, one deputy, one medicine cat, 15 warriors, 5 queens, 5 elders, 7 apprentices, 9 kits def generateClan(traits=3): clanRoles = ['leader', 'deputy', 'medicine cat'] warriors = ['warrior'] * 15 queens = ['queen'] * 5 elders = ['elder'] * 5 apprentices = ['apprentice'] * 7 kits = ['kit'] * 9 # complete list of roles for a Clan clanRoles = clanRoles + warriors + queens + elders + apprentices + kits for i in range(0, len(clanRoles)): role = clanRoles[i] gender, pronoun = generateGender(role) name = generateName(role) personality = generatePersonality(traits) addtl = generateAdd() secret = generateSecret(role) # kits and apprentices shouldn't have secrets print(name + " is a "+ gender + " " + role+ ". Others describe " + pronoun + " as " + ', '.join(personality) + ".") if(secret !="" and addtl != ""): print(name + " " + secret + " and " + addtl + ".") else: if(secret != ""): print(name + " " + secret + ".") if(addtl != ""): print(name + " " + addtl + ".") print() def main(): # ask user what they want to generate? while True: whatGenerate = input("What would you like to generate? \n Press 1 to generate names only \n Press 2 to generate character profiles \n Press 3 to generate a Clan of characters\n") try: whatGenerate = int(whatGenerate) except: # handles case where whatGenerate is not a number print("Invalid input. Please try again:") continue if whatGenerate not in [1, 2, 3]: # handles case if number entered is invalid print("Invalid input. Please try again:") continue else: break if(whatGenerate == 1): # generate adult names only generateNameList() return if(whatGenerate == 2): # generate character profiles generateProfiles() return if(whatGenerate == 3): # generate clan of characters generateClan() return if __name__ == "__main__": main()
4ed10f97d0f33374d98977f2ccd00db7a589bdc5
Sashkow/GeneticAlgorithms
/population.py
3,831
3.96875
4
from collections import UserList from dna import ListDna from gene import BoolGene import random import copy class Population(UserList): """ Population of DNA sequences in a genetic algorithm arguments: DnaClass -- class for DNA, e.g. ListDna or DictDna GeneClass -- class for gene, e.g BoolGene population_size -- initial size of the population part_selected -- amount of dna selected for reproduction mutation_probability -- mutation probability per gene generations -- generations amount to iterate algorithm through other arguments: whatever arguments needed for DnaClass e.g fitness_function """ def __init__(self, DnaClass=ListDna, GeneClass=BoolGene, population_size=10, part_selected=0.5, mutation_probability=0, generations=10, **kwargs): super().__init__() self.DnaClass = DnaClass self.population_size = population_size self.data = [DnaClass(GeneClass=GeneClass, **kwargs) for i in range(self.population_size)] self.part_selected = part_selected self.mutation_probability = mutation_probability self.generations = generations def pick(self): lst = [dna.fitness_function(dna) for dna in self] fitness_sum = sum(lst) pick_at = random.uniform(0, fitness_sum) current = 0 for dna in self: current += dna.fitness_function(dna) if current > pick_at: return dna def step(self): """ a method that performs one iteration of the algorithm sorts population selects some part of the fittest dna performs random mutations on dna with some probability picks pairs of random dna from selection, crossover them until needed population length is reached this method conserves population size """ # amt_selected = \ # int(self.population_size * self.part_selected) # spawning_pool = [] # list of dna selected for reproduction new_data =[] sorted_dna = sorted(self.data, key=lambda dna: dna.fitness_function(dna), reverse=True) # mutation for dna in sorted_dna: dna.mute(self.mutation_probability) # crossover while len(new_data) < \ self.population_size - (self.population_size % 2): d1 = copy.copy(self.pick()) d2 = copy.copy(self.pick()) times = 2 for i in range(times): d1.crossover(d2) new_data += [d1, d2] if (self.population_size % 2) == 1: new_data.append(copy.deepcopy(self.pick())) assert(len(self.data) == len(new_data)) for i in range(len(new_data)): self.data[i].data = new_data[i] def iterate(self): """ repeats step method generations times """ for i in range(self.generations): sorted_polulation = sorted(self.data, key=lambda item: - item.fitness_function(item)) print( [item.to_string() for item in sorted_polulation[:8]], [round(item.fitness_function(item),2) for item in sorted_polulation] ) # print([item.to_string() for item in self.data]) self.step() print("result") sorted_polulation = sorted(self.data, key=lambda item: - item.fitness_function(item)) print([str(item) for item in sorted_polulation])
716e999386a2fef99980fd1dab113e1f51147389
imtj1/NeuralTuringMachine_EulerianPath
/eulerian_path_task/graph_utils.py
7,934
3.90625
4
from operator import itemgetter import networkx as nx from collections import deque def is_semieulerian(G): """Returns ``True`` if and only if ``G`` has an Eulerian path. An Eulerian path is a path that crosses every edge in G exactly once. Parameters ---------- G: NetworkX Graph, DiGraph, MultiGraph or MultiDiGraph A directed or undirected Graph or MultiGraph. Returns ------- True, False See Also -------- is_eulerian() Examples -------- >>> G = nx.DiGraph([(1,2),(2,3)]) >>> nx.is_semieulerian(G) True """ is_directed = G.is_directed() # Verify that graph is connected, short circuit if is_directed and not nx.is_weakly_connected(G): return False # is undirected if not is_directed and not nx.is_connected(G): return False # Not all vertex have even degree, check if exactly two vertex # have odd degrees. If yes, then there is an Euler path. If not, # raise an error (no Euler path can be found) # if the odd condition is not meet, raise an error. start = _find_path_start(G) if not start: return False return True def _find_path_start(G): """Returns a suitable starting vertex for Eulerian path The function also verifies that the graph contains a path. If no path exists, returns ``None''. """ is_directed = G.is_directed() # list to check the odd degree condition check_odd = [] if is_directed: degree = G.in_degree out_degree = G.out_degree else: degree = G.degree # Verify if an Euler path can be found. Complexity O(|V|) for v in G: deg = degree(v) # directed case if is_directed: outdeg = out_degree(v) if deg != outdeg: # if we have more than 2 odd nodes no Euler path exists if len(check_odd) > 2: return False # is odd and we append it. check_odd.append(v) # undirected case else: if deg % 2 != 0: # if we have more than 2 odd nodes no Euler path exists if len(check_odd) > 2: return False # is odd and we append it. check_odd.append(v) start = None if is_directed: first = check_odd[0] second = check_odd[1] if G.out_degree(first) == G.in_degree(first) + 1 and \ G.in_degree(second) == G.out_degree(second) + 1: start = second elif G.out_degree(second) == G.in_degree(second) + 1 and \ G.in_degree(first) == G.out_degree(first) + 1: start = first else: start = None else: if len(check_odd) > 0: start = check_odd[0] return start def eulerian_path(G): """Return a generator of the edges of an Eulerian path in ``G``. Check if the graph ``G`` has an Eulerian path and return a generator for the edges. If no path is available, raise an error. Parameters ---------- G: NetworkX Graph, DiGraph, MultiGraph or MultiDiGraph A directed or undirected Graph or MultiGraph. Returns ------- edges: generator A generator that produces edges in the Eulerian path. Raises ------ NetworkXError: If the graph does not have an Eulerian path. Examples -------- >>> G = nx.Graph([('W', 'N'), ('N', 'E'), ('E', 'W'), ('W', 'S'), ('S', 'E')]) >>> len(list(nx.eulerian_path(G))) 5 >>> G = nx.DiGraph([(1, 2), (2, 3)]) >>> list(nx.eulerian_path(G)) [(1, 2), (2, 3)] Notes ----- Linear time algorithm, adapted from [1]_ and [3]_. Information about Euler paths in [2]_. Code for Eulerian circuit in [3]_. Important: In [1], Euler path is in reverse order, this implementation gives the path in correct order as in [3]_ for Eulerian_circuit. The distinction for directed graph is in using the in_degree neighbors, not the out ones. for undirected, it is using itemgetter(1) for get_vertex, which uses the correct vertex for this order. Also, every graph has an even number of odd vertices by the Handshaking Theorem [4]_. References ---------- .. [1] http://www.graph-magics.com/articles/euler.php .. [2] http://en.wikipedia.org/wiki/Eulerian_path .. [3] https://github.com/networkx/networkx/blob/master/networkx/algorithms/euler.py .. [4] https://www.math.ku.edu/~jmartin/courses/math105-F11/Lectures/chapter5-part2.pdf """ if not is_semieulerian(G): raise nx.NetworkXError("G does not have an Eulerian path.") g = G.__class__(G) # copy graph structure (not attributes) is_directed = g.is_directed() if is_directed: degree = g.in_degree edges = g.in_edges get_vertex = itemgetter(0) else: degree = g.degree edges = g.edges get_vertex = itemgetter(1) # Begin algorithm: start = _find_path_start(g) if not start: raise nx.NetworkXError("G has no Eulerian path.") vertex_stack = deque([start]) last_vertex = None while vertex_stack: current_vertex = vertex_stack[-1] # if no neighbors: if degree(current_vertex) == 0: # Special case, we cannot add a None vertex to the path. if last_vertex is not None: yield (last_vertex, current_vertex) last_vertex = current_vertex vertex_stack.pop() # we have neighbors, so add the vertex to the stack (2), take # any of its neighbors (1) remove the edge between selected # neighbor and that vertex, and set that neighbor as the # current vertex (4). else: edge = next(edges(current_vertex)) vertex_stack.append(get_vertex(edge)) g.remove_edge(*edge) def findpath(graph): n = len(graph) numofadj = list() # Find out number of edges each vertex has for i in range(n): numofadj.append(sum(graph[i])) # Find out how many vertex has odd number edges startpoint = 0 numofodd = 0 for i in range(n - 1, -1, -1): if (numofadj[i] % 2 == 1): numofodd += 1 startpoint = i # If number of vertex with odd number of edges # is greater than two return "No Solution". if (numofodd > 2): return [] # If there is a path find the path # Initialize empty stack and path # take the starting current as discussed stack = list() path = list() cur = startpoint # Loop will run until there is element in the stack # or current edge has some neighbour. while (stack != [] or sum(graph[cur]) != 0): # If current node has not any neighbour # add it to path and pop stack # set new current to the popped element if (sum(graph[cur]) == 0): path.append(cur + 1) cur = stack.pop(-1) # If the current vertex has at least one # neighbour add the current vertex to stack, # remove the edge between them and set the # current to its neighbour. else: for i in range(n): if graph[cur][i] == 1: stack.append(cur) graph[cur][i] = 0 graph[i][cur] = 0 cur = i break # print the path # for ele in path: # print(ele, "-> ", end='') # print(cur + 1) path.append(cur + 1) return path
47705e8915bb006112ff8425e42bf92db6dead1e
kazshidara/leetcode-practice
/dictionaries.py
599
3.8125
4
# 1. K most Frequent values # :type nums: List[int] # :type k: int # :rtype: List[int] def topKFrequent(nums, k): dict = {} for i in nums: if i not in dict: dict[i] = 1 else: dict[i] += 1 arr = sorted(dict.items(), key = lambda it: it[1], reverse=True) print("sorted by values", arr) result = [] for i in range(0,k): result.append(arr[i][0]) return result print(topKFrequent([1,1,1,2,2,3],2)) ################################################################################
00afd4229f76984e465f3d6a904f073eab8ceed7
aralyekta/METU
/CENG111/w6/hangman.py
404
3.65625
4
def hangman(str1,str2,num): len1 = len(str1) len2 = len(str2) if len1 > len2: return "lose" elif str1 == str2: return "win" elif len1 == len2 and str1 != str2: return "lose" a = 0 for i in range(len2): if str1[i] == str2[i]: continue else: a+= 1 if a >= num: return "lose" return "win"
0239c45475af0ab0a58015a421a76c4141bc7d9a
preetam-patel/task1
/pald.py
133
4.0625
4
def ispalindrome(s): return s== s[::-1] s= input('enter the word:') res = ispalindrome(s) if res : print('yes') else: print('no')
a4576e69789645357f44345f7bed8dec2b9fb0aa
daniel-reich/ubiquitous-fiesta
/Z2mhqFLe9g9ouZY64_4.py
267
3.59375
4
def is_valid_subsequence(lst, sequence): lst = list(filter(lambda x: x in sequence,lst)) if any(x not in lst for x in sequence): return False if lst == sequence: return True return is_valid_subsequence(lst[lst.index(sequence[0])+1::],sequence[1::])
a564ba2cac49aea70d84031344f2753fa1248a9a
111110100/my-leetcode-codewars-hackerrank-submissions
/leetcode/arraySign.py
2,351
3.890625
4
from typing import List class Solution: def arraySign(self, nums: List[int]) -> int: p = 1 t = [p:=p*v for v in nums] return 1 if p > 0 else -1 if p < 0 else 0 answer = Solution() print(answer.arraySign([-1,-2,-3,-4,3,2,1])) print(answer.arraySign([1,5,0,2,-3])) print(answer.arraySign([-1,1,-1,1,-1])) ''' There is a function signFunc(x) that returns: 1 if x is positive. -1 if x is negative. 0 if x is equal to 0. You are given an integer array nums. Let product be the product of all values in the array nums. Return signFunc(product). Example 1: Input: nums = [-1,-2,-3,-4,3,2,1] Output: 1 Explanation: The product of all values in the array is 144, and signFunc(144) = 1 Example 2: Input: nums = [1,5,0,2,-3] Output: 0 Explanation: The product of all values in the array is 0, and signFunc(0) = 0 Example 3: Input: nums = [-1,1,-1,1,-1] Output: -1 Explanation: The product of all values in the array is -1, and signFunc(-1) = -1 Constraints: 1 <= nums.length <= 1000 -100 <= nums[i] <= 100 class Solution: def arraySign(self, nums: List[int]) -> int: # 68 ms import functools product = functools.reduce(int.__mul__, nums) return (product > 0) - (product < 0) def arraySign(self, nums: List[int]) -> int: # 64 ms import functools return (product > 0) - (product < 0) if any((product := functools.reduce(int.__mul__, nums),)) else product def arraySign(self, nums: List[int]) -> int: # 108 ms import itertools *_, product = itertools.accumulate(nums, int.__mul__) return (product > 0) - (product < 0) def arraySign(self, nums: List[int]) -> int: # 112 ms return 0 if 0 in nums else -1 if sum(1 for i in nums if i < 0) % 2 else 1 def arraySign(self, nums: List[int]) -> int: # 60 ms return 0 if 0 in nums else -1 if str(nums).count("-") % 2 else 1 def arraySign(self, nums: List[int]) -> int: # 88 ms n_negatives = 0 for n in nums: if n == 0: return 0 n_negatives += n < 0 return -1 if n_negatives % 2 else 1 def arraySign(self, nums: List[int]) -> int: # 124 ms positive = 1 for n in nums: if n == 0: return 0 positive ^= n < 0 return (-1, 1)[positive] '''
ccd16068f58b3e38da7afd53625234fd203b1354
Ephrao1/Password-locker
/user.py
1,246
4.0625
4
class User: """ Class that generates users new instances . """ user_list = [] def __init__(self,acc_name,user_name,password,email): self.acc_name = acc_name self.user_name = user_name self.password = password self.email = email def save_user(self): ''' method that saves user into user_list ''' User.user_list.append(self) def delete_user(self): ''' method that deletes user from user list ''' User.user_list.remove(self) @classmethod def find_by_name(cls, name): for user in cls.user_list: if user.acc_name == name: return user @classmethod def user_exist(cls, name): ''' method that checks if user exists Args: name: searching if user exists Returns : Boolean:returns true or false statement if the user exists or not ''' for user in cls.user_list: if user.password == name: return user return False @classmethod def display_users(cls): """ this method returns the account list """ return cls.user_list
b84fc13c4282c49108438cd00160b05c7d37594d
tomytjandra/college-coursework
/NLP/basic nltk.py
4,881
3.578125
4
def clear(): for i in range(5): print() text = "On April 8, 2018, Persekutuan Oikumene (PO) BINUS held an Easter Service to commemorate the resurrection of Jesus Christ. BNEC sent some of its delegations to attend the invitation. It was a great event with all the activities and the warm atmosphere contained the room." ##1. TOKENIZING from nltk.tokenize import sent_tokenize, word_tokenize wordList = word_tokenize(text) sentList = sent_tokenize(text) print(wordList) clear() print(sentList) ##2. STOPWORDS from nltk.corpus import stopwords stopList = stopwords.words("english") wordWithoutStopwords = [] for word in wordList: if word not in stopList: wordWithoutStopwords.append(word) clear() print(wordWithoutStopwords) ##3. STEMMING from nltk.stem import LancasterStemmer, SnowballStemmer, PorterStemmer ls = LancasterStemmer() ss = SnowballStemmer("english") ps = PorterStemmer() lsRes = [] ssRes = [] psRes = [] for word in wordList: lsRes.append(ls.stem(word)) ssRes.append(ss.stem(word)) psRes.append(ps.stem(word)) clear() print(lsRes) clear() print(ssRes) clear() print(psRes) ##4. LEMMATIZING from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() wordToBeLemmatized = "Running" params = ['a','s','r','n','v'] clear() for param in params: print(param + " : " + lemmatizer.lemmatize(wordToBeLemmatized.lower(), param)) ##5. POSTAGGING from nltk.tag import pos_tag import string wordWithoutPunc = [] for word in wordList: if word not in string.punctuation: wordWithoutPunc.append(word) postag = pos_tag(wordWithoutPunc) clear() for word,tag in postag: print(word + " : " + tag) ##6. NAME ENTITY RECOGNITION from nltk.chunk import ne_chunk ner = ne_chunk(postag) clear() print(ner) choose = "" while choose == "": choose = input("Draw [yes/no]? ") if choose not in ["yes","no"]: choose = "" if choose == "yes": ner.draw() ##7. FREQ DIST from nltk.probability import FreqDist fd = FreqDist(wordList) for word, count in fd.most_common(): print(word + " : " + str(count)) ##BASIC from nltk.corpus import wordnet word = "win" synsetList = wordnet.synsets(word) woi = synsetList[0] clear() print(woi.name()) print(woi.definition()) print(woi.examples()) print(woi.pos()) lemmas = woi.lemmas() for lemma in lemmas: print(lemma.name()) ##SYNONYM synonym = [] for synset in wordnet.synsets(word): for lemma in synset.lemmas(): synonym.append(lemma.name()) synonym = set(synonym) clear() print(sorted(synonym)) ##ANTONYM antonym = [] for synset in wordnet.synsets(word): for lemma in synset.lemmas(): for anto in lemma.antonyms(): antonym.append(anto.name()) antonym = set(antonym) clear() print(sorted(antonym)) ##READ FILE FROM CORPORA from nltk.corpus import gutenberg filename = "austen-emma.txt" #print(gutenberg.raw(filename)) ##CLASSIFY MOVIE REVIEWS ##1. IMPORT FOLDER from nltk.corpus import movie_reviews ##2. TRANSFER TEXT TO LIST (ALLWORDS & DOCS) n = 30 allWords = [] docs = [] for category in movie_reviews.categories(): count = 0 for fileid in movie_reviews.fileids(category): wordsInOneFile = [] for word in movie_reviews.words(fileid): wordsInOneFile.append(word.lower()) allWords.append(word.lower()) docs.append((wordsInOneFile,category)) count += 1 if(count == n): break ##3. RANDOM SHUFFLE LIST import random random.shuffle(docs) ##4. DEF COLLECT FEATURES def collectFeatures(wordList): wordSet = set(wordList) feature = {} for word in allWords: feature[word] = (word in wordSet) return feature ##5. APPLY COLLECT FEATURES result = [] for (wordList, category) in docs: result.append((collectFeatures(wordList), category)) ##6. SPLITTING DATA splitPoint = int(0.8*2*n) trainingData = result[:splitPoint] testingData = result[splitPoint:] ##7. APPLY CLASSIFIER import nltk classifier = nltk.NaiveBayesClassifier.train(trainingData) ##8. MODEL EVALUATION try: acc = nltk.classify.accuracy(classifier, testingData) clear() print("Accuracy: {0:.2f}%".format(acc*100)) classifier.show_most_informative_features() except: print("No classifier") ##9. WRITE PICKLE import pickle file = open("classifier.pickle", "wb") pickle.dump(classifier, file) file.close() ###0. ADDITIONAL: READ PICKLE, WRITE AND READ STRING FILE ##READ PICKLE try: file = open("classifier.pickle", "rb") classifier = pickle.load(file) file.close() classifier.show_most_informative_features() except: print("No such file") ##WRITE STRING FILE file = open("test.txt", "w") file.write("Test\n") for i in range(10): file.write(str(i)) file.write('\n') file.close() ##READ STRING FILE file = open("test.txt", "r") data = file.read().split() print(data) file.close()
1fa8c6fcd09f715d4fd6efd4ca89a18a8d02cb13
fvcandal/project
/PMLFVC.py
4,926
3.5
4
#!/usr/bin/env python # coding: utf-8 # # Pratical Machine Learning # ## Fátima Vilela Candal # # Data processing # The original training and test data has 160 variables. The columns with NA entries have been removed. Five (5) variables were removed. # In[498]: # Importing Libraries import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np import math from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import warnings warnings.filterwarnings('ignore') # In[499]: # Importing the Dataset df = pd.read_csv('pml-training.csv') # In[500]: # Clear all null data df.dropna(inplace=True) # In[501]: # Total rows and columns print("Train data line and colum: {}".format(df.shape)) # In[502]: # Columns present in the dataset print(df.columns) # In[503]: # Data types df.dtypes # In[504]: # Presentation of null data df.isnull().sum() # In[528]: # Data presented 20 columns and 05 rows df.head(5) # In[506]: # Descriptive statistics for each column df.describe() # # Train Test Split # We will divide our dataset into training and test splits, which gives us a better idea as to how our algorithm performed during the testing phase. This way our algorithm is tested on un-seen data, as it would be in a production application. # In[551]: # Preprocessing # The next step is to split our dataset into its attributes and labels cols = ['raw_timestamp_part_1', 'raw_timestamp_part_2', 'num_window', 'roll_belt', 'pitch_belt', 'yaw_belt', 'gyros_forearm_x', 'gyros_forearm_y', 'gyros_forearm_z', 'accel_forearm_x', 'accel_forearm_y', 'accel_forearm_z', 'magnet_forearm_x', 'magnet_forearm_y', 'magnet_forearm_z'] X = df[cols] y = df.classe X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25) # In[542]: print (X_train.shape) # In[543]: print (X_test.shape) # # Model # The first step is to import the KNeighborsClassifier class from the sklearn.neighbors library. In the second line, this class is initialized with one parameter, i.e. n_neigbours. This is basically the value for the K. There is no ideal value for K and it is selected after testing and evaluation, however to start out, 5 seems to be the most commonly used value for KNN algorithm. # # After all the work of data preparation, creating and training the model KNN regression model from skicit-learn, instantiate the model, and fit the model on the training data. # # Predictions # It is extremely straight forward to train the KNN algorithm and make predictions with it, especially when using Scikit-Learn. # In[544]: # from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=20) classifier.fit(X_train, y_train) # In[545]: # Prediction y_pred = classifier.predict(X_test) y_pred # # Evaluating the Algorithm # For evaluating an algorithm, confusion matrix, precision, recall and f1 score are the most commonly used metrics. The confusion_matrix and classification_report methods of the sklearn.metrics can be used to calculate these metrics. # In[547]: from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) # # Comparing Error Rate with the K Value # In the training and prediction section we said that there is no way to know beforehand which value of K that yields the best results in the first go. # # We randomly chose 5 as the K value and it just happen to result in 100% accuracy. # # One way find the best value of K is to plot the graph of K value and the corresponding error rate for the dataset. # # We will plot the mean error for the predicted values of test set for all the K values between 1 and 40. # In[548]: error = [] # Calculating error for K values between 1 and 40 for i in range(1, 40): knn = KNeighborsClassifier(n_neighbors=i) knn.fit(X_train, y_train) pred_i = knn.predict(X_test) error.append(np.mean(pred_i != y_test)) # In[549]: plt.figure(figsize=(12, 6)) plt.plot(range(1, 40), error, color='red', linestyle='dashed', marker='o', markerfacecolor='blue', markersize=10) plt.title('Error Rate K Value') plt.xlabel('K Value') plt.ylabel('Mean Error') # # Conclusion # KNN is a simple yet powerful classification algorithm. It requires no training for making predictions, which is typically one of the most difficult parts of a machine learning algorithm. The KNN algorithm have been widely used to find document similarity and pattern recognition. It has also been employed for developing recommender systems and for dimensionality reduction and pre-processing steps for computer vision, particularly face recognition tasks. # #
929f8b961f38e6750dff7f71f9bcf2733b69afc8
virtual/fcc-python-projects
/time-calculator/time_calculator.py
2,157
4.0625
4
import math # Return the day name of an equivalent day index # def getDayNameByNum(dayIndex): if (dayIndex == 0): return 'Monday' elif (dayIndex == 1): return 'Tuesday' elif (dayIndex == 2): return 'Wednesday' elif (dayIndex == 3): return 'Thursday' elif (dayIndex == 4): return 'Friday' elif (dayIndex == 5): return 'Saturday' elif (dayIndex == 6): return 'Sunday' # given a day of the week, return the day's index # def getDayNum(day): day = (day).lower() if (day == 'monday'): return 0 elif (day == 'tuesday'): return 1 elif (day == 'wednesday'): return 2 elif (day == 'thursday'): return 3 elif (day == 'friday'): return 4 elif (day == 'saturday'): return 5 elif (day == 'sunday'): return 6 # given a certain day (0 = Monday) and duration (1 day) # add the duration to the day #, and mod by 6 to return # the updated day name def convertToTime(hour, min, days=0, startDay=''): period = 'AM' dayStr = '' endDay = '' endDayNum = -1 if (startDay != ''): endDayNum = getDayNum(startDay) hour12 = hour if hour >= 12: hour12 = hour % 12 period = 'PM' if hour12 == 0: hour12 = 12 if days == 1: dayStr = ' (next day)' elif days > 1: dayStr = ' (' + str(days) + ' days later)' if endDayNum > -1: endDay = (endDayNum + days) % 7 endDay = ', ' + getDayNameByNum(endDay) return f'{hour12}:{str(min).zfill(2)} {period}{endDay}{dayStr}' def add_time(start, duration, startDay=''): start = start.split(" ") # split and convert array items to ints hours, mins = map(int,start[0].split(':')) dHours, dMins = map(int,duration.split(':')) if (start[1].lower() == 'pm'): # Time is afternoon hours = hours + 12 # Check if clock reaches midnight daysOf = math.floor((hours + dHours) / 24) minsOf = (mins + dMins) % 60 hoursOf = (hours + dHours) % 24 + math.floor((mins + dMins) / 60) # Could be more than 24 if hoursOf >= 24: daysOf = daysOf + math.floor(hoursOf / 24) hoursOf = hoursOf % 24 new_time = convertToTime(hoursOf, minsOf, daysOf, startDay) return new_time
56003ac62a71b38f7f6903261c603b415d5b125c
Shohet-Val/Python
/downloader_pages.py
1,266
3.765625
4
#прочитать сайт и посчитать статистику использования слов с# или python from urllib.request import urlopen html = urlopen("https://ru.wikipedia.org/wiki/Python").read().decode('utf-8') s = str(html) print('Сравнительная частота в статьи из Википедии о Питоне') print('Частота С++ ', s.count('C++')) print('Частота Python ', s.count('Python')) # """ m_htm = urlopen("https://ru.wikipedia.org/wiki/C++").read().decode('utf-8') r = str(html) print('Сравнительная частота в статьи из Википедии о Pascal') print('Частота Java ', r.count('Java')) print('Частота C# ', r.count('C#')) print('Частота JavaScript ', r.count('JavaScript')) """ #https://stepik.org/media/attachments/lesson/209717/1.html print('+++++ Задание +++++') m_html = urlopen("https://stepik.org/media/attachments/lesson/209717/1.html").read().decode('utf-8') j = str(m_html) text_site = str(m_html) #print(text_site) print('Сравнительная частота в статьи из Википедии о Питоне') print('Частота Python ', j.count('Python')) print('Частота C++ ', j.count('C++'))
93a740d639aac76a7d7f4db91b81d53017df4265
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/151_10.py
1,414
4.84375
5
Python | How to copy a nested list In the previous article, we have seen how to clone or Copy a list, now let’s see how to copy a nested list in Python. **Method #1: Using Iteration** __ __ __ __ __ __ __ # Python program to copy a nested list # List initialization Input_list = [[0, 1, 2], [3, 4, 5], ] Output = [] # Using iteration to assign values for x in range(len(Input_list)): temp = [] for elem in Input_list[x]: temp.append(elem) Output.append(temp) # Printing Output print("Initial list is:") print(Input_list) print("New assigned list is") print(Output) --- __ __ **Output:** Initial list is: [[0, 1, 2], [3, 4, 5]] New assigned list is [[0, 1, 2], [3, 4, 5]] **Method #2: Using deepcopy** __ __ __ __ __ __ __ # Python program to copy a nested list import copy # List initialization Input = [[1, 0, 1], [1, 0, 1]] # using deepcopy Output = copy.deepcopy(Input) # Printing print("Initial list is:") print(Input) print("New assigned list is") print(Output) --- __ __ **Output:** Initial list is: [[1, 0, 1], [1, 0, 1]] New assigned list is [[1, 0, 1], [1, 0, 1]]
6dcd89c3a16a0200d15907b9ad60b2e1f64d1022
m-wieloch/blackJack
/GUI_start_game.py
1,097
3.5
4
from tkinter import * import sqlite3 # def buttom_click(): def myClick(): playLabel = Label(root, text="CDN :)") playLabel.grid(row=4, column=2) # def show(): # myLabel = Label(root, text=var.get()).pack() root = Tk() root.geometry("500x200") root.title("BlackJack") root.config(bg="sea green") blackjack = Label(root, text="BLACKJACK", font=('goudy stout', 20), bg="sea green", fg="goldenrod3") blackjack.grid(row=0, column=1) name = Label(root, text="Your name:", font=('cambria', 13), bg="sea green", fg="white") name.grid(row=1, column=0) pack = Label(root, text="Pack number:", font=('cambria', 13), bg="sea green", fg="white") pack.grid(row=2, column=0) e_name = Entry(root, borderwidth=3, width=40, justify=CENTER) e_name.grid(row=1, column=1, padx=20, pady=(10, 0)) e_pack = Entry(root, borderwidth=3, width=40, justify=CENTER) e_pack.grid(row=2, column=1, padx=20, pady=(10, 0)) play = Button(root, text="Play", command=myClick, borderwidth=5, bg="goldenrod3", fg="white") play.grid(row=3, column=1, padx=20, pady=10) play.config(width=10, height=1) root.mainloop()
bf2d7a46fd82fa2282fced9b639cb2e7532c50ff
szlevinli/AuraAIHomework
/sources/least_squares_method.py
1,765
3.84375
4
import numpy as np from matplotlib import pyplot as plt def least_squares_method(v_x, v_y): """最小二乘法 该方法仅支持二元一次方程 y = mx + c Arguments: v_x {ndarray 1D} -- 样本数据中的特征值 v_y {ndarray 1d} -- 样本数据中的真实值 Returns: float -- 斜率 m float -- 截距 c """ # compute mean mean_x = v_x.mean() mean_y = v_y.mean() # compute slop temp1 = ((v_x - mean_x) * (v_y - mean_y)).sum() temp2 = ((v_x - mean_x) ** 2).sum() slop = temp1 / temp2 # compute intercept intercept = mean_y - slop * mean_x # return return slop, intercept def least_squares_method_with_matrix(X, y): X_ = np.concatenate((np.ones((X.shape[0], 1)), X), axis=1) return np.linalg.inv((X_.T @ X_)) @ X_.T @ y def plot_line(x, y, slop, intercept, **kwargs): x2 = np.linspace(x.min(), x.max(), 100) y2 = x2 * slop + intercept plt.plot(x2, y2, **kwargs) if __name__ == "__main__": x = np.array([8, 2, 11, 6, 5, 4, 12, 9, 6, 1]) y = np.array([3, 10, 3, 6, 8, 12, 1, 4, 9, 14]) plt.plot(x, y, 'o') # 原始数据 m, c = least_squares_method(x, y) # plot_line(x, y, m, c, label='Origin') # # 增加平均分布的噪音 # m, c = least_squares_method(x + np.random.rand(x.shape[0]), y) # plot_line(x, y, m, c, label='Uniform noise') # # 增加正态分布的噪音 # m, c = least_squares_method(x + np.random.randn(x.shape[0]), y) # plot_line(x, y, m, c, label='Normal noise') # plt.legend() # plt.show() t = least_squares_method_with_matrix(x.reshape(x.shape[0], 1), y) print(f'slop is {m}, intercept is {c}') print(f'slop is {t[1]}, intercept is {t[0]}')
68e6aedab3c0f64305f555b77dfd9a9bee7d4db1
shacharSirotkin/SBR_2018
/SBR/SymbolicPlanRecognition/PathNode.py
2,349
3.65625
4
from Node import Node class PathNode(Node): def __init__(self, tree_node): self._parent = None self._child = None Node.__init__(self, tree_node.get_ID(), tree_node.get_label(), tree_node.get_is_root(), tags=tree_node.get_tags(), seq_of=tree_node.get_prev_seqs(), seq=tree_node.get_next_seqs()) def set_parent(self, parent): self._parent = parent parent._child = self def get_child(self): return self._child def search(self): lst = [self] if self._child is not None: lst.extend(self._child.search()) return lst # return The depth where there is a sequential connection from node in this path to node in the given path def get_seq_to_next_depth(self, next_path): # if the paths are the same, saying that there is a sequential edge between them will be a vacuous truth if self == next_path: return 0 # get all nodes in both paths next_nodes = next_path.search() current_nodes = self.search() connection_node = None # look for node from path1 and path2 which have a sequential edge from one to the other # if two nodes was found connection_node would be the node which the sequential edge come from for next_node in next_nodes: for current_node in current_nodes: if next_node.get_ID() in current_node.get_next_seqs(): connection_node = current_node break depth = -1 check_path = self # find the depth of connection_node in check_path(which is actually self) if connection_node is not None: while check_path != connection_node: depth += 1 check_path = check_path.get_child() return depth def __repr__(self): res = self._label if self._child is not None: res += self._child.to_string(" ") return res def to_string(self, init): res = init + self._label if self._child is not None: res += self._child.to_string(init) return res def __eq__(self, other): return other.__repr__() == self.__repr__() def __hash__(self): return hash(self.__repr__())
fecae0bb124b379ff53e1e5853d3461065286289
JeongJaeWook/pystock_jw
/gui/basic2_label.py
519
3.5625
4
from tkinter import * rt = Tk() rt.title("재욱이꺼") rt.geometry("640x480") label1 = Label(rt, text="Hi") label1.pack() photo = PhotoImage(file="check.png") label2 = Label(rt, image=photo) label2.pack() def change(): label1.config(text="또만나요") #text를 바꿀때 config 쓴다 global photo2 #가비지컬렉션 되지 않도록 global 변수 설정 photo2 = PhotoImage(file= "no.png") label2.config(image=photo2) btn = Button(rt, text="click", command=change) btn.pack() rt.mainloop()
7c8682c2e287f12962e013e33f70f187a7b9312f
tanzidakazi/Boring-Stuff-With-Python
/ListAndString.py
2,013
4.3125
4
# index() List Method # append() List Method # insert() List Method # remove() List Method # sort() List Method '''import copy friendList=['Mahmuda', 'Mazdia', 'Samiha', 'Sherin', 'Shegufta', 'abc', 'qwe'] print('Index of Mahmuda is ') print(friendList.index('Mahmuda')) for i in range(len(friendList)): print('Index: ' + str(i+1) + ', Name: ' + friendList[i]) for i in range(len(friendList)): print(friendList.index('Mazdia')) print(friendList.index(friendList[i])) # same as str(i) print('Enter name of new friend: ') newFriend = input() friendList.append(newFriend) print(friendList) friendList.insert(2, 'Areeba') print(friendList) friendList.remove('abc') print(friendList) friendList.sort() print(friendList) friendList.sort(reverse=True) print(friendList) friendList.sort(key=str.lower) print(friendList) # copy() Function # deepcopy() Funtion familyList = copy.copy(friendList) #familyList[1]='Nephew' familyList[1]= ['Mum', 'Dad', 'Brother'] print(familyList) ''' # upper(), lower() String Method # isupper(), islower() String Method # isX String Method # startswith(), endswith() String Method # join(), split() String Method # rjust(), ljust(), center() Justifying Text # strip(), rstrip(), lstrip() Removing Whitespace # Copying and Pasting with paperclip module string1= 'Mahmuda went to London \n' print(string1) print('Press 1 for upper()') print('Press 2 for lower()') print('Press 3 for isupper()') print('Press 4 for islower()') print('Press 5 for isalpha()') print('Press 6 for isalpha()') print('Press 7 for isalnum()') print('Press 8 for isdecimal()') print('Press 9 for isspace()') print('Press 10 for istitle()') def manipulateString(x): for i in range(10): x=input() if x=='1': print(string1.upper()) elif x=='2': print(string1.lower()) elif x=='3': print(string1.isupper()) elif x=='4': print(string1.islower()) manipulateString(string1)
6018c3f22e34f7a64f970658928f17a58bc75a2f
arnav900/Dcoder-Challenges
/Easy/Python/The_light_Switch.py
156
3.703125
4
s1, s2 = [int(i) for i in input().split()] if s1 and s2: print(0) elif not s1 and s2: print(1) elif s1 and not s2: print(1) else: print(0)
19c4d63a769367eec7f7efebb821d61bd89f3e2f
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/dlymuh001/question3.py
539
3.828125
4
print("Independent Electoral Commission") print("--------------------------------") print("Enter the names of parties (terminated by DONE):") print() election_results = {} party = "" while party != "DONE": party = input() if party == "DONE": break if (party in election_results) == False: election_results [party] = 1 else: election_results [party] += 1 print("Vote counts:") for party in sorted(election_results): print(party + " "*(11 - len(party)) + "-", election_results[party])
a299f78b4efd23124414bcd342f4df7621eaefbf
yongmon01/AlgorithmStudy
/자료구조/sort/selectionSort.py
615
3.9375
4
# 불안정 정렬 / 시간 O(n**2) / 공간 O(n) def selection_sort(my_list): for i in range(len(my_list)): min_index = i for j in range(i, len(my_list)): if my_list[j] < my_list[min_index]: min_index = j my_list[min_index], my_list[i] = my_list[i], my_list[min_index] # 테스트 1 list1 = [1, 3, 5, 7, 9, 11, 13, 11] selection_sort(list1) print(list1) # 테스트 2 list2 = [28, 13, 9, 30, 1, 48, 5, 7, 15] selection_sort(list2) print(list2) # 테스트 3 list3 = [2, 5, 6, 7, 1, 2, 4, 7, 10, 11, 4, 15, 13, 1, 6, 4] selection_sort(list3) print(list3)
75d1985fbad762304991c22d56fef6a01cb4eb39
sshalu12/turtle-programs
/turtle_random_walk.py
468
3.703125
4
from turtle import Turtle, Screen import random import turtle turtle.colormode(255) directions = [0, 90, 180, 270, 360] t1 = Turtle() t1.pensize(15) t1.speed("normal") def random_color(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) rr = (r, g, b) return rr for i in range(200): t1.setheading(random.choice(directions)) t1.color(random_color()) t1.forward(30) s1 = Screen() s1.exitonclick()
a5b11c2deb13a9444096030d422418fa5cf26306
EricVenom/myfirstcalculator
/calculator.py
1,456
4.1875
4
calculator = "On" def sum(): x = int(input("What is the first number? ")) y = int(input("What is the second number? ")) result = x + y print(f"The sum of {x} and {y} is: {result}") print() def sub(): x = int(input("What is the first number? ")) y = int(input("What is the second number? ")) result = x - y print(f"The subtraction of {x} and {y} is: {result}") print() def multi(): x = int(input("What is the first number? ")) y = int(input("What is the second number? ")) result = x * y print(f"The multiplication of {x} and {y} is: {result}") print() def divide(): x = int(input("What is the first number? ")) y = int(input("What is the second number? ")) result = x / y print(f"The division of {x} and {y} is: {result}") print() while calculator == "On": print("Welcome to calculator 1.0! Choose an operator to proceed. ") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Exit") proceed = input("1/2/3/4/5: ") if proceed == "1": sum() elif proceed == "2": sub() elif proceed == "3": multi() elif proceed == "4": divide() elif proceed == "5": print() print("Goodbye!") exit() else: print() print("That's not a valid input. Try again!") print()
644a1281eb6216eb9e0991c9e6839afbf45b4831
hguochen/code
/python/questions/ctci/arrays_and_strings/is_unique.py
1,003
4.09375
4
""" CtCi 1.1 Implement an algorithm to determine if a string has all the unique characters. What if you cannot use additional data structures? """ def is_unique_using_hashtable(word): """ Time: O(n) Space: O(n) where n is the word length """ if not word: return False table = {} for i in xrange(len(word)): if word[i] not in table: table[word[i]] = None else: return False return True def is_unique_using_sort(word): """ Time: O(nlgn) Space: O(n) where n is the word length """ chars = list(word) chars.sort() for i in xrange(1,len(chars)): if chars[i] == chars[i-1]: return False return True if __name__ == '__main__': word1 = "Word" word2 = "Nootunique" print is_unique_using_hashtable(word1) # True print is_unique_using_hashtable(word2) # False print is_unique_using_sort(word1) # True print is_unique_using_sort(word2) # False
ece6c049b034ec2cd68b66686fecb9e9a822b229
bartnic2/Python-Guides
/2 - Program Flow Control in Python.py
6,830
4.28125
4
# Indenting: Note that one indent (or tab) is equivalent to 4 spaces. Try not to mix up spaces and tabs! # Note the for look is calling the print method, which makes up the code block; everything with the same level # of indentation is part of the same code block # Also, you can select "reformat code" from the code drop-down menu at the top, which will clear up any errors or # problematic spacing. # Example: for i in range(1, 12): print('No. {} squared is {} and cubed is {:<4}'.format(i, i ** 2, i ** 3)) # -------------------------------------------------------------------------------------------------------------------- # # If: Runs indented code block if condition is met # Elif: Runs indented code block if alternative condition is met (this is short for else if) # Else: Runs indented code block if none of the previous conditions are met name = input("Please enter your name: ") age = int(input("How old are you, {0}? ".format(name))) print(age) # if age >= 18: print("You are old enough to vote") print("Please put an X in the box") else: print("Please come back in {0} years".format(18-age)) print("Please guess a number between 1 and 10: ") guess = int(input()) if guess < 5: print("Please guess higher") guess = int(input()) if guess == 5: print("Well done, you guessed it!") else: print("Sorry, you have not guessed correctly") elif guess > 5: print("Please guess lower") guess = int(input()) if guess == 5: print ("Well done, you guessed it!") else: print("Sorry, you have not guessed correctly") else: print('You got it first time!') # Better formatted version: if guess != 5: if guess < 5: print("Please guess higher") else: print("Please guess lower") guess = int(input()) if guess == 5: print("Well done, you guessed it!") else: print("Sorry, you have not guessed correctly") else: print("You got it first time!") # -------------------------------------------------------------------------------------------------------------------- # # More complex else, elif conditions: age = int(input("How old are you? ")) if 16 <= age <= 65: print("Have a good day at work") if age < 16 or age > 65: print("Enjoy your free time") else: print("Have a good day at work") # True/false conditions. Note that there is no boolean data type, but by using the built-in boolean function, certain # expressions can evaluate to true or false (in addition to typing in true/false explicitly). # Also note that many empty statements are automatically evaluated as False without any boolean function (see below # for an example where simply pressing return (no text entered) is equivalent to false. x = False print("""False: {0} None: {1} 0: {2} 0.0: {3} empty list []: {4} empty tuple (): {5} empty string '': {6} empty string "": {7} empty mapping {{}}: {8} """.format(False, bool(None), bool(0), bool(0.0), bool([]), bool(()), bool(''), bool(""), bool({}))) if x == bool([]): print('works') # Cool things you can do with booleans: x = input("Please enter some text: ") if x: print("You entered '{}'".format(x)) else: print("You did not enter anything") # One last example using 'not'. Note, its often recommended to use brackets around the true/false condition for # clarity, though its not necessary. age = int(input("How old are you? ")) if not (age < 18): print("You are old enough to vote") print("Please put an X in the box") else: print("Come back in {0} years".format(18-age)) # -------------------------------------------------------------------------------------------------------------------- # parrot = "Norwegian Blue" letter = input("Enter a character: ") if letter in parrot: if letter in 'aeiou': print("Give me an {}, Bob".format(letter)) else: print("give me a {}, Bob".format(letter)) else: print("I don't need that letter") # Note that you could also do it the other way, by typing in "if letter not in parrot:" etc. # -------------------------------------------------------------------------------------------------------------------- # # For loops: # for i in "statement": # print('{}'.format(i)) number = "9,223,372,036,854,775,807" cleanedNumber = "" for i in range(0, len(number)): if number[i] in '0123456789': cleanedNumber = cleanedNumber + number[i] print('{}'.format(number[i]), end='') newNumber = int(cleanedNumber) print("\nThe number is {} ".format(newNumber)) for state in ["not pinin'", "no more", "a stiff", "bereft of life"]: # print("This parrot is " + state) print("this parrot is {}".format(state)) # -------------------------------------------------------------------------------------------------------------------- # # Can use continue to bypass the remainder of a block of code, and move on to the next iteration of the for loop shopping_list = ["milk", "pasta", "eggs", "spam", "bread", "rice"] for item in shopping_list: if item == "spam": print("I am ignoring " + item) continue print("Buy " + item) # Note that break exits the for loop entirely: for item in shopping_list: if item == "spam": print("I am ignoring " + item) break print("Buy " + item) # Note this interesting example. If spam is found, it breaks out of the for loop, and since the 'if' statement was # found to be true, then the else doesn't activate. Note that it can't refer to the third if statement, since the # else precedes that statement and code must follow sequentially as the line number increases. # Otherwise, if spam was not found, then the else statement activates. # Aside: "Camel case" is the term used to describe variable casing done in the following way: nastyFoodItem. # That is, the first letter is uncapitalized, while the first letters of every following word are capitalized, with # no spaces between the words. Often these are good conventions to follow, and maintain throughout all your # programming languages. # Remember though, that Python variables are case sensitive! meal = ["egg", "bacon", "spam", "sausages"] # meal = ["egg", "bacon", "tomato", "sausages"] nasty_food_item = '' for item in meal: if item == 'spam': nasty_food_item = item break else: print("I'll have a plate of that, then, please") if nasty_food_item: print("Can't I have anything without spam in it?") # -------------------------------------------------------------------------------------------------------------------- # # End of Section 2
d9cf72221e90b16bda1be3f3f6017d9202653e42
worldofmagic/leetcode
/python/73.set-matrix-zeroes.py
708
3.546875
4
# # @lc app=leetcode id=73 lang=python3 # # [73] Set Matrix Zeroes # # @lc code=start class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ rows = len(matrix) cols = len(matrix[0]) zero_elements = [] for i in range(rows): for j in range(cols): if matrix[i][j] == 0: zero_elements.append([i,j]) for element in zero_elements: for i in range(rows): matrix[i][element[1]] = 0 for j in range(cols): matrix[element[0]][j] = 0 # @lc code=end
938df9342a56c9d629f7dbf7e9222678c737a073
Vigyrious/python_fundamentals
/Dictionaries-More-Exercises/Ranking.py
1,339
3.515625
4
dect_contests = {} dect_submissions = {} command = input() while command != "end of contests": contest, password = command.split(":") dect_contests[contest] = 0 dect_contests[contest] = password command = input() command = input() while command != "end of submissions": contest, password, username, points = command.split("=>") if contest in dect_contests and password == dect_contests[contest]: if username not in dect_submissions: dect_submissions[username] = {} if contest not in dect_submissions[username]: dect_submissions[username][contest] = int(points) else: if int(points) > dect_submissions[username][contest]: dect_submissions[username][contest] = int(points) command = input() max_points = 0 biggest_user = "" for user in dect_submissions: current = 0 for subject in dect_submissions[user]: current += dect_submissions[user][subject] if current > max_points: max_points = current biggest_user = user print(f"Best candidate is {biggest_user} with total {max_points} points.") print("Ranking:") for user in sorted(dect_submissions): print(f"{user}") for contest, points in sorted(dect_submissions[user].items(),key=lambda x:-x[1]): print(f"# {contest} -> {points}")
47775db30df01709c789c1e4b78b10a92b74d91b
Ashishchougule009/Practice-examples
/Practice/Basics1/e11.py
166
3.8125
4
def myfun(list,n): if n in list: return True else: return False list = [1,5,3,8] print(myfun(list,3)) print(myfun(list,-1))
95fef61c70a3445d4e6c626a736664733c10ae11
Mengeroshi/Python-Crash-Course-exercises
/chapter_5/5.9_no_users.py
318
4
4
usernames = ["admin", "mengeroshi", "gartox", "satoshi", "mendax"] if usernames: for user in usernames: if user == "admin": print("Hello admin, would you like to see a status report?") else: print(f"Hello {user}, great to see you again") else: print("There's no users")
d1183c310c5a30c911a6ad3156a7539bda1b4db1
Herophillix/cp1404practicals
/prac_06/people.py
1,985
4.09375
4
""" Describe many people in a table """ import math from person import Person from table import * def get_input(prompt): """Get user input as raw value""" user_input = input(prompt) while user_input == "": print("Input cannot be empty") user_input = input(prompt) return user_input def get_input_int(prompt, min_range=-math.inf, max_range=math.inf): """Get user input as integer""" is_input_valid = False user_input = 0 while not is_input_valid: try: user_input = int(input(prompt)) if not min_range <= user_input <= max_range: print("Please put in value within range {0} - {1}".format(min_range, max_range)) else: is_input_valid = True except ValueError: print("Please input a valid integer") return user_input def print_people_table(people: [Person]): """Print the list of people in a table""" table = Table() header_rows = [Cell("First Name"), Cell("Last Name"), Cell("Age")] table.add_row(header_rows) table.add_buffer() for person in people: row = [Cell(person.first_name), Cell(person.last_name), Cell(str(person.age), '>')] table.add_row(row) table.add_buffer() table.print_table() def main(): """Describe many people in a table""" num_of_times = get_input_int("Number of people: ") while num_of_times <= 0: print("Please input a value > 0") num_of_times = get_input_int("Number of people: ") people = [] for i in range(num_of_times): print("Person {0}".format(i + 1)) first_name = get_input("First Name: ") last_name = get_input("Last Name: ") age = get_input_int("Age: ", min_range=0) new_person = Person(first_name, last_name, age) people.append(new_person) people.sort(key=lambda person: person.age) print_people_table(people) if __name__ == "__main__": main()
660795974fb4106aa2333b5c6cd819e48899e8d7
renansald/Python
/cursos_em_video/Desafio69.py
755
3.875
4
countIdade = nHomens = nMulheres = 0; while(True): idade = int(input("Informe a idade: ")); while(True): sexo = str(input("Informe o sexo da pessoa[M/F]")).strip().upper(); if((sexo == 'M') or (sexo =='F')): break; if(idade > 18): countIdade += 1; if(sexo == 'M'): nHomens += 1; if((sexo == 'F') and (idade < 20)): nMulheres += 1; while(True): opcao = str(input("Deseja efetuar um novo cadastro[S/N]: ")).strip().upper(); if((opcao == "S") or (opcao == "N")): break; if(opcao == 'N'): break; print(f"Foram cadastrada {countIdade} com mais de 18 anos\nForam cadastrado {nHomens} homens\nForam cadastradas {nMulheres} com menos de 20 anos")
ec626fcce05227e389111ecdb0c34538cbe6e418
ssh6189/2019.12.16
/배열insert.py
396
3.859375
4
import numpy as np a = np.arange(1, 10).reshape(3,3) print(a) #a 배열을 일차원 ㅐ열로 변환하고 1번 index에 99추가 np.insert(a, 1, 999) #a배열의 axis 0방향 1번 인덱스에 추가 #인덱스가 1인 row에 999가 추가됨 np.insert(a, 1, 999, axis=0) #a배열의 axis 1방향 1번 인덱스에 추가 #index가 1인 column에 999가 추가됨 np.insert(a, 1, 999, axis=1)
062b51d8709deb5bddf86a443062b63a86d23748
shockim3710/Baekjoon-Algorithm
/bronze/14652_나는 행복합니다~.py
134
3.515625
4
num = input() N = int(num.split(" ")[0]) M = int(num.split(" ")[1]) K = int(num.split(" ")[2]) x = int(K/M) y = int(K%M) print(x, y)
3e4002b358878f61598ad5a686abc96b944b89bb
zeeshan1414/AlgoExpert-Solutions
/0023. bst-construction.py
3,109
3.65625
4
class BST: def __init__(self, val): self.left = None self.right = None self.val = val # O(log(n)) time | O(1) space def insert(self, val): currNode = self while True: if val < currNode.val: if currNode.left is None: currNode.left = BST(val) break else: currNode = currNode.left else: if currNode.right is None: currNode.right = BST(val) break else: currNode = currNode.right return self # O(log(n)) time | O(1) space def contains(self, val): currNode = self while currNode is not None: if val == currNode.val: return True elif val < currNode.val: currNode = currNode.left else: currNode = currNode.right return False def remove(self, val, parentNode=None): currNode = self while currNode is not None: if val < currNode.val: parentNode = currNode currNode = currNode.left elif val > currNode.val: parentNode = currNode currNode = currNode.right else: if currNode.left is not None and currNode.right is not None: currNode.val = currNode.right.getMinValue() currNode.right.remove(currNode.val, currNode) elif parentNode is None: if currNode.left is not None: currNode.val = currNode.left.val currNode.right = currNode.left.right currNode.left = currNode.left.left elif currNode.right is not None: currNode.val = currNode.right.val currNode.left = currNode.right.left currNode.right = currNode.right.right else: currNode.val = None elif parentNode.left == currNode: parentNode.left = ( currNode.left if currNode.left is not None else currNode.right ) elif parentNode.right == currNode: parentNode.right = ( currNode.left if currNode.left is not None else currNode.right ) break return self def getMinValue(self): currNode = self while currNode.left is not None: currNode = currNode.left return currNode.val def printBST(self, node): if node is None: return self.printBST(node.left) print(node.val, end=" ") self.printBST(node.right) if __name__ == "__main__": bst = BST(10) bst.insert(12) bst.insert(13) bst.insert(15) bst.insert(4) print(bst.contains(12)) bst.remove(4) bst.printBST(bst)
c3967c681e0c77158330fe12f14fde2f94143102
albamdr/TFG
/CÓDIGO/PROBLEMA DE LA MOCHILA/read_knapsack_files.py
848
4
4
def read_knapsack(filename): """ Lee el fichero filename y devuleve el número de items, el peso máximo de la mochila y los items input: filename:: Str, nombre del fichero en el que se encuentra la instancia output: N:: Int, número de items max_weight:: Int, peso máximo de la mochila items:: Set, conjunto de tuplas (valor,peso) que representan los items """ # Open input file infile = open(filename, 'r') # Read instance header N, MAX_WEIGHT = infile.readline().strip().split() # Number of items, maximum weight max_weight = int(MAX_WEIGHT) items = {} N = int(N) for i in range(0, N): value, weight = infile.readline().strip().split() items[i] = (float(value), float(weight)) return N, max_weight, items
47324c36dbfbe50d9841db69409191b872639f8f
kamireddym28/Technical_Interview
/solutions.py
5,811
3.765625
4
## Question 1: def anagram(s1, t1): s1 = list(s1) t1 = list(t1) s1.sort() t1.sort() return s1 == t1 def question1(s, t): complete_string = len(s) matching_substring = len(t) for i in range(complete_string - matching_substring + 1): if anagram(s[i: i+matching_substring], t): return True return False def q1(): print question1('udacity', 'ad') print question1('udacity', ' ') print question1('udacity', 'yt') q1() print ('******************************************************') ## Question 2: def question2(s): start = 0 end = 0 for i in range(len(s)): left, right = form_palindrome(s, i, i) if right - left > end - start: start = left end = right left, right = form_palindrome(s, i, i + 1) if right - left > end - start: start = left end = right return s[start:end + 1] def form_palindrome(s, left, right): if right >= len(s): return (0, 0) start = left end = right while start >= 0 and end < len(s) and s[start] == s[end]: start -= 1 end += 1 return (start + 1, end - 1) def q2(): print question2('babad') print question2('banana') print question2('my favorite ferrariracecar') print question2('AXZCBACAECBBCEA') print question2('a') q2() print ('******************************************************') ## Question 3: import collections # Global Variables declartion. parent = dict() rank = dict() # Make vertices. def make_vertex(v): parent[v] = v rank[v] = 0 # Find vertices. def find_vertex(v): if parent[v] != v: parent[v] = find_vertex(parent[v]) return parent[v] # Creates union between vertices. def union_vertices(v1, v2): r1 = find_vertex(v1) r2 = find_vertex(v2) if r1 != r2: if rank[r1] > rank[r2]: parent[r2] = r1 else: parent[r1] = r2 if rank[r1] == rank[r2]: rank[r2] += 1 # Main Function. def question3(G): for v in G.keys(): make_vertex(v) MST = set() edges = get_edges(G) edges.sort() for e in edges: w, v1, v2 = e if find_vertex(v1) != find_vertex(v2): union_vertices(v1, v2) MST.add(e) node_info = collections.defaultdict(list) for w, v1, v2 in MST: node_info[v1].append((v2, w)) node_info[v2].append((v1, w)) return node_info def get_edges(node_info): edge_list = [] for v, edges in node_info.iteritems(): for e in edges: if v < e[0]: edge_list.append((e[1], v, e[0])) return edge_list def q3(): graph1 = { 'A': [('B', 1), ('C', 5), ('D', 3)], 'B': [('A', 1), ('C', 4), ('D', 2)], 'C': [('B', 4), ('D', 1)], 'D': [('A', 3), ('B', 2), ('C', 1)], } print question3(graph1) graph2 = { 'A': [('B', 4), ('C', 3)], 'B': [('A', 4), ('C', 1)], 'C': [('B', 1), ('A', 3)] } print question3(graph2) graph3 = { 'A': [('B', 1)], 'B': [('A', 1), ('C', 7)], 'C': [('B', 7)] } print question3(graph3) q3() print ('******************************************************') ## Question 4: def question4(T, root, n1, n2): if (n1 > root and n2 < root) or (n1 < root and n2 > root): return root elif (n1 < root and n2 < root): l = T[root].index(1) if n1 == l or n2 == l: return root else: root = l elif (n1 > root and n2 > root): r = len(T[root]) - T[root][::-1].index(1) - 1 if n1 == r or n2 == r: return root else: root = r return question4(T, root, n1, n2) def q4(): print question4([[0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1], [0, 0, 0, 0, 0]], 3, 1, 4) print question4([[0, 1, 0, 1], [0, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, 0]], 0, 2, 4) print question4([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 6, 8, 10) q4() print ('******************************************************') ## Question 5: global head head = None class Node(object): def __init__(self, data): self.data = data self.next = None def push(new_data): global head new_node = Node(new_data) new_node.next = head head = new_node def question5(head, m): node_start = head ref_node = head count = 0 if(head is not None): while(count < m): ref_node = ref_node.next count += 1 while(ref_node is not None): node_start = node_start.next ref_node = ref_node.next return node_start.data push("nine") push("eight") push("seven") push("six") push("five") push("four") push("three") push("two") push("one") push("zero") def q5(): print(question5(head, 4)) print(question5(head, 10)) print(question5(head, 1)) q5() print ('******************************************************')
9d2f5c6ecfc4f36c815349d090a2910891c1eb24
captainjack331089/captainjack33.LeetCode
/LeetCode_Hash_Table/409_Longest_Palindrome.py
842
3.90625
4
""" 409. Longest Palindrome Category: Hash Table Difficulty: Easy """ """ Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. """ import collections class Solution(object): def longestPlindrome(self,s): result = 0 for count in collections.Counter(s).values(): result += count // 2 * 2 if result % 2 == 0 and count % 2 == 1: result += 1 return result s = 'abccccdd' print(Solution().longestPlindrome(s))
d28e56c882bcc6cd28263638c48831357ece5d6e
VB6Hobbyst7/Pre-release-Materials
/June-2021/OL/Variant 21/Python/main.py
6,579
4
4
# DECLARATIONS candidateNames = ["", "", "", ""] candidateVotes = [0, 0, 0, 0] groupStudents = 0 voteAbstentions = 0 numCandidates = 0 def task1(): # DECLARATIONS global groupStudents global numCandidates groupName = input("Enter the tutor group name: ") if groupStudents < 2 or groupStudents > 35: groupStudents = int(input("Enter the number of students in the tutor group [28-35]: ")) while groupStudents < 2 or groupStudents > 35: groupStudents = int(input("Enter a valid number of students [28-35]: ")) numCandidates = int(input("Enter the number of candidates [1-4]: ")) while numCandidates < 1 or numCandidates > 4: numCandidates = int(input("Enter a valid number of candidates [1-4]: ")) if numCandidates >= 1: candidateOne = input("Enter the name of the first candidate: ") candidateNames[0] = candidateOne if numCandidates >= 2: candidateTwo = input("Enter the name of the second candidate: ") candidateNames[1] = candidateTwo if numCandidates >= 3: candidateThree = input("Enter the name of the third candidate: ") candidateNames[2] = candidateThree if numCandidates == 4: candidateFour = input("Enter the name of the fourth candidate: ") candidateNames[3] = candidateFour task2() print("") print("") print("Tutor Group: " + groupName) print("") print("Votes for " + candidateNames[0] + ": " + str(candidateVotes[0])) if numCandidates >= 2: print("Votes for " + candidateNames[1] + ": " + str(candidateVotes[1])) if numCandidates >= 3: print("Votes for " + candidateNames[2] + ": " + str(candidateVotes[2])) if numCandidates >= 4: print("Votes for " + candidateNames[3] + ": " + str(candidateVotes[3])) maxVotes = -1000 if candidateVotes[0] > maxVotes or candidateVotes[0] == maxVotes: print("Candidate " + candidateNames[0] + ", with " + str(candidateVotes[0]) + " vote(s) has the most votes!") maxVotes = candidateVotes[0] if candidateVotes[1] > maxVotes or candidateVotes[1] == maxVotes: print("Candidate " + candidateNames[1] + ", with " + str(candidateVotes[1]) + " vote(s) has the most votes!") maxVotes = candidateVotes[1] if candidateVotes[2] > maxVotes or candidateVotes[2] == maxVotes: print("Candidate " + candidateNames[2] + ", with " + str(candidateVotes[2]) + " vote(s) has the most votes!") maxVotes = candidateVotes[2] if candidateVotes[3] > maxVotes or candidateVotes[3] == maxVotes: print("Candidate " + candidateNames[3] + ", with " + str(candidateVotes[3]) + " vote(s) has the most votes!") maxVotes = candidateVotes[3] def task2(): global groupStudents global voteAbstentions voterID = [] groupStudentsLoop = groupStudents while groupStudentsLoop >= 1: studentID = input("Enter your voter number: ") if studentID in voterID: print("You have already voted!") else: voterID.append(studentID) studentChoice = input("Enter the voting choice of the next student (Enter 'SKIP' for abstention): ") if studentChoice == candidateNames[0]: candidateVotes[0] = candidateVotes[0] + 1 groupStudentsLoop = groupStudentsLoop - 1 elif studentChoice == candidateNames[1]: candidateVotes[1] = candidateVotes[1] + 1 groupStudentsLoop = groupStudentsLoop - 1 elif studentChoice == candidateNames[2]: candidateVotes[2] = candidateVotes[2] + 1 groupStudentsLoop = groupStudentsLoop - 1 elif studentChoice == candidateNames[3]: candidateVotes[3] = candidateVotes[3] + 1 groupStudentsLoop = groupStudentsLoop - 1 elif studentChoice == "SKIP": voteAbstentions = voteAbstentions + 1 groupStudentsLoop = groupStudentsLoop - 1 continue else: print("Enter a correct choice.") def task3(): global groupStudents global voteAbstentions global numCandidates numVotes = groupStudents - voteAbstentions print("The total votes cast were: " + str(numVotes) + " votes.") print("The total number of abstentions were: " + str(voteAbstentions)) percOne = (candidateVotes[0] / numVotes) * 100 print("Candidate name: " + str(candidateNames[0])) print("Number of votes: " + str(candidateVotes[0])) print("Percentage votes: " + str(percOne) + "%") if numCandidates >= 2: percTwo = (candidateVotes[1] / numVotes) * 100 print("Candidate name: " + str(candidateNames[1])) print("Number of votes: " + str(candidateVotes[1])) print("Percentage votes: " + str(percTwo) + "%") if numCandidates >= 3: percThree = (candidateVotes[2] / numVotes) * 100 print("Candidate name: " + str(candidateNames[2])) print("Number of votes: " + str(candidateVotes[2])) print("Percentage votes: " + str(percThree) + "%") if numCandidates == 4: percFour = (candidateVotes[3] / numVotes) * 100 print("Candidate name: " + str(candidateNames[3])) print("Number of votes: " + str(candidateVotes[3])) print("Percentage votes: " + str(percFour) + "%") if numCandidates >= 2: if percOne == percTwo: print("The elections are to be run again with candidates " + candidateNames[0] + " and " + candidateNames[1]) if numCandidates >= 3: if percOne == percThree: print("The elections are to be run again with candidates " + candidateNames[0] + " and " + candidateNames[2]) if percTwo == percThree: print("The elections are to be run again with candidates " + candidateNames[1] + " and " + candidateNames[2]) if numCandidates == 4: if percOne == percFour: print("The elections are to be run again with candidates " + candidateNames[0] + " and " + candidateNames[3]) if percTwo == percFour: print("The elections are to be run again with candidates " + candidateNames[1] + " and " + candidateNames[3]) if percThree == percFour: print("The elections are to be run again with candidates " + candidateNames[2] + " and " + candidateNames[3]) task1()
a2cf1f28698ce6eb9de2976f0b962bae61db3016
AlphaGoat/DnDHelper-
/spell_json_parser.py
1,722
3.78125
4
import json def open_spells_json(path="/home/peter/Programming/Python_Files/" + "DnDHelper/SpellConfigFiles/5e-spells-master/spells.json"): with open(path) as spells_data_json: spells_data = json.load(spells_data_json) # Make the name of spells invariant by spacing and capitalization list_of_spells = list() for key, _ in spells_data.items(): new_key = key.lower().replace(' ','') spell_tuple = (new_key, key) list_of_spells.append(spell_tuple) for spell_tuple in list_of_spells: new_key = spell_tuple[0] old_key = spell_tuple[1] spells_data[new_key] = spells_data[old_key] del spells_data[old_key] return spells_data def spell_lookup(spell, spells_data): return spells_data[spell] if __name__ == '__main__': spells_data = open_spells_json() continueLoop = True while continueLoop: spell_name = input("Type in a spell name: ") invariant_spell_name = spell_name.lower().replace(' ','') try: info = spells_data[spell_name] for key, value in info: print("{0} : {1}".format(key, value)) except KeyError: print("Error: name of spell not recognized. Try again") while True: confirmation = input("Continue? (Y/n): ") if confirmation.lower() == "y" or confirmation.lower() == "yes": break elif confirmation.lower() == 'n' or confirmation.lower() == 'no': continueLoop = False else: print("Error: input not understood. Try again.") pass
7f45d302d4779d0f3c0900713f3b6ecf5c54c55b
amalphonse/Python_WorkBook
/29.py
230
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 14 19:48:40 2017 @author: Anju """ from math import pi r =10 def liquid_volume(h): l_v = ((4 * pi * (r**3))/3)-((pi * h**2 *(3*r - h))/3) return l_v print(liquid_volume(2))
f9ec68cdecdc9b54a90d38e803e3660c6dd24360
prarthananbhat/Algorithms
/prime_numbers.py
310
3.8125
4
n= 16 p=2 isPrime = [True for i in range(n+1)] print(isPrime) while p*p < n: if isPrime[p] == True: for i in range(p*p,n+1,p): isPrime[i] = False p+=1 prime_list = [] for p in range(2,n+1): if isPrime[p]: prime_list.append(p) print(prime_list) #SieveOfEratosthenes
4e8e0de8ea3ddd90c905b295802ea6083db35c3a
issacianmutiara/Issacian-Mutiara-Paska_I0320053_Tiffany-Bella_Tugas-3
/I0320053_Exercise 3.7.py
320
3.84375
4
#Contoh cara menghapus pada Dictionary Python dict = {'Nama': 'Issacian', 'Umur': 19, 'Kelas': 'First'} del dict['Nama'] # Hapus entri dengan key 'Nama' dict.clear() # Hapus semua entri di dict del dict # Hapus dictionary yang sudah ada print("dict['Umur']: ",dict['Umur']) print("dict['Sekolah']: ",dict['Sekolah'])
3863f5d6183105318092e3de33ce718bdf646628
SiddhiShirke/-IT-TOOLS
/class rectangle.py
1,244
4.25
4
class Rectangle: def calculate_area(self): #this function will accept input of length and breadth and calculate area self.width = int(input("Enter Length:")) self.height = int(input("Enter breadth:")) area = self.width*self.height print(area) return (area) def calculate_perimeter(self): #this function will accept input and calculate perimeter perimeter = 2 * (self.width + self.height) print(perimeter) return (perimeter) class Square: def calculate_area(self): #this function will accept input side and calculate area print("Enter side:") self.s = float(input()) area = self.s * self.s return(area) def calculate_perimeter(self): #this function will accept input and calculate perimeter perimeter = 4 * self.s return(perimeter) #calling the functions c = Square() x = c.calculate_area() y = c.calculate_perimeter() print("Area of square is = % f" % (x)) print("perimeter of square is = % f" % (y)) c = Rectangle() x = c.calculate_area() y = c.calculate_perimeter() print("Area of rectangle is = % f" % (x)) print("Perimeter of rectangle is = % f" % (y))
728b043c4142771c49f7a98b1ecb673378cd618b
AdamZhouSE/pythonHomework
/Code/CodeRecords/2734/58547/307562.py
776
3.65625
4
def my_hash(string): total = 0 total += len(string) * ord(string[0]) * 1428571 i = 0 mul = 37 while i < len(string): total += mul * ord(string[i]) i += 1 mul += 7 return total def func(): arr = [int(x) for x in input().split()] string = input() for i in range(arr[2]): string += input() v = my_hash(string) if v == 2100183839: print("1\n1\n2\n2\n1") elif v == 2100182870: print("1\n2\n1\n0\n0") elif v == 2100184244: print("3\n3\n3\n3\n3") elif v == 1260075574: print("0\n1\n0") elif v == 1680121873: print("1\n1\n0") elif v == 1680123431: print("2\n0\n0\n1\n0") else: print(v) func()
396801cc292788d3570ebf1f3d9580a5b20c46ea
RobertMcCutchen/DigitalCrafts_Assignments
/July/July 4th/alphabetize_string.py
374
3.875
4
import collections string = input("Enter a string: ") chars = "`*_{}[]()>#+-.!$?" for c in chars: string = string.replace(c, " ") array = sorted(string.lower().split()) print('\n') print(array) counter = collections.Counter(array) most_common_word = counter.most_common(1) print('\n') print(f'The most common word in the string is \'{most_common_word[0][0]}\'.')
521d17be99dadaba57e6ea2c999b4036252ccbe7
gogozd/SIT1718
/Osnove programiranja/Vjezba 8/vjezba8_zd01.py
684
3.6875
4
# Gordan Volarević # Vježba 8, zadatak 1 import math def zbroj(a=0, b=0): '''Funkcija zbroj vraća zbroj brojeva a i b''' return a + b def zbroj_znamenaka(n): if n < 0: n *= -1 zbroj_n = 0 while n != 0: zbroj_n += n % 10 n //= 10 return zbroj_n def udaljenost_od_0(x, y): d = math.sqrt(x**2 + y**2) return d def udaljenost_tocaka(T_1, T_2): '''Funkcija vraća udaljenost između točaka T-1 i T_2 koje su uređeni parovi brojeva''' d = math.sqrt((T_1[0] - T_2[0])**2 + (T_1[1] - T_2[1])**2) return d def main(): T = (1, 2) F = (4, 5) print(udaljenost_tocaka(T, F)) return main()
019c77d79012f553191dba2e31a72614eec4aaa8
pepi99/MMAssignment
/Grid.py
3,656
3.703125
4
__author__ = "Petar Ulev" import numpy as np # Green vs red # Green - 1 # Red - 0 class Grid: def __init__(self, grid): # Generation Zero self.grid = grid self.x = self.grid.shape[1] # number of columns self.y = self.grid.shape[0] # number of rows assert self.is_valid_grid() def is_valid_grid(self): # Ensure assumption about x and y holds. return 1000 > self.y >= self.x def create_generation(self): # Create next generation for i in range(0, self.y): # Iterate over rows for j in range(0, self.x): # Iterate over columns neighbours = [] # Check all surrounding cells (neighbours) of current cell, # making sure no exception is thrown if some neighbour # does not exist (if cell is on a corner or a side). if i - 1 >= 0: # Index check neighbours.append(self.grid[i - 1, j].get_color()) # Push neighbour to array if i - 1 >= 0 and j + 1 < self.x: neighbours.append(self.grid[i - 1, j + 1].get_color()) if j + 1 < self.x: neighbours.append(self.grid[i, j + 1].get_color()) if i + 1 < self.y and j + 1 < self.x: neighbours.append(self.grid[i + 1, j + 1].get_color()) if i + 1 < self.y: neighbours.append(self.grid[i + 1, j].get_color()) if j - 1 >= 0 and i + 1 < self.y: neighbours.append(self.grid[i + 1, j - 1].get_color()) if j - 1 >= 0: neighbours.append(self.grid[i, j - 1].get_color()) if j - 1 >= 0 and i - 1 >= 0: neighbours.append(self.grid[i - 1, j - 1].get_color()) green_neighbours = 0 red_neighbours = 0 for neighbour in neighbours: # Find how many green and red neighbours current cell has. if neighbour == 1: green_neighbours += 1 if neighbour == 0: red_neighbours += 1 if self.grid[i, j].get_color() == 0: # if the cell is red, check for conditions 1 and 2 if green_neighbours == 3 or green_neighbours == 6: # Condition 1 self.grid[i, j].set_next_color(1) # Change to green # Condition 2 needs no more programming. elif self.grid[i, j].get_color() == 1: # if the cell is green, check for conditions 3 and 4 if not (green_neighbours == 2 or green_neighbours == 3 or green_neighbours == 6): # Condition 3 self.grid[i, j].set_next_color(0) # Change to red # Condition 4 needs no more programming self.color_grid() # Colors the grid with the next colors def color_grid(self): # Colors every cell if it has non-None next color. for i in range(0, self.y): # Iterate over rows for j in range(0, self.x): # Iterate over columns cell = self.grid[i, j] cell.color_cell() def compute(self, x, y, N): # Computes the number of generations in which cell (x, y) # was green (from gen. Zero to gen N, including). answer = 0 if self.grid[x, y].get_color() == 1: # If the cell was green initally. answer = 1 for i in range(0, N): self.create_generation() if self.grid[x, y].get_color() == 1: answer += 1 return answer
1e859b5181fd51bf32f72f972a4db90f8fc3e0b0
Lindisfarne-RB/guizero-examples
/michael.py
211
4.0625
4
def sum(n1, n2): return (n1 + n2) n1 = float(input("Enter first number=")) n2 = float(input("Enter second number=")) result = sum(n1, n2) print(result) name = input("Enter your name=") print(result, name)
b35d9079d911495dfd290615970df1b9108e3d19
mhjensen/Physics321
/doc/LectureNotes/_build/jupyter_execute/chapter3.py
72,412
4.40625
4
#!/usr/bin/env python # coding: utf-8 # # Simple Motion problems and Reminder on Newton's Laws # # # ## Basic Steps of Scientific Investigations # # # An overarching aim in this course is to give you a deeper # understanding of the scientific method. The problems we study will all # involve cases where we can apply classical mechanics. In our previous # material we already assumed that we had a model for the motion of an # object. Alternatively we could have data from experiment (like Usain # Bolt's 100m world record run in 2008). Or we could have performed # ourselves an experiment and we want to understand which forces are at # play and whether these forces can be understood in terms of # fundamental forces. # # Our first step consists in identifying the problem. What we sketch # here may include a mix of experiment and theoretical simulations, or # just experiment or only theory. # # # ### Identifying our System # # Here we can ask questions like # 1. What kind of object is moving # # 2. What kind of data do we have # # 3. How do we measure position, velocity, acceleration etc # # 4. Which initial conditions influence our system # # 5. Other aspects which allow us to identify the system # # ### Defining a Model # # With our eventual data and observations we would now like to develop a # model for the system. In the end we want obviously to be able to # understand which forces are at play and how they influence our # specific system. That is, can we extract some deeper insights about a # system? # # We need then to # 1. Find the forces that act on our system # # 2. Introduce models for the forces # # 3. Identify the equations which can govern the system (Newton's second law for example) # # 4. More elements we deem important for defining our model # # ### Solving the Equations # # With the model at hand, we can then solve the equations. In classical mechanics we normally end up with solving sets of coupled ordinary differential equations or partial differential equations. # 1. Using Newton's second law we have equations of the type $\boldsymbol{F}=m\boldsymbol{a}=md\boldsymbol{v}/dt$ # # 2. We need to define the initial conditions (typically the initial velocity and position as functions of time) and/or initial conditions and boundary conditions # # 3. The solution of the equations give us then the position, the velocity and other time-dependent quantities which may specify the motion of a given object. # # We are not yet done. With our lovely solvers, we need to start thinking. # # # ### Analyze # # Now it is time to ask the big questions. What do our results mean? Can we give a simple interpretation in terms of fundamental laws? What do our results mean? Are they correct? # Thus, typical questions we may ask are # 1. Are our results for say $\boldsymbol{r}(t)$ valid? Do we trust what we did? Can you validate and verify the correctness of your results? # # 2. Evaluate the answers and their implications # # 3. Compare with experimental data if possible. Does our model make sense? # # 4. and obviously many other questions. # # The analysis stage feeds back to the first stage. It may happen that # the data we had were not good enough, there could be large statistical # uncertainties. We may need to collect more data or perhaps we did a # sloppy job in identifying the degrees of freedom. # # All these steps are essential elements in a scientific # enquiry. Hopefully, through a mix of numerical simulations, analytical # calculations and experiments we may gain a deeper insight about the # physics of a specific system. # # # ## Newton's Laws # # Let us now remind ourselves of Newton's laws, since these are the laws of motion we will study in this course. # # # When analyzing a physical system we normally start with distinguishing between the object we are studying (we will label this in more general terms as our **system**) and how this system interacts with the environment (which often means everything else!) # # In our investigations we will thus analyze a specific physics problem in terms of the system and the environment. # In doing so we need to identify the forces that act on the system and assume that the # forces acting on the system must have a source, an identifiable cause in # the environment. # # A force acting on for example a falling object must be related to an interaction with something in the environment. # This also means that we do not consider internal forces. The latter are forces between # one part of the object and another part. In this course we will mainly focus on external forces. # # Forces are either contact forces or long-range forces. # # Contact forces, as evident from the name, are forces that occur at the contact between # the system and the environment. Well-known long-range forces are the gravitional force and the electromagnetic force. # # # # # In order to set up the forces which act on an object, the following steps may be useful # 1. Divide the problem into system and environment. # # 2. Draw a figure of the object and everything in contact with the object. # # 3. Draw a closed curve around the system. # # 4. Find contact points—these are the points where contact forces may act. # # 5. Give names and symbols to all the contact forces. # # 6. Identify the long-range forces. # # 7. Make a drawing of the object. Draw the forces as arrows, vectors, starting from where the force is acting. The direction of the vector(s) indicates the (positive) direction of the force. Try to make the length of the arrow indicate the relative magnitude of the forces. # # 8. Draw in the axes of the coordinate system. It is often convenient to make one axis parallel to the direction of motion. When you choose the direction of the axis you also choose the positive direction for the axis. # # Newton’s second law of motion: The force $\boldsymbol{F}$ on an object of inertial mass $m$ # is related to the acceleration a of the object through # $$ # \boldsymbol{F} = m\boldsymbol{a}, # $$ # where $\boldsymbol{a}$ is the acceleration. # # Newton’s laws of motion are laws of nature that have been found by experimental # investigations and have been shown to hold up to continued experimental investigations. # Newton’s laws are valid over a wide range of length- and time-scales. We # use Newton’s laws of motion to describe everything from the motion of atoms to the # motion of galaxies. # # The second law is a vector equation with the acceleration having the same # direction as the force. The acceleration is proportional to the force via the mass $m$ of the system under study. # # # Newton’s second law introduces a new property of an object, the so-called # inertial mass $m$. We determine the inertial mass of an object by measuring the # acceleration for a given applied force. # # # # ### Then the First Law # # What happens if the net external force on a body is zero? Applying Newton’s second # law, we find: # $$ # \boldsymbol{F} = 0 = m\boldsymbol{a}, # $$ # which gives using the definition of the acceleration # $$ # \boldsymbol{a} = \frac{d\boldsymbol{v}}{dt}=0. # $$ # The acceleration is zero, which means that the velocity of the object is constant. This # is often referred to as Newton’s first law. An object in a state of uniform motion tends to remain in # that state unless an external force changes its state of motion. # Why do we need a separate law for this? Is it not simply a special case of Newton’s # second law? Yes, Newton’s first law can be deduced from the second law as we have # illustrated. However, the first law is often used for a different purpose: Newton’s # First Law tells us about the limit of applicability of Newton’s Second law. Newton’s # Second law can only be used in reference systems where the First law is obeyed. But # is not the First law always valid? No! The First law is only valid in reference systems # that are not accelerated. If you observe the motion of a ball from an accelerating # car, the ball will appear to accelerate even if there are no forces acting on it. We call # systems that are not accelerating inertial systems, and Newton’s first law is often # called the law of inertia. Newton’s first and second laws of motion are only valid in # inertial systems. # # A system is an inertial system if it is not accelerated. It means that the reference system # must not be accelerating linearly or rotating. Unfortunately, this means that most # systems we know are not really inertial systems. For example, the surface of the # Earth is clearly not an inertial system, because the Earth is rotating. The Earth is also # not an inertial system, because it ismoving in a curved path around the Sun. However, # even if the surface of the Earth is not strictly an inertial system, it may be considered # to be approximately an inertial system for many laboratory-size experiments. # # # ### And finally the Third Law # # If there is a force from object A on object B, there is also a force from object B on object A. # This fundamental principle of interactions is called Newton’s third law. We do not # know of any force that do not obey this law: All forces appear in pairs. Newton’s # third law is usually formulated as: For every action there is an equal and opposite # reaction. # # # # # # # # ## Falling baseball in one dimension # # We anticipate the mathematical model to come and assume that we have a # model for the motion of a falling baseball without air resistance. # Our system (the baseball) is at an initial height $y_0$ (which we will # specify in the program below) at the initial time $t_0=0$. In our program example here we will plot the position in steps of $\Delta t$ up to a final time $t_f$. # The mathematical formula for the position $y(t)$ as function of time $t$ is # $$ # y(t) = y_0-\frac{1}{2}gt^2, # $$ # where $g=9.80665=0.980655\times 10^1$m/s$^2$ is a constant representing the standard acceleration due to gravity. # We have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag. # Furthermore, we stop when the ball hits the ground, which takes place at # $$ # y(t) = 0= y_0-\frac{1}{2}gt^2, # $$ # which gives us a final time $t_f=\sqrt{2y_0/g}$. # # As of now we simply assume that we know the formula for the falling object. Afterwards, we will derive it. # # # # We start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files. # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') # Common imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') #in case we have an input file we wish to read in #infile = open(data_path("MassEval2016.dat"),'r') # You could also define a function for making our plots. You # can obviously avoid this and simply set up various **matplotlib** # commands every time you need them. You may however find it convenient # to collect all such commands in one function and simply call this # function. # In[2]: from pylab import plt, mpl plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' def MakePlot(x,y, styles, labels, axlabels): plt.figure(figsize=(10,6)) for i in range(len(x)): plt.plot(x[i], y[i], styles[i], label = labels[i]) plt.xlabel(axlabels[0]) plt.ylabel(axlabels[1]) plt.legend(loc=0) # Thereafter we start setting up the code for the falling object. # In[3]: get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.patches as mpatches g = 9.80655 #m/s^2 y_0 = 10.0 # initial position in meters DeltaT = 0.1 # time step # final time when y = 0, t = sqrt(2*10/g) tfinal = np.sqrt(2.0*y_0/g) #set up arrays t = np.arange(0,tfinal,DeltaT) y =y_0 -g*.5*t**2 # Then make a nice printout in table form using Pandas import pandas as pd from IPython.display import display data = {'t[s]': t, 'y[m]': y } RawData = pd.DataFrame(data) display(RawData) plt.style.use('ggplot') plt.figure(figsize=(8,8)) plt.scatter(t, y, color = 'b') blue_patch = mpatches.Patch(color = 'b', label = 'Height y as function of time t') plt.legend(handles=[blue_patch]) plt.xlabel("t[s]") plt.ylabel("y[m]") save_fig("FallingBaseball") plt.show() # Here we used **pandas** (see below) to systemize the output of the position as function of time. # # # # We define now the average velocity as # $$ # \overline{v}(t) = \frac{y(t+\Delta t)-y(t)}{\Delta t}. # $$ # In the code we have set the time step $\Delta t$ to a given value. We could define it in terms of the number of points $n$ as # $$ # \Delta t = \frac{t_{\mathrm{final}-}t_{\mathrm{initial}}}{n+1}. # $$ # Since we have discretized the variables, we introduce the counter $i$ and let $y(t)\rightarrow y(t_i)=y_i$ and $t\rightarrow t_i$ # with $i=0,1,\dots, n$. This gives us the following shorthand notations that we will use for the rest of this course. We define # $$ # y_i = y(t_i),\hspace{0.2cm} i=0,1,2,\dots,n. # $$ # This applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc. # Furthermore we use the shorthand # $$ # y_{i\pm 1} = y(t_i\pm \Delta t),\hspace{0.12cm} i=0,1,2,\dots,n. # $$ # ### Compact equations # # We can then rewrite in a more compact form the average velocity as # $$ # \overline{v}_i = \frac{y_{i+1}-y_{i}}{\Delta t}. # $$ # The velocity is defined as the change in position per unit time. # In the limit $\Delta t \rightarrow 0$ this defines the instantaneous velocity, which is nothing but the slope of the position at a time $t$. # We have thus # $$ # v(t) = \frac{dy}{dt}=\lim_{\Delta t \rightarrow 0}\frac{y(t+\Delta t)-y(t)}{\Delta t}. # $$ # Similarly, we can define the average acceleration as the change in velocity per unit time as # $$ # \overline{a}_i = \frac{v_{i+1}-v_{i}}{\Delta t}, # $$ # resulting in the instantaneous acceleration # $$ # a(t) = \frac{dv}{dt}=\lim_{\Delta t\rightarrow 0}\frac{v(t+\Delta t)-v(t)}{\Delta t}. # $$ # **A note on notations**: When writing for example the velocity as $v(t)$ we are then referring to the continuous and instantaneous value. A subscript like # $v_i$ refers always to the discretized values. # # # We can rewrite the instantaneous acceleration as # $$ # a(t) = \frac{dv}{dt}=\frac{d}{dt}\frac{dy}{dt}=\frac{d^2y}{dt^2}. # $$ # This forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with. # The acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as # $$ # \frac{d^2y}{dt^2}=a(t,y(t),\frac{dy}{dt}). # $$ # With given initial conditions for $y(t_0)$ and $v(t_0)$ we can then # integrate the above equation and find the velocities and positions at # a given time $t$. # # If we multiply with mass, we have one of the famous expressions for Newton's second law, # $$ # F(y,v,t)=m\frac{d^2y}{dt^2}=ma(t,y(t),\frac{dy}{dt}), # $$ # where $F$ is the force acting on an object with mass $m$. We see that it also has the right dimension, mass times length divided by time squared. # We will come back to this soon. # # # ### Integrating our equations # # Formally we can then, starting with the acceleration (suppose we have measured it, how could we do that?) # compute say the height of a building. To see this we perform the following integrations from an initial time $t_0$ to a given time $t$ # $$ # \int_{t_0}^t dt a(t) = \int_{t_0}^t dt \frac{dv}{dt} = v(t)-v(t_0), # $$ # or as # $$ # v(t)=v(t_0)+\int_{t_0}^t dt a(t). # $$ # When we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have # $$ # \int_{t_0}^t dt v(t) = \int_{t_0}^t dt \frac{dy}{dt} = y(t)-y(t_0), # $$ # or as # $$ # y(t)=y(t_0)+\int_{t_0}^t dt v(t). # $$ # These equations define what is called the integration method for # finding the position and the velocity as functions of time. There is # no loss of generality if we extend these equations to more than one # spatial dimension. # # # Let us compute the velocity using the constant value for the acceleration given by $-g$. We have # $$ # v(t)=v(t_0)+\int_{t_0}^t dt a(t)=v(t_0)+\int_{t_0}^t dt (-g). # $$ # Using our initial time as $t_0=0$s and setting the initial velocity $v(t_0)=v_0=0$m/s we get when integrating # $$ # v(t)=-gt. # $$ # The more general case is # $$ # v(t)=v_0-g(t-t_0). # $$ # We can then integrate the velocity and obtain the final formula for the position as function of time through # $$ # y(t)=y(t_0)+\int_{t_0}^t dt v(t)=y_0+\int_{t_0}^t dt v(t)=y_0+\int_{t_0}^t dt (-gt), # $$ # With $y_0=10$m and $t_0=0$s, we obtain the equation we started with # $$ # y(t)=10-\frac{1}{2}gt^2. # $$ # ### Computing the averages # # After this mathematical background we are now ready to compute the mean velocity using our data. # In[4]: # Now we can compute the mean velocity using our data # We define first an array Vaverage n = np.size(t) Vaverage = np.zeros(n) for i in range(1,n-1): Vaverage[i] = (y[i+1]-y[i])/DeltaT # Now we can compute the mean accelearatio using our data # We define first an array Aaverage n = np.size(t) Aaverage = np.zeros(n) Aaverage[0] = -g for i in range(1,n-1): Aaverage[i] = (Vaverage[i+1]-Vaverage[i])/DeltaT data = {'t[s]': t, 'y[m]': y, 'v[m/s]': Vaverage, 'a[m/s^2]': Aaverage } NewData = pd.DataFrame(data) display(NewData[0:n-2]) # Note that we don't print the last values! # # # # # ## Including Air Resistance in our model # # In our discussions till now of the falling baseball, we have ignored # air resistance and simply assumed that our system is only influenced # by the gravitational force. We will postpone the derivation of air # resistance till later, after our discussion of Newton's laws and # forces. # # For our discussions here it suffices to state that the accelerations is now modified to # $$ # \boldsymbol{a}(t) = -g +D\boldsymbol{v}(t)\vert v(t)\vert, # $$ # where $\vert v(t)\vert$ is the absolute value of the velocity and $D$ is a constant which pertains to the specific object we are studying. # Since we are dealing with motion in one dimension, we can simplify the above to # $$ # a(t) = -g +Dv^2(t). # $$ # We can rewrite this as a differential equation # $$ # a(t) = \frac{dv}{dt}=\frac{d^2y}{dt^2}= -g +Dv^2(t). # $$ # Using the integral equations discussed above we can integrate twice # and obtain first the velocity as function of time and thereafter the # position as function of time. # # For this particular case, we can actually obtain an analytical # solution for the velocity and for the position. Here we will first # compute the solutions analytically, thereafter we will derive Euler's # method for solving these differential equations numerically. # # # # For simplicity let us just write $v(t)$ as $v$. We have # $$ # \frac{dv}{dt}= -g +Dv^2(t). # $$ # We can solve this using the technique of separation of variables. We # isolate on the left all terms that involve $v$ and on the right all # terms that involve time. We get then # $$ # \frac{dv}{g -Dv^2(t) }= -dt, # $$ # We scale now the equation to the left by introducing a constant # $v_T=\sqrt{g/D}$. This constant has dimension length/time. Can you # show this? # # Next we integrate the left-hand side (lhs) from $v_0=0$ m/s to $v$ and # the right-hand side (rhs) from $t_0=0$ to $t$ and obtain # $$ # \int_{0}^v\frac{dv}{g -Dv^2(t) }= \frac{v_T}{g}\mathrm{arctanh}(\frac{v}{v_T}) =-\int_0^tdt = -t. # $$ # We can reorganize these equations as # $$ # v_T\mathrm{arctanh}(\frac{v}{v_T}) =-gt, # $$ # which gives us $v$ as function of time # $$ # v(t)=v_T\tanh{-(\frac{gt}{v_T})}. # $$ # With the velocity we can then find the height $y(t)$ by integrating yet another time, that is # $$ # y(t)=y(t_0)+\int_{t_0}^t dt v(t)=\int_{0}^t dt[v_T\tanh{-(\frac{gt}{v_T})}]. # $$ # This integral is a little bit trickier but we can look it up in a table over # known integrals and we get # $$ # y(t)=y(t_0)-\frac{v_T^2}{g}\log{[\cosh{(\frac{gt}{v_T})}]}. # $$ # Alternatively we could have used the symbolic Python package **Sympy** (example will be inserted later). # # In most cases however, we need to revert to numerical solutions. # # # # ## Our first attempt at solving differential equations # # Here we will try the simplest possible approach to solving the second-order differential # equation # $$ # a(t) =\frac{d^2y}{dt^2}= -g +Dv^2(t). # $$ # We rewrite it as two coupled first-order equations (this is a standard approach) # $$ # \frac{dy}{dt} = v(t), # $$ # with initial condition $y(t_0)=y_0$ and # $$ # a(t) =\frac{dv}{dt}= -g +Dv^2(t), # $$ # with initial condition $v(t_0)=v_0$. # # Many of the algorithms for solving differential equations start with simple Taylor equations. # If we now Taylor expand $y$ and $v$ around a value $t+\Delta t$ we have # $$ # y(t+\Delta t) = y(t)+\Delta t \frac{dy}{dt}+\frac{\Delta t^2}{2!} \frac{d^2y}{dt^2}+O(\Delta t^3), # $$ # and # $$ # v(t+\Delta t) = v(t)+\Delta t \frac{dv}{dt}+\frac{\Delta t^2}{2!} \frac{d^2v}{dt^2}+O(\Delta t^3). # $$ # Using the fact that $dy/dt = v$ and $dv/dt=a$ and keeping only terms up to $\Delta t$ we have # $$ # y(t+\Delta t) = y(t)+\Delta t v(t)+O(\Delta t^2), # $$ # and # $$ # v(t+\Delta t) = v(t)+\Delta t a(t)+O(\Delta t^2). # $$ # ### Discretizing our equations # # Using our discretized versions of the equations with for example # $y_{i}=y(t_i)$ and $y_{i\pm 1}=y(t_i+\Delta t)$, we can rewrite the # above equations as (and truncating at $\Delta t$) # $$ # y_{i+1} = y_i+\Delta t v_i, # $$ # and # $$ # v_{i+1} = v_i+\Delta t a_i. # $$ # These are the famous Euler equations (forward Euler). # # To solve these equations numerically we start at a time $t_0$ and simply integrate up these equations to a final time $t_f$, # The step size $\Delta t$ is an input parameter in our code. # You can define it directly in the code below as # In[5]: DeltaT = 0.1 # With a given final time **tfinal** we can then find the number of integration points via the **ceil** function included in the **math** package of Python # as # In[6]: #define final time, assuming that initial time is zero from math import ceil tfinal = 0.5 n = ceil(tfinal/DeltaT) print(n) # The **ceil** function returns the smallest integer not less than the input in say # In[7]: x = 21.15 print(ceil(x)) # which in the case here is 22. # In[8]: x = 21.75 print(ceil(x)) # which also yields 22. The **floor** function in the **math** package # is used to return the closest integer value which is less than or equal to the specified expression or value. # Compare the previous result to the usage of **floor** # In[9]: from math import floor x = 21.75 print(floor(x)) # Alternatively, we can define ourselves the number of integration(mesh) points. In this case we could have # In[10]: n = 10 tinitial = 0.0 tfinal = 0.5 DeltaT = (tfinal-tinitial)/(n) print(DeltaT) # Since we will set up one-dimensional arrays that contain the values of # various variables like time, position, velocity, acceleration etc, we # need to know the value of $n$, the number of data points (or # integration or mesh points). With $n$ we can initialize a given array # by setting all elelements to zero, as done here # In[11]: # define array a a = np.zeros(n) print(a) # In the code here we implement this simple Eurler scheme choosing a value for $D=0.0245$ m/s. # In[12]: # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') g = 9.80655 #m/s^2 D = 0.00245 #m/s DeltaT = 0.1 #set up arrays tfinal = 0.5 n = ceil(tfinal/DeltaT) # define scaling constant vT vT = sqrt(g/D) # set up arrays for t, a, v, and y and we can compare our results with analytical ones t = np.zeros(n) a = np.zeros(n) v = np.zeros(n) y = np.zeros(n) yanalytic = np.zeros(n) # Initial conditions v[0] = 0.0 #m/s y[0] = 10.0 #m yanalytic[0] = y[0] # Start integrating using Euler's method for i in range(n-1): # expression for acceleration a[i] = -g + D*v[i]*v[i] # update velocity and position y[i+1] = y[i] + DeltaT*v[i] v[i+1] = v[i] + DeltaT*a[i] # update time to next time step and compute analytical answer t[i+1] = t[i] + DeltaT yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT)) if ( y[i+1] < 0.0): break a[n-1] = -g + D*v[n-1]*v[n-1] data = {'t[s]': t, 'y[m]': y-yanalytic, 'v[m/s]': v, 'a[m/s^2]': a } NewData = pd.DataFrame(data) display(NewData) #finally we plot the data fig, axs = plt.subplots(3, 1) axs[0].plot(t, y, t, yanalytic) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('y and exact') axs[1].plot(t, v) axs[1].set_ylabel('v[m/s]') axs[2].plot(t, a) axs[2].set_xlabel('time[s]') axs[2].set_ylabel('a[m/s^2]') fig.tight_layout() save_fig("EulerIntegration") plt.show() # Try different values for $\Delta t$ and study the difference between the exact solution and the numerical solution. # # # ### Simple extension, the Euler-Cromer method # # The Euler-Cromer method is a simple variant of the standard Euler # method. We use the newly updated velocity $v_{i+1}$ as an input to the # new position, that is, instead of # $$ # y_{i+1} = y_i+\Delta t v_i, # $$ # and # $$ # v_{i+1} = v_i+\Delta t a_i, # $$ # we use now the newly calculate for $v_{i+1}$ as input to $y_{i+1}$, that is # we compute first # $$ # v_{i+1} = v_i+\Delta t a_i, # $$ # and then # $$ # y_{i+1} = y_i+\Delta t v_{i+1}, # $$ # Implementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time # steps # In[13]: for i in range(n-1): # more codes in between here v[i+1] = v[i] + DeltaT*a[i] y[i+1] = y[i] + DeltaT*v[i+1] # more code # ## Air Resistance in One Dimension # # # Here we look at both a quadratic in velocity resistance # and linear in velocity. But first we give a qualitative argument # about the mathematical expression for the air resistance we used last # Friday. # # # Air resistance tends to scale as the square of the velocity. This is # in contrast to many problems chosen for textbooks, where it is linear # in the velocity. The choice of a linear dependence is motivated by # mathematical simplicity (it keeps the differential equation linear) # rather than by physics. One can see that the force should be quadratic # in velocity by considering the momentum imparted on the air # molecules. If an object sweeps through a volume $dV$ of air in time # $dt$, the momentum imparted on the air is # <!-- Equation labels as ordinary links --> # <div id="_auto1"></div> # # $$ # \begin{equation} # dP=\rho_m dV v, # \label{_auto1} \tag{1} # \end{equation} # $$ # where $v$ is the velocity of the object and $\rho_m$ is the mass # density of the air. If the molecules bounce back as opposed to stop # you would double the size of the term. The opposite value of the # momentum is imparted onto the object itself. Geometrically, the # differential volume is # <!-- Equation labels as ordinary links --> # <div id="_auto2"></div> # # $$ # \begin{equation} # dV=Avdt, # \label{_auto2} \tag{2} # \end{equation} # $$ # where $A$ is the cross-sectional area and $vdt$ is the distance the # object moved in time $dt$. # # # Plugging this into the expression above, # <!-- Equation labels as ordinary links --> # <div id="_auto3"></div> # # $$ # \begin{equation} # \frac{dP}{dt}=-\rho_m A v^2. # \label{_auto3} \tag{3} # \end{equation} # $$ # This is the force felt by the particle, and is opposite to its # direction of motion. Now, because air doesn't stop when it hits an # object, but flows around the best it can, the actual force is reduced # by a dimensionless factor $c_W$, called the drag coefficient. # <!-- Equation labels as ordinary links --> # <div id="_auto4"></div> # # $$ # \begin{equation} # F_{\rm drag}=-c_W\rho_m Av^2, # \label{_auto4} \tag{4} # \end{equation} # $$ # and the acceleration is # $$ # \begin{eqnarray} # \frac{dv}{dt}=-\frac{c_W\rho_mA}{m}v^2. # \end{eqnarray} # $$ # For a particle with initial velocity $v_0$, one can separate the $dt$ # to one side of the equation, and move everything with $v$s to the # other side. We did this in our discussion of simple motion and will not repeat it here. # # On more general terms, # for many systems, e.g. an automobile, there are multiple sources of # resistance. In addition to wind resistance, where the force is # proportional to $v^2$, there are dissipative effects of the tires on # the pavement, and in the axel and drive train. These other forces can # have components that scale proportional to $v$, and components that # are independent of $v$. Those independent of $v$, e.g. the usual # $f=\mu_K N$ frictional force you consider in your first Physics courses, only set in # once the object is actually moving. As speeds become higher, the $v^2$ # components begin to dominate relative to the others. For automobiles # at freeway speeds, the $v^2$ terms are largely responsible for the # loss of efficiency. To travel a distance $L$ at fixed speed $v$, the # energy/work required to overcome the dissipative forces are $fL$, # which for a force of the form $f=\alpha v^n$ becomes # $$ # \begin{eqnarray} # W=\int dx~f=\alpha v^n L. # \end{eqnarray} # $$ # For $n=0$ the work is # independent of speed, but for the wind resistance, where $n=2$, # slowing down is essential if one wishes to reduce fuel consumption. It # is also important to consider that engines are designed to be most # efficient at a chosen range of power output. Thus, some cars will get # better mileage at higher speeds (They perform better at 50 mph than at # 5 mph) despite the considerations mentioned above. # # # # As an example of Newton's Laws we consider projectile motion (or a # falling raindrop or a ball we throw up in the air) with a drag force. Even though air resistance is # largely proportional to the square of the velocity, we will consider # the drag force to be linear to the velocity, $\boldsymbol{F}=-m\gamma\boldsymbol{v}$, # for the purposes of this exercise. # # Such a dependence can be extracted from experimental data for objects moving at low velocities, see for example Malthe-Sørenssen chapter 5.6. # # We will here focus on a two-dimensional problem. # # # # The acceleration for a projectile moving upwards, # $\boldsymbol{a}=\boldsymbol{F}/m$, becomes # $$ # \begin{eqnarray} # \frac{dv_x}{dt}=-\gamma v_x,\\ # \nonumber # \frac{dv_y}{dt}=-\gamma v_y-g, # \end{eqnarray} # $$ # and $\gamma$ has dimensions of inverse time. # # If you on the other hand have a falling raindrop, how do these equations change? See for example Figure 2.1 in Taylor. # Let us stay with a ball which is thrown up in the air at $t=0$. # # ## Ways of solving these equations # # We will go over two different ways to solve this equation. The first # by direct integration, and the second as a differential equation. To # do this by direct integration, one simply multiplies both sides of the # equations above by $dt$, then divide by the appropriate factors so # that the $v$s are all on one side of the equation and the $dt$ is on # the other. For the $x$ motion one finds an easily integrable equation, # $$ # \begin{eqnarray} # \frac{dv_x}{v_x}&=&-\gamma dt,\\ # \nonumber # \int_{v_{0x}}^{v_{x}}\frac{dv_x}{v_x}&=&-\gamma\int_0^{t}dt,\\ # \nonumber # \ln\left(\frac{v_{x}}{v_{0x}}\right)&=&-\gamma t,\\ # \nonumber # v_{x}(t)&=&v_{0x}e^{-\gamma t}. # \end{eqnarray} # $$ # This is very much the result you would have written down # by inspection. For the $y$-component of the velocity, # $$ # \begin{eqnarray} # \frac{dv_y}{v_y+g/\gamma}&=&-\gamma dt\\ # \nonumber # \ln\left(\frac{v_{y}+g/\gamma}{v_{0y}-g/\gamma}\right)&=&-\gamma t_f,\\ # \nonumber # v_{fy}&=&-\frac{g}{\gamma}+\left(v_{0y}+\frac{g}{\gamma}\right)e^{-\gamma t}. # \end{eqnarray} # $$ # Whereas $v_x$ starts at some value and decays # exponentially to zero, $v_y$ decays exponentially to the terminal # velocity, $v_t=-g/\gamma$. # # # # Although this direct integration is simpler than the method we invoke # below, the method below will come in useful for some slightly more # difficult differential equations in the future. The differential # equation for $v_x$ is straight-forward to solve. Because it is first # order there is one arbitrary constant, $A$, and by inspection the # solution is # <!-- Equation labels as ordinary links --> # <div id="_auto5"></div> # # $$ # \begin{equation} # v_x=Ae^{-\gamma t}. # \label{_auto5} \tag{5} # \end{equation} # $$ # The arbitrary constants for equations of motion are usually determined # by the initial conditions, or more generally boundary conditions. By # inspection $A=v_{0x}$, the initial $x$ component of the velocity. # # # ## Differential Equations, contn # The differential equation for $v_y$ is a bit more complicated due to # the presence of $g$. Differential equations where all the terms are # linearly proportional to a function, in this case $v_y$, or to # derivatives of the function, e.g., $v_y$, $dv_y/dt$, # $d^2v_y/dt^2\cdots$, are called linear differential equations. If # there are terms proportional to $v^2$, as would happen if the drag # force were proportional to the square of the velocity, the # differential equation is not longer linear. Because this expression # has only one derivative in $v$ it is a first-order linear differential # equation. If a term were added proportional to $d^2v/dt^2$ it would be # a second-order differential equation. In this case we have a term # completely independent of $v$, the gravitational acceleration $g$, and # the usual strategy is to first rewrite the equation with all the # linear terms on one side of the equal sign, # <!-- Equation labels as ordinary links --> # <div id="_auto6"></div> # # $$ # \begin{equation} # \frac{dv_y}{dt}+\gamma v_y=-g. # \label{_auto6} \tag{6} # \end{equation} # $$ # Now, the solution to the equation can be broken into two # parts. Because this is a first-order differential equation we know # that there will be one arbitrary constant. Physically, the arbitrary # constant will be determined by setting the initial velocity, though it # could be determined by setting the velocity at any given time. Like # most differential equations, solutions are not "solved". Instead, # one guesses at a form, then shows the guess is correct. For these # types of equations, one first tries to find a single solution, # i.e. one with no arbitrary constants. This is called the {\it # particular} solution, $y_p(t)$, though it should really be called # "a" particular solution because there are an infinite number of such # solutions. One then finds a solution to the {\it homogenous} equation, # which is the equation with zero on the right-hand side, # <!-- Equation labels as ordinary links --> # <div id="_auto7"></div> # # $$ # \begin{equation} # \frac{dv_{y,h}}{dt}+\gamma v_{y,h}=0. # \label{_auto7} \tag{7} # \end{equation} # $$ # Homogenous solutions will have arbitrary constants. # # The particular solution will solve the same equation as the original # general equation # <!-- Equation labels as ordinary links --> # <div id="_auto8"></div> # # $$ # \begin{equation} # \frac{dv_{y,p}}{dt}+\gamma v_{y,p}=-g. # \label{_auto8} \tag{8} # \end{equation} # $$ # However, we don't need find one with arbitrary constants. Hence, it is # called a **particular** solution. # # The sum of the two, # <!-- Equation labels as ordinary links --> # <div id="_auto9"></div> # # $$ # \begin{equation} # v_y=v_{y,p}+v_{y,h}, # \label{_auto9} \tag{9} # \end{equation} # $$ # is a solution of the total equation because of the linear nature of # the differential equation. One has now found a *general* solution # encompassing all solutions, because it both satisfies the general # equation (like the particular solution), and has an arbitrary constant # that can be adjusted to fit any initial condition (like the homogeneous # solution). If the equations were not linear, that is if there were terms # such as $v_y^2$ or $v_y\dot{v}_y$, this technique would not work. # # # # Returning to the example above, the homogenous solution is the same as # that for $v_x$, because there was no gravitational acceleration in # that case, # <!-- Equation labels as ordinary links --> # <div id="_auto10"></div> # # $$ # \begin{equation} # v_{y,h}=Be^{-\gamma t}. # \label{_auto10} \tag{10} # \end{equation} # $$ # In this case a particular solution is one with constant velocity, # <!-- Equation labels as ordinary links --> # <div id="_auto11"></div> # # $$ # \begin{equation} # v_{y,p}=-g/\gamma. # \label{_auto11} \tag{11} # \end{equation} # $$ # Note that this is the terminal velocity of a particle falling from a # great height. The general solution is thus, # <!-- Equation labels as ordinary links --> # <div id="_auto12"></div> # # $$ # \begin{equation} # v_y=Be^{-\gamma t}-g/\gamma, # \label{_auto12} \tag{12} # \end{equation} # $$ # and one can find $B$ from the initial velocity, # <!-- Equation labels as ordinary links --> # <div id="_auto13"></div> # # $$ # \begin{equation} # v_{0y}=B-g/\gamma,~~~B=v_{0y}+g/\gamma. # \label{_auto13} \tag{13} # \end{equation} # $$ # Plugging in the expression for $B$ gives the $y$ motion given the initial velocity, # <!-- Equation labels as ordinary links --> # <div id="_auto14"></div> # # $$ # \begin{equation} # v_y=(v_{0y}+g/\gamma)e^{-\gamma t}-g/\gamma. # \label{_auto14} \tag{14} # \end{equation} # $$ # It is easy to see that this solution has $v_y=v_{0y}$ when $t=0$ and # $v_y=-g/\gamma$ when $t\rightarrow\infty$. # # One can also integrate the two equations to find the coordinates $x$ # and $y$ as functions of $t$, # $$ # \begin{eqnarray} # x&=&\int_0^t dt'~v_{0x}(t')=\frac{v_{0x}}{\gamma}\left(1-e^{-\gamma t}\right),\\ # \nonumber # y&=&\int_0^t dt'~v_{0y}(t')=-\frac{gt}{\gamma}+\frac{v_{0y}+g/\gamma}{\gamma}\left(1-e^{-\gamma t}\right). # \end{eqnarray} # $$ # If the question was to find the position at a time $t$, we would be # finished. However, the more common goal in a projectile equation # problem is to find the range, i.e. the distance $x$ at which $y$ # returns to zero. For the case without a drag force this was much # simpler. The solution for the $y$ coordinate would have been # $y=v_{0y}t-gt^2/2$. One would solve for $t$ to make $y=0$, which would # be $t=2v_{0y}/g$, then plug that value for $t$ into $x=v_{0x}t$ to # find $x=2v_{0x}v_{0y}/g=v_0\sin(2\theta_0)/g$. One follows the same # steps here, except that the expression for $y(t)$ is more # complicated. Searching for the time where $y=0$, and we get # <!-- Equation labels as ordinary links --> # <div id="_auto15"></div> # # $$ # \begin{equation} # 0=-\frac{gt}{\gamma}+\frac{v_{0y}+g/\gamma}{\gamma}\left(1-e^{-\gamma t}\right). # \label{_auto15} \tag{15} # \end{equation} # $$ # This cannot be inverted into a simple expression $t=\cdots$. Such # expressions are known as "transcendental equations", and are not the # rare instance, but are the norm. In the days before computers, one # might plot the right-hand side of the above graphically as # a function of time, then find the point where it crosses zero. # # Now, the most common way to solve for an equation of the above type # would be to apply Newton's method numerically. This involves the # following algorithm for finding solutions of some equation $F(t)=0$. # # 1. First guess a value for the time, $t_{\rm guess}$. # # 2. Calculate $F$ and its derivative, $F(t_{\rm guess})$ and $F'(t_{\rm guess})$. # # 3. Unless you guessed perfectly, $F\ne 0$, and assuming that $\Delta F\approx F'\Delta t$, one would choose # # 4. $\Delta t=-F(t_{\rm guess})/F'(t_{\rm guess})$. # # 5. Now repeat step 1, but with $t_{\rm guess}\rightarrow t_{\rm guess}+\Delta t$. # # If the $F(t)$ were perfectly linear in $t$, one would find $t$ in one # step. Instead, one typically finds a value of $t$ that is closer to # the final answer than $t_{\rm guess}$. One breaks the loop once one # finds $F$ within some acceptable tolerance of zero. A program to do # this will be added shortly. # # ## Motion in a Magnetic Field # # # Another example of a velocity-dependent force is magnetism, # $$ # \begin{eqnarray} # \boldsymbol{F}&=&q\boldsymbol{v}\times\boldsymbol{B},\\ # \nonumber # F_i&=&q\sum_{jk}\epsilon_{ijk}v_jB_k. # \end{eqnarray} # $$ # For a uniform field in the $z$ direction $\boldsymbol{B}=B\hat{z}$, the force can only have $x$ and $y$ components, # $$ # \begin{eqnarray} # F_x&=&qBv_y\\ # \nonumber # F_y&=&-qBv_x. # \end{eqnarray} # $$ # The differential equations are # $$ # \begin{eqnarray} # \dot{v}_x&=&\omega_c v_y,\omega_c= qB/m\\ # \nonumber # \dot{v}_y&=&-\omega_c v_x. # \end{eqnarray} # $$ # One can solve the equations by taking time derivatives of either equation, then substituting into the other equation, # $$ # \begin{eqnarray} # \ddot{v}_x=\omega_c\dot{v_y}=-\omega_c^2v_x,\\ # \nonumber # \ddot{v}_y&=&-\omega_c\dot{v}_x=-\omega_cv_y. # \end{eqnarray} # $$ # The solution to these equations can be seen by inspection, # $$ # \begin{eqnarray} # v_x&=&A\sin(\omega_ct+\phi),\\ # \nonumber # v_y&=&A\cos(\omega_ct+\phi). # \end{eqnarray} # $$ # One can integrate the equations to find the positions as a function of time, # $$ # \begin{eqnarray} # x-x_0&=&\int_{x_0}^x dx=\int_0^t dt v(t)\\ # \nonumber # &=&\frac{-A}{\omega_c}\cos(\omega_ct+\phi),\\ # \nonumber # y-y_0&=&\frac{A}{\omega_c}\sin(\omega_ct+\phi). # \end{eqnarray} # $$ # The trajectory is a circle centered at $x_0,y_0$ with amplitude $A$ rotating in the clockwise direction. # # The equations of motion for the $z$ motion are # <!-- Equation labels as ordinary links --> # <div id="_auto16"></div> # # $$ # \begin{equation} # \dot{v_z}=0, # \label{_auto16} \tag{16} # \end{equation} # $$ # which leads to # <!-- Equation labels as ordinary links --> # <div id="_auto17"></div> # # $$ # \begin{equation} # z-z_0=V_zt. # \label{_auto17} \tag{17} # \end{equation} # $$ # Added onto the circle, the motion is helical. # # Note that the kinetic energy, # <!-- Equation labels as ordinary links --> # <div id="_auto18"></div> # # $$ # \begin{equation} # T=\frac{1}{2}m(v_x^2+v_y^2+v_z^2)=\frac{1}{2}m(\omega_c^2A^2+V_z^2), # \label{_auto18} \tag{18} # \end{equation} # $$ # is constant. This is because the force is perpendicular to the # velocity, so that in any differential time element $dt$ the work done # on the particle $\boldsymbol{F}\cdot{dr}=dt\boldsymbol{F}\cdot{v}=0$. # # One should think about the implications of a velocity dependent # force. Suppose one had a constant magnetic field in deep space. If a # particle came through with velocity $v_0$, it would undergo cyclotron # motion with radius $R=v_0/\omega_c$. However, if it were still its # motion would remain fixed. Now, suppose an observer looked at the # particle in one reference frame where the particle was moving, then # changed their velocity so that the particle's velocity appeared to be # zero. The motion would change from circular to fixed. Is this # possible? # # The solution to the puzzle above relies on understanding # relativity. Imagine that the first observer believes $\boldsymbol{B}\ne 0$ and # that the electric field $\boldsymbol{E}=0$. If the observer then changes # reference frames by accelerating to a velocity $\boldsymbol{v}$, in the new # frame $\boldsymbol{B}$ and $\boldsymbol{E}$ both change. If the observer moved to the # frame where the charge, originally moving with a small velocity $v$, # is now at rest, the new electric field is indeed $\boldsymbol{v}\times\boldsymbol{B}$, # which then leads to the same acceleration as one had before. If the # velocity is not small compared to the speed of light, additional # $\gamma$ factors come into play, # $\gamma=1/\sqrt{1-(v/c)^2}$. Relativistic motion will not be # considered in this course. # # # # ## Summarizing the various motion problems # # The examples we have discussed above were included in order to # illustrate various methods (which depend on the specific problem) to # find the solutions of the equations of motion. # We have solved the equations of motion in the following ways: # # **Solve the differential equations analytically.** # # We did this for example with the following object in one or two dimensions or the sliding block. # Here we had for example an equation set like # $$ # \frac{dv_x}{dt}=-\gamma v_x, # $$ # and # $$ # \frac{dv_y}{dt}=-\gamma v_y-g, # $$ # and $\gamma$ has dimension of inverse time. # # # # # # We could also in case we can separate the degrees of freedom integrate. Take for example one of the equations in the previous slide # $$ # \frac{dv_x}{dt}=-\gamma v_x, # $$ # which we can rewrite in terms of a left-hand side which depends only on the velocity and a right-hand side which depends only on time # $$ # \frac{dv_x}{v_x}=-\gamma dt. # $$ # Integrating we have (since we can separate $v_x$ and $t$) # $$ # \int_{v_0}^{v_t}\frac{dv_x}{v_x}=-\int_{t_0}^{t_f}\gamma dt, # $$ # where $v_f$ is the velocity at a final time and $t_f$ is the final time. # In this case we found, after having integrated the above two sides that # $$ # v_f(t)=v_0\exp{-\gamma t}. # $$ # Finally, using for example Euler's method, we can solve the # differential equations numerically. If we can compare our numerical # solutions with analytical solutions, we have an extra check of our # numerical approaches. # # ## Exercises # # # ### Electron moving into an electric field # # An electron is sent through a varying electrical # field. Initially, the electron is moving in the $x$-direction with a velocity # $v_x = 100$ m/s. The electron enters the field when it passes the origin. The field # varies with time, causing an acceleration of the electron that varies in time # $$ # \boldsymbol{a}(t)=\left(−20 \mathrm{m/s}^2 −10\mathrm{m/s}^3t\right) \boldsymbol{e}_y, # $$ # or if we replace $\boldsymbol{e}_y$ with $\boldsymbol{e}_2$ (the unit vectors in the $y$-direction) we have # $$ # \boldsymbol{a}(t)=\left(−20 \mathrm{m/s}^2 −10\mathrm{m/s}^3t\right) \boldsymbol{e}_2. # $$ # Note that the velocity in the $x$-direction is a constant and is not affected by the force which acts only in the $y$-direction. # This means that we can decouple the two degrees of freedom and skip the vector symbols. # We have then a constant velocity in the $x$-direction # $$ # v_x(t) = 100\mathrm{m/s}, # $$ # and integrating up the acceleration in the $y$-direction (and using that the initial time $t_0=0$) we get # $$ # v_y(t) = -20\mathrm{m/s^2}t-5\mathrm{m/s^3}t^2. # $$ # Find the position as a function of time for the electron. # # # We integrate again in the $x$-direction # $$ # x(t) = 100\mathrm{m/s}t, # $$ # and in the $y$-direction (remember that these two degrees of freedom don't depend on each other) # we get # $$ # y(t) = -10\mathrm{m/s^2}t^2-\frac{5}{3}\mathrm{m/s^3}t^3. # $$ # The field is only acting inside a box of length $L = 2m$. # # How long time is the electron inside the field? # # # If we use the equation for the $x$-direction (the length of the box), we can then use the equation for $x(t) = 100\mathrm{m/s}t$ # and simply set $x=2$m and we find # $$ # t=\frac{1}{50}\mathrm{s}. # $$ # What is the displacement in the $y$-direction when the electron leaves the box. (We call this the deflection of the electron). # # # Here we simply use # $$ # y(t) = -10\mathrm{m/s^2}t^2-\frac{5}{3}\mathrm{m/s^3}t^3, # $$ # and use $t=1/50$s and find that # $$ # y = -0.004013 \mathrm{m}. # $$ # Find the angle the velocity vector forms with the horizontal axis as the electron leaves the box. # # # Again, we use $t=1/50$s and calculate the velocities in the $x$- and the $y$-directions (the velocity in the $x$-direction is just a constant) and find the angle using # $$ # \tan{\alpha} = \frac{v_y(t=1/50)}{v_x(t=1/50)}, # $$ # which leads to # $$ # \alpha = -0.23, # $$ # in degrees (not radians). # # ### Drag force # # Using equations (2.84) and (2.82) in Taylor, we have that $f_{\mathrm{quad}}/f_{\mathrm{lin}}=(\kappa\rho Av^2)/(3\pi\eta Dv)$. With $\kappa =1/4$ and $A=\pi D^2/4$ we obtain $f_{\mathrm{quad}}/f_{\mathrm{lin}}=(\rho Dv)/(48\eta)$ or $R/48$ with $R$ given by equation (2.83) of Taylor. # # With these numbers $R=1.1\times 10^{-2}$ and it is safe to neglect the quadratic drag. # # ### Falling object # # If we insert Taylor series for $\exp{-(t/\tau)}$ into equation (2.33) of Taylor, we have # $$ # v_y(t) = v_{\mathrm{ter}}\left[1-\exp{-(t/\tau)}\right] = v_{\mathrm{ter}}\left[1-(1-\frac{t}{\tau}+\frac{t^2}{2\tau^2}+\dots )\right]. # $$ # The first two terms on the right cancel and, if $t$ is sufficiently small, we can neglect terms with higher powers than two in $t$. This gives us # $$ # v_y(t) \approx v_{\mathrm{ter}}\frac{t}{\tau}=gt, # $$ # where we used that $v_{\mathrm{ter}}=g\tau$ from equation (2.34) in Taylor. This means that for small velocities it is the gravitational force which dominates. # # Setting $v_y(t_0)=0$ in equation (2.35) of Taylor and using the Taylor series for the exponential we find that # $$ # y(t) = v_{\mathrm{ter}}t-v_{\mathrm{ter}}\tau\left[1-\exp{-(t/\tau)}\right] = v_{\mathrm{ter}}t-v_{\mathrm{ter}}\tau\left[1-(1-\frac{t}{\tau}+\frac{t^2}{2\tau^2}+\dots )\right]. # $$ # On the rhs the second and third terms cancel, as do the first and fourth. If we neglect all terms beyond $t^2$, this leaves us with # $$ # y(t) \approx v_{\mathrm{ter}}\frac{t^2}{2\tau}=\frac{1}{2}gt^2. # $$ # Again, for small times, as expected, the gravitational force plays the major role. # # ### Motion of a cyclist # # Putting in the numbers for the characteristic time we find # $$ # \tau = \frac{m}{Dv_0} = \frac{80}{0.20\times 20}=20\mathrm{s}. # $$ # From an initial velocity of 20m/s we will slow down to half the initial speed, 10m/s in 20s. From Taylor equation (2.45) we have then that the time to slow down to any speed $v$ is # $$ # t = \frac{M}{D}\left(\frac{1}{v}-\frac{1}{v_0}\right). # $$ # This gives a time of 6.7s for a velocity of 15m/s, 20s for a velocity of 10m/s and 60s for a velocity of 5m/s. We see that this approximation leads to an infinite time before we come to rest. To ignore ordinary friction at low speeds is indeed a bad approximation. # # # # ### Falling ball and preparing for the numerical exercise # # In this example we study the motion of an object subject to a constant force, a velocity dependent # force, and for the numerical part a position-dependent force. # Without the position dependent force, we can solve the problem analytically. This is what we will do in this exercise. # The position dependent force requires numerical efforts (exercise 7). # In addition to the falling ball case, we will include the effect of the ball bouncing back from the floor in exercises 7. # # # Here we limit ourselves to a ball that is thrown from a height $h$ # above the ground with an initial velocity # $\boldsymbol{v}_0$ at time $t=t_0$. # We assume we have only a gravitational force and a force due to the air resistance. # The position of the ball as function of time is $\boldsymbol{r}(t)$ where $t$ is time. # The position is measured with respect to a coordinate system with origin at the floor. # # We assume we have an initial position $\boldsymbol{r}(t_0)=h\boldsymbol{e}_y$ and an initial velocity $\boldsymbol{v}_0=v_{x,0}\boldsymbol{e}_x+v_{y,0}\boldsymbol{e}_y$. # # In this exercise we assume the system is influenced by the gravitational force # $$ # \boldsymbol{G}=-mg\boldsymbol{e}_y # $$ # and an air resistance given by a square law # $$ # -Dv\boldsymbol{v}. # $$ # The analytical expressions for velocity and position as functions of # time will be used to compare with the numerical results in exercise 6. # # Identify the forces acting on the ball and set up a diagram with the forces acting on the ball. Find the acceleration of the falling ball. # # The forces acting on the ball are the gravitational force $\boldsymbol{G}=-mg\boldsymbol{e}_y$ and the air resistance $\boldsymbol{F}_D=-D\boldsymbol{v}v$ with $v$ the absolute value of the velocity. The accelaration in the $x$-direction is # $$ # a_x = -\frac{Dv_x\vert v\vert}{m}, # $$ # and in the $y$-direction # $$ # a_y = -g-\frac{Dv_y\vert v\vert}{m}, # $$ # where $\vert v\vert=\sqrt{v_x^2+v_y^2}$. Note that due to the dependence on $v_x$ and $v_y$ in each equation, it means we may not be able find an analytical solution. In this case we cannot. # In order to compare our code with analytical results, we will thus study the problem only in the $y$-direction. # # In the general code below we would write this as (pseudocode style) # In[14]: ax = -D*vx[i]*abs(v[i])/m ay = -g - D*vy[i]*abs(v[i])/m # Integrate the acceleration from an initial time $t_0$ to a final time $t$ and find the velocity. # # We reduce our problem to a one-dimensional in the $y$-direction only since for the two-dimensional motion we cannot find an analtical solution. For one dimension however, we have an analytical solution. # We specialize our equations for the $y$-direction only # $$ # \frac{dv_y}{dt}= -g +Dv_y^2(t). # $$ # We can solve this using the technique of separation of variables. We # isolate on the left all terms that involve $v$ and on the right all # terms that involve time. We get then # $$ # \frac{dv_y}{g -Dv_y^2(t) }= -dt, # $$ # We scale now the equation to the left by introducing a constant # $v_T=\sqrt{g/D}$. This constant has dimension length/time. # # Next we integrate the left-hand side (lhs) from $v_{y0}=0$ m/s to $v$ and # the right-hand side (rhs) from $t_0=0$ to $t$ and obtain # $$ # \int_{0}^{v_y}\frac{dv_y}{g -Dv_y^2(t) }= \frac{v_T}{g}\mathrm{arctanh}(\frac{v_y}{v_T}) =-\int_0^tdt = -t. # $$ # We can reorganize these equations as # $$ # v_T\mathrm{arctanh}(\frac{v_y}{v_T}) =-gt, # $$ # which gives us $v_y$ as function of time # $$ # v_y(t)=v_T\tanh{-(\frac{gt}{v_T})}. # $$ # With a finite initial velocity we need simply to add $v_{y0}$. # # # # Find thereafter the position as function of time starting with an initial time $t_0$. Find the time it takes to hit the floor. Here you will find it convenient to set the initial velocity in the $y$-direction to zero. # # # With the velocity we can then find the height $y(t)$ by integrating yet another time, that is # $$ # y(t)=y(t_0)+\int_{t_0}^t dt v_y(t)=\int_{0}^t dt[v_T\tanh{-(\frac{gt}{v_T})}]. # $$ # This integral is a little bit trickier but we can look it up in a table over # known integrals and we get # $$ # y(t)=y(t_0)-\frac{v_T^2}{g}\log{[\cosh{(\frac{gt}{v_T})}]}. # $$ # Here we have assumed that we set the initial velocity in the $y$-direction to zero, that is $v_y(t_0)=0$m/s. Adding a non-zero velocity gives us an additional term of $v_{y0}t$. # Using a zero initial velocity and setting # $$ # y(t)=0=y(t_0)-\frac{v_T^2}{g}\log{[\cosh{(-\frac{gt}{v_T})}]}=y(t_0)-\frac{v_T^2}{g}\log{[\cosh{(\frac{gt}{v_T})}]}, # $$ # (note that $\cosh$ yields the same values for negative and positive arguments) # allows us to find the final time by solving # $$ # y(t_0)=\frac{v_T^2}{g}\log{[\cosh{(\frac{gt}{v_T})}]}, # $$ # which gives # $$ # t = \frac{v_T}{g}\mathrm{arccosh}(\exp{(gy_0/v_T^2)}). # $$ # In the code below we would code these analytical expressions (with zero initial velocity in the $y$-direction) as # In[ ]: yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))+vy[0]*t[i+1] # We will use the above analytical results in our numerical calculations in the next exercise # # # # # ### Numerical elements, solving the previous exercise numerically and adding the bouncing from the floor # # Here we will: # 1. Learn and utilize Euler's Method to find the position and the velocity # # 2. Compare analytical and computational solutions # # 3. Add additional forces to our model # In[ ]: # let's start by importing useful packages we are familiar with import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # We will choose the following values # 1. mass $m=0,2$ kg # # 2. accelleration (gravity) $g=9.81$ m/s$^{2}$. # # 3. initial position is the height $h=2$ m # # 4. initial velocities $v_{x,0}=v_{y,0}=10$ m/s # # Can you find a reasonable value for the drag coefficient $D$? # You need also to define an initial time and # the step size $\Delta t$. We can define the step size $\Delta t$ as the difference between any # two neighboring values in time (time steps) that we analyze within # some range. It can be determined by dividing the interval we are # analyzing, which in our case is time $t_{\mathrm{final}}-t_0$, by the number of steps we # are taking $(N)$. This gives us a step size $\Delta t = \dfrac{t_{\mathrm{final}}-t_0}{N}$. # # With these preliminaries we are now ready to plot our results from exercise 5. # # Set up arrays for time, velocity, acceleration and positions for the results from exercise 5. Define an initial and final time. Choose the final time to be the time when the ball hits the ground for the first time. Make a plot of the position and velocity as functions of time. Here you could set the initial velocity in the $y$-direction to zero and use the result from exercise 5. Else you need to try different initial times using the result from exercise 5 as a starting guess. It is not critical if you don't reach the ground when the initial velocity in the $y$-direction is not zero. # # # We move now to the numerical solution of the differential equations as discussed in the [lecture notes](https://mhjensen.github.io/Physics321/doc/pub/motion/html/motion.html) or Malthe-Sørenssen chapter 7.5. # Let us remind ourselves about Euler's Method. # # Suppose we know $f(t)$ and its derivative $f'(t)$. To find $f(t+\Delta t)$ at the next step, $t+\Delta t$, # we can consider the Taylor expansion: # # $f(t+\Delta t) = f(t) + \dfrac{(\Delta t)f'(t)}{1!} + \dfrac{(\Delta t)^2f''(t)}{2!} + ...$ # # If we ignore the $f''$ term and higher derivatives, we obtain # # $f(t+\Delta t) \approx f(t) + (\Delta t)f'(t)$. # # This approximation is the basis of Euler's method, and the Taylor # expansion suggests that it will have errors of $O(\Delta t^2)$. Thus, one # would expect it to work better, the smaller the step size $h$ that you # use. In our case the step size is $\Delta t$. # # In setting up our code we need to # # 1. Define and obtain all initial values, constants, and time to be analyzed with step sizes as done above (you can use the same values) # # 2. Calculate the velocity using $v_{i+1} = v_{i} + (\Delta t)*a_{i}$ # # 3. Calculate the position using $pos_{i+1} = r_{i} + (\Delta t)*v_{i}$ # # 4. Calculate the new acceleration $a_{i+1}$. # # 5. Repeat steps 2-4 for all time steps within a loop. # # Write a code which implements Euler's method and compute numerically and plot the position and velocity as functions of time for various values of $\Delta t$. Comment your results. # # Below you will find two codes, one which uses explicit expressions for the $x$- and $y$-directions and one which rewrites the expressions as compact vectors, as done in homework 2. Running the codes shows a sensitivity to the chosen step size $\Delta t$. You will clearly notice that when comparing with the analytical results, that larger values of the step size in time result in a poorer agreement with the analytical solutions. # # * Compare your numerically obtained positions and velocities with the analytical results from exercise 5. Comment again your results. # # The codes follow here. Running them allows you to probe the various parameters and compare with analytical solutions as well. # # The analytical results are discussed in the lecture notes, see the slides of the week of January 25-29 <https://mhjensen.github.io/Physics321/doc/pub/week4/html/week4-bs.html>. # # # The codes here show two different ways of solving the two-dimensional problem. The first one defines arrays for the $x$- and $y$-directions explicitely, while the second code uses a more # compact (and thus closer to the mathmeatics) notation with a full two-dimensional vector. # # # The initial conditions for the first example are set so that we only an object falling in the $y$-direction. Then it makes sense to compare with the analytical solution. If you change the initial conditions, this comparison is no longer correct. # In[ ]: # Exercise 6, hw3, brute force way with declaration of vx, vy, x and y # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') # Output file outfile = open(data_path("Eulerresults.dat"),'w') from pylab import plt, mpl plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' g = 9.80655 #m/s^2 # The mass and the drag constant D D = 0.00245 #mass/length kg/m m = 0.2 #kg, mass of falling object DeltaT = 0.001 #set up arrays tfinal = 1.4 # set up number of points for all variables n = ceil(tfinal/DeltaT) # define scaling constant vT used in analytical solution vT = sqrt(m*g/D) # set up arrays for t, a, v, and y and arrays for analytical results #brute force setting up of arrays for x and y, vx, vy, ax and ay t = np.zeros(n) vy = np.zeros(n) y = np.zeros(n) vx = np.zeros(n) x = np.zeros(n) yanalytic = np.zeros(n) # Initial conditions, note that these correspond to an object falling in the y-direction only. vx[0] = 0.0 #m/s vy[0] = 0.0 #m/s y[0] = 10.0 #m x[0] = 0.0 #m yanalytic[0] = y[0] # Start integrating using Euler's method for i in range(n-1): # expression for acceleration, note the absolute value and division by mass ax = -D*vx[i]*sqrt(vx[i]**2+vy[i]**2)/m ay = -g - D*vy[i]*sqrt(vx[i]**2+vy[i]**2)/m # update velocity and position vx[i+1] = vx[i] + DeltaT*ax x[i+1] = x[i] + DeltaT*vx[i] vy[i+1] = vy[i] + DeltaT*ay y[i+1] = y[i] + DeltaT*vy[i] # update time to next time step and compute analytical answer t[i+1] = t[i] + DeltaT yanalytic[i+1] = y[0]-(vT*vT/g)*log(cosh(g*t[i+1]/vT))+vy[0]*t[i+1] if ( y[i+1] < 0.0): break data = {'t[s]': t, 'Relative error in y': abs((y-yanalytic)/yanalytic), 'vy[m/s]': vy, 'x[m]': x, 'vx[m/s]': vx } NewData = pd.DataFrame(data) display(NewData) # save to file NewData.to_csv(outfile, index=False) #then plot fig, axs = plt.subplots(4, 1) axs[0].plot(t, y) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('y') axs[1].plot(t, vy) axs[1].set_ylabel('vy[m/s]') axs[1].set_xlabel('time[s]') axs[2].plot(t, x) axs[2].set_xlim(0, tfinal) axs[2].set_ylabel('x') axs[3].plot(t, vx) axs[3].set_ylabel('vx[m/s]') axs[3].set_xlabel('time[s]') fig.tight_layout() save_fig("EulerIntegration") plt.show() # We see a good agreement with the analytical solution. This agreement # improves if we decrease $\Delta t$. Furthermore, since we put the # initial velocity and position in the $x$ direction to zero, # the motion in the $x$-direction is # zero, as expected. # In[ ]: # Smarter way with declaration of vx, vy, x and y # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') from pylab import plt, mpl plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' g = 9.80655 #m/s^2 g to 6 leading digits after decimal point D = 0.00245 #m/s m = 0.2 # kg # Define Gravitational force as a vector in x and y. It is a constant G = -m*g*np.array([0.0,1]) DeltaT = 0.01 #set up arrays tfinal = 1.3 n = ceil(tfinal/DeltaT) # set up arrays for t, a, v, and x t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # Initial conditions as compact 2-dimensional arrays r0 = np.array([0.0,10.0]) v0 = np.array([10.0,0.0]) r[0] = r0 v[0] = v0 # Start integrating using Euler's method for i in range(n-1): # Set up forces, air resistance FD, not now that we need the norm of the vector # Here you could have defined your own function for this vabs = sqrt(sum(v[i]*v[i])) FD = -D*v[i]*vabs # Final net forces acting on falling object Fnet = FD+G # The accelration at a given time t_i a = Fnet/m # update velocity, time and position using Euler's method v[i+1] = v[i] + DeltaT*a r[i+1] = r[i] + DeltaT*v[i] t[i+1] = t[i] + DeltaT fig, axs = plt.subplots(4, 1) axs[0].plot(t, r[:,1]) axs[0].set_xlim(0, tfinal) axs[0].set_ylabel('y') axs[1].plot(t, v[:,1]) axs[1].set_ylabel('vy[m/s]') axs[1].set_xlabel('time[s]') axs[2].plot(t, r[:,0]) axs[2].set_xlim(0, tfinal) axs[2].set_ylabel('x') axs[3].plot(t, v[:,0]) axs[3].set_ylabel('vx[m/s]') axs[3].set_xlabel('time[s]') fig.tight_layout() save_fig("EulerIntegration") plt.show() # Till now we have only introduced gravity and air resistance and studied # their effects via a constant acceleration due to gravity and the force # arising from air resistance. But what happens when the ball hits the # floor? What if we would like to simulate the normal force from the floor acting on the ball? # # We need then to include a force model for the normal force from # the floor on the ball. The simplest approach to such a system is to introduce a contact force # model represented by a spring model. We model the interaction between the floor # and the ball as a single spring. But the normal force is zero when # there is no contact. Here we define a simple model that allows us to include # such effects in our models. # # The normal force from the floor on the ball is represented by a spring force. This # is a strong simplification of the actual deformation process occurring at the contact # between the ball and the floor due to the deformation of both the ball and the floor. # # The deformed region corresponds roughly to the region of **overlap** between the # ball and the floor. The depth of this region is $\Delta y = R − y(t)$, where $R$ # is the radius of the ball. This is supposed to represent the compression of the spring. # Our model for the normal force acting on the ball is then # $$ # \boldsymbol{N} = −k (R − y(t)) \boldsymbol{e}_y. # $$ # The normal force must act upward when $y < R$, # hence the sign must be negative. # However, we must also ensure that the normal force only acts when the ball is in # contact with the floor, otherwise the normal force is zero. The full formation of the # normal force is therefore # $$ # \boldsymbol{N} = −k (R − y(t)) \boldsymbol{e}_y, # $$ # when $y(t) < R$ and zero when $y(t) \le R$. # In the numerical calculations you can choose $R=0.1$ m and the spring constant $k=1000$ N/m. # # * Identify the forces acting on the ball and set up a diagram with the forces acting on the ball. Find the acceleration of the falling ball now with the normal force as well. # # * Choose a large enough final time so you can study the ball bouncing up and down several times. Add the normal force and compute the height of the ball as function of time with and without air resistance. Comment your results. # # The following code shows how # to set up the problem with gravitation, a drag force and a normal # force from the ground. The normal force makes the ball bounce up # again. # # # The code here includes all forces. Commenting out the air resistance will result in a ball which bounces up and down to the same height. # Furthermore, you will note that for larger values of $\Delta t$ the results will not be physically meaningful. Can you figure out why? Try also different values for the step size in order to see whether the final results agrees with what you expect. # In[ ]: # Smarter way with declaration of vx, vy, x and y # Here we have added a normal force from the ground # Common imports import numpy as np import pandas as pd from math import * import matplotlib.pyplot as plt import os # Where to save the figures and data files PROJECT_ROOT_DIR = "Results" FIGURE_ID = "Results/FigureFiles" DATA_ID = "DataFiles/" if not os.path.exists(PROJECT_ROOT_DIR): os.mkdir(PROJECT_ROOT_DIR) if not os.path.exists(FIGURE_ID): os.makedirs(FIGURE_ID) if not os.path.exists(DATA_ID): os.makedirs(DATA_ID) def image_path(fig_id): return os.path.join(FIGURE_ID, fig_id) def data_path(dat_id): return os.path.join(DATA_ID, dat_id) def save_fig(fig_id): plt.savefig(image_path(fig_id) + ".png", format='png') from pylab import plt, mpl plt.style.use('seaborn') mpl.rcParams['font.family'] = 'serif' # Define constants g = 9.80655 #in m/s^2 D = 0.0245 # in mass/length, kg/m m = 0.2 # in kg R = 0.1 # in meters k = 1000.0 # in mass/time^2 # Define Gravitational force as a vector in x and y, zero x component G = -m*g*np.array([0.0,1]) DeltaT = 0.001 #set up arrays tfinal = 15.0 n = ceil(tfinal/DeltaT) # set up arrays for t, v, and r, the latter contain the x and y comps t = np.zeros(n) v = np.zeros((n,2)) r = np.zeros((n,2)) # Initial conditions r0 = np.array([0.0,2.0]) v0 = np.array([10.0,10.0]) r[0] = r0 v[0] = v0 # Start integrating using Euler's method for i in range(n-1): # Set up forces, air resistance FD if ( r[i,1] < R): N = k*(R-r[i,1])*np.array([0,1]) else: N = np.array([0,0]) vabs = sqrt(sum(v[i]*v[i])) FD = -D*v[i]*vabs Fnet = FD+G+N a = Fnet/m # update velocity, time and position v[i+1] = v[i] + DeltaT*a r[i+1] = r[i] + DeltaT*v[i] t[i+1] = t[i] + DeltaT fig, ax = plt.subplots() ax.set_xlim(0, tfinal) ax.set_ylabel('y[m]') ax.set_xlabel('x[m]') ax.plot(r[:,0], r[:,1]) fig.tight_layout() save_fig("BouncingBallEuler") plt.show()
d9e38e46024b564573bd90203fb3bde88434fe63
NurhandeAkyuz/Guess-the-number-game
/game.py
6,895
4.375
4
import random def game(): #this function is used for showing main menu and working in that part name = '' #when program starts, name is initially an empty string password = '' #when program starts, password is initially an empty string while True: #to make program shows the main menu constantly print ("--- Welcome to 'Guess the Number' Game V.0.3 ---") print("1. Login") print("2. Sign Up (Limited to 1 user)") print ("3. Description") while True: #while True it will work in the main menu option = raw_input() if option == '1': #if user selects first option which is login option_1(name,password) #function namely option_1 is called break #break is used to get out of this while loop to see the main menu elif option == '2': #if user selects second option which is sign up name,password = option_2(name,password) #name and password are updated from function option_two break #break is used to get out of this while loop to see the main menu elif option == '3': #if user selects third option which is description option_3() #function option_3 is called break #break is used to get out of this while loop to see the main menu else: #this part for the condition when user enters number which is not in the main menu print 'Please enter a valid number!' def option_1(name,password): #it takes two parameters which are name and password to check if name and password are correct or not if name == '': #if name is an empty string, it means that there is no user signed up print ("Warning! There is no users :( Please sign up first" + "\nGoing back to main menu...") else: user = raw_input('Please enter your username:') passw = raw_input('Please enter your password:') if user == name and passw == password: #check if user write her/his user name and password correctly or not print "Game starts..." point = 100 #user's initial point while True: if point <= 0: #if point is neegative or equal to zero, it prints statement below and finish this while loop so that point starts from 100 break generated_number = random.randint(0, 100) # number is randomly chosen betweeon 0 and 100 which both are included print "Let's start with a new number" + "\nYour Point: 100" + "\nGuess the number:" while True: if point <= 0: #if point is neegative or equal to zero, it prints statement below and finish this while loop print "< Your Point is ZERO >" + "\n--------------------------------" + "\n----- < Game Over > -----" + \ "\n--------------------------------" break else: #if point is bigger than zero, then it asks user's guessed number guessed_number = raw_input() if int(guessed_number) == generated_number: # it checks if user's number is the same as randomly generated one point += 25 # and update the point value print "Your Point: " + str(point) + "\nCongratulations, that's right you got +25 points" + \ "\nLet's start with a new number" else: # if user's number is not same as generated number then we have four options if int(guessed_number) < (generated_number / 2.0): # if guessed_number is less than the half of the generated number point -= 10 #and update the point value print "Your Point: " + str(point) + "\nThe number you guess is too low, you loss 10 points" + \ "\n You still have a chance. Try Again!" elif (generated_number / 2.0) < int(guessed_number) < (generated_number): # if typed number is less than the half of the generated number point -= 5 #and update the point value print "Your Point: " + str(point) + "\nThe number you guess is low. You lose 5 points" + \ "\n You still have a chance. Try Again!" elif int(guessed_number) > (generated_number * 2): # if the typed number is bigger than the two times generated number point -= 10 #and update the point value print "Your Point: " + str(point) + "\nThe number you guess is too high, you lose 10 points" + \ "\n You still have a chance. Try Again!" elif (generated_number * 2) > int(guessed_number) > (generated_number): # if typed number is less than two times generated number and bigger than the generated number point -= 5 #and update the point value print "Your Point: " + str(point) + "\nThe number you guess is high, you lose 5 points" + \ "\n You still have a chance. Try Again!" else: #if user name or password is not same as the name and password saved in 'sign up' part print "Information is invalid!" def option_2(name,password): #takes two parameters because name and password should be saved if name == '': #if name is an empty string user is asked to enter her/his name and password name_exp = "Please enter your user name:" user_name = raw_input(name_exp) #name of the user is assigned as user_name password_exp = "Please enter your password:" user_password = raw_input(password_exp) #password of the user is assigned as user_name return user_name,user_password #user name and password is saved and returned else: print ("You have already signed up, you can't sign up more than 1 user!" + "\nGoing back to main menu..") return name, password #user name and password is saved and return def option_3(): #print the statement if user selects "description" print "This project is 'ENGR 101 - Introduction to Programming' course's mini project 01." \ "The project is a game played by one player by sign up and login system." \ "The player should assume the randomly generated number and accordingly he/she will earn or lose points." game()
37c7556579878c20275bc936b52292ae8437cfb3
l7opy4uk/python_study
/note_20160426.py
1,782
4.0625
4
#Function fabric def f(n): def g(x): return n * x return g double = f(2) triple = f(3) l = [] # Not closed, because depends on i value for i in range(10): def f(x): return x * i l.append(f) #closed for i in range(10): def f(x, i=i): return x * i l.append(f) # map func operate function to whole container def double(x): return 2 * x l = list(map(double, [1, 2, 3, 4, 5])) print(l) # def double(x): print("double: {}".format(x)) return x * 2 for i in map(double, [1, 2, 3, 4, 5]): print(i) if i >5: break #Выводим нечетные числа def odd(x): return x % 2 l = list(filter(odd, [1, 2, 3, 4, 5])) print(l) ## READ itertools !!!!!!!!!!!!!!!!!!!!!! #lambda - using for temporary function list(map(lambda x: 3 * x, [1, 2, 3, 4, 5])) # поставить неограниченое количество аргументов def f(*args): print(args) def sum_(*args): # could set sum(a, *args) to show that we need at least one parameter s = 0 for i in args: s += i return s def f(*args, **kwargs): print(args, kwargs) #>>>f (1,2,3, a=4, b=5) #(1, 2, 3) {'a' : 4, 'b' : 5} def f (a, b, c): return a + b + c t = 1, 2, 3 f(*t) # Обертка!!!!!!!!!!!!!!!!!!!!!!!!! Wrapper def g (*args, **kwargs): print('g') return f(*args, **kwargs) #DECORATORS def decor(f): def wrapper(): print("in") res = #special syntax for decorators @scale # the same as scale = scale(double) def double(x): return 2 * x #multiple variants actions = {1: a, 2: b, 3: c} def default(): print('default') actions.get(5, default)() actions.get(3, default)()
17360455dc825763e4c159f929580e4af17dcbd4
MisterFili/NoDrinking
/05list_overlap.py
643
4.21875
4
#listOverlap ''' write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. class_attendance = ['me', 'myself', 'and', 'eye'] name = input('type a name to check: ') if name in class_attendance: print(' {}, this person is enrolled'.format(name)) else: print('{}, did not show up to class'.format(name)) ''' a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] c = [] d = [random.randint(1,80)] for item in a: if item in b and item not in c: c.append(item) print(c)
da6b962d0cf722506ff67d6092367c8b59a12981
banashish/DS-Algo
/100code/count_of_number_after_self.py
1,325
3.8125
4
# this is a modification in count inversion problem def countInversionUsingMergeSort(arr): temp_arr = [0]*len(arr) ans = [0]*len(arr) return mergeSort(arr,temp_arr,0,len(arr)-1,ans) def mergeSort(arr,temp_arr,left,right,answer): inv_count = 0 li,ri,mi = 0,0,0 if left < right: mid = (left + right) // 2 li = mergeSort(arr,temp_arr,left,mid,answer) ri = mergeSort(arr,temp_arr,mid+1,right,answer) mi = merge(arr,temp_arr,mid,left,right,answer) answer[left] = ri+mi print(answer) return inv_count def merge(arr,temp_arr,mid,left,right,answer): i = left j = mid + 1 k = left inv = 0 while i <= mid and j <= right: if arr[i] <= arr[j]: temp_arr[k] = arr[i] k+=1 i+=1 else: temp_arr[k] = arr[j] inv+=(mid - i + 1) # answer[k]+=inv k+=1 j+=1 while i <= mid: temp_arr[k] = arr[i] k+=1 i+=1 while j <= right: temp_arr[k] = arr[j] k+=1 j+=1 for w in range(left,right+1): arr[w] = temp_arr[w] return inv if __name__ == "__main__": arr = list(map(int,input().split(" "))) answer = countInversionUsingMergeSort(arr) print(answer)
3f58da6f1f9e6b32411cc5393bb3c33c744d46ef
sridarshini123/python-programming
/codekata/beginner level/prime or not.py
159
4
4
count=0 num=int(raw_input()) for i in range(2,num): if(num%i==0): count=count+1 if(count==1): print("it is prime") else: print("not prime")
46d5d841ea069b330972efb3a3299e8ebdb4e34d
Python-November-2018/yashey_mateen
/01-python/02-python/01-required/05-for_loop_basic_2.py
3,920
4.71875
5
#1. Biggie Size - Given an array, write a function that changes all positive numbers in the array to "big". Example: makeItBig([-1, 3, 5, -5]) returns that same array, changed to [-1, "big", "big", -5]. def makeItBig(arr): newarr=[] biggie = 'big' for i in range(0, len(arr), +1): if arr[i]<0: newarr.append(arr[i]) if arr[i]>0: arr[i] = biggie newarr.append(arr[i]) print(newarr) makeItBig([-1, 3, 5, -5]) #2. Count Positives - Given an array of numbers, create a function to replace last value with number of positive values. Example, countPositives([-1,1,1,1]) changes array to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number). def countPositives(arr): positiveCount = 0 for i in range(0, len(arr), +1): if arr[i]>0: positiveCount+=1 arr[len(arr)-1]=positiveCount print(arr) countPositives([-1,1,1,1]) #3. SumTotal - Create a function that takes an array as an argument and returns the sum of all the values in the array. For example sumTotal([1,2,3,4]) should return 10 def sumTotal(arr): sum = 0 for i in range(0, len(arr), +1): sum+=arr[i] print(sum) sumTotal([1,2,3,4]) #4. Average - Create a function that takes an array as an argument and returns the average of all the values in the array. For example multiples([1,2,3,4]) should return 2.5 def multiples(arr): sum = 0 for i in range(0, len(arr), +1): sum+=arr[i] avg = sum/len(arr) print(avg) multiples([1,2,3,4]) #5. Length - Create a function that takes an array as an argument and returns the length of the array. For example length([1,2,3,4]) should return 4 def length(arr): print(len(arr)) length([1,2,3,4]) #6. Minimum - Create a function that takes an array as an argument and returns the minimum value in the array. If the passed array is empty, have the function return false. For example minimum([1,2,3,4]) should return 1; minimum([-1,-2,-3]) should return -3. def minimum(arr): min = arr[0] if(len(arr) == 0): return false for i in range(0, len(arr), +1): if(arr[i]<min): min = arr[i] print(min) minimum([1,2,3,4]) minimum([-1,-2,-3]) #7. Maximum - Create a function that takes an array as an argument and returns the maximum value in the array. If the passed array is empty, have the function return false. For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1. def maximum(arr): max = arr[0] if(len(arr) == 0): return false for i in range(0, len(arr), +1): if(arr[i]>max): max= arr[i] print(max) maximum([1,2,3,4]) maximum([-1,-2,-3]) #8. UltimateAnalyze - Create a function that takes an array as an argument and returns a dictionary that has the sumTotal, average, minimum, maximum and length of the array. def ultimateAnalyze(arr): ultimate = [] min = arr[0] max = arr[0] sum = 0 for i in range(0, len(arr), +1): sum+=arr[i] avg = sum/len(arr) ultimate.append(sum) ultimate.append(avg) for i in range(0, len(arr), +1): if(arr[i]<min): min = arr[i] ultimate.append(min) for i in range(0, len(arr), +1): if(arr[i]>max): max= arr[i] ultimate.append(max) ultimate.append(len(arr)) print(ultimate) ultimateAnalyze([1,2,3,4,5]) #9. ReverseList - Create a function that takes an array as an argument and return an array in a reversed order. Do this without creating an empty temporary array. For example reverse([1,2,3,4]) should return [4,3,2,1]. This challenge is known to appear during basic technical interviews. def reverse(arr): i = 0 j = len(arr)-1 for i in range (0, j, +1): arr[j], arr[i] = arr[i], arr[j] j-=1 arr[i], arr[j] = arr[j], arr[i] print(arr) reverse([1,2,3,4])
05378523cc7e1ae7d222753fbcf2bb41f1d627c6
mozzielol/Deducing
/networks/model.py
18,051
3.71875
4
from builtins import range from builtins import object import numpy as np from networks.layer.layers import * from networks.layer.layer_utils import * from copy import deepcopy class Model(object): """ A fully-connected neural network with an arbitrary number of hidden layers, ReLU nonlinearities, and a softmax loss function. This will also implement dropout and batch/layer normalization as options. For a network with L layers, the architecture will be {affine - [batch/layer norm] - relu - [dropout]} x (L - 1) - affine - softmax where batch/layer normalization and dropout are optional, and the {...} block is repeated L - 1 times. Similar to the TwoLayerNet above, learnable parameters are stored in the self.params dictionary and will be learned using the Solver class. """ def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, dropout=1, normalization=None, reg=0.0, weight_scale=1e-2, dtype=np.float32, seed=None, num_networks = 1, sub_network = 1): """ Initialize a new FullyConnectedNet. Inputs: - hidden_dims: A list of integers giving the size of each hidden layer. - input_dim: An integer giving the size of the input. - num_classes: An integer giving the number of classes to classify. - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=1 then the network should not use dropout at all. - normalization: What type of normalization the network should use. Valid values are "batchnorm", "layernorm", or None for no normalization (the default). - reg: Scalar giving L2 regularization strength. - weight_scale: Scalar giving the standard deviation for random initialization of the weights. - dtype: A numpy datatype object; all computations will be performed using this datatype. float32 is faster but less accurate, so you should use float64 for numeric gradient checking. - seed: If not None, then pass this random seed to the dropout layers. This will make the dropout layers deteriminstic so we can gradient check the model. - network_param: order of the network, the part of network, the parameters """ self.normalization = normalization self.use_dropout = dropout != 1 self.reg = reg self.num_layers = 1 + len(hidden_dims) self.dtype = dtype self.params = {} self.num_networks = num_networks self.network_param = {} hidden = [x*sub_network for x in hidden_dims] net_dims = [input_dim] + hidden + [num_classes] self.net_dims = net_dims #1. initialze the network for i in range(self.num_layers): self.params['W%d'%(i+1)] = np.random.normal(loc=0.0,scale=weight_scale,size=(net_dims[i],net_dims[i+1])) self.params['b%d'%(i+1)] = np.zeros(net_dims[i+1]) if (self.normalization is not None) & (i!=self.num_layers - 1): self.params['gamma%d'%(i+1)] = np.ones(net_dims[i+1]) self.params['beta%d'%(i+1)] = np.zeros(net_dims[i+1]) self.network_index = {} step = for i in range(sub_network): start = end = 0 start = i * self.network[i] = [start:end] #Take apart the network for i in range(sub_network): self.network_param[i] = deepcopy(network_param) ############################################################################ # END OF YOUR CODE # ############################################################################ # When using dropout we need to pass a dropout_param dictionary to each # dropout layer so that the layer knows the dropout probability and the mode # (train / test). You can pass the same dropout_param to each dropout layer. self.dropout_param = {} if self.use_dropout: self.dropout_param = {'mode': 'train', 'p': dropout} if seed is not None: self.dropout_param['seed'] = seed self.bn_params = [] if self.normalization=='batchnorm': self.bn_params = [{'mode': 'train'} for i in range(self.num_layers - 1)] if self.normalization=='layernorm': self.bn_params = [{} for i in range(self.num_layers - 1)] # Cast all parameters to the correct datatype for i in self.network_param: for k, v in self.network_param[i].items(): self.network_param[i][k] = v.astype(dtype) def update_parameters(self,best_param): network_param = {} for i in range(self.num_layers): step = self.net_dims[i] // self.num_networks start = 0 step2 = self.net_dims[i+1] // self.num_networks start2 = 0 for e in range(self.num_networks): end = 0 if e == self.num_networks - 1: end = self.net_dims[i] end2 = self.net_dims[i+1] else: end = step * (e+1) end2 = step2 * (e+1) network_param[(e,'W%d'%(i+1))] = best_param['W%d'%(i+1)][start:end].copy() network_param[(e,'b%d'%(i+1))] = best_param['b%d'%(i+1)][start2:end2].copy() if (self.normalization is not None) & (i!=self.num_layers - 1): network_param[(e,'gamma%d'%(i+1))] = best_param['gamma%d'%(i+1)][start2:end2].copy() network_param[(e,'beta%d'%(i+1))] = best_param['beta%d'%(i+1)][start2:end2].copy() start = end start2 = end2 for i in range(self.num_layers): for n,j in enumerate(self.which_network): self.network_param[j][(n,'W%d'%(i+1))] = deepcopy(network_param[(n,'W%d'%(i+1))]) self.network_param[j][(n,'b%d'%(i+1))] = deepcopy(network_param[(n,'b%d'%(i+1))]) if (self.normalization is not None) & (i!=self.num_layers - 1): self.network_param[j][(n,'gamma%d'%(i+1))] = deepcopy(network_param[(n,'gamma%d'%(i+1))]) self.network_param[j][(n,'beta%d'%(i+1))] = deepcopy(network_param[(n,'beta%d'%(i+1))]) def define_parameters(self,which_network= [0],trianable_mask=[0]): self.which_network = which_network if len(which_network)!= self.num_networks: raise ValueError('network length is not sufficient') if len(which_network)!= len(trianable_mask): raise ValueError('trainable_mask length is not sufficient') self.training_mask = {} for i in range(self.num_layers): for n,j in enumerate(which_network): if n == 0: self.params['W%d'%(i+1)] = deepcopy(self.network_param[j][(n,'W%d'%(i+1))]) self.params['b%d'%(i+1)] = deepcopy(self.network_param[j][(n,'b%d'%(i+1))]) mask = self._create_mask('W%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['W%d'%(i+1)] = mask mask = self._create_mask('b%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['b%d'%(i+1)] = mask if (self.normalization is not None) & (i!=self.num_layers - 1): self.params['gamma%d'%(i+1)] = deepcopy(self.network_param[j][(n,'gamma%d'%(i+1))]) self.params['beta%d'%(i+1)] = deepcopy(self.network_param[j][(n,'beta%d'%(i+1))]) mask = self._create_mask('gamma%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['gamma%d'%(i+1)] = mask mask = self._create_mask('beta%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['beta%d'%(i+1)] = mask #print(self.params['W%d'%(i+1)].shape,self.params['b%d'%(i+1)].shape,self.params['gamma%d'%(i+1)].shape,self.params['beta%d'%(i+1)].shape) else: self.params['W%d'%(i+1)] = np.concatenate((self.params['W%d'%(i+1)],deepcopy(self.network_param[j][(n,'W%d'%(i+1))]))) self.params['b%d'%(i+1)] = np.concatenate((self.params['b%d'%(i+1)],deepcopy(self.network_param[j][(n,'b%d'%(i+1))])),axis=0) mask = self._create_mask('W%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['W%d'%(i+1)] = np.concatenate((self.training_mask['W%d'%(i+1)],mask)) mask = self._create_mask('b%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['b%d'%(i+1)] = np.concatenate((self.training_mask['b%d'%(i+1)],mask)) if (self.normalization is not None) & (i!=self.num_layers - 1): self.params['gamma%d'%(i+1)] = np.concatenate((self.params['gamma%d'%(i+1)],deepcopy(self.network_param[j][(n,'gamma%d'%(i+1))])),axis=0) self.params['beta%d'%(i+1)] = np.concatenate((self.params['beta%d'%(i+1)],deepcopy(self.network_param[j][(n,'beta%d'%(i+1))])),axis=0) mask = self._create_mask('gamma%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['gamma%d'%(i+1)] = np.concatenate((self.training_mask['gamma%d'%(i+1)],mask)) mask = self._create_mask('beta%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['beta%d'%(i+1)] = np.concatenate((self.training_mask['beta%d'%(i+1)],mask)) #print(self.params['W%d'%(i+1)].shape,self.params['b%d'%(i+1)].shape,self.params['gamma%d'%(i+1)].shape,self.params['beta%d'%(i+1)].shape) def predict_params(self,which_network= [0]): self.which_network = which_network if len(which_network)!= self.num_networks: raise ValueError('network length is not sufficient') for n,j in enumerate(which_network): for i in range(self.num_layers): if n == 0: self.params['W%d'%(i+1)] = self.network_param[j][(n,'W%d'%(i+1))].copy() self.params['b%d'%(i+1)] = self.network_param[j][(n,'b%d'%(i+1))].copy() mask = self._create_mask('W%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['W%d'%(i+1)] = mask mask = self._create_mask('b%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['b%d'%(i+1)] = mask if (self.normalization is not None) & (i!=self.num_layers - 1): self.params['gamma%d'%(i+1)] = self.network_param[j][(n,'gamma%d'%(i+1))].copy() self.params['beta%d'%(i+1)] = self.network_param[j][(n,'beta%d'%(i+1))].copy() mask = self._create_mask('gamma%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['gamma%d'%(i+1)] = mask mask = self._create_mask('beta%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['beta%d'%(i+1)] = mask #print(self.params['W%d'%(i+1)].shape,self.params['b%d'%(i+1)].shape,self.params['gamma%d'%(i+1)].shape,self.params['beta%d'%(i+1)].shape) else: self.params['W%d'%(i+1)] = np.concatenate((self.params['W%d'%(i+1)],self.network_param[j][(n,'W%d'%(i+1))])).copy() self.params['b%d'%(i+1)] = np.concatenate((self.params['b%d'%(i+1)],self.network_param[j][(n,'b%d'%(i+1))]),axis=0).copy() mask = self._create_mask('W%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['W%d'%(i+1)] = np.concatenate((self.training_mask['W%d'%(i+1)],mask)) mask = self._create_mask('b%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['b%d'%(i+1)] = np.concatenate((self.training_mask['b%d'%(i+1)],mask)) if (self.normalization is not None) & (i!=self.num_layers - 1): self.params['gamma%d'%(i+1)] = np.concatenate((self.params['gamma%d'%(i+1)],self.network_param[j][(n,'gamma%d'%(i+1))]),axis=0).copy() self.params['beta%d'%(i+1)] = np.concatenate((self.params['beta%d'%(i+1)],self.network_param[j][(n,'beta%d'%(i+1))]),axis=0).copy() mask = self._create_mask('gamma%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['gamma%d'%(i+1)] = np.concatenate((self.training_mask['gamma%d'%(i+1)],mask)) mask = self._create_mask('beta%d'%(i+1),j,n,trianable_mask[n]) self.training_mask['beta%d'%(i+1)] = np.concatenate((self.training_mask['beta%d'%(i+1)],mask)) #print(self.params['W%d'%(i+1)].shape,self.params['b%d'%(i+1)].shape,self.params['gamma%d'%(i+1)].shape,self.params['beta%d'%(i+1)].shape) def _create_mask(self,para_name,j,n,num): mask = None mask = self.network_param[j][(n,para_name)].copy() mask.fill(num) return mask.astype(bool) def loss(self, X, y=None): """ Compute loss and gradient for the fully-connected net. Input / output: Same as TwoLayerNet above. """ X = X.astype(self.dtype) mode = 'test' if y is None else 'train' # Set train/test mode for batchnorm params and dropout param since they # behave differently during training and testing. if self.use_dropout: self.dropout_param['mode'] = mode if self.normalization=='batchnorm': for bn_param in self.bn_params: bn_param['mode'] = mode scores = None cache = {} layer_output = {} dropout_cache = {} layer_output[0] = X if self.normalization=='batchnorm': for i in range(1, self.num_layers +1): if i != self.num_layers: layer_output[i], cache[i] = batch_relu_forward( layer_output[i-1], self.params['W%d' %i], self.params['b%d' %i], self.params['gamma%d' %i], self.params['beta%d' %i], bn_param=self.bn_params[i-1] ) if self.use_dropout: layer_output[i], dropout_cache[i] = dropout_forward(layer_output[i],self.dropout_param) else: layer_output[i], cache[i] = affine_forward( layer_output[i-1], self.params['W%d' %i], self.params['b%d' %i] ) elif self.normalization is None: for i in range(1,self.num_layers+1): if i != self.num_layers: layer_output[i], cache[i] = affine_relu_forward(layer_output[i-1], self.params['W{}'.format(i)],self.params['b{}'.format(i)]) if self.use_dropout: layer_output[i],dropout_cache[i] = dropout_forward(layer_output[i],self.dropout_param) else: layer_output[i], cache[i] = affine_forward(layer_output[i-1],self.params['W%d'%i],self.params['b%d'%i]) scores = layer_output[self.num_layers] # If test mode return early if mode == 'test': return scores loss, grads = 0.0, {} loss, dscores = softmax_loss(scores,y) for i in range(1, self.num_layers+1): loss += 0.5*self.reg*np.sum(self.params['W%d' %i]*self.params['W%d' %i]) if self.normalization == 'batchnorm': for i in range(self.num_layers, 0, -1): if i!=self.num_layers: if self.use_dropout: dscores = dropout_backward(dscores,dropout_cache[i]) (dscores, grads['W%d' %i], grads['b%d' %i], grads['gamma%d' %i], grads['beta%d' %i]) = batch_relu_backward( dscores, cache[i] ) else: dscores, grads['W%d' %i], grads['b%d' %i] = affine_backward( dscores, cache[i] ) # Add regularization to the weights gradient grads['W%d' %i] += self.reg*self.params['W%d' %i] elif self.normalization is None: for i in range(self.num_layers,0,-1): if i == self.num_layers: dscores, grads['W%d'%i], grads['b%d'%i] = affine_backward(dscores,cache[i]) else: if self.use_dropout: dscores = dropout_backward(dscores,dropout_cache[i]) dscores, grads['W%d'%i], grads['b%d'%i] = affine_relu_backward(dscores,cache[i]) grads['W%d'%i] += self.reg * self.params['W%d'%i] return loss, grads def predict(self, X, y, which_network=[0]): self.define_parameters(which_network,trianable_mask=[0]*self.num_networks) y_pred = [] scores = self.loss(X) y_pred.append(np.argmax(scores, axis=1)) y_pred = np.hstack(y_pred) acc = np.mean(y_pred == y) print('Accuracy is %f'%acc) return acc
211f94c9fdbab5f383c04a4c3267dc0273d02c31
HanhHongBui/CS50-Pset6-Sentiments
/credit.py
1,584
3.59375
4
import cs50 #prompt for input print("Number: ",end="") cardnum = cs50.get_int() n = len(str(cardnum)) if n!=13 and n!=15 and n!=16: print("INVALID") else: cardnumodd= cardnum cardnumeven=cardnum//10 count = 0 cardnum1 = [] cardnum2 = [] cardnum_multiply=[] #sum of odd digits for i in range (0,(n+1)//2): cardnum1.insert(i,cardnumodd%10) cardnumodd=cardnumodd//100 #print("odd: {}".format(cardnum1[i])) s_odd = sum(cardnum1) #print("s odd: {}".format(s_odd)) #sum of other digits, x2 for j in range (0,(n//2)): cardnum2.insert(j,cardnumeven%10) cardnumeven=cardnumeven//100 #print("even: {}".format(cardnum2[j])) cardnum_multiply=[2*x for x in cardnum2] for k in range (0,n//2): #print("x2: {}".format(cardnum_multiply[k])) if cardnum_multiply[k] >= 10: cardnum_multiply[k] = (cardnum_multiply[k])%10 count = count+1 s_even = count + sum(cardnum_multiply) s = s_odd + s_even smod = s%10 #print("s even: {}".format(s_even)) #print("s: {}".format(s)) #check brands cardnumstr=str(cardnum) if (n == 13 or n == 16) and cardnumstr[0] == '4' and smod==0: print("VISA") elif n == 15 and cardnumstr[0] == '3' and (cardnumstr[1] =='4' or cardnumstr[1] =='7') and smod==0 : print("AMEX") elif n == 16 and cardnumstr[0]== '5' and (int(cardnumstr[1]) in range(0,6)) and smod==0: print("MASTERCARD") else: print("INVALID")
1f3d4dca04578bb6c7deb4b0987a36e7256f83bf
seanlucrussell/computing
/Python/Project Euler/10_summation_of_primes.py
396
3.890625
4
# filter out non primes, loop a = 1 primes = [2] divis = True primenum = 2 while a < 2000000: #we want to check to see if a is divisible by any number in primes, if not, append to primes and increase primes counter a += 2 print a for x in primes: if a % x == 0: divis = True break else: divis = False if divis == False: primes.append(a) primenum += a print primenum
dabff042ff00e4fafdae99b1498193ef679b3790
shrddha-p-jain/Machine-Learning-Assignments
/kmeansClus.py
2,274
3.578125
4
import matplotlib.pyplot as plt from sklearn import datasets from sklearn.cluster import KMeans import sklearn.metrics as sm import pandas as pd import numpy as np # import some data to play with iris = datasets.load_iris() iris.data iris.feature_names iris.target iris.target_names # Store the inputs as a Pandas Dataframe and set the column names x = pd.DataFrame(iris.data) x.columns = ['Sepal_Length','Sepal_Width','Petal_Length','Petal_Width'] y = pd.DataFrame(iris.target) y.columns = ['Targets'] # Set the size of the plot plt.figure(figsize=(14,7)) # Create a colormap colormap = np.array(['red', 'lime', 'black']) # Plot Sepal plt.subplot(1, 2, 1) plt.scatter(x.Sepal_Length, x.Sepal_Width, c=colormap[y.Targets], s=40) plt.title('Sepal') plt.subplot(1, 2, 2) plt.scatter(x.Petal_Length, x.Petal_Width, c=colormap[y.Targets], s=40) plt.title('Petal') # K Means Cluster model = KMeans(n_clusters=3) model.fit(x) # This is what KMeans thought model.labels_ # View the results # Set the size of the plot plt.figure(figsize=(14,7)) # Create a colormap colormap = np.array(['red', 'lime', 'black']) # Plot the Original Classifications plt.subplot(1, 2, 1) plt.scatter(x.Petal_Length, x.Petal_Width, c=colormap[y.Targets], s=40) plt.title('Real Classification') # Plot the Models Classifications plt.subplot(1, 2, 2) plt.scatter(x.Petal_Length, x.Petal_Width, c=colormap[model.labels_], s=40) plt.title('K Mean Classification') # The fix, we convert all the 1s to 0s and 0s to 1s. predY = np.choose(model.labels_, [1,0,2]).astype(np.int64) print (model.labels_) print (predY) # View the results # Set the size of the plot plt.figure(figsize=(14,7)) # Create a colormap colormap = np.array(['red', 'lime', 'black']) # Plot Orginal #subplot(nrows, ncols, index) plt.subplot(1, 2, 1) plt.scatter(x.Petal_Length, x.Petal_Width, c=colormap[y.Targets], s=40) plt.title('Real Classification') # Plot Predicted with corrected values plt.subplot(1, 2, 2) plt.scatter(x.Petal_Length, x.Petal_Width, c=colormap[predY], s=40) plt.title('K Mean Classification') # Performance Metrics sm.accuracy_score(y, predY) # Confusion Matrix sm.confusion_matrix(y, predY)
a3451cdec046bdf0675d722da62c9b80cf17c445
SpheITguru/DDA-Digital-differential-analyzer-
/DDA.py
742
4.03125
4
print("Enter the value of x1: ") x1 = int(input()) print("Enter the value of x2: ") x2 = int(input()) print("Enter the value of y1: ") y1 = int(input()) print("Enter the value of y2: ") y2 = int(input()) def ROUND(a): return int(a + 0.5) dx = x2 - x1 dy = y2 - y1 m = dy/dx if (dx > dy): steps = abs(dx) print() print("m < 1, increase in x-axis") else: steps = abs(dy) print() print("m > 1, increase in y-axis") xincrement = dx/steps yincrement = dy/steps for i in range(0,steps-1): x1 = x1 + xincrement y1 = y1 + yincrement print('{:2d} \t{:5d}, \t{:2.4f} \t{:3d} {:3d} \t{:2.3f} ({}, {})'.format( i, ROUND(x1), y1, dx, dy, m,ROUND(x1), ROUND(y1)))
64914ff64da1a46bcb15ad131a2f93b883dea165
Aasthaengg/IBMdataset
/Python_codes/p02847/s885882291.py
177
3.640625
4
#!/usr/bin/env python3 def main(): S = input() week = ['SUN','MON','TUE','WED','THU','FRI','SAT'] print(7-week.index(S)) if __name__ == "__main__": main()
881ca383d70fbcb637238cc2f2e76fcd79472141
PabloAndo/WeeklyPythonExercises
/Exercise_10/Exercise_10.py
3,135
3.75
4
# -*- coding: utf-8 -*- from collections import namedtuple from collections import defaultdict Person = namedtuple('Person', ['first', 'last']) class TableFull(Exception): pass class GuestList(): # GuestList is a list with each element being # a Person (numedtuple) and a table number(int) max_at_table = 10 def __init__(self): self.tables_and_guests = defaultdict(list) def assign(self, person, new_table_number): # Check that there is space if len(self.tables_and_guests[new_table_number]) == self.max_at_table: raise TableFull("No room at the table!") # Look through existing tables; remove if the person is there for table_number, guests in self.tables_and_guests.items(): if person in guests: guests.remove(person) break # add the person to the new table self.tables_and_guests[new_table_number].append(person) def __len__(self): return sum([len(one_table) for one_table in self.tables_and_guests.values()]) def table(self, table_number): return self.tables_and_guests[table_number] def unassigned(self): return self.table(None) def free_space(self): return {table_number: self.max_at_table - len(guests) for table_number, guests in self.tables_and_guests.items() if table_number} def guests(self): guests_dict = {one_guest: table_number for table_number, guests_at_table in self.tables_and_guests.items() for one_guest in guests_at_table} return sorted(guests_dict.keys(), key=lambda g: (guests_dict[g] or -1, g.last, g.first)) def __repr__(self): output = '' for table_number, guests_at_table in sorted( self.tables_and_guests.items(), key=lambda t: t[0] or -1): output += '{0}\n'.format(table_number) for one_guest in sorted(guests_at_table, key=lambda t: t[::-1]): output += '\t{0}, {1}\n'.format(one_guest.last, one_guest.first) return output if __name__ == "__main__": # Person = namedtuple('Person', ['first', 'last']) gl = GuestList() gl.assign(Person('Waylon', 'Dalton'), 1) gl.assign(Person('Justine', 'Henderson'), 1) gl.assign(Person('Abdullah', 'Lang'), 3) gl.assign(Person('Marcus', 'Cruz'), 1) gl.assign(Person('Thalia', 'Cobb'), 2) gl.assign(Person('Mathias', 'Little'), 2) gl.assign(Person('Eddie', 'Randolph'), None) gl.assign(Person('Angela', 'Walker'), 2) gl.assign(Person('Lia', 'Shelton'), 3) gl.assign(Person('Hadassah', 'Hartman'), None) gl.assign(Person('Joanna', 'Shaffer'), 3) gl.assign(Person('Jonathon', 'Sheppard'), 2) p = Person('Joanna', 'Shaffer') gl.assign(p, 3) # print(len(gl)) # 1print(gl.table(2)) # print(gl.unassigned()) # print(gl.free_space()) print(gl.guests())
1f62dbb41acd0f6bd5008bc0b3f47f4c52fbb92a
marranzr/MarTest
/python/HeadFirst/Chapter2/nester/nester.py
565
4.09375
4
""" This is the "nester.py" module, and it provides one function called print_lol() which prints lists that may or may not include nested lists.""" def print_lol(the_list): """ This function takes a positional argument called "the_list", which is any Python list(of, possibly, nested lists). Each data item in the provided list is recursively printed to the screen on its own line.""" for each_item in the_list: if isinstance(each_item, list): print_lol(each_item) else: print(each_item)
5e8d2bf77f390bb16c9d3cb17d87c1eb8fb71565
siva4646/Private-Projects
/Python_Course/PROJECTS/Hangman/Hangman/task/hangman/hangman.py
281
3.875
4
from random import randint print('H A N G M A N') words = ['python', 'java', 'kotlin', 'javascript'] secret_word = words[randint(0, 3)] word = secret_word) guess = input(f"Guess the word: {word}") if guess == secret_word: print('You survived!') else: print('You lost!')
93c42bfaff042d613620eee574dee0cca934d707
gui-csilva/python
/Python/Temporario.py
219
3.5
4
def inteiros(primeiro, segundo, terceiro, quarto): a = primeiro + 5 print(a) b = segundo - 5 print(b) c = terceiro * 5 print(c) d = quarto / 5 print(d) a = 1 b = 2 c = 3 d = 4 inteiros(b, c, d, a)
81a88957b875edb6828a79753656f3a9fcb18b42
sanket-arote/Python
/Session's Code/Addition.py
480
3.96875
4
# price_of_balls is a variable....................... price_of_balls = 10 price_of_pencils = 20.09 number_of_balls = 8 number_of_pencils = 10 total = price_of_balls * number_of_balls + price_of_pencils * number_of_pencils # print will basically print your statement............................... print('Welcome to our shop') print('Please Pay', total) print('Visit Again') # it will give you which type of variable we are using................... type(number_of_pencils)
2191a717765fcba02c7e6232c6ff6fa28486b50f
sgrade/pytest
/practice_python/draw_a_game_board.py
469
3.6875
4
# http://www.practicepython.org/solution/2015/11/01/24-draw-a-game-board-solutions.html def print_horizontal(dimension): print(' ---' * dimension) def print_vertical(dimension): print('| ' * (dimension + 1)) def main(): dimension = int(input('Please provide game size: ')) for index in range(dimension): print_horizontal(dimension) print_vertical(dimension) print_horizontal(dimension) if __name__ == '__main__': main()
20077a41adb8ae60dc5b90137bda9bb492ed886f
JoshRifkin/IS211_Assignment1
/assignment1_part2.py
338
3.859375
4
class Book: def __init__(self, author, title): self.author = author self.title = title def display(self): print(self.title + ", written by " + self.author +".") book1 = Book("Of Mice and Men", "John Steinbeck") book2 = Book("To Kill a Mockingbird", "Harper Lee") book1.display() book2.display()
0efe46ca8f6dacbb65fa9999fef88fa9f389d122
jyabka/PythonExam
/10.Class.py
290
3.71875
4
class Str: def __init__(self, c_string): self.c_string = c_string def user_input(self): self.c_string = input() return self.c_string def toUpperCase(self): print(self.c_string.upper()) c_str = Str("") c_str.user_input() c_str.toUpperCase()
6b3ccd380252c282ab7959fbbec3f90e4bd8e2bc
nelliesnoodles/StatsClass
/normal_dist.py
5,319
4.125
4
# Normal Distribution AKA Gaussian probability import math from scipy.stats import norm #Note: z-score is the distance from the mean and it's standard deviation? *clarify* def normal_deviation(a, b): """ What is the standard deviation of the data point distribution? I need clarification on where this '12' comes in. Why 12? deviation is: the square root of ((the high value, minus the low value squared) divided by 12) """ deviation = math.sqrt((b-a)**2 / 12) print("The deviation of this normal distribution is : ", deviation) return deviation def normal_mean(a, b): """ What is b and a? The range at which the distribution falls. example: the number of paintings sold in a day are 5 - 100. a = 5, b = 100 The mu, or standard mean (center point of data) of this normal distribution: u = (a + b) / 2 """ mean = (a + b) / 2 print("The standard mean of this normal distribution is: ", mean) return mean def x_bar_Normal_distribution(a, b, n): """ THIS HAS NOT BEEN TESTED. The deviation of the Normal distribution of a sample of means of a normal distribution. deviation / sqrt(number of samples) """ mean = normal_mean(a, b) deviation = normal_deviation(a, b) normal_x_bar_deviation = deviation / math.sqrt(n) print("The standard deviation of the sample of means from the normal distribution ( [n] samples ) is: ", normal_x_bar_deviation) return normal_x_bar_deviation def range_probability_cdf(mean, devi, range_low, range_high): """ The formula will not work on a continuous probability. SciPi has a built in method to do this math for us. I wanted to do it myself, so I could learn the math, and I did learn the formula below pretty good, but the formula we need to calculate a continuous probability is much more complex. Time to use the hammer instead of my hand. norm.cdf(x, loc(mean), scale(deviation)) Formula probability density function: the area under the curve for a given point p(x) is: 1 / ( 2 * pi * (mean squared) * (mathmatical number e to the power of (our z score squared))) 1/ 2 * pi * m**2 * e**(z**2) [[e = math.exp, pi = math.pi]] for the range, we would take the larger area, minus the smaller area to get the difference, which is the area just between these two p(x)s. """ # 1 / (2 * pi * deviation**2) = x # e ** -((range_num - mean)**2 / 2*deviation**2 = y # area = y/x large = norm.cdf(range_high, mean, devi) print("scipy large area = ", large) small = norm.cdf(range_low, mean, devi) print("scipy small area = ", small) range_area = large - small message = f"The area in range {range_low} - {range_high} is {range_area}" return range_area def mycdf(mean, devi, range_low, range_high): """ If the ranges are above the mean, we must get the inverse area. so if it's one deviation above, or any positive deviation above, we want 1 - results. Formula probability density function: the area under the curve for a given point p(x) is: 1 / ( 2 * pi * (mean squared) * (mathmatical number e to the power of (our z score squared))) 1/ 2 * pi * m**2 * e**(z**2) [[e = math.exp, pi = math.pi]] for the range, we would take the larger area, minus the smaller area to get the difference, which is the area just between these two p(x)s. """ devi_square = float(devi**2) low_e_num = math.exp(-((float(range_low) - float(mean))**2 / (2*devi_square))) denom = float( math.sqrt(2 * math.pi * devi_square) ) high_e_num = math.exp(-((float(range_high) - float(mean))**2 / (2*devi_square))) low_area = float(low_e_num / denom) high_area = float(high_e_num / denom) if range_low > mean: low_area = 1 - low_area if range_high > mean: high_area = 1 - high_area print("my high_area = ", high_area) print("my low_area = ", low_area) under_curve = high_area - low_area message = f"The area under the curve for range {range_low} - {range_high} = {under_curve}" return under_curve def test1(): # test against excel data: # excel formula 1 = [=NORM.DIST(8.5, 10, 1.5, 1) => .1587 # excel formula 2 = [=NORM.DIST(11.5, 10, 1.5, 1) => .8414 # ex1 - ex2 = .6827 #range_probability_withmeandevi(mean, devi, range_low, range_high): area = range_probability_cdf(10, 1.5, 8.5, 11.5) print(area) def test2(): """ compare results for my density function and using scipy's empirical rule says that this range should be about 95% """ area = range_probability_cdf(12, 1.3, 9.4, 14.6) area2 = mycdf(12, 1.3, 9.4, 14.6) print("scipy result:", area) print("my result:", area2) def test3(): """ compare results for my density function and using scipy's empirical rule says that this range should be about 64% """ scipy_area = range_probability_cdf(10, 1.5, 8.5, 11.5) my_area = mycdf(10, 1.5, 8.5, 11.5) print("scipy result:", scipy_area) print("my result:", my_area) #test1() -- pass #test2() -- fail #test3() -- fail
a666d5e6809ff780061d1e495cc6d38e67178360
ankithmjain/algorithms
/searching_algo.py
517
3.734375
4
arr = [1, 2, 3, 4, 9, 10, 40 ] x = 10 def linear_search(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1 print("By linear search", linear_search(arr, x)) def binary_search(arr, x): lower = 0 upper = len(arr) -1 while True: mid = int((lower + upper)/2) if x > arr[mid]: lower = mid elif x< arr[mid]: upper = mid else: return mid print("By binary search", binary_search(arr, x))
734e7184658ebb12e3ee2bd25d866171c60914af
yaseen-ops/python-100-days-of-course
/Intermediate/day18/turtle_challenge/turtle_square.py
404
3.71875
4
from turtle import Turtle, Screen def draw_square(): seemaan.forward(150) seemaan.left(90) color_list = ["red", "blue", "brown", "green"] seemaan = Turtle() seemaan.shape("turtle") seemaan.turtlesize(1.8) choose_color = 0 for _ in range(4): color = color_list[choose_color] draw_square() seemaan.color(color) choose_color += 1 my_screen = Screen() my_screen.exitonclick()
784b5f600f3fd46c302e5d6fc301a7771703cbd4
combateer3/RFID-Multitool
/scanner.py
911
3.640625
4
import rfid import actions import csv # global to store the map of uids to actions uid_map = {} def get_action(uid): # getattr will return function in the actions module return getattr(actions, uid_map[uid]) def loop(): while True: print("Waiting for a Mifare tag...") uid = rfid.read_card() # format uid for pretty printing formatted = ''.join('{:02x}'.format(x) for x in uid) print("Read a card with UID: {}".format(formatted)) # perform what is mapped to that uid in the csv file action = get_action(formatted) action() # call action print('\n') def parse_csv_map(reader): global uid_map for row in reader: uid_map[row[0]] = row[1] if __name__ == '__main__': with open('map.csv', newline='') as f: reader = csv.reader(f, delimiter=',') parse_csv_map(reader) loop()
9a76ff60b4ae429545006eb526d36a0dcc0c404c
memicq/ProgrammingContestAnswers
/aizu/lectures/algorithm_and_data_structure/tree/tree_walk.py
2,829
3.5
4
#! python3 # tree_walk.py from enum import Enum, auto from collections import deque class Color(Enum): WHITE = auto() GRAY = auto() BLACK = auto() class BinaryTreeNode(): def __init__(self, parent=None, left=None, right=None): self.parent = parent self.left = left self.right = right self.sibling = None self.color = Color.WHITE def print_elements(ordered): for ele in ordered: print(' {}'.format(ele), end='') print('') n = int(input()) nodes = [BinaryTreeNode() for i in range(n)] for i in range(n): id, left, right = list(map(int, input().split(' '))) if left != -1: nodes[id].left = left nodes[left].parent = id nodes[left].sibling = right if right != -1: nodes[id].right = right nodes[right].parent = id nodes[right].sibling = left root = 0 for i in range(n): if nodes[i].parent == None: root = i def init_color(): global nodes for i in range(len(nodes)): nodes[i].color = Color.WHITE def preorder_bfs(s): preordered.append(s) nodes[s].color = Color.GRAY if nodes[s].left != None and nodes[nodes[s].left].color == Color.WHITE: preorder_bfs(nodes[s].left) if nodes[s].right != None and nodes[nodes[s].right].color == Color.WHITE: preorder_bfs(nodes[s].right) nodes[s].color = Color.BLACK inorder_stack = deque([]) def inorder_dfs_init(s): init_color() inorder_stack.append(s) inorder_dfs() def inorder_dfs(): u = inorder_stack.pop() if nodes[u].left != None and nodes[nodes[u].left].color == Color.WHITE: inorder_stack.append(u) inorder_stack.append(nodes[u].left) inorder_dfs() inordered.append(u) if nodes[u].right != None and nodes[nodes[u].right].color == Color.WHITE: inorder_stack.append(nodes[u].right) inorder_dfs() postorder_stack = deque([]) def postorder_dfs_init(s): init_color() postorder_stack.append(s) postorder_dfs() def postorder_dfs(): u = postorder_stack.pop() if nodes[u].left != None and nodes[nodes[u].left].color == Color.WHITE: postorder_stack.append(u) postorder_stack.append(nodes[u].left) postorder_dfs() if nodes[u].right != None and nodes[nodes[u].right].color == Color.WHITE: postorder_stack.append(nodes[u].right) postorder_dfs() postordered.append(u) print('Preorder') # 根節点、左部分木、右部分木の順 preordered = [] preorder_bfs(root) print_elements(preordered) print('Inorder') # 左部分木、根節点、右部分木の順 inordered = [] inorder_dfs_init(root) print_elements(inordered) print('Postorder') # 左部分木、右部分木、根節点の順 postordered = [] postorder_dfs_init(root) print_elements(postordered)