blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e2f9867fa525b01ffadecbe5b5185228cbe17464
tupakulasuresh/practice
/py/remove_linked_list_ele.py
3,335
4.15625
4
import unittest # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): return '{}(val={})'.format(self.__class__.__name__, self.val) def __repr__(self): return self.__str__() def remove_elements(head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ new_head = None previous = None print "Removing {} from the list".format(val) while head: if head.val == val: if previous: previous.next = head.next else: previous = head if new_head is None: new_head = head head = head.next print_linked_list(new_head) return new_head def create_linked_list(eles): print "Creating linked list with ", eles head = None current = None for i in eles: l = ListNode(i) if head is None: head = l current = l else: current.next = l current = l # print_linked_list(head) return head def print_linked_list(head): for i in traverse_list(head): print i, print "" def traverse_list(head): while head: yield head.val head = head.next def merge_lists(l1, l2): if not l1: return l2 if not l2: return l1 if l1.val > l2.val: l2, l1 = l1, l2 head = l1 l1_prev = l1 l2_prev = l2 while l1 and l2: while l1 and l1.val <= l2.val: l1_prev = l1 l1 = l1.next l1_prev.next = l2 if l1: while l2 and l2.val <= l1.val: l2_prev = l2 l2 = l2.next l2_prev.next = l1 print_linked_list(head) return head class TestMergeSortedList(unittest.TestCase): def verify(self, input1, input2): print "\n", "=" * 80 exp_output = sorted(input1 + input2) input1 = create_linked_list(input1) input2 = create_linked_list(input2) got_output = list(traverse_list(merge_lists(input1, input2))) print "exp_output: ", exp_output print "got_output: ", got_output self.assertEquals(exp_output, got_output) def test01(self): l1 = [2] l2 = [1] self.verify(l1, l2) def test02(self): l1 = [2] l2 = [3] self.verify(l1, l2) def test03(self): l1 = [1, 2, 4] l2 = [1, 3, 4] self.verify(l1, l2) def test04(self): l1 = [1, 2, 5] l2 = [3, 4, 6] self.verify(l1, l2) def test05(self): l1 = [1, 2, 2, 6] l2 = [3, 4, 5] self.verify(l1, l2) class TestRemoveElement(unittest.TestCase): def verify(self, list1, val): print "\n", "=" * 80 exp_output = [ele for ele in list1 if ele != val] list1 = create_linked_list(list1) got_output = list(traverse_list(remove_elements(list1, val))) print "exp_output: ", exp_output print "got_output: ", got_output self.assertEquals(exp_output, got_output) def test01(self): self.verify([1], 1) def test02(self): self.verify([1, 2, 3, 5, 6, 7, 8, 6], 6) if __name__ == '__main__': unittest.main()
7f3d555b76e0dfb93f83212b0c4d0211d0c9824c
guilherme-witkosky/MI66-T5
/Lista 2/L2E04.py
270
4.0625
4
#Exercício 4 letra = input("Informe uma letra :") if letra.upper() == "A" or letra.upper() == "E" or letra.upper() == "I" == letra.upper() == "O" or letra.upper() == "U": print("O letra informado é vogal") else: print("O letra informado é consoante")
a86c6112acbf26ef2d81ab7cc45c0f10725e34e9
AlessioVallero/algorithms-coursera
/part1/week2/intersection-of-two-sets/intersections_of_two_sets.py
1,381
3.6875
4
from functools import cmp_to_key class TwoSets: """ Given two arrays a[] and b[], each containing n distinct 2D points in the plane we count the number of points that are contained both in array a[] and array b[] """ @staticmethod def compare(first, second): if first[0] < second[0] or (first[0] == second[0] and first[1] < second[1]): return -1 elif first[0] > second[0] or (first[0] == second[0] and first[1] > second[1]): return 1 else: return 0 @staticmethod def intersection(a, b): if len(a) < 1 or len(b) < 1: return 0 sorted_a = sorted(a, key=cmp_to_key(TwoSets.compare)) sorted_b = sorted(b, key=cmp_to_key(TwoSets.compare)) i = j = count = 0 while i < len(sorted_a) and j < len(sorted_b): compare_elements = TwoSets.compare(sorted_a[i], sorted_b[j]) if compare_elements == 0: count += 1 i += 1 j += 1 elif compare_elements == -1: i += 1 else: j += 1 return count def unit_test(): """ Test TwoSets """ first_ar = [[10, 1], [4, 5], [7, 2]] second_ar = [[50, 4], [7, 2], [17, 2], [10, 1], [4, 5]] print(TwoSets.intersection(first_ar, second_ar)) unit_test()
7e841ae4292af9f9b67ae2ca4d721e599b4e1b21
turdasanbogdan/PythonExs
/PythonWork/while_loop.py
725
4.0625
4
sandwich_orders=['pui','vita', 'pastrami','paine', 'pastrami', 'pastrami'] finished_sandwiches=[] print("We ran out of pastrami") while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') while sandwich_orders : finished = sandwich_orders.pop() finished_sandwiches.append(finished) print(finished_sandwiches) print(sandwich_orders) responses = {} quit="" while quit != "x": name=input("Whats`s your name? ") nation = input("Where are you from ? ") responses[name] = nation quit=input("To continue the poll prex any key, else pres x") print("responses" + str(responses)) print("---------Poll response, got the next countries: -----------") for country in set(responses.values()): print(country)
15883e8c6caad904459a635e13ea7e9a7861b971
mish-511/cse-470-final
/view.py
276
3.515625
4
class Choose: def choices(): n = """ ====== Bakery ======= 1. Number of available cakes 2. Vanilla cake $5 3. Chocolate cake $10 4. Strawberry cake $12 5. Total bill 6. Exit """ print(n)
5bc11fb46e6a48766b8d5a2e1dfbaee38949d4b7
rishi772001/Competetive-programming
/DataStructures/BST/sum of tree.py
553
3.703125
4
''' @Author: rishi https://binarysearch.com/problems/Tree-Sum ''' class Tree: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution: sum = 0 def find(self, root): if root is None: return Solution.sum += root.val self.find(root.left) self.find(root.right) def solve(self, root): self.find(root) return Solution.sum root = Tree(0) root.left = Tree(1) s = Solution() print(s.solve(root))
a91d74e5f2f5c17e76152bd4a615da62dc8c7c47
Suraksha-sachan/tathastu_week_of_code
/day5/program1.py
594
3.84375
4
def replace0with5(number): number += suraksha(number) return number def suraksha(number): result = 0 a = 1 if (number == 0): result += (5 * a) while (number > 0): if (number % 10 == 0): result += (5 * a) number //= 10 a *= 10 return result n=int(input("ENTER NUMBER: ")) print(replace0with5(n))
9327d7e6f0f5036352db40e28100dafe0a5b2ed8
Tylerssmith/pythonista-scripts
/TimeClock.py
4,767
3.8125
4
# coding: utf-8 ''' #---Filename: TimeClock.py #---Author: coomlata1 #---Created: 02-17-2018 #---Last Updated: 02-18-2018 #---Description: Calculates the time elapsed in hours & minutes between two user selected times. Ideal for calculating hours in shift work. Code includes time deductions for lunches if applicable. #---Contributors: Time arithmetic info gathered from: https://stackoverflow.com/questions/3096953/how-to- calculate-the-time-interval-between-two-time-strings https://stackoverflow.com/questions/46402022/subtract- hours-and-minutes-from-time ''' import ui import datetime from datetime import timedelta import time # Action for Start Time DateTimePicker def change_start_time(self): # Sync label text with DateTimePicker to match selected start time lbl_pick_start.text = self.date.strftime('%I:%M %p') # Action for End Time DateTimePicker def change_end_time(self): # Sync label text with DateTimePicker to match selected end time lbl_pick_end.text = self.date.strftime('%I:%M %p') # Action for 'Select' button on title bar def select(self): # Formst for 12 hour clock with AM-PM syntax FMT = '%I:%M %p' # Assign start & end times as selected on the respective DateTimePickers start = dp_start.date.strftime(FMT) end = dp_end.date.strftime(FMT) # Lunch time in minutes...set to more, less, or zero as applicable. lunch = 30 # Calculate time elapsed between start & end times, subtracting for any unpaid lunch time as necessary tdelta = datetime.datetime.strptime(end, FMT) - datetime.datetime.strptime(start, FMT) - timedelta(hours = 0, minutes = lunch) ''' If you want the code to assume the interval crosses midnight (i.e. it should assume the end time is never earlier than the start time), you add the following lines to the above code: ''' if tdelta.days < 0: tdelta = timedelta(days = 0, seconds = tdelta.seconds, microseconds = tdelta.microseconds) lbl_tpassed.text = '{}'.format(tdelta) # DateTimePicker ui dp = ui.View(name = 'Pick Start & End Times', frame = (0, 0, 414, 736)) dp.flex = 'HLRTB' dp.background_color = 'cyan' b1 = ui.ButtonItem('Select', action = select, tint_color = 'green') dp.right_button_items = [b1] dp_lb1 = ui.Label(frame = (130, 6, 160, 24)) dp_lb1.flex = 'HLRTB' dp_lb1.font = ('<system>', 14) dp_lb1.alignment = ui.ALIGN_CENTER dp_lb1.text = 'Start Time:' dp.add_subview(dp_lb1) dp_lb2 = ui.Label(frame = (130, 325, 160, 24)) dp_lb2.flex = 'HLRTB' dp_lb2.font = ('<system>', 14) dp_lb2.alignment = ui.ALIGN_CENTER dp_lb2.text = 'End Time:' dp.add_subview(dp_lb2) dp_lb3 = ui.Label(frame = (80, 645, 265, 24)) dp_lb3.flex = 'HLRTB' dp_lb3.font = ('<system>', 14) dp_lb3.alignment = ui.ALIGN_CENTER dp_lb3.text = 'Time Passed...Click \'Select\' To Calculate:' dp.add_subview(dp_lb3) lbl_pick_start = ui.Label(frame = (105, 35, 200, 35)) lbl_pick_start.flex = 'HLRTB' lbl_pick_start.font = ('<system-bold>', 14) lbl_pick_start.alignment = ui.ALIGN_CENTER lbl_pick_start.border_width = 2 lbl_pick_start.corner_radius = 10 lbl_pick_start.background_color = 'yellow' lbl_pick_start.text = 'Time' dp.add_subview(lbl_pick_start) lbl_pick_end = ui.Label(frame = (105, 355, 200, 35)) lbl_pick_end.flex = 'HLRTB' lbl_pick_end.font = ('<system-bold>', 14) lbl_pick_end.alignment = ui.ALIGN_CENTER lbl_pick_end.border_width = 2 lbl_pick_end.corner_radius = 10 lbl_pick_end.background_color = 'yellow' lbl_pick_end.text = 'Time' dp.add_subview(lbl_pick_end) lbl_tpassed = ui.Label(frame = (105, 675, 200, 35)) lbl_tpassed.flex = 'HLRTB' lbl_tpassed.font = ('<system-bold>', 14) lbl_tpassed.alignment = ui.ALIGN_CENTER lbl_tpassed.border_width = 2 lbl_tpassed.corner_radius = 10 lbl_tpassed.background_color = 'yellow' lbl_tpassed.text_color = 'red' lbl_tpassed.text = '00:00:00' dp.add_subview(lbl_tpassed) dp_start = ui.DatePicker(frame = (48, 85, 320, 225)) dp_start.flex = 'HLRTB' dp_start.border_width = 2 dp_start.corner_radius = 10 dp_start.background_color = 'yellow' dp_start.mode = ui.DATE_PICKER_MODE_TIME dp_start.action = change_start_time dp.add_subview(dp_start) dp_end = ui.DatePicker(frame = (48, 405, 320, 225)) dp_end.flex = 'HLRTB' dp_end.border_width = 2 dp_end.corner_radius = 10 dp_end.background_color = 'yellow' dp_end.mode = ui.DATE_PICKER_MODE_TIME dp_end.action = change_end_time dp.add_subview(dp_end) # Pick times...Default times on start and end picker is current time. dp_start.date = datetime.datetime.now() dp_end.date = datetime.datetime.now() # Format today's time as '%I:%M %p' and put them on labels lbl_pick_start.text = dp_start.date.strftime('%I:%M %p') lbl_pick_end.text = dp_end.date.strftime('%I:%M %p') # Show the DateTimePicker ui dp.present(orientations = ['portrait'])
f8b36e5839d467d7743339e53ad3a516c45f74ae
mcaptain79/common-data-structures-implementation-in-python
/singlyLinkedList.py
2,232
3.96875
4
class X: def __init__(self,key): self.key = key self.nexty = None class LinkedList: def __init__(self): self.head = None def List_Insert(self,key): x = X(key) x.nexty = self.head self.head = x def List_Delete(self,key): isFound = False x = self.head if self.head == None: return if self.head.key == key: self.head = x.nexty return while x != None: if x.key == key: isFound = True break previous = x x = x.nexty if isFound: previous.nexty = x.nexty #if exists returns attribute else returns not found def List_Search(self,key): counter = 0 x = self.head while x != None: if x.key == key: return counter counter += 1 x = x.nexty return 'NotFound' def Union(self,L2): x = self.head while x != None: y = x x = x.nexty y.nexty = L2.head def printList(self): tmp = self.head while tmp != None: print(tmp.key,end = '-->') tmp = tmp.nexty print('None') #I made an object and tested all the functions and they work properly L1 = LinkedList() for i in range(10): L1.List_Insert(i) print('initial list:') L1.printList() print('-------------------------------------------------------') L1.List_Delete(9) L1.List_Delete(8) L1.List_Delete(7) L1.List_Delete(11) L1.List_Delete(0) L1.List_Delete(3) L1.List_Delete(111) print('List after deleting some items:') L1.printList() print('-------------------------------------------------------') print('searching some elements:') print(L1.List_Search(6),L1.List_Search(2),L1.List_Search(1),L1.List_Search(20),L1.List_Search(9)) print('-------------------------------------------------------') L2 = LinkedList() L2.List_Insert(100) L2.List_Insert(200) L2.List_Insert(300) L2.List_Insert(25) L2.List_Insert(777) #union code test print('union of list1 and List2:') L1.Union(L2) L1.printList()
5b7b3d6c97b6c2b5db1f1d71e21ab69d9c9170f0
annisa-nur/wintersnowhite
/processingnumeric.py
2,031
4.28125
4
# Program ini meminta pengguna memasukkan tiga buah angka float # dan menuliskan keduanya, masing-masing dalam satu baris, # ke file angka.txt def main(): # [1] Minta pengguna memasukkan tiga buah angka desimal # Gunakan prompt "Masukkan sebuah angka desimal: " untuk angka pertama # dan prompt "Masukkan sebuah angka desimal lainnya: " untuk angka kedua dan ketiga angka1 = input("Masukkan sebuah angka desimal: ") angka2 = input("Masukkan sebuah angka desimal lainnya: ") angka3 = input("Masukkan sebuah angka desimal lainnya: ") # [2] Buka file angka.txt untuk ditulis dan tuliskan angka-angka yang didapat # dari pengguna ke file tersebut masing-masing dalam baris baru. with open('angka.txt', 'w') as out_file: out_file.write(str(angka1) + '\n') out_file.write(str(angka2) + '\n') out_file.write(str(angka3) + '\n') # [3] Tampilkan pesan "Data telah berhasil disimpan dalam file angka.txt." print('Data telah berhasil disimpan dalam file angka.txt.') # Panggil fungsi main main() ## another example # Program ini membaca isi file angka_float.txt # dan mengalikan angka yang terdapat dalam file tersebut def main(): # [1] Buka file dengan statement with atau 3 langkah menggunakan file: buka, proses, tutup. # Lalu ambil angka pertama pada baris pertama dan angka kedua pada baris kedua, simpan # angka pada setiap baris isi file masing-masing ke sebuah variabel with open('angka_float.txt', 'r') as infile: angka1 = float(infile.readline()) angka2 = float(infile.readline()) # [2] Hitung hasi kali dan tampikan sesuai dengan ketentuan program yang diminta kali = round(angka1 * angka2, 2) print('Baris 1 file angka_float.txt berisi: ' + str(angka1)) print('Baris 2 file angka_float.txt berisi: ' + str(angka2)) print('Hasil kali baris 1 dan baris 2 = ' + str(kali)) # Panggil fungsi main main()
752b6ddfe6acc5ce0b1f50a654e1d51836329be4
NenadPantelic/GeeksforGeeks-Must-Do-Interview-preparation
/String/Anagram.py
468
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 3 20:13:57 2020 @author: nenad """ def anagram(str1, str2): return "YES" if sorted(str1) == sorted(str2) else "NO" # Test 1 str1, str2 = "geeksforgeeks forgeeksgeeks".split() print(anagram(str1,str2)) # Test 2 str1, str2 = "allergy allergic".split() print(anagram(str1,str2)) # Testing t = int(input()) for i in range(t): str1, str2 = input().split() print(anagram(str1, str2))
5704e97650acf987e7fb88e707eb0ada2f96fd74
AndProg/lesson1
/numbers.py
190
3.734375
4
v = int(input('введите число от 1 до 10: ')) print('введенное значение:' + ' ' + str(v)) print('введенное значение +10:' + ' ' + str(v+10))
3fee6fe64615eefc561f1cfdb45b434c69a1f0ab
lhayhurst/exercism
/python/isogram/isogram.py
285
3.609375
4
def is_isogram(string): if string is None or len(string) == 0: return True string = string.lower() letters = set(string) for l in letters: if not l.isalnum(): continue if string.count(l) > 1: return False return True
23b3c46f1a00862fd00f31749827e38c915ccd26
rafaelperazzo/programacao-web
/moodledata/vpl_data/83/usersdata/195/42385/submittedfiles/dec2bin.py
137
3.65625
4
# -*- coding: utf-8 -*- from __future__ import division n=int(input('digite n:')) resto=n%2 i=0 soma=0 while n>0: s=s+resto*10**i n=n//2
2eb3fbd4ae7a9e2fe4118f7c1186ed85f2f4274c
Fightingkeyboard/CompSci
/03/PigLatin.py
168
3.890625
4
def PigLatin(str): vowels = 'aeiouAEIOU' if str[0] not in vowels: str = str[1:] + str[0] + 'ay' return (str) else: return str + 'ay'
a35291a4a267d8f1a704959b9d30af99a985e178
Neetika23/Machine-Learning
/Preprocessing/Standardization/without_normalizing.py
268
3.515625
4
# Split the dataset and labels into training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y) # Fit the k-nearest neighbors model to the training data knn.fit(X_train,y_train) # Score the model on the test data print(knn.score(X_test,y_test))
99e7ce60cd9061a3d0125226d9ff9609b2dea775
surajdakua/Exploratory-Data-Analysis
/HabermanEDA.py
5,540
3.625
4
''' @author Suraj Dakua Haberman Dataset/Kaggel to perform Exploratory Data Analysis(EDA). EDA is for seeing what the data can tell us beyond the formal modelling and also summarize the data characteristics often with visual methods. EDA can be also used for better understanding of data and main features of data. Machine learning is more about getting insights of data that is very very important. In machine learning is not about how much lines of cde you write but it is about how much richness you bring to the analysis of the data. ''' #import libraries required for the EDA. import numpy as np import pandas as pd import matplotlib.pyplot as plt #seaborn is a very good data visualization tool used in python. import seaborn as sns #load the dataset. # Source: https://www.kaggle.com/gilsousa/habermans-survival-data-set #dataset I'm using here is imbalanced dataset. haberman = pd.read_csv('haberman.csv') print(haberman.shape) #prints the number of rows and columns in the dataset print(haberman.columns) #prints the objects present in the dataset. print(haberman['year'].value_counts) # haberman.plot(kind='scatter', x='age',y='status') ''' This plots are 2D Scatter plots''' sns.set_style('whitegrid') sns.FacetGrid(haberman, hue='status', size=5)\ .map(plt.scatter, 'age', 'status') plt.legend(labels=['Survived more than 5yrs','Died within 5yrs']) sns.set_style('whitegrid') sns.FacetGrid(haberman, hue='year', size=5)\ .map(plt.scatter, 'age', 'year') plt.legend() '''Histogram plots''' sns.FacetGrid(haberman, hue='year', size=5)\ .map(sns.distplot, 'year') plt.legend() sns.FacetGrid(haberman, hue='age', size=5)\ .map(sns.distplot, 'age') plt.legend() sns.FacetGrid(haberman, hue='status', size=5)\ .map(sns.distplot, 'status') ''' Pair plots''' #pairplots plots pairwise scatter plot. #pair plot can be used to study the relationship between the two variables. sns.pairplot(haberman,hue='year',size=4) counts, bin_edges = np.histogram(haberman['age'],bins=5,density=True) ''' To seperate two most usefull features amongst all the features in a plot we use pair plots. ''' ''' univariate analysis as the name suggest one variable analysis. which of the variable is more usefull as compared to my other variables is known as univariate analysis. we only pick any one feature which is best suitable for the analysis. ''' ''' Cummulative Density Function(CDF) What percentage of Y-axis has value less than the corresponding point on the X-axis. It is the cummulative sum of the the probablities. Area under the curve of the PDF till that point is called as CDF. If we differentiate CDF we get PDF and if we integrate our PDF we get our CDF. ''' #to compute the pdf pdf = counts/(sum(counts)) print(pdf) print(bin_edges) #to compute the cdf cdf = np.cumsum(pdf) #cumsum = cummulative sum. plt.plot(bin_edges[1:],pdf) plt.plot(bin_edges[1:],cdf) ''' Mean, Variance and Standard Deviation. OUTLIER: Suppose we have 50 observtions and all observations lie between 1-10 but there is one observation which is 50 then such a point is called an OUTLIER If we have an outlier then the mean will increase drastically this this will be an error and we should take care of outliers using percentile std etc. Varince is average square distance from the mean value. And square rooot of variance is nothing but the standard deviation. Spread mathematicallly means standard deviation. ''' print(np.mean(haberman['age'])) print(np.std(haberman['year'])) ''' Mean, Variance and Standard Deviation can be easily corrupted easily if we have outliers. Median is the middle value of the observations If more than 50% of the values are corrupted or have outlier then the median gets corrupted. ''' print(np.median(haberman['age'])) #here 50 is the extreme value means an outlier we can see the difference. print(np.median(np.append(haberman['age'],50))) ''' Percentile: Suppose we want a 10th percentile value of the sorted array the the percentile value tells us that how many points are less than the 10th index and how many values are greater than the 10th index thats what a percentile is. Quantile: Break the sorted array into four parts(quant) is known as quantile. ''' #Quantile with gap of 25 in a range of 0,100 print(np.percentile(haberman['age'],np.arange(0,100,25))) #90th Percentile print(np.percentile(haberman['age'],90)) ''' Median Absolute Deviation Numpy dont have mad function so we use statsmodel(robust) to do this. ''' from statsmodels import robust print(robust.mad(haberman['age'])) ''' IQR: Inter Quartile Range Subtracting 75th value from 25th value gives the IQR range or value. ''' ''' Box plot tells us what is the value for 25th percentile, 50th percentile and 75th percentile. Whiskers are the lines around the box plot. SNS calculate whiskers values as 1.5xIQR Box plot takes the mean,median and quartiles and put them in the box form. ''' sns.boxplot(x='age',y='year', data=haberman) ''' Violin Plots: Combinatiom of histogram,pdf and box plot is violin plot. The thick box in the violin is the box plot with 25th.75th and 50th values. ''' sns.violinplot(x='age',y='status',data=haberman,size=7) ''' When we are looking at two variables and doing the analysis it is called bivariate analysis. Example is pair plots or scatetr plots. When we are looking for multiple variables then it is called multivariate analysis. Machine learning is all about multivariate analysis. ''' sns.jointplot(x='age',y='status',data=haberman,kind='kde ') plt.show()
76ae4d67a8f9709403c6ab3844834e6638c4c095
rodmur/hackerrank
/algorithms/implementation/utopiantree_recur.py
245
3.828125
4
#!/usr/bin/python3 import sys def grow(n): growth = 0 if n == 0: return 1 elif n & 1: growth = 2*(grow(n-1)) else: growth = grow(n-1) + 1 return growth n = int(sys.argv[1]) h = grow(n) print(h)
a7a9f37fa98cf6fc72cebe85d9f187e802ebe8c9
GuilhermeAntony14/Estudando-Python
/ex040.py
317
3.84375
4
print('vamos descobrir a sua nota!') n = float(input('Digite sua primeira nota: ')) n1 = float(input('Digite o segundo valor: ')) n2 = float((n+n1)/2) print(f'A media e {n2}!') if n2 <= 4: print('Reprovado!') elif n2 >= 5 and n2 < 7: print('Recuperação!') elif n2 >= 7: print('\033[32mAprovado!\033[m')
11ff8c482b2c7813ea0766be7f3186a3cc33776a
calabaza91/python
/CoxCaleb_Lab10_EmployeeClass.py
1,265
4.25
4
#This program creates a list of three employees using a class import Cox_employee def main(): #Get list of Employees employees = make_list() #Display data in list print('Here is the list of employees:') display_list(employees) def make_list(): #Make empty list emp_list = [] #Get Susan data name1 = 'Susan Meyers' idNum1 = '47899' dept1 = 'Accounting' title1 = 'Vice President' emp1 = Cox_employee.Employee(name1, idNum1, dept1, title1) emp_list.append(emp1) #Get Mark data name2 = 'Mark Jones' idNum2 = '39119' dept2 = 'IT' title2 = 'Programmer' emp2 = Cox_employee.Employee(name2, idNum2, dept2, title2) emp_list.append(emp2) #Get Joy data name3 = 'Joy Rogers' idNum3 = '81774' dept3 = 'Manufacturing' title3 = 'Engineer' emp3 = Cox_employee.Employee(name3, idNum3, dept3, title3) emp_list.append(emp3) return emp_list def display_list(emp_list): for item in emp_list: print("\n-------------------") print("Name: ", item.get_Name()) print("ID Number: ", item.get_IdNum()) print("Department: ", item.get_Dept()) print("Job Title: ", item.get_Title()) print("-------------------") main()
4bc86e76eb75ea25f5d12df13ecb70df9f65ee13
CodecoolBP20172/pbwp-3rd-si-game-statistics-DeboraCsomos
/part2/export.py
1,083
3.703125
4
#!/usr/bin/env python # Export functions from reports import * def exporting_results_to_file(export_file="reports.txt"): data_file = input("Give name of data file (e.g. game_stat.txt): \n") title = input("Enter title for question 5 (e.g. Diablo II): \n") with open(export_file, "w") as file: file.write(str(get_most_played(data_file)) + "\n"*2) file.write(str(round(sum_sold(data_file), 3)) + "\n"*2) file.write(str(round(get_selling_avg(data_file), 3)) + "\n"*2) file.write(str(count_longest_title(data_file)) + "\n"*2) file.write(str(get_date_avg(data_file)) + "\n"*2) file.write("\n".join([str(item) for item in get_game(data_file, title)]) + "\n"*2) file.write("\n".join({"{}: {}".format(k, str(v)) for k, v in count_grouped_by_genre(data_file).items()}) + "\n"*2) file.write("\n".join([str(item) for item in get_date_ordered(data_file)]) + "\n"*2) def main(): exporting_results_to_file() print ("Check your new reports.txt file.") if __name__ == "__main__": main()
6229e051c318e2f0a31404b7447cc5b3f49c40cb
Srinivas-Rao-au27/Accomplish_classes-
/Extra-Things/Extra_Files/27may.py
583
4.0625
4
# data = [ # [1, 2, 3], # [5, 6, 7], # [7, 8, 9] # ] # # for i in range(0, len(data)): # # for j in range(0, len(data)): # # print(data[i][j]) # for i in range(0, len(data)): # print(data[0][i]) Raw = int(input("Enter the number of rows:")) Clm = int(input("Enter the number of columns:")) mat = [] print("Enter the entries rowwise:") a = [] for i in range(Raw): for j in range(Clm): a.append(int(input())) mat.append(a) for i in range(Raw): for j in range(Clm): print(mat[i][j], end = " ") print()
fb8ae919bf14fee6f8058458fa3355d8569e15bc
datAnir/GeekForGeeks-Problems
/Dynamic Programming/equal_sum_partition_subsets.py
2,098
3.828125
4
''' https://practice.geeksforgeeks.org/problems/subset-sum-problem/0 Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not. Input: 2 4 1 5 11 5 3 1 3 5 Output: YES NO Explanation: Testcase 1: There exists two subsets such that {1, 5, 5} and {11}. ''' # variation of target sum subsets (0-1 knapsack) # if sum is odd, it can never partition into 2 subsets # if sum if even, it can be partition, call targetSumSubet with sum/2 to check availability of one partiion # if one partition is available, then second must be there def equalPartition(arr, n, summ): dp = [[False]*(summ+1) for _ in range(n+1)] for i in range(n+1): dp[i][0] = True for i in range(1, n+1): for j in range(1, summ+1): if arr[i-1] <= j: dp[i][j] = dp[i-1][j] or dp[i-1][j-arr[i-1]] else: dp[i][j] = dp[i-1][j] return dp[n][summ] # using 1-D def equalPartition(arr, n, summ): dp = [False]*(summ+1) dp[0] = True for i in range(n): # we need previous row value, that is why we started opposite # because for 4 if we need 2 as prv value, we can obtain it by running loop opposite # if we run loop from starting, then for 4 , value of 2 becomes of current row, not of previous row for j in range(summ, arr[i]-1, -1): dp[j] = dp[j] or dp[j-arr[i]] return dp[summ] if __name__ == '__main__': t = int(input()) while t: n = int(input()) arr = list(map(int, input().split())) summ = sum(arr) if summ&1: # if sum is odd, it can never partition into 2 subsets print('NO') else: ans = equalPartition(arr, n, summ//2) # if sum if even, it can be partition if ans: print('YES') else: print('NO') t -= 1
295e356fb69874b5b84c1199c814e3db25bb4c62
LucijaJ/Python_projekti
/FizzBuzz/fizzBuzz.py
344
3.734375
4
# -*- coding: utf-8 -*- print "To je FizzBuzz igrica" stevilka = raw_input(u"Izberi številko med 1 in 100: ") stevilka = int(stevilka) for num in range(1, stevilka+1): if num % 3 == 0 and num % 5 == 0: print "fizzbuzz" elif num % 3 == 0: print "fizz" elif num % 5 == 0: print "buzz" else: print num
67f528fb6fe2120269547a66de4a37fe6b6f8d5a
nathanin/histo-seg
/pca/clean_all_folders.py
698
3.5625
4
#!/usr/bin/python ### # Clean up all folders # ### import os import shutil def lstdirs(lookin='.'): dlist = os.listdir(lookin) return [d for d in os.listdir(lookin) if os.path.isdir(d)] def purge(dlist): for d in dlist: print 'Removing {}'.format(d) shutil.rmtree(d) if __name__ == '__main__': response = raw_input('Are you sure? [y,n] ') if response == 'y': print "Cleaning up...." dl = sorted(lstdirs()) print "Found {} folders to delete:".format(len(dl)) for d in dl: print d response = raw_input('Are you sure? [y,n] ') if response == 'y': print 'OK.' purge(dl)
be7a72158d2e8e879d5262f3dd5f351e49f38d1c
caleb-train/Competetive-programming
/Data Structures/Hashtable/Linear probing.py
1,708
3.671875
4
''' @Author: rishi ''' # Implement Hashmap with collision using Linear probing class Hashmap: def __init__(self): self.MAXSIZE = 5 self.arr = [None for i in range(self.MAXSIZE)] def find_hash(self, key): if type(key) == int: return (2*key+1)%self.MAXSIZE elif type(key) == str: s = 0 for i in range(len(key)): s += ord(key) return s%self.MAXSIZE else: raise TypeError("Only integers or strings are allowed") def __setitem__(self, key, value): h = self.find_hash(key) flag = True for i in range(self.MAXSIZE): temp = (h + i) % self.MAXSIZE if self.arr[temp] is None: self.arr[temp] = (key, value) flag = False break if flag: raise MemoryError("Memory limit exceeded") def __getitem__(self, key): h = self.find_hash(key) for i in range(self.MAXSIZE): temp = (h + i) % self.MAXSIZE if self.arr[temp] == None: continue if self.arr[temp][0] == key: return self.arr[temp][1] raise KeyError("Key does not exist") def __delitem__(self, key): h = self.find_hash(key) for i in range(self.MAXSIZE): if self.arr[i] == None: continue if self.arr[i][0] == key: self.arr[i] = None def __str__(self): return str(self.arr) obj = Hashmap() obj[1] = 10 obj[2] = 20 obj[3] = 30 obj["a"] = 1 del obj["a"] print(obj['a']) print(obj)
cc80e14b499d6737e02c24533b161b87b87f2a2b
TheAragont97/Python
/Actividades/Relacion 1/Relacion de ejercicios - Tipos de Datos Simples/ejercicio3/ejercicio3.py
75
3.59375
4
nombre=input("Ingresa el nombre del usuario: ") print("¡Hola",nombre,"!")
c73a659321099aa3d0bee06b0f0562211a8f5a67
kumaranika/MyCaptain
/fibonacci.py
282
4.21875
4
n=int(input("How many terms? ")) a=0 b=1 c=0 if n<=0: print("Please enter a positive integer") elif n==1: print("Fibonacci sequence upto",n,":") print(a) else: print("Fibonacci sequence:") while c<n: print(a) fib=a+b a=b b=fib c+=1
82301f6c6b1b14b6be893176944a4ae4ea3199c1
jbischof/algo_practice
/udacity/sort.py
1,801
4.1875
4
# Sorting algorithms def bubblesort(array): l = len(array) # Number of swaps in last pass swaps = 1 while swaps > 0: # Set swap counter back to zero swaps = 0 for i in range(l - 1): if array[i + 1] < array[i]: array[i], array[i + 1] = array[i + 1], array[i] swaps += 1 def mergearr(arr1, arr2): """ Merging util for merge sort. Both input arrays are assumed sorted. """ ans = [] while len(arr1) > 0 or len(arr2) > 0: if not arr2: ans.append(arr1.pop(0)) elif not arr1: ans.append(arr2.pop(0)) elif arr1[0] <= arr2[0]: ans.append(arr1.pop(0)) else: ans.append(arr2.pop(0)) return ans def mergesort(array): # Base case: length 0 or 1 l = len(array) if l < 2: return array # Split array and sort mid = l / 2 return mergearr(mergesort(array[: mid]), mergesort(array[mid: ])) def swap_pivot(array, pivot_pos, swap_pos): # Swaps out value in array for value in front of pivot # Pivot placed in front of swapped value if pivot_pos <= swap_pos: return False move_pos = pivot_pos - 1 array[swap_pos], array[move_pos] = array[move_pos], array[swap_pos] # Swap pivot with compared value array[pivot_pos], array[move_pos] = array[move_pos], array[pivot_pos] return True def quicksort(array, low, high): #print array[low : min(high+1, len(array) - 1)] # Base case: array length < 2 if low >= high: return pivot_pos = high pivot = array[pivot_pos] # Index of comparison i = low while pivot_pos > low and (pivot_pos - i > 0): # Keep comparing position i value to pivot until value is less while array[i] < pivot: # Move ith value behind pivot swap_pivot(array, pivot_pos, i) # New position of pivot pivot_pos -= 1 i += 1 quicksort(array, low, max(pivot_pos - 1, low)) quicksort(array, min(pivot_pos + 1, high), high)
23fd40e9efe313ef4072e7caed9bd2e5276699d1
alch/python-bitcoin
/bc/field_element.py
2,591
3.5625
4
from __future__ import annotations class FieldElement: def __init__(self, num: int, prime: int): if num >= prime or num < 0: error = "Num {} not in field range 0 to {}".format(num, prime - 1) raise ValueError(error) self.num = num self.prime = prime def __repr__(self): return "FieldElement_{}({})".format(self.prime, self.num) def __eq__(self, other: FieldElement) -> bool: if other is None: return False return self.num == other.num and self.prime == other.prime def __ne__(self, other: FieldElement) -> bool: return not (self == other) def __add__(self, other: FieldElement) -> FieldElement: if self.prime != other.prime: raise TypeError("Cannot add two numbers in different Fields") num = (self.num + other.num) % self.prime return self.__class__(num, self.prime) def __sub__(self, other: FieldElement) -> FieldElement: if self.prime != other.prime: raise TypeError("Cannot subtract two numbers in different Fields") num = (self.num - other.num) % self.prime return self.__class__(num, self.prime) def __mul__(self, other: FieldElement) -> FieldElement: if self.prime != other.prime: raise TypeError("Cannot multiply two numbers in different Fields") num = (self.num * other.num) % self.prime return self.__class__(num, self.prime) def __rmul__(self, coefficient): num = (self.num * coefficient) % self.prime return self.__class__(num=num, prime=self.prime) def __truediv__(self, other: FieldElement) -> FieldElement: """ See Fermat's little theorem for the theory behind the finite field division: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem Also note that modulo is not the reminder! See https://bit.ly/30lNfGE self.num and other.num are the actual values self.prime is what we need to mod against use fermat's little theorem: self.num**(p-1) % p == 1 this means: 1/n == pow(n, p-2, p) """ if self.prime != other.prime: raise TypeError("Cannot divide two numbers in different Fields") num = (self.num * pow(other.num, self.prime - 2, self.prime)) % self.prime return self.__class__(num, self.prime) def __pow__(self, exponent: int) -> FieldElement: n = exponent % (self.prime - 1) num = pow(self.num, n, self.prime) return self.__class__(num, self.prime)
d412984c907a53b8ebac38145f85cf9af18a270f
dishantpatel27/CS61A-UoC-berkeley-
/lab3/Q5.py
1,200
4.1875
4
def cycle(f1, f2, f3): """ Returns a function that is itself a higher order function >>> add1 = lambda x: x+1 >>> times2 = lambda x: 2*x >>> add3 = lambda x: x+3 >>> my_cycle = cycle(add1, times2, add3) >>> identity = my_cycle(0) >>> identity(5) 5 >>> add_one_then_double = my_cycle(2) >>> add_one_then_double(1) # semanitcally the same as times2(add1(1)) 4 >>> do_all_functions = my_cycle(3) >>> do_all_functions(2) # semantically the same as add3(times2(add1(2))) 9 >>> do_more_than_a_cycle = my_cycle(4) >>> do_more_than_a_cycle(2) # semantically the same as add1(add3(times2(add1(2)))) 10 >>> do_two_cycles = my_cycle(6) # semantically the same as add3(times2(add1(add3(times2(add1(1)))))) >>> do_two_cycles(1) 19 """ " *** YOUR CODE HERE *** " def ret_fn(n): def ret(x): i = 0 while i < n: if i % 3 == 0: x = f1(x) elif i % 3 == 1: x = f2(x) else: x = f3(x) i += 1 return x return ret return ret_fn
bffb90a90232c4bf9af3e48c9e5d556bbb2ec631
judigunkel/Exercicios-Python
/Mundo 2/ex058.py
834
4.1875
4
""" Melhore o jogo 028 onde o computador vai 'pensar' em um número de 0 a 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. """ from random import randint print('Sou seu computador...\n' 'Acabei de pesar em um número entre 0 e 10.\n' 'Será que você consegue adivinhar qual foi?\n') palpite_computador = randint(0, 10) palpite_jogador = int(input('Qual é o seu palpite? ')) tentativas = 1 while palpite_computador != palpite_jogador: tentativas += 1 if palpite_computador < palpite_jogador: palpite_jogador = int(input('É um número menor... Tente mais uma vez. ')) else: palpite_jogador = int(input('É um número maior... Tente mais uma vez. ')) print(f'Acertou com {tentativas} tentativas. Parabéns')
116d92cce52314e9335d01cc8344daeee2dca681
Elliotcomputerguy/LearningPython
/LogicalOperators.py
6,363
4
4
#!/usr/bin/env python # and, or, not are logical operators that are used to combine Boolean expressions. # When combined with simple conditions such as a Boolean comparators they become compound conditions. # =============================================================== # === # and # === # =============================================================== # The logical operator 'and' evaluates two Boolean expressions in which both simple conditionals either side of # the logical operator have to be True for the compound condition to evaluate to True. Any other evaluation will result as False. # =============================================================== # Example 100 < 5 and 11 < 50 # = False # =============================================================== # The following evaluated compound condition evaluates to False because the first simple conditonal evaluates to False. # A 100 is not less than 5 and evaluates to False. 11 is less than 50 and evaluates to True. # The 'and' logical operator uses the below rules when evalauting simple conditions. # =============================================================== # =============================================================== # and Operator Rules # =============================================================== # True and True True # True and False False # False and True False # False and False False # =============================================================== # === # or # === # Saying the phrase it can be either be True or False is the same logic applied in the 'or' operator. If one of the simple conditions # on either side of the 'or' logical operator evaluates to True the compound condition evaluates to True. # If both simple conditions evalaute to False the compund condition evaluates to False. # =============================================================== # Example 1 > 2 or 1 < 2 # = True # =============================================================== # the first simple condition evalautes to False as 1 is not greater than 2. While the second conditional evalutes to True as 1 is less # than 2. Therefore this compound condition evaluates to True as one of the simple conditions evaluates to True. # =============================================================== # =============================================================== # or Operator rules # =============================================================== # True or True True # True or False True # False or True True # False or False False # =============================================================== # === # not # === # =============================================================== # The not logical operator reverses True from False. If something is not True then it is False. If something is not False then it is True. # There is an order of operator precedence. When you attempt to evaluate False == not True you will receive an error # as the == operator precedes the logical not operator and attempts to evaluate the == operator first. # You have to use parentheses to tell python to evaluate which conditions first in the compound condition. # =============================================================== # =============================================================== # not Operator rules # =============================================================== # not True False # not False True # =============================================================== # =============================================================== # Example not True == False # = True: False is equal to False so therfore is True. False == (not True) # = True: False is equal to False so therfore the evaluation is evaluated as True. # =============================================================== # =============================================================== # Operator Order of Precedence # =============================================================== # <, <=, == , =>, > # not # and # or # =============================================================== # =============================================================== # Example not (5 > 6) == (not True) or (5 == 2) and (7 <= 8) # This complex compound condition evaluates to False. # =============================================================== # Breaking it down. # not (5 > 6) = not True. 5 is not greater than 6 so therfore it is not True. So is evaluated as False. not False. # not False == not True evaluates to False. # (5 == 2) is not True so this is False. # (7 <= 8) is True as 7 is less than 8. # The or logical operator evaluates its compound conditional as False as both conditions either side of 'or' evaluate to False. # The and operator evaluates its compound conditonal as False because the conditions on both side are not True so therfore is # evaluated as False # =============================================================== # Example True and not (5 == 3) # = True # =============================================================== # Breaking it down. # 5 does not eqaual to 3 so there for it is not True and evaluates to False. # True and not False evaluates to True. As not False evaluates to True. As both conditions are True the 'and' logical operator # evaluates the compound condition as True. # =============================================================== # Example ('b' != 'b') or not (5 >= 6) # = True # =============================================================== # Breaking it down. # b is equal to b so evalutes to False. # 5 is not greater than 6 so is also evaluated to False. # False or not False evalutes to True as not False evaluates to True and the 'or' logical operator has a rule that either one condition # to be True or False to evaluate as True.
8da3f91803bc311f46fbfb0a7734d4dc9e1f6462
henryxian/leetcode
/remove_element.py
1,071
3.84375
4
# Remove Element class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ length = len(nums) index = 0 index_not_val = 0 count = 0 while(index < length): if (nums[index] != val): count = count + 1 index = index + 1 index = 0 while (index_not_val < length): if nums[index_not_val] != val: nums[index] = nums[index_not_val] index = index + 1 index_not_val = index_not_val + 1 else: while index_not_val < length and nums[index_not_val] == val: index_not_val = index_not_val + 1 del nums[count:] return count if __name__ == '__main__': solution = Solution() li1 = [1, 2, 3, 1] print solution.removeElement(li1, 1), li1 li1 = [1, 2, 3, 1] print solution.removeElement(li1, 2), li1 li1 = [1, 2, 3, 1] print solution.removeElement(li1, 3), li1 li = [] print solution.removeElement(li, 3), li
ee3e7faf30d82af54060c755e6fee732d36a786f
avasich/a3200-2015-algs
/lab8/Vasich/queue.py
2,072
3.8125
4
from sys import stdin, stdout class Queue: def pop(self): pass def push(self, n): pass def size(self): pass # implement Queue class StacksQueue(Queue): def __init__(self): self._seq = [] def push(self, a): self._seq.append(a) def pop(self): if self.size() > 0: return self._seq.pop() else: return None def size(self): return len(self._seq) class MaxElementQueue(Queue): def __init__(self): self._maxes = [float("-inf")] self._push_max = float("-inf") self._pop = StacksQueue() self._push = StacksQueue() def pop(self): if self._pop.size() == 0: element = self._push.pop() while element is not None: self._pop.push(element) self._maxes.append(max(element, self._maxes[len(self._maxes) - 1])) element = self._push.pop() self._push_max = float("-inf") value = self._pop.pop() if value is not None: self._maxes.pop() return value else: return "empty" def push(self, n): self._push.push(n) self._push_max = max(self._push_max, n) def size(self): return self._push.size() + self._pop.size() def max(self): value = max(self._push_max, self._maxes[len(self._maxes) - 1]) if value != float("-inf"): return value else: return "empty" def parse_line(string, max_element_queue): string = string.split("\n")[0] if string == "max": return str(max_element_queue.max()) elif string == "pop": return str(max_element_queue.pop()) else: command = string.split() if len(command) == 2 and command[0] == "push": max_element_queue.push(int(command[1])) return "ok" return "unknown command" if __name__ == "__main__": queue = MaxElementQueue() for line in stdin: print(parse_line(line, queue))
60cc3f1ac13d96d3a3297c0ed687afb4667ff063
Glimtoko/pyramid
/pyramid.py
650
3.828125
4
class Pyramid(): def __init__(self, initial): self.data = [[initial]] def __repr__(self): result = "" for entry in reversed(self.data): result += str(entry) + "\n" result += "\n" return result def add(self, value): # First, add value to bottom level of pyramid self.data[0].append(value) # Now extend pyramid for i in range(len(self.data)): v1 = self.data[i][-1] v2 = self.data[i][-2] try: self.data[i + 1].append(v1 + v2) except IndexError: self.data.append([v1 + v2])
0cc53c3071eadfe43c602dbd1eac67470f63ea4b
rishabhgupta03/Hacker-Rank-python
/Set .union(), .intersection() Operation.py
254
3.546875
4
n = int(input()) english = set(map(int, input().split())) b = int(input()) french = set(map(int, input().split())) set_union = english.union(french) set_intersection = english.intersection(french) print(len(set_union)) print(len(set_intersection))
ae0df91871f9e5d24ad1effffd3eac0b107929a8
dhruv3/IntroToPython
/Unit 3/palinTools.py
140
3.625
4
# # # def isPalindrome(a): if a == a[::-1]: return True else: return False #a = isPalindrome("rwadar") #print(a)
596f4a08e06c6ec4dcf7afbce01ae81bc60c483b
lingxiaomeng/CS305
/lab2/prime.py
383
3.9375
4
def find_prime(start: int, end: int): prime_list = [] for num in range(start, end + 1): if is_prime(num): prime_list.append(num) return prime_list def is_prime(num: int): if num > 1: for i in range(2, num): if (num % i) == 0: return False else: return True else: return False
f600b3f6eebf05c40bd05e6b85c556d3fbd0aa4a
advaittrivedi1122/Contact-Book-in-Python
/Contact_Book.py
5,092
3.921875
4
import sys import sqlite3 from prettytable import from_db_cursor # Connecting database db = sqlite3.connect('contacts.db') cursor = db.cursor() # Declaring SQL database statements def create(): create = ''' CREATE TABLE IF NOT EXISTS CONTACTS(Name TEXT, Number TEXT); ''' cursor.execute(create) return def select_all(): select_all = ''' SELECT * FROM CONTACTS; ''' cursor.execute(select_all) print(from_db_cursor(cursor)) return def select_by_name(): select_by_name = f''' SELECT * FROM CONTACTS WHERE Name = "{input('Enter name to search: ')}"; ''' cursor.execute(select_by_name) print(from_db_cursor(cursor)) return def select_by_number(): select_by_number = f''' SELECT * FROM CONTACTS WHERE Number = "{input('Enter number to search: ')}"; ''' cursor.execute(select_by_number) print(from_db_cursor(cursor)) return def insert(): insert = f''' INSERT INTO CONTACTS(Name,Number) VALUES("{input('Enter name to add: ')}","{input('Enter phone number: ')}"); ''' cursor.execute(insert) db.commit() return def update_name(): number = input('Enter number for which you want to update the name: ') update_name = f''' UPDATE CONTACTS SET Name = "{input('Enter new name: ')}" WHERE Number = "{number}"; ''' cursor.execute(update_name) db.commit() return def update_number(): name = input('Enter name for which you want to update the number: ') update_number = f''' UPDATE CONTACTS SET Number = "{input('Enter new number: ')}" WHERE Name = "{name}"; ''' cursor.execute(update_number) db.commit() return def final_choice(): final_choice = input('\nYou will not be able to restore this contact once deleted.\nDo you still want to continue? (yes/no)\n') if final_choice.lower() == 'yes': return True else: return False def delete_by_name(): delete_by_name = f''' DELETE FROM CONTACTS WHERE Name = "{input('Enter name for which you want to delete the contact: ')}"; ''' if final_choice() == True: cursor.execute(delete_by_name) db.commit() print('\nContact Deleted Successfully !!!') else: print('\nYour Contact was not deleted !!!\n') return def delete_by_number(): delete_by_number = f''' DELETE FROM CONTACTS WHERE Number = "{input('Enter number for which you want to delete the contact: ')}"; ''' if final_choice() == True: cursor.execute(delete_by_number) db.commit() print('\nContact Deleted Successfully !!!') else: print('\nYour Contact was not deleted !!!\n') return def delete_all(): delete_all = f''' DELETE FROM CONTACTS; ''' if final_choice() == True: cursor.execute(delete_all) db.commit() print('\nContact Deleted Successfully !!!') else: print('\nYour Contact was not deleted !!!\n') return # Driver Code - Main print('\n!!! Welcome to the Contact Book !!!') while True: print(''' 1 - Add Contact 2 - Search Contact 3 - Update Contact 4 - Delete Contact 5 - Exit from Contact Book ''') create() try: choice = int(input('Enter your choice to perform task: ')) if choice == 1: insert() print('\nContact Added Succesfully !!!') elif choice == 2: print(''' 1 - Search Contact by Name 2 - Search Contact by Number 3 - See All Contacts ''') search_choice = int(input('Enter your choice how you want get contact: ')) if search_choice == 1: select_by_name() elif search_choice == 2: select_by_number() else: select_all() elif choice == 3: print(''' 1 - Update Contact Name 2 - Update Contact Number ''') update_choice = int(input('Enter your choice how you want to update the contact: ')) if update_choice == 1: update_name() else: update_number() print('\nContact Updated Successfully !!!') elif choice == 4: print(''' 1 - Delete Contact by Name 2 - Delete Contact by Number 3 - Delete All Contacts ''') delete_choice = int(input('Enter your choice how you want to delete the contact: ')) if delete_choice == 1: delete_by_name() elif delete_choice == 2: delete_by_number() else: delete_all() elif choice == 5: print('\n\n!!! Contact Book was closed succesfully !!!\n\n') # Saving and closing the databse db.commit() db.close() # Stopping the program execution sys.exit() except ValueError as error: print('\n\n!!!PLEASE, enter valid choices only !!!\n\n')
ce4daf5269a408f6676b51c506b8f3e1acb75e16
giladse19-meet/y2s18-python_review
/exercises/superheros.py
584
3.6875
4
# Write your solutions for 1.5 here! class Superheros: def __init__(self, name, superpower, strengh): self.name = name self.superpower = superpower self.strengh = strengh def hero(self): print(self.name) print(self.strengh) def save_civilian(self, work): if self.strengh - work < 0: print("not strong enough") else: left = self.strengh - work self.strengh = left print(left) hero_1 = Superheros("dicktetor", "superpoop", 7) hero_1.hero() hero_1.save_civilian(3)
ea98690ae25b74ebfb2137d1ba4d000965931ea2
danbev/learning-python
/src/get_item.py
326
3.5625
4
class Results(object): def __init__(self, contenders): self._places = [None]*contenders def __setitem__(self, place, data): self._places[place] = data def __getitem__(self, place): return self._places[place] r = Results(3) r[0] = 'Gold' r[1] = 'Silver' r[2] = 'Bronce' print(r[2])
809d1f255dc8609194442651bf4fcdd14ef78bbb
chxj1992/leetcode-exercise
/152_maximum_product_subarray/_1.py
687
3.84375
4
import unittest from typing import List class Solution: def maxProduct(self, nums: List[int]) -> int: max_product, max_here, min_here = nums[0], nums[0], nums[0] for x in nums[1:]: if x < 0: max_here, min_here = min_here, max_here max_here = max(max_here * x, x) min_here = min(min_here * x, x) max_product = max(max_here, max_product) return max_product class Test(unittest.TestCase): def test(self): s = Solution() self.assertEqual(6, s.maxProduct([2, 3, -2, 4])) self.assertEqual(0, s.maxProduct([-2, 0, -1])) if __name__ == '__main__': unittest.main()
626d28f084048953122b1ffe24dc215ab1890288
sresis/practice-problems
/weighted-path/weighted_path.py
1,387
3.765625
4
def Helper(start, end, connections, routes, curr, weight): """Get possible routes and add to routes dict.""" # if start and end are the same, add to routes if start == end: routes[curr+start] = weight # otherwise, iterate through possible connections else: for connection in connections: if start in connection: temp = connection[:] temp.remove(start) curr_weight = weight + int(temp[1]) # remove this connection from considered list new_connections = connections[:] new_connections.remove(connection) # use updated vals in recursive call Helper(temp[0], end, new_connections, routes, curr+start+'-', curr_weight) return def WeightedPath(strArr): node_count = int(strArr[0]) # get the nodes all_nodes = strArr[1:node_count+1] start = all_nodes[0] end = all_nodes[-1] # seperate the weighted strings into relevant components connections = [item.split('|') for item in strArr[node_count+1:]] # store possible routes routes = {} # helper function to get all of the possible routes Helper(start, end, connections, routes, curr='', weight=0) if routes: # get the min value from routes val = list(routes.values()) key = list(routes.keys()) return key[val.index(min(val))] else: return -1 # keep this function call here print(WeightedPath(input()))
2797c075a11ae211a79c6087209a64636ce835d5
VsPun/learning
/sample/chapt02/chapt02-13.py
107
3.875
4
a = 10 while a < 10: a = a + 1 print( a ) else: print( 'no loop' ) # 「no loop」と表示される
35379aea4ec7a62f63a1cbb743803e4ea8fdf374
Clay190/Unit-2
/adventure.py
386
3.6875
4
#Clay Kynor #9/18/17 #adventure.py - Create an adventure answer = input("You are strolling along a field and see a wild Claire sitting on her most prized possesion, her bench. Do you approach her, yes or no?") if "yes" in answer: answer2 = input("You approach her and she leaps from the bench, eyes bulging, trying to defend her property, do you engage her in battle, yes or no?")
3343294eb8fa8377e5c40f0b6b2f86d09854f8db
eric-olson/AutoGrader
/flowers_old/problems/carrotboxes/convert.py
273
3.71875
4
#!/usr/bin/python3 import re expr = r"\[(.*)\],\s+([0-9]+)\s+([0-9]+)" input = open("input") for line in input: result = re.search(expr, line) if result: print("\t{{{" + result.group(1) + "},", result.group(2)+"},", result.group(3)+"},") input.close()
b1f400e0dcf56e30d0c93f3483505907dd4941b9
mxh970120/leetcode_python
/medium/49. group-anagrams.py
699
3.78125
4
''' Author: mxh970120 Date: 2020.12.14 ''' class Solution: def groupAnagrams(self, strs): res = {} for item in strs: k = ''.join(sorted(item)) # 字符串排序,Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。 print(k) if k not in res: # 判断是否存在 res[k] = [] res[k].append(item) # 相同字符串放到同一个字典的键key中 print(res) return [res[x] for x in res] # 输出结果 if __name__ == '__main__': strs = ['eat', 'tea', 'tan', 'ate', 'nat', 'bat'] solu = Solution() print(solu.groupAnagrams(strs))
7a9dd98eea7432cf54e7afed56be6feae54a94f6
ver007/pythonjumpstart
/.history/day3/oops/employee.py
666
3.71875
4
#!/usr/bin/env python from person import Person class Employee(Person): def __init__(self, eid, firstName, lastName, age, gender,\ designation, department): self.eid = eid super(Employee, self).__init__(firstName, lastName, \ age, gender) #calling the base class constructor self.designation = designation self.department = department def getEmployee(self): print "employee id : %s" % self.eid self.getPerson() print "Designation : %s" % self.designation print "Department : %s" % self.department if __name__ == '__main__': e = Employee('1001', 'henry', 'jacob', 12, 'male', \ 'manager', 'sales') e.getEmployee()
c60d6f43a03f1604de7be6d7d9ad57c97c723559
Smithry9/InClassActivity4
/test_wordCount.py
707
3.84375
4
#test_palindrome import unittest import wordCount class testCaseAdd(unittest.TestCase): #1 word def test_wordCount1(self): self.assertEqual(wordCount.numWords("Hi"), 1) #2 words def test_wordCount2(self): self.assertEqual(wordCount.numWords("Hello World!"), 2) #empty string def test_wordCount3(self): self.assertEqual(wordCount.numWords(""), 0) #invalid input def test_wordCount4(self): self.assertEqual(wordCount.numWords(10), "Not a valid string") #intentionally incorrect test, should fail def test_wordCount5(self): self.assertEqual(wordCount.numWords("Hello World!"), 5) if __name__ == "__main__": unittest.main()
50b1be7a68dcce6b3c193a3390df2ff5931608c2
MahoHarasawa/Maho
/uranai02.py
5,773
4
4
'''ソウルナンバー占い 合計が1桁になるまで足し、最終的に出た数がソウルナンバー ぞろ目はそのまま''' #8桁の生年月日を入力 1998/04/11生まれ⇒1,9,9,8,0,4,1,1 num1=int(input("1桁目⇒")) while num1>=10 or num1<0: print("0または1桁の正の数で入力してください") print() num1=int(input("1桁目⇒")) num2=int(input("2桁目⇒")) while num2>=10 or num2<0: print("0または1桁の正の数で入力してください") print() num2=int(input("2桁目⇒")) num3=int(input("3桁目⇒")) while num3>=10 or num3<0: print("0または1桁の正の数で入力してください") print() num3=int(input("3桁目⇒")) num4=int(input("4桁目⇒")) while num4>=10 or num4<0: print("0または1桁の正の数で入力してください") print() num4=int(input("4桁目⇒")) num5=int(input("5桁目⇒")) while num5>=10 or num5<0: print("0または1桁の正の数で入力してください") print() num5=int(input("5桁目⇒")) num6=int(input("6桁目⇒")) while num6>=10 or num6<0: print("0または1桁の正の数で入力してください") print() num6=int(input("6桁目⇒")) num7=int(input("7桁目⇒")) while num7>=10 or num7<0: print("0または1桁の正の数で入力してください") print() num7=int(input("7桁目⇒")) num8=int(input("8桁目⇒")) while num8>=10 or num8<0: print("0または1桁の正の数で入力してください") print() num8=int(input("8桁目⇒")) total1=num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 print() print("合計: ",total1) #ループ処理を使ってコードの無駄を省けないものか?? def get_total(x,y): return x+y #while文がありプログラム内で一度しか使わないため本来は不要 while total1 >= 10: if total1 == 11: print("あなたのソウルナンバーは11です!ソウルナンバー11の人を一言でいうと「直感で人が何考えているか、どういう人か察知してしまう鋭い感受性」の人です。") break elif total1 == 22: print("あなたのソウルナンバーは22です!ソウルナンバー22の人を一言でいうと「しっかりと準備をしてから行動を行う、冷静な分析力と大胆な行動力」の人です。") break elif total1 == 33: print("あなたのソウルナンバーは33です!ソウルナンバー33の人を一言でいうと「カリスマ性を持つ、人々を魅了する、スター中のスター」です。") break elif total1 == 44: print("あなたのソウルナンバーは44です!ソウルナンバー44の人を一言でいうと「鋭い考えをもった、まさにキレ者。乗り越えられる重責を負う人」です。") break else: num9=int(input("1桁目⇒")) while num9>=10 or num9<0: print("0または1桁の正の数で入力してください") print() num9=int(input("1桁目⇒")) num10=int(input("2桁目⇒")) while num10>=10 or num10<0: print("0または1桁の正の数で入力してください") print() num10=int(input("2桁目⇒")) total1=get_total(num9,num10) print() print("合計: ",total1) else: if total1 == 1: print("あなたのソウルナンバーは1です!ソウルナンバー1の人を一言でいうと「才能も運もあるが、ハートが弱く小心者」です。") elif total1 == 2: print("あなたのソウルナンバーは2です!ソウルナンバー2の人を一言でいうと「頭がよく直感も働くが、短気で人からあれこれ言われたくない人」です。") elif total1 == 3: print("あなたのソウルナンバーは3です!ソウルナンバー3の人を一言でいうと「面倒見がよく芸術センスもあるがストレスをためやすい人」です。") elif total1 == 4: print("あなたのソウルナンバーは4です!ソウルナンバー4の人を一言でいうと「働き者でリーダーシップがあるがクールで人間味がない人」です。") elif total1 == 5: print("あなたのソウルナンバーは5です!ソウルナンバー5の人を一言でいうと「マイペースで安定志向だが恋愛下手な人」です。") elif total1 == 6: print("あなたのソウルナンバーは6です!ソウルナンバー6の人を一言でいうと「八方美人で愛情深いが裏切りを許さない人」です。") elif total1 == 7: print("あなたのソウルナンバーは7です!ソウルナンバー7の人を一言でいうと「お調子者でぱわふるだがデリケートで傷つきやすい人」です。") elif total1 == 8: print("あなたのソウルナンバーは8です!ソウルナンバー8の人を一言でいうと「こだわりが強く金運もあるがものの考え方が極端な人」です。") elif total1 == 9: print("あなたのソウルナンバーは9です!ソウルナンバー9の人を一言でいうと「記憶力がよく天才肌だが寂しがりや。一番浮気しやすい人」です。") '''引用 http://soulnumber.me/ https://www.denwauranaichan.com/%E3%82%BD%E3%82%A6%E3%83%AB%E3%83%8A%E3%83%B3%E3%83%90%E3%83%BC/'''
b9dd5b022c76da7295c1eaa48e64ff7344f802d6
deepakpesumalnai/Project
/Sample Programs/Function/Function_withLopp.py
264
3.953125
4
def Check_even(number_list): for num in number_list: if num % 2 == 0: print(f'number {num} is even') else: print(f'number {num} is odd') if __name__ == '__main__': numberlist = [2,3,4,5,6] Checkeven(numberlist)
0c6b61f149e86237efc55ece80ad9350fdfb7fd5
Manoj-t/PythonExamples
/String/findOperator.py
420
4.21875
4
#There are total 4 functions in Python String to find substrings #1. find() method - which returns the index of first occurence of the given substring. If substring not present, it returns -1 s = input("Enter a string: ") substr = input("Enter substring: ") print(s.find(substr)) #we can specify our own boundaries for find method to search within print(s.find(substr,5,10)) #beginIndex = 5, endIndex = end-1 i.e. 9
bdb55e038623ae35fdadaf0a02fcd8de58b3abb4
AustinTSchaffer/DailyProgrammer
/Cracking the Coding Interview/Python/ctci/chapter01/_q08.py
652
4.0625
4
from typing import List def zero_matrix(matrix: List[List[int]]) -> List[List[int]]: """ Sets entire rows and columns of the input matrix to 0 if any of the values in the row or column are 0. Modifies and returns the input matrix. """ cols_to_0 = set() rows_to_0 = set() for i, row in enumerate(matrix): for j, value in enumerate(row): if value == 0: rows_to_0.add(i) cols_to_0.add(j) for i, row in enumerate(matrix): for j, _ in enumerate(row): if (i in rows_to_0) or (j in cols_to_0): matrix[i][j] = 0 return matrix
c4e72ffc3199c03902b759c77bc0fdc035b25d35
ikenticus/blogcode
/python/tasks/10-days-stats/00-weighted-mean.py
395
3.71875
4
# Easy # https://www.hackerrank.com/challenges/s10-weighted-mean/problem # Enter your code here. Read input from STDIN. Print output to STDOUT N = int(raw_input()) X = [ float(i) for i in raw_input().rstrip().split(' ') ] W = [ int(i) for i in raw_input().rstrip().split(' ') ] num = [] for i in range(len(X)): num.append(X[i] * W[i]) # weighted mean print '%.1f' % (sum(num) / sum(W))
95936a709fe9f146cfd8af938268071f000ca0ea
shsh9888/leet
/min_chairs_required/sol.py
1,500
3.875
4
def min_chairs(S, E): if len(S) is 0 or len(E) is 0: return 0 ##the maximum timestamp where a person leaves max_time = max(E) arrives = {} ##stores how many chairs neeeded at each timestamp. index is the timestamp here time_array = [0]*(max_time+1) ##Filling the leave time stamps (-1s) at each point where person leaves for time in E: time_array[time] = time_array[time] -1 ##Arrival count dictionary for arrival_time in S: if arrival_time in arrives: arrives[arrival_time] += 1 else: arrives[arrival_time] = 1 ## Go through each time stamp and see if someone is arriving at that point. lev for index,time in enumerate(time_array): if index is 0: continue number_ppl_arriving = 0 if index in arrives: number_ppl_arriving = arrives[index] # print(number_ppl_arriving) time_array[index] = time_array[index-1] + time_array[index] + number_ppl_arriving # print(time_array) return max(time_array) print(min_chairs([1,2,6,5,3],[5,5,7,6,8]),3) ##randome print(min_chairs([1,2,6,5,3],[8,8,8,8,8]),5) ##everyone leaves late print(min_chairs([1,2,6,5,3],[1,2,6,5,3]),0) ## same time as arrive print(min_chairs([1,2,6,5,3],[1,3,6,5,3]),1) ## 2nd person waits for one time stamp print(min_chairs([],[]),0) ## 2nd person waits for one time print(min_chairs([1,2,6,5,3],[2,3,7,6,4]),1) ## leave at the next time stamp
9bc4980ea0fbceaf90b33ace879138ec71a37099
Danilo-Araujo-Silva/A-Python-Neural-Network
/neuralNetwork.py
10,224
3.671875
4
#!/usr/bin/env python """Erik Hope --- CSC 578 --- Neural Network Midterm Project""" from optparse import OptionParser import random import math import sys THRESHOLD_VALUE = -1.0 def set_threshold_value(value): """A function which sets the value of the threshold nodes in the neural network""" global THRESHOLD_VALUE THRESHOLD_VALUE = value class Instance(object): """Contains some convenience functions for dealing with instances. Takes a list of values, assuming the last value is the target attribute, and assigns the first n-1 elements plus a threshold value to the attributes property, and the last value in the list to thetarget property""" def __init__(self, data): self._attributes = [float(x) for x in data[:-1]] + [THRESHOLD_VALUE] self._target = float(data[-1]) @property def attributes(self): return self._attributes @property def target(self): return self._target class Neural_Network(): def make_input_node_matrix(self, data, hidden_nodes): """return a matrix where the number of rows is the number of hidden nodes and the number of columns is the number of input nodes """ inputs = len(self.data[0].attributes) matrix = [] for i in range(hidden_nodes): matrix.append([0]*inputs) return matrix def make_output_node_matrix(self, hidden_nodes): return [0] * (hidden_nodes + 1) def __init__(self, hidden_nodes, data, eta=.1, error_margin = .01, momentum=0): self.data = [] for d in data: self.data.append(Instance(d)) self.eta = eta self.momentum = momentum self.error_margin = error_margin self.epochs = 0 self.epoch_results = {} self.hidden_node_range = range(0, hidden_nodes+1) number_of_inputs = len(self.data[0].attributes) self.input_range = range(0, number_of_inputs) self.instance = 0 self.hidden_layer_weights = self.make_input_node_matrix(self.data, hidden_nodes) self.output_layer_weights = self.make_output_node_matrix(hidden_nodes) self.hidden_layer_errors = [0] * hidden_nodes self.hidden_nodes = [0] * hidden_nodes + [THRESHOLD_VALUE] def _back_propagate(self, output, instance): """Perform the back propagation step""" self.error = output*(1.0-output)*(instance.target-output) hidden_layer_errors = self.hidden_layer_errors output_layer_weights = self.output_layer_weights hidden_nodes = self.hidden_nodes error = self.error for node in self.hidden_node_range[:-1]: node_value = hidden_nodes[node] hidden_layer_errors[node] = node_value * (1.0 - node_value) * output_layer_weights[node] * error def _forward_propagate(self, instance): """Forward propagates an instance through the network""" attributes = instance.attributes hidden_layer_weights = self.hidden_layer_weights hidden_nodes = self.hidden_nodes sigmoid = self._sigmoid input_range = self.input_range for row in self.hidden_node_range[:-1]: current_row = hidden_layer_weights[row] value = 0.0 for cell in input_range: value += attributes[cell] * current_row[cell] self.hidden_nodes[row] = sigmoid(value) output_value = 0 output_layer_weights = self.output_layer_weights for h in self.hidden_node_range: output_value += hidden_nodes[h] * output_layer_weights[h] return sigmoid(output_value) def _update_weights(self, output, instance): """Update weights based on errors computed in the back propagation step""" eta = self.eta error = self.error output_layer_weights = self.output_layer_weights hidden_nodes = self.hidden_nodes input_nodes = instance.attributes hidden_layer_weights = self.hidden_layer_weights hidden_layer_errors = self.hidden_layer_errors input_range = self.input_range for row in self.hidden_node_range: hidden_node_value = hidden_nodes[row] output_layer_weights[row] = eta*error*hidden_node_value + output_layer_weights[row] for row in self.hidden_node_range[:-1]: hidden_node = hidden_layer_weights[row] error = hidden_layer_errors[row] for cell in input_range: input_node_value = input_nodes[cell] hidden_node[cell] = eta*error*input_node_value + hidden_node[cell] def _sigmoid(self, value): return 1.0/(1.0 + math.e**(-value)) def initialize_with_random_weights(self, minimum=0, maximum=.2): for row in self.hidden_layer_weights: for cell in self.input_range: row[cell] = random.uniform(minimum, maximum) for cell in self.hidden_node_range: self.output_layer_weights[cell] = random.uniform(minimum, maximum) def initialize_with_uniform_weight(self, weight=.1): for row in self.hidden_layer_weights: for cell in self.input_range: row[cell] = weight for cell in self.hidden_node_range: self.output_layer_weights[cell] = weight def evaluate_instance(self, input_instance): """Once the network is trained, this method can be used to evaluate new instances""" instance = Instance(input_instance) return self._forward_propagate(instance) def run_epoch(self): """Performs all of the tasks required in running an epoch during training: forward propagation, back propagation and weight update. stores the result in epoch_results""" correct = 0 RMSes = [] for instance in self.data: output = self._forward_propagate(instance) self._back_propagate(output, instance) self._update_weights(output, instance) for instance in self.data: #### Determine the accuracy #### output = self._forward_propagate(instance) RMS = math.sqrt((instance.target - output)**2) RMSes.append(RMS) if RMS < self.error_margin: correct += 1 self.epoch_results[self.epochs] = (max(RMSes), sum(RMSes)/float(len(RMSes)), float(correct)/len(self.data)) self.epochs += 1 if __name__ == "__main__": usage = "usage: %prog [options] INPUT_FILE" parser = OptionParser(usage) parser.add_option("-n", "--hidden_nodes", dest="hidden_nodes", help="the number of hidden nodes (default 10)", default=10, type="int") parser.add_option("-l", "--learning_rate", dest="learning_rate", help="the learning rate for the network (default .1)", default=.1, type="float") #### Momentum Not Implemented Yet #### # parser.add_option("-m", "--momentum", dest="momentum", # help="the momentum of the network", default=0, type="float") parser.add_option("-e", "--epochs", dest="epochs", help="the number of epochs before terminating (default 10000)", default=10000, type="int") parser.add_option("-a", "--accuracy", dest="accuracy", help="the accuracy needed before terminating (default 100)", default=100, type="float") parser.add_option("-d", "--delimiter", dest="delimiter", help="delimiter of attributes in input file (default ',')", default=",") parser.add_option("-r", "--error_margin", dest="error_margin", help="the error margin for training (default .05)", default=.05, type="float") parser.add_option("-w", "--start_weights", dest="start_weights", help="""the initial weights of the network, one value if all weights are to be same, comma delimited [n,n] if the weights should be initialized to a random value in a range (default -5,5)""", default="-5,5") parser.add_option("-o", "--output_file", dest="output_file", help="""The file to which output is written (default stdout)""", default=None) (options, args) = parser.parse_args() data = [] if len(args) == 0: print "provide an input file!" sys.exit(0) with open(args[0], "r") as f: for l in f: data.append([x.replace('\r','').replace('\n','') for x in l.split(",")]) nn = Neural_Network(options.hidden_nodes, data, options.learning_rate, options.error_margin) weights = [float(x) for x in options.start_weights.split(",")] if len(weights) == 1: nn.initialize_with_uniform_weight(*weights) elif len(weights) == 2: nn.initialize_with_random_weights(*weights) else: print "provide proper input weights!" sys.exit(0) accuracy = options.accuracy old_stdout = None outp_file = None if options.output_file: outp_file = open(options.output_file, "w") old_stdout = sys.stdout sys.stdout = outp_file for i in range(options.epochs): nn.run_epoch() print "***** Epoch %s *****" % (i + 1) print "Maximum RMSE: %s" % nn.epoch_results[i][0] print "Average RMSE: %s" % nn.epoch_results[i][1] print "Percent Correct: %s" % nn.epoch_results[i][2] if nn.epoch_results[i][2] *100 >= accuracy: break if outp_file: outp_file.close() sys.stdout = old_stdout print """Neural Network Trained. Enter a comma delimited instance or type \"quit\" to quit.""" inp = "" quit = False while not quit: inp = raw_input("... ") try: print nn.evaluate_instance([x.replace('\n','').replace('\r','') for x in inp.split(",")] + [1]) except Exception as e: quit = ('quit' == inp.lower().strip()) if not quit: print "Input a valid instance!"
c3fb59e7baa777d61e0f3f4153da529bb570ff8f
jaliagag/21_python
/UCEMA/06.py
793
4.25
4
"""print("Multiplicación") print(5 * 4) print("División") print(5 / 4) print("Potencia") print(5 ** 4) print("Módulo") print(5 % 4) print("Parte entera") print(5 // 4) 1. Declarar las variables "numero1" y "numero2" y pedirle al usuario que ingrese estas con la linea "Ingrese un número entero: " 2. Imprimir solamente los resultados de las operaciones suma, resta, multiplicación, división, potencia, módulo y parte entera entre las variables en ese mismo orden, uno por linea.""" numero1 = int(input("Ingrese el primer número entero: ")) numero2 = int(input("Ingrese el segundo número entero: ")) print(numero1 + numero2) print(numero1 - numero2) print(numero1 * numero2) print(numero1 / numero2) print(numero1 ** numero2) print(numero1 % numero2) print(numero1 // numero2)
9902e7c9640fa47c8290756ba7117d9f40a2310f
jngirakwizera/python-class
/JeanNgirakwizeraLab7 2/Hangman_delete.py
1,076
4.125
4
import sqlite3 import Hangman_readone #The delete functino deletes an item def delete(): hiddenword = "" level = "" hint = "" hiddenword, level, hint = Hangman_readone.getWord() if hiddenword == "-1": print("Word not found") else: sure = input('Are you sure you want to delete this word? (y/n)') if sure.lower() == 'y': num_deleted = delete_row(hiddenword) print(f'{num_deleted} row(s) deleted') #The delete_row function deletes an existing item #The number of rows deleted is returned def delete_row(hiddenword): conn = None num_deleted = 0 try: conn = sqlite3.connect('hangmanwords.db') cur = conn.cursor() cur.execute('''DELETE FROM words WHERE hiddenword == ?''', (hiddenword,)) conn.commit() num_deleted = cur.rowcount except sqlite3.Error as err: print('Database Error', err) finally: if conn != None: conn.close() return num_deleted #Execute the main function if __name__ == '__main__': delete()
0c090d3272d3874d7577eccfd1686d2934ac8015
parkus/ffd
/utils.py
2,166
3.5625
4
from __future__ import division, print_function, absolute_import import numpy as _np class OutOfRange(Exception): pass def error_bars(x, x_best=None, interval=0.683): """ Get the error bars from an MCMC chain of values, x. Parameters ---------- x : array-like The randomly sampled data for which to find a most likely value and error bars. x_best : float Value to use as the "best" value of x. If not specified, the median is used. interval : float The width of the confidence interval (such as 0.683 for 1-sigma error bars). Returns ------- x_best, err_neg, err_pos : floats The "best" x value (median or user specified) and the negative (as a negative value) and positive error bars. Examples -------- import numpy as np from matplotlib import pyplot as plt x = np.random.normal(10., 2., size=100000) _ = plt.hist(x, 200) # see what the PDF it looks like error_bars(x) # should return roughly 10, -2, 2 """ if _np.any(_np.isnan(x)): raise ValueError('There are NaNs in the samples.') if x_best is None: x_best = np.median(x) interval_pcntl = 100 * _np.array([(1-interval)/2, (1+interval)/2]) x_min, x_max = _np.percentile(x, interval_pcntl) return x_best, x_min - x_best, x_max - x_best def loglike_from_hist(bins, counts): """ Create a function to represent a likelihood function based on histogrammed values. Parameters ---------- bins : bin edges used in the histogram. counts : counts in each bin (histogram will be normalized such that integral is 1, though it shouldn't really matter) Returns ------- loglike : function A function loglike(x) that returns ln(likelihood(x)) based on the value of the input histogram at x. """ integral = np.sum(np.diff(bins)*counts) norm = counts/integral def loglike(x): if x <= bins[0]: return -np.inf if x >= bins[-1]: return -np.inf i = np.searchsorted(bins, x) return np.log(norm[i - 1]) return loglike
912f4dbafbc27bd55cd3bd76058eadf3741afc95
LangchunSi/0-1-Knapsack-problem
/dKnapsack.py
3,375
3.796875
4
# Dynamic programming method ''' # mainRun(weight,value,capacity,type) n: number of items value: value of each item weight: weight of each item capacity: capacity of bag m: memery matrix type: 'right2left' or 'left2right' ''' # right to left def Knapsack(value,weight,capacity,n,m): jMax = min(weight[n-1]-1,capacity) for j in range(0,jMax+1): m[n-1][j] = 0 for j in range(weight[n-1],capacity+1): m[n-1][j] = value[n-1] for i in range(n-2,-1,-1): jMax = min(weight[i]-1,capacity+1) for j in range(0,jMax+1): m[i][j] = m[i+1][j] for j in range(weight[i],capacity+1): m[i][j] = max(m[i+1][j],m[i+1][j-weight[i]]+value[i]) return m def Trackback(m,weight,capacity,n,select): for i in range(0,n-1): if m[i][capacity] == m[i+1][capacity]: select[i] = 0 else: select[i] = 1 capacity = capacity - weight[i] if m[n-1][capacity] != 0: select[n-1] = 1 return select # left to right def KnapsackL(value,weight,capacity,n,m): jMax = min(weight[0]-1,capacity) for j in range(0,jMax+1): m[0][j] = 0 for j in range(weight[0],capacity+1): m[0][j] = value[0] for i in range(1,n,1): jMax = min(weight[i]-1,capacity+1) for j in range(0,jMax+1): m[i][j] = m[i-1][j] for j in range(weight[i],capacity+1): m[i][j] = max(m[i-1][j],m[i-1][j-weight[i]]+value[i]) return m def TrackbackL(m,weight,capacity,n,select): for i in range(n-1,0,-1): if m[i][capacity] == m[i-1][capacity]: select[i] = 0 else: select[i] = 1 capacity = capacity - weight[i] if m[0][capacity] != 0: select[0] = 1 return select # switch between left2right and right2left def switchFunc(value,weight,capacity,n,m,Select,type): if type == 'right2left': # print('Type: right to left.') m = Knapsack(value,weight,capacity,n,m) select = Trackback(m,weight,capacity,n,Select) else: # print('Type: left to right.') m = KnapsackL(value,weight,capacity,n,m) select = TrackbackL(m,weight,capacity,n,Select) return m, select def mainRun(weight = [6,5,4,1,2,3,9,8,7],value = [1,2,3,7,8,9,6,5,4],capacity = 20,type = 'left2right'): ''' weight = [6,5,4,1,2,3,9,8,7] value = [1,2,3,7,8,9,6,5,4] capacity = 20 ''' ''' weight = [3, 5, 1, 4, 2, 6] value = [2, 3, 4, 2, 5, 1] capacity = 11 ''' n = len(weight) try: n == len(value) except ValueError: print("Please check the number of weights and values.") m = [[-1]*(capacity+1) for _ in range(n)] select = [0 for _ in range(n)] (m,select) = switchFunc(value,weight,capacity,n,m,select,type) maxValue = 0; for i in range(0,n): if select[i] == 1: maxValue = maxValue + value[i] ''' print("Dymamic programming method is done.") print("m matrix: ", m) print("Select: ",select) print("Maximum value: ",maxValue,"\n") ''' if __name__ == '__main__': mainRun(type = 'right2left') mainRun(type = 'left2rightt')
83bbc292acc57c352d83d1e19c5cc9ca1a2e68bb
pinal-012/MY-PROJECTS
/Pizza_store_management.py
6,311
3.96875
4
#write a python program that handles pizzeria customers and at the end of day show the # full day report(like total earning of day,pizza earning, pasta earning etc..) import os os.system('cls') from decimal import Decimal from datetime import datetime class Pizzeria: shift=0 def __init__(self): print("'Welcome to Amazing Pizza and Pasta Store-Pizzeria'".center(160)) ;print() self.pizza_earning=0 self.pasta_earning=0 self.full_day_earning=0 self.full_day_quantity=0 self.soft_drink=0 self.bruschetta=0 self.brownies=0 def showPizza(self,price): self.price=price print("Get 1 large pizza @",self.price,"AUD") print("Get 2 large pizza @",self.price+10,"AUD") print("Get 3 large pizza @",self.price+19,"AUD") print('***Buy 4 or more pizza and get 1.5lt of soft drink free***');print() def showPasta(self,price): self.price=price print("Get 1 large pasta @",self.price,"AUD") print("Get 2 large pasta @",self.price+Decimal('7.5'),"AUD") print("Get 3 large pasta @",self.price+18,"AUD") print('***Buy 4 or more pastas and get 2 bruschetta free.***') print('***Buy 4 or more pizzas and pastas and get 2 chocco brownies ice cream free.');print() print('--------------------------------------------------------------------------------------') def pizzaChoice(self,price): self.price=price self.pizza_quantity=int(input("Enter number of pizza, you want to order:")) if self.pizza_quantity==1: return self.price elif self.pizza_quantity==2: return self.price+10 elif self.pizza_quantity==3: return self.price+19 else: return self.price*self.pizza_quantity #,"\n*** Congratulations !! 1.5lt softdrink free *** " def pastaChoice(self,price): self.price=price print() self.pasta_quantity=int(input("Enter number of pasta, you want to order:")) if self.pasta_quantity==1: return self.price elif self.pasta_quantity==2: return self.price+Decimal('7.5') elif self.pasta_quantity==3: return self.price+18 else: return self.price*self.pasta_quantity def main(self): print("Press 1 to order food and 2 for quit") choice=int(input("Enter your choice:"));print() if choice==1: status=True while status: self.name=input("Enter Your Good name: ") print("Welcome",self.name);input() obj.showPizza(Decimal('10.99')) # showPizza method called obj.showPasta(Decimal('9.50')) # showPasta method called pizzaNetTotal=obj.pizzaChoice(Decimal('10.99')) #pizzaChoice method is called print("Your Pizza Order Amount is:",pizzaNetTotal,"AUD");print() if self.pizza_quantity>3: print('*** Congratulations !! 1.5lt softdrink free ***') self.soft_drink+=1 pastaNetTotal=obj.pastaChoice(Decimal('9.5')) #pizzaChoice method is called print("Your Pasta Order Amount is:",pastaNetTotal,"AUD");print() if self.pasta_quantity>3: print('*** Congratulations !! get 2 bruschetta free ***') self.bruschetta+=2 if self.pizza_quantity>3 and self.pasta_quantity>3: print('*** Congratulations !! get 2 chocco brownies ice cream free *** ') self.brownies+=2 print("Your Total Order Amount is:",pizzaNetTotal+pastaNetTotal,"AUD");print() print('--------------------------------------------------------------------------------------') self.pizza_earning+=pizzaNetTotal #Total pizza earning of the day self.pasta_earning+=pastaNetTotal #Total pizza earning of the day self.full_day_earning+=(pizzaNetTotal+pastaNetTotal) #total earning of the day self.full_day_quantity+=(self.pizza_quantity+self.pasta_quantity) #total quantity pizza+pasta sold in a day allow_next=input("Do you want to allow next customer to enter into pizzaria? Press 'y' for Yes and 'n' for No:").lower() if allow_next=='n': status=False elif choice==2: print("You choosed, not to order from pizzeria!") def show_bill(self): print() n1="<<<<<<<<<<<<<<<<<<<<< Pizza & Pasta Bill >>>>>>>>>>>>>>>>>>>>>>>>>>>>" n00=" " n2="Total Earning of the day: "+ str(self.full_day_earning) +"AUD" n3="Payment Received from Pizza: "+str(self.pizza_earning)+"AUD" n4="Payment Received from Pasta: "+str(self.pasta_earning)+"AUD" n5="Total number of Pizza & Pasta sold in a day: "+str(self.full_day_quantity) n6="Total Number of 1.5lt soft drink bottles given: "+str(self.soft_drink) n7="Total Number of bruschetta given to customer: "+str(self.bruschetta) n8="Total Number of chocco brownies with ice cream given to customer: "+str(self.brownies) n01=" " n9="------------------------------------END----------------------------------------" self.l1=[n1,n00,n2,n3,n4,n5,n6,n7,n8,n01,n9] for i in self.l1: print(i) def print_bill(self): #obj.shift+=1 current_Dt_Time = datetime.now() dt_time_format = current_Dt_Time.strftime("%d-%m-%Y %H:%M:%S") today=dt_time_format[:10] #Displays today's date if not os.path.exists("Pizzeria_Database"): os.mkdir("Pizzeria_Database") with open('Pizzeria_Database/'+str(today)+'.txt','a+') as f: f.write("%s\n"%dt_time_format) #f.write("%s\n"%('Shift: '+str(obj.shift))) l1=map(lambda x:x+'\n', self.l1) f.writelines(l1) obj=Pizzeria() obj.main() obj.show_bill() obj.print_bill() print("Thank You!! ")
a93ca3594739e64904970c9ff2cc18ff33bb360c
Dhrumilcse/Project-Euler
/Problem2.py
460
3.703125
4
#Sum of Even Fibonacci Numbers (Unitil the number Exceeds 4 million) #Recursive function to find Fibonacci of the number def fib(n): if (n == 0 or n == 1): return(1) else: return(fib(n-1) + fib(n-2)) #Printing out Sum of even Fibonacci numbers def testFib(n): sum = 0 for i in range(1,n): #print(fib(i)) if (fib(i) % 2 == 0): sum = sum + fib(i) print(sum) #Not exceeding 4 million testFib(33)
c6aba5e8d7822343ca2a22dd3fd4ea6cfd22cb8c
LewisT543/Notes
/Learning_Tkinter/23Labs-tic-tak-toe.py
4,104
3.75
4
#### TRAFFIC LIGHTS MODEL #### # Tik tak toe... again. This time with more gui. # use grid() geometry manager # define and use callbacks # identifying and servicing GUI events # pc plays x's, who are always red # player plays O's, who are always green # 9 tiles (buttons) # first move: # PC will always play first and place an X in the middle of the board # user choses a tile by clicking them # check for win on every turn and display messagebox if there is a win condition met # PC will choose a move RANDOMLY, because no I dont want to mess about with AI right now. import tkinter as tk from tkinter import messagebox import tkinter.font as font from random import randrange window = tk.Tk() window.title('TicTacToe') window.geometry('400x440') class TicTacToe: def __init__(self, master): self.player_turn = tk.BooleanVar() self.player_turn.set(True) # Make the buttonframe self.button_frame = tk.Frame(master, width=400, height=400) self.button_frame.place(x=0,y=0) self.set_buttons() self.display_frame = tk.Frame(master, width=400, height=60, bg='black') self.display_frame.place(x=0, y=380) self.player_turn_label = tk.Label(self.display_frame, textvariable=str(self.player_turn.get()), bg='black', fg='white') self.player_turn_label.place(x=80, y=10) self.p_turn_plus_label = tk.Label(self.display_frame, text='Player Turn?', bg='black', fg='white') self.p_turn_plus_label.place(x=10, y=10) self.button_font = font.Font(family='Ariel', size=24) self.set_ox(self.board[1][1], 'X') def set_buttons(self): self.board = [[None for c in range(3)]for r in range(3)] for r in range(3): for c in range(3): self.button = tk.Button(self.button_frame, width=1, height=1, padx=45, pady=6, text=(''), font=('Ariel', 45)) self.button.bind('<Button-1>', self.button_clicked) self.button.grid(row=r, column=c) self.board[r][c] = self.button def set_ox(self, btn, sign): btn["fg"] = btn["activeforeground"] = "red" if sign == 'X' else "green" btn["text"] = sign def winner(self): for sign in ['X', 'O']: for x in range(3): if sign == self.board[x][0]['text'] == self.board[x][1]['text'] == self.board[x][2]['text']: return sign if sign == self.board[0][x]['text'] == self.board[1][x]['text'] == self.board[2][x]['text']: return sign if sign == self.board[0][0]['text'] == self.board[1][1]['text'] == self.board[2][2]['text']: return sign if sign == self.board[0][2]['text'] == self.board[1][1]['text'] == self.board[2][0]['text']: return sign return None def win_message(self, sign=None): if sign: messagebox.showinfo('Game Over!', ('Player wins' if sign == 'O' else 'Computer wins')) else: messagebox.showinfo('Draw!', 'Its a Draw.\nTry again!') window.destroy() def free_cells(self): list = [] for row in range(3): for col in range(3): if self.board[row][col]['text'] == '': list.append( (row, col) ) return list def button_clicked(self, event): target = event.widget if target['text'] != '': return # Player Move self.set_ox(target, 'O') if not self.winner() is None: self.win_message('O') # Cpu Move free_cells = self.free_cells() selection = free_cells[randrange(0, len(free_cells))] self.set_ox(self.board[selection[0]][selection[1]], 'X') if not self.winner() is None: self.win_message('X') # Check for draw if len(self.free_cells()) == 0: self.win_message() tiktak = TicTacToe(window) window.mainloop()
1b32e1fec25f16ee7e7a73b1a3ff0330677c6117
mdfarazzakir/Pes_Python_Assignment-3
/Program60/stringPackage/string6.py
2,089
4.40625
4
""" Strings: Write a program to check how many ovals present in the given string. That is, count the number of " a e i o u" in the given string and print the numbers against each oval. Example:- "This is Python" Number of total ovals = 3, i = 2, o =1 """ """Function to calculate vowels in a string""" def vowels(strg): a = e = i = o = u = 0 for j in strg: if j =='a': a = a + 1 elif j == 'e': e = e + 1 elif j =='i' : i= i + 1 elif j == 'o': o = o + 1 elif j =='u' : u = u + 1 print("\nCount of a is: ",a) print("\nCount of e is: ",e) print("\nCount of i is: ",i) print("\nCount of o is: ",o) print("\nCount of u is: ",u) total= a+e+i+o+u print("\nTotal Vowels in strg is",total) """Taking string as input""" strg = input("Enter the string: ").lower() """Calling the function""" vowels(strg) # Output: # (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program28.py # Enter the string: aeiou # # Count of a is: 1 # # Count of e is: 1 # # Count of i is: 1 # # Count of o is: 1 # # Count of u is: 1 # # Total Vowels in strg is 5 # # (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program28.py # Enter the string: AEIOU # # Count of a is: 1 # # Count of e is: 1 # # Count of i is: 1 # # Count of o is: 1 # # Count of u is: 1 # # Total Vowels in strg is 5 # # (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program28.py # Enter the string: United States # # Count of a is: 1 # # Count of e is: 2 # # Count of i is: 1 # # Count of o is: 0 # # Count of u is: 1 # # Total Vowels in strg is 5 # # (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2> # (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>python Program28.py # Enter the string: India # # Count of a is: 1 # # Count of e is: 0 # # Count of i is: 2 # # Count of o is: 0 # # Count of u is: 0 # # Total Vowels in strg is 3 # # (base) C:\Users\faraz\Desktop\Python\Pes_Python_Assignment-2>
9c3497b7b440a40556e690e70c771e221f119a3e
SpencerBeloin/Python-files
/maxnumber.py
310
4.09375
4
#maxnumber.py x1,x2,x3= eval(input("Please eneter three values : ")) if x1 >= x2 and x1 >= x3: max = x1 print( x1, " x1 is the biggest" ) elif x2 >=x1 and x2 >= x3: max = x2 print( x2, " x2 is the biggest" ) else: max = x3 print( x3, " x3 is the biggest" )
64b36f1560095ef719a0ee3c1bc85ab516addcf6
Nehanavgurukul/function_ques
/harshad_number.py
212
3.859375
4
num=int(input("enter the number")) c=num sum=0 modulus=0 while(c!=0): modulus=c%10 sum=sum+modulus c=c//10 if(num%sum==0): print("it is harshad number") else: print("it is not harshad number")
84bcd25ce6ff77615db54a08f7b15ace7578cebb
simgek/simge3-2
/3.2for4.py
276
3.640625
4
# 10 ile 20 arasındaki asal sayıları gösterin for num in range(10,21): for i in range(2,num): if num % i == 0: j = num/i print("{} eşittir{}*{}".format(num,i,int(j))) break else: print(num, "asal sayıdır")
bfa5b5035647d16639732d4af0a045994813738e
Jamesburgess44/Marketing-Sweepstakes
/contestant.py
1,059
3.875
4
from userinterface import UserInterface class Contestant: """, I want to create a Contestant class that has a first name, last name, email address, and registration number.""" def __init__(self): self.first_name = UserInterface.get_user_input_string("Enter first name") self.last_name = UserInterface.get_user_input_string("Enter last name") self.email = UserInterface.get_user_input_string("Enter email address") self.registration_number = 0 pass def notify(self, is_winner): """, I want to use the observer design pattern to notify all users of the winning contestant, with the winner of the sweepstakes receiving a different message specifically congratulating them on being the winner. This notification will be triggered within the sweepstakes pick_winner method. """ is_winner = False if is_winner == False: pass else: pass """if false needs to send (not a winner) message if ture needs to send congrats message"""
3d49c005dca3f40a21e6464783b7f70dc95cce31
PropeReferio/practice-exercises
/random_exercises/factorial.py
204
4.15625
4
def factorial(number): x = 1 while number > 0: x *= number number = number - 1 return x n = int(input("Give me a number, and I'll compute the factorial!")) print(factorial(n))
2a5cb04a9194f75ae0cbd9872d750476db81ccb7
Sunilbhat717/python_programs
/Input_output.py
352
3.9375
4
#!/usr/bin/env python print("Please enter the following details") name = input("Enter your name\n") age = int(input("Enter your age\n")) while age > 100 or age < 0: print("Invalid input..please re-enter the age") age = int(input("Enter your age\n")) ans = 100 - age print("Hey %s, Good day. You will turn 100 in next %d year" % (name, ans))
eff583ca91cc155142b566064789cbc3b951a5fa
Mehvix/competitive-programming
/Codeforces/Individual Problems/P_4A.py
166
3.78125
4
user_input = int(input().strip()) if (user_input % 2 == 0) and (user_input > 0) and (user_input != 2) and (user_input <= 100): print("YES") else: print("NO")
8f85abd2fc2dd8cbd26c41d5dc5fc49d11d237b3
aliakseik1993/skillbox_python_basic
/module1_13/module7_hw/task_7.py
943
4.125
4
print('Задача 7. Отрезок') # Напишите программу, # которая считывает с клавиатуры два числа a и b, # считает и выводит на консоль #среднее арифметическое всех чисел из отрезка [a; b], которые кратны числу 3. number_begin = int(input("Введите начальное число: ")) number_end = int(input("Введите конечное число: ")) divider = 0 number_summ = 0 for number in range(number_begin, number_end + 1): #print(number) if number % 3 == 0: divider += 1 number_summ += number #print("Число подходящие под условия", number) #print("сумма таких чисел", number_summ) #print("Колличество такие числе", divider) print("Среднее арифметическое =", number_summ / divider)
60c2fe22aff00c820f40a0d65e65d689e70fd620
rafa3lmonteiro/python
/python3-course/aula17/aula17-parte2-b.py
1,420
4.25
4
#Curso Python #17 - Listas (Parte 2) #continuacão teste = list() teste.append('Gustavo') teste.append('40') galera = list() galera.append(teste) #Nesta forma de append eu faco uma ligacão, e tudo que acontecer nesta lista flete nos futuros appends teste[0] = 'Maria' teste[1] = 22 galera.append(teste) print(galera) #-------------------- Fazendo o mesmo com Copia de fatiamento teste2 = list() teste2.append('Gustavo') teste2.append('40') galera2 = list() galera2.append(teste2[:]) # Nesta maneira eu realizo uma COPIA de fateamento e sigo sem ligacão teste2[0] = 'Maria' teste2[1] = 22 galera2.append(teste2[:]) print(galera2) #--------------- galera3 = [['João', 10], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]] print(galera3) print(galera3[2][1]) for p in galera3: print(f'{p[0]} tem {p[1]} anos de idade ') #--------------- galera4 = list() dado = list() totmai = totmen = 0 for c in range(0, 3): dado.append(str(input('Nome: '))) dado.append(str(input('Idade: '))) galera4.append(dado[:]) # Neste caso como eu estou fazendo uma copia, quando eu fizer o clear abaixo, eu não perco esta informacão no galera4 dado.clear() print(galera4) for p in galera4: if p[1] >= "21": print(f'{p[0]} é maior de idade') totmai += 1 else: print(f'{p[0]} é menor de idade') totmen += 1 print(f'Temos {totmai} maiores de idade e {totmen} menos de idade')
eaac1f951ce6638228a58b4f5b9ee9dca7f6a3fe
arjunsawhney1/graph-algorithms
/number_of_shortest_paths.py
1,252
3.8125
4
import graph from collections import deque def number_of_shortest_paths(graph, source): status = {node: 'undiscovered' for node in graph.nodes} distance = {node: float('inf') for node in graph.nodes} paths = {node: 0 for node in graph.nodes} status[source] = 'pending' pending = deque([source]) distance[source] = 0 # There is one shortest path to the source node of length 0 paths[source] = 1 while pending: u = pending.popleft() for v in graph.neighbors(u): if status[v] == 'undiscovered': status[v] = 'pending' distance[v] = distance[u] + 1 # The number of paths to a node is equal to the number of # paths to its predecessor node when it is first discovered paths[v] = paths[u] pending.append(v) else: # if node has already been visited by bfs, check if the current # path to node has same length as shortest path if distance[u] + 1 == distance[v]: # Add 1 to number of paths if it is paths[v] += 1 status[u] = 'visited' return paths
2274acc0bd401e910a669a259fd72a9ca075ac80
vvspearlvvs/CodingTest
/1.알고리즘정리/DFS와BFS/bfs.py
676
3.703125
4
#BFS -큐(deque)이용 import collections import deque #각 노드가 연결된 정보 표현 graph=[ [], [2,3,8], [1,7], [1,4,5], [3,5], [3,4], [7], [2,6,8], [1,7] ] visited=[False]*9 def bfs(graph,start,visited): #현재노드 방문처리 queue=deque([start]) visited[start]=True while queue: #큐에서 하나의 원소 뽑아 v=queue.popleft() print(v,end=' ') #아직 방문하지 않은 인접한 노드를 큐에 삽입 for i in graph[v]: if not visited[i]: queue.append(i) visited[i]=True print("##최종") bfs(graph,1,visited)
af642079a5ec8dfa332a5e37ce9433587857321e
daniel-reich/ubiquitous-fiesta
/gnaxzuGNPnxKkJo39_0.py
363
3.75
4
def easter_date(y): # I have no idea what I'm doing g = y%19 +1 s = (y -1600)//100 -(y -1600)//400 l = (((y -1400)//100)*8)//25 p = (3 +s -l -11*g)%30 p -= 1 if p == 29 or (p == 28 and g > 11) else 0 d = (y +(y//4) -(y//100) +(y//400))%7 e = p +1 +(4 -d -p)%7 return 'March ' + str(e +21) if e < 11 else 'April '+ str(e -10)
953d8f795de9c6693bd04aa68d5fd402c65cfd24
Fahad-Hassan/itp-test
/test.py
2,716
3.6875
4
class Contact(object): def __init__(self, name, email,phone): self.name = name self.email = email self.phone = phone def __str__(self): return f"{self.name} <{self.email}> {self.phone}" class Leads(object): def __init__(self, name, email,phone): self.name = name self.email = email self.phone = phone def __str__(self): return f"{self.name} <{self.email}> {self.phone}" class registrants(object): def __init__(self, name, email,phone): self.name = name self.email = email self.phone = phone def __str__(self): return f"{self.name} <{self.email}> {self.phone}" if __name__ == "__main__": obj_con=[] obj_le=[] obj_reg =[] obj_con.append(Contact('Alice Brown' ,None,'1231112223')) obj_con.append(Contact('Bob Crown' ,'bob@crowns.com',None)) obj_con.append(Contact('Carlos Drew' ,'carl@drewess.com','3453334445')) obj_con.append(Contact('Doug Emerty' ,None,'4564445556')) obj_con.append(Contact('Egan Fair' ,'eg@fairness.com','5675556667')) obj_le.append(Leads(None,'kevin@keith.com',None)) obj_le.append(Leads('Lucy' ,'lucy@liu.com','3210001112')) obj_le.append(Leads('Mary Middle' ,'mary@middle.com','3331112223')) obj_le.append(Leads(None ,None,'4442223334')) obj_le.append(Leads(None ,'ole@olson.com',None)) obj_reg.append(registrants('Lucy Liu','lucy@liu.com',None)) obj_reg.append(registrants('Doug' ,'doug@emmy.com','4564445556')) obj_reg.append(registrants('Uma Thurman' ,'uma@thurs.com',None)) reg1={ "registrant": { "name": "Tom Jones", "email": "tom@jones.com", "phone": "3211234567", } } if reg1['registrant']['email'] in [c.email for c in obj_con] : print('email matched') elif reg1['registrant']['phone'] in [c.phone for c in obj_con] : print("phone matched") else: for l in obj_le: if reg1['registrant']['email'] == l.email: temp=l obj_le.remove(l) obj_con.append(temp) elif not reg1['registrant']['phone'] == l.phone : obj_con.append(Contact(l.name,l.email,l.phone)) print("**********CONTACTS*************") for c in obj_con: print(c.__str__()) # print('name %s email %s phone %s '%(c.name,c.email,c.phone )) print("**********LEADS****************") for le in obj_le: print(le.__str__()) # print('name %s email %s phone %s '%(le.name,le.email, le.phone )) print("**********REGISTRANTS**********") for r in obj_reg: print(r.__str__()) # print('name %s email %s phone %s '%(r.name,c.email,c.phone))
e7fef429f1fb85396de9763916b65ff409aa6efa
YoonhoRayLee/BOJ_Solution
/Math/1475.py
453
3.546875
4
#Dongguk University Computer Science Engineering #Yoonho Ray Lee #BOJ Solution for Problem.1475 import math N = list(input()) list1 = [] list2 = [] count = 0 for i in N: if i == '6': count += 1 continue if i == '9': count += 1 continue if N.count(i) != 1: list1.append(i) avg = int(math.ceil(count/2)) for i in list1: list2.append(list1.count(i)) list2.append(1) list2.append(avg) print(max(list2))
cea60137e987a2a6b008dd75acdb17fcea23a36f
Charlymaitre/30exo_python
/25.py
534
4.03125
4
# Faire un programme python qui demande à un utilisateur d’entrer un entier positif. Le programme indique ensuite si l’entier positif est pair ou impair ? Le programme vérifie et redemande l’entier si ce n’est pas un entier positif. valeurInitiale = int(input("Choississez un nombre ")) while valeurInitiale < 0: valeurInitiale = int(input("Veuillez saisir un entier positif ")) if valeurInitiale % 2 == 0: print("Le nombre est pair") else: print("Le nombre est impair")
33cbc7d3d2cefac3b4a3f6afde5509621d9f3512
algo2020-lesnaya-skazka/python1_tasks
/python_book_page_128_ex_1.py
86
3.875
4
names = ['Simon' , 'Kate' , 'Vanya'] for item in names : print('Hello' , item)
ef18474fe312b0d17f3342b7417b740f2a1390dd
daniel-reich/ubiquitous-fiesta
/gdzS7pXsPexY8j4A3_9.py
378
3.90625
4
def count_digits(lst, t): result = [] total = 0 digits = [list(str(n)) for n in lst] for number in digits: for digit in number: if t == "even" and int(digit) % 2 == 0: total += 1 elif t == "odd" and int(digit) % 2 != 0: total += 1 result.append(total) total = 0 return result
838bcc64ee4c849ab9139dbd4ac51e6b9a1d0e10
james-cape/exercisms
/python/twelve-days/twelve_days.py
1,260
3.65625
4
def recite(start_verse, end_verse): last_line = "a Partridge in a Pear Tree." if end_verse > 1: last_line = "and " + last_line numbers = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth", 11: "eleventh", 12: "twelfth" } first_line = "On the {} day of Christmas my true love gave to me: ".format(numbers[start_verse]) all_lines = [ "two Turtle Doves, ", "three French Hens, ", "four Calling Birds, ", "five Gold Rings, ", "six Geese-a-Laying, ", "seven Swans-a-Swimming, ", "eight Maids-a-Milking, ", "nine Ladies Dancing, ", "ten Lords-a-Leaping, ", "eleven Pipers Piping, ", "twelve Drummers Drumming, ", last_line ] song = "" if start_verse == end_verse: for i in range(1, end_verse): song = all_lines[end_verse - start_verse] for i in range(1, end_verse + 1): if i == end_verse: song += last_line else: song = all_lines[i] + song breakpoint() return [song]
505109e91722fa1f0cc3c22a61ca1a6e0e64d909
hanameee/Algorithm
/Leetcode/파이썬 알고리즘 인터뷰/12_그래프/src/dfs_bfs.py
1,048
3.765625
4
from collections import deque graph = { 1: [2, 3, 4], 2: [5], 3: [5], 4: [], 5: [6, 7], 6: [], 7: [3] } def recursive_dfs(v, visited=[]): visited.append(v) for w in graph[v]: if not w in visited: visited = recursive_dfs(w, visited) return visited def iterative_dfs(start_v): visited = [] need_visit = [start_v] while need_visit: v = need_visit.pop() # element in stk can be already visited if v not in visited: visited.append(v) for w in graph[v]: need_visit.append(w) return visited def bfs(v): visited = [v] need_visit = deque([v]) while need_visit: v = need_visit.popleft() for w in graph[v]: if w not in visited: # adjacent node should be checked as visited before it is pushed to queue visited.append(w) need_visit.append(w) return visited print(recursive_dfs(1)) print(iterative_dfs(1)) print(bfs(1))
e2f4b1ce77039cf4c73b04062c690f6160ecc8e8
veenakruthi-1694/TestGithub
/stopwords .py
484
3.875
4
def remove_stopwords(text, is_lower_case=False): tokens = tokenizer.tokenize(text) tokens = [token.strip() for token in tokens] if is_lower_case: filtered_tokens = [token for token in tokens if token not in stopword_list] else: filtered_tokens = [token for token in tokens if token.lower() not in stopword_list] filtered_text = ' '.join(filtered_tokens) return filtered_text remove_stopwords("The, and, if are stopwords, computer is not")
def8754f3b81042ce38bcba35a2df0a6201b3f7b
AricA05/Python_OOP
/init_method.py
965
4.5625
5
#object orientated programming in Python #objects will have attributes and behaviours #class = the design/blueprint to create the object #object = what the class produces #define class: class Computer: #initialize objects (constructor), in this case we are passing three arguments/paramters def __init__(self,cpu,ram): #assign values to an object self.cpu = cpu self.ram = ram #behaviour (methods) def config(self):#this is the method print("Config is",self.cpu,self.ram) #create necessary parameters/define parameter to call the function com1 = Computer('i5',16) com2 = Computer('Ryzen 3',8) #calls functions com1.config() com2.config() #this example is an int object, a(object) = 5(integer class), therefore a object type is an int #a = 5 #print(type(a))#this will print what type of class it is #for each class you have to say what it equals so it knows if it is aafunction,int,string,float,etc... #the below example is a function
3094c30520205c981881338ce5baf31b72977d7f
felixvor/flipfacts
/flask-backend/flipfacts/api/validate.py
824
3.609375
4
import string def username(username): if not (len(username) >= 3 and len(username) < 35): return False whitelist_chars = [".","-","_"] blacklist_chars = string.punctuation+" " #whitespace not included for c in blacklist_chars: if c in whitelist_chars: continue if c in username: return False for c in username: if not (32 <= ord(c) <= 126): return False #not letter from ascii return True def email(email): if not "@" in email: return False if not "." in email: return False if not (len(email) >= 3 and len(email) < 200): return False return True def password(password): if len(password) <= 7: return False if len(password) >= 60: return False return True
a5a75ed14c1ffebaa43a707f5c059e1df960f208
ZakawarMaw/python-learning
/input.py
176
4.09375
4
# print("Hello World"); # name=input(' Name :'); # print('Hello ' +name); # Calculate Area ( Formula Pi r**2) PI=3.142; r=int(input('radius : ')); area=PI*r**2; print(area);
ff5d1907589f5647fcdea36cfd59acbb1e408952
gschen/where2go-python-test
/1906101009肖文星/ago/练习4.py
292
3.78125
4
'''斐波那契数列。(斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。前两项相加等于第三项)求前101项''' a=0 b=1 for i in range(99): c=a+b a,b=b,c print(c)
a0caa3a78c80c98b101056b02df97dc525df9eb5
shivamar/geeks
/src/mthSequence.py
808
3.703125
4
## Generate mth permutation sequence lexicographically ## 0,1,2 : 5th sequence is 201 def fact(n): if(n==1): return 1 if(n < 1): return 0 return n * fact(n-1) def combination(N, M): num_list = [0,1,2,3,4,5,6,7,8,9] num_list = num_list[0:N] ans='' i=1 fac = fact(N-i) rem = M coeff = N-i while(i < N+1 ): for coeff in range(N-i,-1,-1): if(fac * coeff >= rem and coeff > 0): continue else: print(num_list, coeff*fac, rem) digit = num_list.pop(coeff) ans += str(digit) rem = rem - (coeff*fac) i=i+1 fac = fact(N-i) break print(ans) combination(3,2)
b2037c4bf2463315f7868277a4f1e4edf3451800
Ilya225/codingChallenges
/python/leet_code/jump_game_II.py
668
3.5625
4
from typing import List class Solution: def jump(self, nums: List[int]) -> int: i = 0 jumps = 0 while i < len(nums)-1: max_index = 0 for j in range(1, nums[i]+1): if i + j < len(nums): if max_index == 0: max_index = i+j elif nums[i + j] >= nums[max_index]: max_index = i + j else: jumps += 1 return jumps i = max_index jumps += 1 return jumps if __name__ == '__main__': sol = Solution() print(sol.jump([2,3,1]))
6112c410016c172d5338bb78508e49dbf91f7e01
14021612946/python_all-hedengyong
/pythonProject2day11.0/day11.3.py
1,688
3.640625
4
class student: __username=None __age=None __deskmatename=None __daskmateage=None def setUsername(self,username): self.__username=username def getUsername(self): return self.__username def setAge(self,age): self.__age=age def getAge(self): return self.__age def setDaskmatename(self,daskmatename): self.__daskmatename=daskmatename def getDaskmatename(self): return self.__daskmatename def setDaskmateage(self,daskmateage): self.__daskmateage=daskmateage def getDaskmateage(self): return self.__daskmateage def daskmate(self): print("大家好","我叫",self.__daskmatename,"我今年",self.__daskmateage,"岁了") def presentation(self): print("大家好","我叫",self.__username,"我今年",self.__age,"岁了!") # # def compare(self): # if self.__age>self.__daskmateage: # print("我比同桌大",(self.__age-self.__daskmateage),"岁") # elif self.__age<self.__daskmateage: # print("我比同桌大",(self.__age-self.__daskmateage),"岁") # else: # print("我和同桌一样大") def Compare(self,p1): if self.__age > p1.getAge(): print("我比同桌大",self.__age - p1.getAge(),"岁") elif self.__age<p1.getAge(): print("我比同桌小",p1.getAge() - self.__age,"岁") else: print("我和同桌一样大") p=student() p.setUsername("小明") p.setAge(15) p.presentation() p1=student() p1.setUsername("小花") p1.setAge(27) p.Compare(p1)
f81676fdd4ce88191ad55d9fa83ca4954d77b66c
nookalaramu/python
/list.py
750
4.25
4
# Take 5 different names from user which should have first name middle name and last name , # and should be stored in List called as "nameList" Example: # 1) suresh kumar angadi # 2) basappa chennappa gadad # 3) rakesh kumar miskin # 4) rithwik ullagaddi mathad # 5) shankar gowda kumar # 1)Suresh K.A # 2)Basappa C.G # 3)Rakesh K.M # 4)Rithwik U.M # 5)Shankar G.K nameList = ["suresh kumar angadi","basappa chennappa gadad","rakesh kumar miskin","rithwik ullagaddi mathad","shankar gowda kumar"] print(nameList) updateList=[] for i in nameList: separate = i.split() fname = separate[0].capitalize() mname = separate[1][:1].capitalize() lname = separate[2][:1].capitalize() uname = fname + " " + mname + "."+lname updateList.append(uname) print("Given Name List as ", nameList) print("Name List is converted to short form as :") for j in updateList: print(j)
e223d8261e5b5253f6cd5d4b3a0ded2c78a39d7c
matt-a-a-achooo/DukeTip
/rocket.py
697
3.875
4
import array as np import matplotlib.pyplot as plt x = [-40, -20, 0, 20, 40, 60, 80] # angle measurements y = [61, 177.33, 296.33, 680.33, 651, 534.67, 24.67] # average result = np.polyfit(x, y, 2) print(result) eq = np.poly1d(result) print(eq) print(eq(2)) x2 = np.arange(-40, 90) # gives a range for the angles yfit = np.polyval(result, x2) print(yfit) plt.plot(x, y, label='Point') plt.plot(x2, yfit, label='Fit') user_input = raw_input("Enter Angle:") # asks user for an angle mynumber=user_input try: number = int(user_input) # prints answer based off of user input except ValueError: print 'Exception Happened' #just in case user_input is not an integer print eq(number)
694ccf14ab1fd174eafdfbc3d5c25ff5b5461644
veratsurkis/enjoy_sleeping
/ex10_1.py
201
3.765625
4
import turtle as tr tr.shape('turtle') tr.speed(0) def circle(n): turn = 360/n for i in range(n): tr.forward(1) tr.right(turn) p=400 for i in range(6): circle(p) tr.right(60)
4d3ce1f21ea9ad03a801886e9cd673a67aa393de
jhsmaciel/PythonZombie
/Python/List 3/Exer2.py
351
4.1875
4
nome = input("Digite o nome de usuário: ") senha = input("Digite a sua senha: ") x = -1 while x != 0: if nome == senha: print("Usuário e senha não podem ser iguais!") nome = input("Digite o nome de usuário: ") senha = input("Digite a sua senha: ") else: x = 0 print("Usuário e senha estão aceitos!")
23d8c168396cf84a41ff5ec802f9a6e47ad04427
spike688023/Python-for-Algorithms--Data-Structures
/Graphs/Graph Interview Questions/BFS.py
1,881
4.09375
4
# -*- coding: utf-8 -*- graph = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} print graph """ 實作DFS, BFS: 最大的差別在, 使用的儲存結構, BFS因為要從相鄰的往外延申, 所以要用queue, DFS則是用stack, 喔, 它媽的想到了, DFS, BFS只是對圖的search的方式不同而己, function的呼叫,也是可以給個目地. """ def BFS(graph, start): result, queue = [start], [start] visited = set(start) # 這裡 for loop要用set while queue: vertex = queue.pop(0) for i in graph[vertex] - visited: queue.append(i) visited.add(i) result.append(i) return result print "BFS : " + str( BFS(graph, 'A') ) """ DFS , 會用到 yield DFS停的點在那裡? 找到 goal的時侯, 即便我的寫法是錯的,yield也要有回傳一些路徑才對丫。 喔,它媽的,我知道, 首先,我沒有用while去判斷stack內是否有東西, 整個func內,只有一個for loop,所以這個loop, 沒有跑到,我們要的end, 所以沒有東西return, 即便我code裡面有寫要return的行。 所以,我改成要到b ,就 會有東西了 """ graph2 = {'A': set(['B', 'C']), 'B': set(['A', 'D', 'E']), 'C': set(['A', 'F']), 'D': set(['B']), 'E': set(['B', 'F']), 'F': set(['C', 'E'])} def DFS(graph2, start, end): path, stack = [start], [start] visited = set(start) print path vertex = stack.pop() for i in graph2[vertex] - visited: if i == end: yield path + [i] else: stack.append(i) visited.add(i) path.append(i) print list( DFS(graph2, 'A', 'B') )
9de37e1a00bdb0c05f1d5ded8a72145b0ba3c333
Dawsen64/hello-world
/LeetCode-python/T844.py
796
3.609375
4
class Solution: def backspaceCompare(self, s: str, t: str) -> bool: left, right = 0, 0 S = list(s) while right < len(S): if S[right] != "#": S[left] = S[right] left += 1 else: left -= 1 if left < 0: left = 0 right += 1 temp = left left, right = 0, 0 T = list(t) while right < len(T): if T[right] != "#": T[left] = T[right] left += 1 else: left -= 1 if left < 0: left = 0 right += 1 if S[0:temp] == T[0:left]: return True else: return False
e55fb660b2899364e553868ac8be14f6c8d0dfee
vmathurdev/Customer-Analytics-for-banking-services
/NN_Keras.py
5,781
4.5625
5
#Presenting an Artificial Neural Network implementation to find out reasons as to why and which customers are leaving the bank and their dependencies on one another. #This is a classification problem 0-1 classification(1 if Leaves 0 if customer stays) #We make use of Keras which enables us writing powerful Neural Networks with a few lines of code #Keras runs on Theano and Tensorflow and imagine it as a Sklearn for Deep Learning Artificial Neural Network # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset save it in Pycharm Projects/Name of Project dataset = pd.read_csv('Churn_Modelling.csv') #Looking at the features we can see that row no.,name will have no relation with a customer with leaving the bank #so we drop them from X which contains the features Indexes from 3 to 12 X = dataset.iloc[:, 3:13].values #We store the Dependent value/predicted value in y by storing the 13th index in the variable y y = dataset.iloc[:, 13].values #Printing out the values of X --> Which contains the features # y --> Which contains the target variable print(X) print(y) # Encoding categorical data # Now we encode the string values in the features to numerical values # The only 2 values are Gender and Region which need to converted into numerical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder()#creating label encoder object no. 1 to encode region name(index 1 in features) X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])#encoding region from string to just 3 no.s 0,1,2 respectively labelencoder_X_2 = LabelEncoder()#creating label encoder object no. 2 to encode Gender name(index 2 in features) X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])#encoding Gender from string to just 2 no.s 0,1(male,female) respectively #Now creating Dummy variables onehotencoder = OneHotEncoder(categorical_features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Part 2 - Now let's make the ANN! ''' Listing out the steps involved in training the ANN with Stochastic Gradient Descent 1)Randomly initialize the weights to small numbers close to 0(But not 0) 2)Input the 1st observation of your dataset in the Input Layer, each Feature in one Input Node 3)Forward-Propagation from Left to Right, the neurons are activated in a way that the impact of each neuron's activation is limited by the weights.Propagate the activations until getting the predicted result y. 4)Compare the predicted result with the actual result. Measure the generated error. 5)Back-Propagation: From Right to Left, Error is back propagated.Update the weights according to how much they are responsible for the error.The Learning Rate tells us by how much such we update the weights. 6)Repeat Steps 1 to 5 and update the weights after each observation(Reinforcement Learning). Or: Repeat Steps 1 to 5 but update the weights only after a batch of observations(Batch Learning) 7)When the whole training set is passed through the ANN.That completes an Epoch. Redo more Epochs ''' # Importing the Keras libraries and packages import keras from keras.models import Sequential#For building the Neural Network layer by layer from keras.layers import Dense#To randomly initialize the weights to small numbers close to 0(But not 0) # Initialising the ANN #So there are actually 2 ways of initializing a deep learning model #------1)Defining each layer one by one #------2)Defining a Graph classifier = Sequential()#We did not put any parameter in the Sequential object as we will be defining the Layers manually # Adding the input layer and the first hidden layer #This remains an unanswered question till date that how many nodes of the hidden layer do we actually need # There is no thumb rule but you can set the number of nodes in Hidden Layers as an Average of the number of Nodes in Input and Output Layer Respectively. #Here avg= (11+1)/2==>6 So set Output Dim=6 #Init will initialize the Hidden Layer weights uniformly #Activation Function is Rectifier Activation Function #Input dim tells us the number of nodes in the Input Layer.This is done only once and wont be specified in further layers. classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11)) # Adding the second hidden layer classifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu')) # Adding the output layer classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid')) #Sigmoid activation function is used whenever we need Probabilities of 2 categories or less(Similar to Logistic Regression) #Switch to Softmax when the dependent variable has more than 2 categories # Compiling the ANN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training set classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 100) # Part 3 - Making the predictions and evaluating the model # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5)#if y_pred is larger than 0.5 it returns true(1) else false(2) print(y_pred) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print(cm) accuracy=(1550+175)/2000#Obtained from Confusion Matrix print(accuracy)
c5a67c631481ff858ec374c26c10b4446bab7bdc
MihaiCatescu/python_exercises
/exercise10.py
1,016
4.25
4
# This exercise is for checking whether a number given by the user is prime or not. # Solution 1 - Using functions number = int(input("Give me a number: ")) numbers = list(range(1, number + 1)) divisors = [] def get_divisors(number): for i in numbers: if number % i == 0: divisors.append(i) return divisors get_divisors(number) def is_prime(number): if len(divisors) <= 2: print(number, "is a prime number.") else: print(number, "is not a prime number.") is_prime(number) # Solution 2 - without the use of functions import sys number = int(input("Insert a number" + "\n" + ">>> ")) prime = False if number > 0: for i in range(2, number - 1): if number % i != 0: continue elif number % i == 0: sys.exit("The number is not prime.") sys.exit("The number is prime.") elif number == 0: sys.exit("The number is not prime.") else: sys.exit("The number is not prime.")