blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
edbf3c59e3bd5a353e438bb79921a189e2019eff
Anubhav27/python_handson
/listdemo.py
327
3.734375
4
__author__ = 'Anubhav' shoplist = ['a','b','c','d'] print shoplist.__len__() shoplist.append('e') print shoplist.__len__() shoplist.append('z') shoplist.append('f') print shoplist.__len__() print shoplist shoplist.sort() print shoplist for items in shoplist: print items for i in range(100): print i
bceac41714c08ff36ed0481b68cfffe69f61f3ad
Kanguru9/SimpleLogin
/login.py
3,121
4.28125
4
def login(): username_vault = ["john", ] password_vault = ["smith", ] choose = input( "Do you want to create a account or login? Type login for logging in or type create for creating an account: ") choose.lower() six = 6 if choose == "create": Create() elif choose == "login": logging() else: print("there was a error, make sure you typed everything correctly") # create an accounty def Create(): print("create an account") username = input("Username: ") username.lower() if len(username) < six: print("you need at least 6 characters") username = input("Username: ") username.lower() if len(username) < six: print("you need at least 6 characters") elif len(username) > six: password = input("Password: ") else: print("username needs at least 6 characters long try again") elif len(username) > six: password = input("Password: ") if True: if any(username in word for word in username_vault): print("this username already exists") elif any(username in word for word in username_vault) and any( password in word for word in password_vault): print("you already have an account") else: print("you created an account") username_vault.append(username) password_vault.append(password) print("-" * 50) print("login") username3 = input("Username: ") password3 = input("Password: ") if True: if any(username3 in word for word in username_vault) and any( password3 in word for word in password_vault): print("you logged in") elif any(username3 in word for word in username_vault) and any( password3 not in word for word in password_vault): print("Wrong Password") else: print("error") print("-" * 50) # logging in def logging(): print("login") username2 = input("Username: ") password2 = input("Password: ") if True: if any(username2 in word for word in username_vault) and any(password2 in word for word in password_vault): print("you logged in") elif any(username2 in word for word in username_vault) and any( password2 not in word for word in password_vault): print("Wrong Password") else: print("This account does not exist") else: print("error") print("-" * 50) question = input("Do you want to login? Y or N") question.lower() if question == "y": print("ok") login() elif question == "n": print("ok") exit
d94c3e993bd855c950dfe809dba92957b40c4a20
JimiofEden/PyMeth
/Week 1/TEST_roots_FalsePosition.py
470
4.25
4
import roots_FalsePosition import numpy ''' Adam Hollock 2/8/2013 This will calculate the roots of a given function in between two given points via the False Position method. ''' def f(x): return x**3+2*x**2-5*x-6 results = roots_FalsePosition.falsePosition(f,-3.8,-2.8,0.05) print results results = roots_FalsePosition.falsePosition(f,-1.3,-0.9,0.05) print results results = roots_FalsePosition.falsePosition(f,1.8,2.3,0.05) print results print numpy.roots([1, 2, -5, -6])
9356de0d86bb5dd10b881f2e71df30e6bf827c58
mitalshivam1789/python
/else with for file.py
235
4.09375
4
khana = ["roti","sabzi","chawal"] for item in khana: if item == "roti": print(item) break else: # it will execute when for loop goes properly. or their is no break in loop print("Your item is not found")
b591d8d0928cc4e959880875bd3003d07efa20fc
mitalshivam1789/python
/practice_test_3.py
708
3.890625
4
list_value=input("enter a list with spaces between numbers.") list_value=list_value.split(" ") for i in range(len(list_value)): list_value[i] = int(list_value[i]) print(list_value) print(type(list_value[1])) list_value.reverse() print(list_value) list_value.reverse() print(list_value[::-1]) len=len(list_value) if len%2 == 0: for i in range(int(len/2)): temp = list_value[i] list_value[i]=list_value[len-1-i] list_value[len-1-i] = temp elif len%2!=0: for i in range(int((len-1)/2)): temp = list_value[i] list_value[i]=list_value[len-1-i] list_value[len-1-i] = temp print(list_value) #print("By method 1 - ",reverse_list1)
7126fe424d609939ae4aa0247f6681c261b1c13a
mitalshivam1789/python
/project6differentway.py
978
3.796875
4
def adddata(name): whattoadd = input("diet or exercise") details = input("what you what to add") f = open(name + whattoadd + ".txt", "a") f.write(details) f.close() def retrievedata(name): whattoretrieve = input("diet or exercise") f = open(name + whattoretrieve + ".txt") print(f.read()) f.close() def newfile(name): namearray.append(name) print(namearray) whattodo = input("want to add or retrieve or add new") name = input("enter name of the person") namearray = ["harry", "shivam", "sagar"] differentfun=["add","retrieve","add new"] if name in namearray: if whattodo == differentfun[0]: adddata(name) elif whattodo == differentfun[1]: retrievedata(name) elif name not in namearray: print(name) wanttoadd = input("did you want to add this name then press y :") if wanttoadd == "y": newfile(name) if whattodo == differentfun[2]: newfile(name)
ab806e66a29e7c19be1b8fa9b3703a723604597d
mitalshivam1789/python
/functionsfile.py
427
3.953125
4
c = sum((5,7)) print(c) def function1(a,b): """this is a doc which we can print using doc whic i will show you . So we should write here about the role of the function so that we can see it using the the doc function.""" print("thsi is a nice function.") print(function1.__doc__) num1 = input() num2 = input() try: print("sum is", int(num1) + int(num2)) except Exception as e: print(e) print("nice")
055edf392302483538c41b1b0739c445dc08598a
mitalshivam1789/python
/mapfilterreduce.py
576
3.71875
4
lis = ["1","2","5","3","4"] num = list(map(int,lis)) print(num,type(num),lis) def sq (a): return a*a square = list(map(sq,num)) print(square) sqr = list(map(lambda x: x*x,num)) print(sqr) def sqr1(a): return a*a def cube(a): return a*a*a func = [sqr1,cube] for i in range(5): val = list(map(lambda x : x(i),func)) print(val) list1 =[1,2,3,5,6,7,4,54,6,3,66,0] def greater(num): return num>5 gr = list(filter(greater,list1)) print(gr) from functools import reduce list2 =[1,2,3,4] num = reduce(lambda x,y:x+y,list2) print(num)
a935561050f1775260a7f7fa3da95d9ab53c718f
mitalshivam1789/python
/updating a spread sheet.py
511
3.578125
4
import openpyxl wb=openpyxl.load_workbook('produceSales.xlsx') sheet = wb.get_sheet_by_name('Sheet') PU = {'Garlic':3.07, 'Celery': 1.19, 'Lemon':1.27} condition = "y" while condition == "y": produce = input("item whose price is increased") for keys,values in PU.items(): if keys == produce: changed_value = input("what is the changed value") PU[keys]= changed_value condition = input("did you what to change something else") print(PU)
e579fadc31160475af8f2a8d42a20844575c95fa
mitalshivam1789/python
/oopfile4.py
940
4.21875
4
class A: classvar1= "I am a class variable in class A." def __init__(self): self.var1 = "I am in class A's constructor." self.classvar1 = "Instance variable of class A" self.special = "Special" class B(A): classvar1="I am in class B" classvar2 = "I am variable of class B" def __init__(self): #super().__init__()# as we call this then the values of var1 and classvar1 will change as per class A instance self.var1 = "I am in class B's constructor." self.classvar1 = "Instance variable of class B" # values of var1 and classvar1 will change again super().__init__() #as we call this then the values of var1 and classvar1 will change as per class A instance # if we comment 1st one then from here the values of var1 and classvar1 will not change a = A() b= B() print(b.classvar1) print(b.classvar2) print(b.special,b.var1)
5a4875dbdec041460161d45c208d4313b797fd16
yangyang6/daily-python
/chapter8/python8.4.py
859
3.71875
4
def greet_users(names): for name in names: print ("hello : " + name) #python中不用main方法也可以运行方法也,这样不同于java usernames = ["yang","li","he"] greet_users(usernames) unprinted_designs = ["iphone_case","robot_pendant","yyy"] completed_models = [] def print_mode(unprinted_designs): while unprinted_designs: current_design = unprinted_designs.pop() print("current_design:" + current_design) completed_models.append(current_design) #参数的传递,由于方法里对参数变量做了操作导致列表数据为空 print_mode(unprinted_designs) print(unprinted_designs) unprinted_designs2 = ["zzz","xxx","ccc"] completed_models2 = [] #传递的是列表的副本,不改变列表本身的值,是改变的副本的值 print_mode(unprinted_designs2[:]) print(unprinted_designs2)
267083e774a5a5d9f79b25de916509f214d938cc
yangyang6/daily-python
/chapter5/note5-9.py
486
3.796875
4
#完整删除整个列表元素 实现 foods = ["egg","beaf","dock"] # 第一种方式 # print(foods) # del foods[len(foods):] # print(foods) # 第二种方式(最简单的方式) # foods = [] # print(foods) #第三种方式 #创建两个列表解决循环删除列表中多个元素的问题 # del_foods = ["egg","beaf","dock"] # for i in del_foods: # foods.remove(i) # print(foods) #第四种方式 for i in foods: print(foods[:]) del foods[:] print(foods)
f5acf4093e6c85483e029ecee6a146d2e9ddef6f
yangyang6/daily-python
/design-pattern/decorator-pattren.py
1,493
3.9375
4
#装饰器模式 import time # def display_time(func): # def wrapper(): # t1 = time.time() # func() # t2 = time.time() # print((t2-t1)) # return wrapper # def display_time(func): # def wrapper(): # t1 = time.time() # result = func() # t2 = time.time() # print("Total time: {:4}s".format(t2-t1)) # return result # return wrapper #带参数的装饰器模式 def display_time(func): def wrapper(*args): t1 = time.time() result = func(*args) t2 = time.time() print("Total time: {:4}s".format(t2-t1)) return result return wrapper #判断是否是素数 def is_prime(num): if(num <2): return False elif num == 2: return True else: for i in range(2,num): if num % i == 0: return False return True # 最原始的 # @display_time # def print_prime(): # for i in range(2,10000): # if is_prime(i): # print(i) # 中间 # @display_time # def print_prime(): # count = 0 # for i in range(2,10000): # if is_prime(i): # count = count + 1 # return count @display_time def print_prime(maxNum): count = 0 for i in range(2,maxNum): if is_prime(i): count = count + 1 return count # print_prime(); #不带参数调用方法 # count = print_prime() #带参数调用方法 count = print_prime(5000) print(count)
d07692da0f2fe51c22231e55d589a0fd1ea91f4c
vjek/procedural_generation
/otp-enc.py
2,499
3.828125
4
#!/usr/bin/env python3 # script to demonstrate mod10 Message + Key = Ciphertext # by vjek, 20200426, updated 20230422 ### from getpass import getpass import random,hashlib,sys def getphrase(): #get sha512 of passphrase, use it as rand seed to generate OTP of any length #if you wanted true OTP, add ISO 8601 metric date to seed value #this permits arbitrary encryption and decryption based on date & passphrase passphrase = getpass("Passphrase:") if len(passphrase) < 16: print("Passphrase too short, enter at least 16 characters.") exit() hashphrase = hashlib.sha512(passphrase.encode('utf-8')).hexdigest() return hashphrase def make_custom_dict(rand1): #use 00-99 values to map a-zA-Z0-9.. and create custom dictionary for mod10 # instead of 01 = a and 26=z, the assignment will vary procedurally x=0 my_dict={} dictionary = list(range(0,99)) letters = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]\{}|;':",./<>? \n''' rand1.shuffle(dictionary) #this shuffle will be procedural based on rand1 seed for letter in letters: my_dict[letter]="%02d" % dictionary[x] x=x+1 return my_dict def mod10(num): #this function will discard the tens place of a given two digit number num %= 10 return num #first, get the hash of a passphrase, as a random seed hashphrase = getphrase() rand1=random.Random() rand1.seed(hashphrase) #use the hashed passphrase as seed cust_dict=make_custom_dict(rand1) #take input print("Enter the message to encrypt. You may use any printable key on the us-english keyboard, plus space and newline. End with newline + ctrl-d: ") cleartext1=sys.stdin.read().rstrip() if len(cleartext1) < 1: print("Your message is too short.") exit() hashclear = hashlib.sha512(cleartext1.encode('utf-8')).hexdigest() #get hash of message cleartext1=hashclear+cleartext1 #prepend message hash to message #this produces the message line, using the custom dictionary entries try: cleartext1=''.join(str(cust_dict[c]) for c in cleartext1) except: print("ERROR:Some part of your message exceeded the bounds of the dictionary.") exit() s_len=len(cleartext1) key1='' for a in range(0,s_len): key1 += str(rand1.randint(0,9)) #create OTP key of message length ciph1='' for a in range(0,s_len): m1=int(cleartext1[a]) k1=int(key1[a]) ciph1 += str(mod10(m1+k1)) #mod10 message + key print("Your cipher text is:\n"+ciph1)
35776a487367e9338bb0701f87b9f5bea1425ed6
Gavin4th/Meituan-Crawl
/test.py
716
3.546875
4
#导入必要的包 import requests from bs4 import BeautifulSoup # 武汉理工大学科url url = 'https://www.whut.edu.cn/' # 发起访问请求 page = requests.get(url = url) # 输出返回信息 print(page.url) print(page.status_code) for k,v in page.headers.items(): print(k,":\t",v) # 初始化soup对象 soup = BeautifulSoup(page.text,"html.parser") # 找到class属性为art_list的标签,实质是获取所有的学校动态 soup = soup.find("ul",{"class":"art_list"}) # 找到上面一层标签下的所有li标签,并输出其中的title内容 soup = soup.find_all("li") for item in soup: result = item.find('a') print(result.get('href')+"\t"+result.get('title'))
311d777bd37de1334727b61fb383a67f3a80f117
zhangxiutao/AIScripts
/yield.py
111
3.59375
4
def func1(x): while True: print(x) x=x-1 if x == 0: break func(5)
18f3122df32eab19f3346206fedc3bec28cab042
Nerubes/review1
/ceasar.py
956
3.921875
4
import alphabet def encrypt(string, seed, n): """ Шифрует или дешифрует строку используя шифр Цезаря :param string: текст для шифровки или дешифровки :param seed: ключ :param n: указывает на то, будет ли функция шифровать или дешифровать строку :return: зашифрованый или расшифрованный текст """ res = "" if string[0] in alphabet.eng: using_alphabet = alphabet.eng elif string[0] in alphabet.rus: using_alphabet = alphabet.rus else: return "Incorrect Input. Try again." for letter in string: index = using_alphabet.find(letter) if index >= 0: res += using_alphabet[(index + n * seed) % len(using_alphabet)] else: res += letter return res
ce8e51cd0072f1c34eb34655d5c753e5267e383d
harfeyar/python-noobie
/index.py
165
4
4
# x = 10 # y = 20 # print (x) # x += y # print (x) # x -= y # print (x) # x *= y # print (x) # x /= y # print (x) x = 10 y = 20 resulte = x < y print (resulte)
4ecd4d3a20e875b9c0b5019531e8858f4722b632
victorbianchi/Toolbox-WordFrequency
/frequency.py
1,789
4.5
4
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string def get_word_list(file_name): """ Reads the specified project Gutenberg book. Header comments, punctuation, and whitespace are stripped away. The function returns a list of the words used in the book as a list. All words are converted to lower case. """ #loading file and stripping away header comment f = open(file_name,'r') lines = f.readlines() curr_line = 0 while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1: curr_line += 1 lines = lines[curr_line+1:] #remove excess for i in range(len(lines)): lines[i] = lines[i].strip().translate(string.punctuation).lower() while '' in lines: lines.remove('') words = [] for line in lines: line_words = line.split(' ') words = words + line_words return words def get_top_n_words(word_list, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequentlyoccurring """ word_counts = {} for word in word_list: if word not in word_counts: word_counts[word] = 1 else: word_counts[word] += 1 ordered_by_frequency = sorted(word_counts, key=word_counts.get, reverse=True) return ordered_by_frequency[:n+1] if __name__ == "__main__": result = get_word_list('pg32325.txt') list = get_top_n_words(result, 100) print(list)
8851fb83fd60acb70bd883e09f89a51673195729
dev-vishalgaurav/algo
/codechef/TSORT/python/TSORT_ARRAY.py
397
3.5
4
maxValue = 1000001 inputValue = int(raw_input()) sortedList = [0] * maxValue for each in range(inputValue): number = int(raw_input()) sortedList[number] = sortedList[number] + 1 printList = "" for number in range(maxValue): while(sortedList[number] > 0): printList = printList + str(number) + "\n" sortedList[number] = sortedList[number] - 1 print printList
2ac130b6bad97756b27258e8148c9c15a59be86d
vanechipi/Python-BeautifulSoup-Sqlite-Tkinter
/Practice-with-Python/p3_tuplas.py
1,174
3.828125
4
#encoding: utf-8 t = ("Vanessa", "Alvaro", "Juana", "Rocio") def campanaNombres(var): for l in var: print "Estimad@",l+",","vote por mi" if __name__ == "__main__": campanaNombres(t) t = ("Vanessa", "Alvaro", "Juana", "Rocio") def campanaNombresYPosicion(var, p): if p >= len(var): print "ERROR: Te has salido del tamaño" res= var[p:] for l in res: print "Estimad@",l+",","vote por mi" if __name__ == "__main__": print "--------------------" campanaNombresYPosicion(t,2) t = (("Vanessa","Mujer"), ("Alvaro","Hombre"), ("Juana","Mujer"), ("Rocio","Mujer"), ("Mario","Hombre")) def campanaNombresPosicionYGenero(var, p): if p >= len(var): print "ERROR: Te has salido del tamaño" res= var[p:] for l in res: if l[1] == "Mujer": print "Estimada",l[0]+",","vote por mi" elif l[1] == "Hombre": print "Estimado",l[0]+",","vote por mi" if __name__ == "__main__": print "--------------------" campanaNombresPosicionYGenero(t,2)
3419d96ab611b0fb171ed8b27b23d996cb63820c
Pradoshks/CS513-Data-Cleaning-Project
/CS513 - Data Cleaning Final Project - Submission/Python Code & python YW diagrams/ywparse.py
3,494
3.78125
4
import pandas as pd import re # @BEGIN main def main(): # @Param data @URI file: data/NYPL-menus.csv # @Param subset data = pd.read_csv("../data/NYPL-menus.csv") # print(data.head()) '''Select a subset of the data for cleaning with Python''' subset = data[['event', 'venue', 'place', 'date']] # print(subset.head()) '''Destructure DataFrame to return individual column Series to pass to functions''' (event, venue, place, date) = subset['event'], subset['venue'], subset['place'], subset['date'] '''Functions to operate on each column and return cleaned data''' # @BEGIN cleaned_event # @IN event @as Event # Work on this to remove all quotes event = event.str.replace('"', '', regex=True) event = event.str.replace('""', '', regex=True) event = event.str.lstrip('"') event = event.str.rstrip('"') event = event.str.replace('[', '', regex=True) event = event.str.replace(']', '', regex=True) # Match this: (?) pattern1 = '\(\?\)' event = event.str.replace(pattern1, '', regex=True) # Match semicolons at the end of the string pattern2 = '\;$' event = event.str.replace(pattern2, '', regex=True) # Match semicolons in the middle of a string and replace with : pattern3 = '\\b;' cleaned_event = event.str.replace(pattern3, ':', regex=True) cleaned_event.to_csv("../data/test_event.csv") # @OUT cleaned_event @as Cleaned_event # @END clean_event # @BEGIN clean_venue # @IN venue @as Venue venue = venue.str.replace(';', '') venue = venue.str.replace('?', '') venue = venue.str.replace('[', '', regex=True) venue = venue.str.replace(']', '', regex=True) cleaned_venue = venue.str.replace('\(\)', '', regex=True) cleaned_venue.to_csv("../data/test_venue.csv") # @OUT cleaned_venue @as Cleaned_venue # @END clean_venue # @BEGIN clean_place # @IN place @as Place place = place.str.replace('"', '', regex=True) place = place.str.replace('""', '', regex=True) place = place.str.lstrip('"') place = place.str.rstrip('"') place = place.str.replace(';', '') place = place.str.replace('?', '') place = place.str.replace('[', '', regex=True) place = place.str.replace(']', '', regex=True) place = place.str.replace('\(', '', regex=True) cleaned_place = place.str.replace('\)', '', regex=True) cleaned_place.to_csv("../data/test_place.csv") # @OUT cleaned_place @as Cleaned_place # @END clean_place # @BEGIN clean_date # @IN date @as Date # Use a list comprehension to filter bad values and create a new Pandas Series cleaned_date = pd.Series([d for d in date if d != '0190-03-06' and d != '1091-01-27' and d != '2928-03-26']) cleaned_date.to_csv("../data/test_date.csv") # @OUT cleaned_date @As Cleaned_date # @END clean_date '''Merge Pandas Series to DataFrame and output as CSV''' # @BEGIN merge_series_to_df # @IN cleaned_event @As Cleaned_event # @In cleaned_venue @As Cleaned_venue # @In cleaned_place @As Cleaned_Place # @In cleaned_date @As Cleaned_date all_series = {"cleaned_event": cleaned_event, "cleaned_venue": cleaned_venue, "cleaned_place": cleaned_place, "cleaned_date": cleaned_date} df = pd.concat(all_series, axis=1) df.to_csv("../data/cleaned-NYPL-menus.csv") # @OUT df @As Cleaned_DataFrame # @END merge_series_to_df # @END main main()
f0010c9aa51410c1ab24f6a75467c630d6d42e2e
Gecazo/RockPaperScissors
/rockpaperscissors.py
1,226
3.890625
4
import random count_draws = 0 # Counter - Draw, Loose, Win count_loses = 0 count_wins = 0 TYPE_LIST = ('rock', 'scissors', 'paper') # Items - rock, scissors, paper def inp(): # Number of turns global n while True: try: n = int(input('Enter an amount of games n ')) return n except ValueError: print("It's not a number!") def logic(x, y): # Game logic global count_draws, count_wins, count_loses if x == y: print('Draw') count_draws += 1 elif (x == 'rock' and y == 'scissors') or (x == 'scissors' and y == 'paper') or (x == 'paper' and y == 'rock'): print('Win') count_wins += 1 else: print('Lose') count_loses += 1 return count_draws, count_loses, count_wins # Start inp() while n != 0: while True: x = input('Choose your item: rock , scissors , paper ') if x not in TYPE_LIST: print('Enter rock, scissors, paper') else: break y = random.choice(TYPE_LIST) logic(x, y) n -= 1 else: print('Wins - {0}\nLoses - {1}\nDraws- {2}'.format(count_wins, count_loses, count_draws))
d2de097ee33f0060830681df81f87f600f5da69c
Scott-Dixon-Dev-Team-Organization/cs-guided-project-linked-lists
/src/demonstration_3.py
804
4.1875
4
""" Given a non-empty, singly linked list with a reference to the head node, return a middle node of linked list. If there are two middle nodes, return the second middle node. Example 1: Input: [1,2,3,4,5] Output: Node 3 from this list The returned node has value 3. Note that we returned a `ListNode` object `ans`, such that: `ans.val` = 3, `ans.next.val` = 4, `ans.next.next.val` = 5, and `ans.next.next.next` = NULL. Example 2: Input: [1,2,3,4,5,6] Output: Node 4 from this list Since the list has two middle nodes with values 3 and 4, we return the second one. *Note: The number of nodes in the given list will be between 1 and 100.* """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def middleNode(self, head): # Your code here
5cfd2d5724a2113b3cfa67233d6532400cb32c7f
QixiangLiu/personalWeb
/webPage/EECS/2019/EECS660/Project/HW2/bfs_dfs_input-output/dfs_liu.py
1,529
3.890625
4
# use python 3.7.2 # -*- coding: UTF-8 -*- """ Author: Qixiang Liu Description: depth-first search Date: 03/14/2019 Log: depth-first search is recursion; """ import os import sys if len(sys.argv) != 2: print ("python3 <EXE><Input.txt>") exit(1) # open a file: default access: ready only # Enter a input file filename = sys.argv[1] inFile = open(filename) # read the first head head = inFile.readline(); head = int(head.strip()); set = []; def findAdjacent(file,current): "return a list to store adjacent nodes with the current node" storeNode = []; inFile.seek(0); dismissTheHead = inFile.readline(); for line in inFile: line = line.strip(); line = line.split(","); s = int(line[0]); v = int(line[1]); if current == s: storeNode.append(v); return storeNode; def initMap(): "Set false for all nodes" map = {}; inFile.seek(0); dismissTheHead = inFile.readline(); for line in inFile: line = line.strip(); line = line.split(","); s = int(line[0]); v = int(line[1]); map[s] = False; map[v] = False; return map; # two empty integer list; set for storing output; queue for traversal checkMap = initMap(); def dfsRec(u): checkMap[u] = True; set.append(u); nodeAdj = findAdjacent(inFile,u); for x in nodeAdj: if checkMap[x] == False: dfsRec(x); dfsRec(head); #print(printAllNodes); inFile.close() for x in set: print(x,end=" ");#int
3294384c70f73640b4eb72b0b24888738293c161
QixiangLiu/personalWeb
/webPage/EECS/2019/EECS660/Project/HW4/minimum_spanning_tree/msp_2856114.py
4,279
4.0625
4
# use python 3.7.2 # -*- coding: UTF-8 -*- """ Author: Qixiang Liu Description: Minimum spanning tree in Kruskal's Algorithm Date: 04/05/2019 Log: Always choose the minimum edges, if edges have been connected, just give up; Sort by edges 1) learn class in python 2) how to create 2D array in python 3) Use Union-Find Set Data structure 4) how to optimize union-find set .. 5) worst case O(n) Find1-Union2 Set worst case O(lgn) Find2-Union3 Set; important to optimize union part """ import os import sys from collections import defaultdict if len(sys.argv) != 2: print ("<./EXE><Input.txt>") exit(1) filename = sys.argv[1] #string class Graph: def __init__(self,file): self.graph =[] #read a file graph self.numberOfNode = 0 self.result = [] self.map = {} # map(u,v) = w ==>nodes (u,v) = weight self.vertices = set() # all nodes self.edges = 0 # the minimum edges self.filename = file self.parent = [] self.height = [] self.readFile(self.filename) self.makeMap() def readFile(self,filename): # open a file: default access: ready only # Enter a input file inFile = open(filename) # read the input file inFile.seek(0) # read from begin for line in inFile: line = line.strip() #read the whole line line = line.split(" ") # spilt data into the list by whitespace but it is string type line = list(map(int,line)) # string type to int type in list self.graph.append(line) inFile.close() self.numberOfNode = len(self.graph) # find-union set def find(self,index): "Find part" if(self.parent[index]==index): return index return self.find(self.parent[index]) def find2(self,index): "# OPTIMIZE: find part; compress route" if self.parent[index] ==index: return index else: temp = self.find2(self.parent[index]) self.parent[index] = temp return temp def union(self,u,v): "maybe wrong" self.parent[v] = self.parent[u] def union2(self,u,v): self.parent[v] = u def union3(self,u,v): "Optimize union part; smaller height is parent" if self.height[u]>self.height[v]: self.parent[v] = u elif self.height[u]<self.height[v]: self.parent[u] = v else: self.parent[v] = u self.height[u] = self.height[u] + 1 def makeMap(self): "Algorithm for map" for i in range(len(self.graph)): for j in range(len(self.graph[i])): if j>i: if self.graph[i][j]!= 0: self.map[(i,j)] = self.graph[i][j] self.vertices.add(i) self.vertices.add(j) #sort map increasing order by weight tempList = sorted(self.map.items(),key=lambda item:item[1]) #print(tempList); self.map.clear() for eachData in tempList: self.map[eachData[0]] = eachData[1] #minimum edges self.edges = len(self.vertices)-1 #init self.parent; set each node is itself in set for i in range(len(self.vertices)): self.parent.append(i) self.height.append(0)#height means rank of each child def kruskal(self): "Algorithm for MSP" count = 0 for x in self.map.keys(): if(count==self.edges): break rootU = self.find2(x[0]) rootV = self.find2(x[1]) #print (rootU,rootV) if(rootU!=rootV): self.result.append(x) self.union3(rootU,rootV) count+=1 minimumSpanningTree = Graph(filename) #[graph init] alloc #minimumSpanningTree.makeMSP() # print(minimumSpanningTree.vertices) # print(minimumSpanningTree.edges) # print(minimumSpanningTree.map) #print(minimumSpanningTree.parent) minimumSpanningTree.kruskal() for x in minimumSpanningTree.result: print(x[0],x[1],end="\r\n") #print(minimumSpanningTree.map) # print(minimumSpanningTree.graph) # print(minimumSpanningTree.numberOfNode)
54488222c54e9107dbd48dd5e29fe68ccd4bbe23
AryanshuArindam08/Simple-Quiz-Game-In-Python
/Quiz_game.py
899
3.953125
4
# Simple-Quiz-Game-In-Python print('Welcome to Aryanshu Quiz') answer=input('Are you ready to play the Quiz ? (yes/no) :') score=0 total_questions=3 if answer.lower()=='yes': answer=input('Question 1: what is the easiest programming language?') if answer.lower()=='python': score += 1 print('correct') else: print('Wrong Answer :(') answer=input('Question 2: who is the world richest person ? ') if answer.lower()=='Elon Musk': score += 1 print('correct') else: print('Wrong Answer :(') answer=input('Question 3: Birthday of Elon Musk?') if answer.lower()=='28 June': score += 1 print('correct') else: print('Wrong Answer :(') print('Than kyou for Playing',score,"questions correctly!") mark=(score/total_questions)*100 print('Marks obtained:',mark) print('BYE!') print('Made by ARYANSHU')
961f89e5aa40a3377dc4e513b67afb232e4e525f
KayWinkler/nirs
/curve.py
6,506
4.03125
4
""" curve fitting - approximate the given values of a data frame with a polynomial curve x^8 used to identify the curve minima and maxima to identify the direction and calculate the tendencies """ from scipy import optimize class Curve(): """ low level mathematical helper to fit a data set """ def __init__(self, params=None): self.curve_params = params def curve_fitting(self, x, a, b, c, d, e, f, g, h): """ calculate the polynomial curve values """ sumup = 0.0 count = 0 for var in [a, b, c, d, e, f, g, h]: sumup += var * x**count count += 1 return sumup def get_curve_data(self, row_num, data): """ get the y values for the given index """ params, _covariance = optimize.curve_fit( self.curve_fitting, row_num, data) self.curve_params = params values = [] for x in row_num: y = self.curve_fitting(x, *self.curve_params) values.append(y) return values class CurveDataFrame(): """ data frame with data of the interpolated function """ def __init__(self, df): self.curve_df = self.get_curve_df(df) @staticmethod def get_curve_df(df): """ create a copy of a given data frame and for each column interpolate the data at each values """ ts_curve_df = df.copy() ts_index = ts_curve_df.index.tolist() for column_name in ts_curve_df.columns.tolist(): try: curve = Curve() values = curve.get_curve_data( ts_index, ts_curve_df[column_name]) ts_curve_df[column_name] = values except Exception as _exx: ts_curve_df[column_name] = '' return ts_curve_df def get_df(self): """ provide the interpolated data frame for other pandas operations :return: the pandas data frame """ return self.curve_df @staticmethod def _slices(curve_df, slices=3): """ helper - to slide with overlap over a data frame [--------][-------][--------] [--------][--------] [-------][--------] [--------] [--------] :yield: a sub data frame """ first = curve_df.index.tolist()[0] last = curve_df.index.tolist()[-1] len_df = last - first slice_size = ((last - len_df) // slices) slice_shift = (slice_size // 2) for range_start in range(first, last, slice_shift): range_end = range_start + slice_size if range_end > last: range_end = last # slices of data frames are not index based! they are arrays! slice_df = curve_df[range_start - first:range_end - first] yield slice_df @staticmethod def _get_min_max(curve_df, maxima=True): """ internal helper: iterate through the slices of a data frame and get the min or max of the local slice. If the min or max is direct on the border of the slice, we skip this entry as it might be no local max or min. In case it is a min or max, the next slice will identify this. :param curve_df: the interpolated data frame :param maxima: switch if minima or maxima are searched :return: dict for each column with a sorted list of x,y tuples """ column_names = curve_df.columns.tolist() extrema_dict = {} for slice_df in CurveDataFrame._slices(curve_df): _idx = slice_df.index start = slice_df.index.tolist()[0] end = slice_df.index.tolist()[-1] for column_name in column_names: try: if maxima: row_num = slice_df[column_name].idxmax() else: row_num = slice_df[column_name].idxmin() row = slice_df.iloc[slice_df.index == row_num] row_data = row[column_name].tolist()[0] # preserve the data in a dictionary val = extrema_dict.get(column_name, {}) if row_num > start + 2 and row_num < end - 2: val[row_num] = row_data extrema_dict[column_name] = val except TypeError as _exx: extrema_dict[column_name] = extrema_dict.get( column_name, {}) except Exception as exx: print('unknown exception occured: %r' % exx) # finally convert the dict of values into a sorted list of tuples for column_name in column_names: value_dict = extrema_dict[column_name] values = [] for entry in sorted(value_dict.keys()): values.append((entry, value_dict[entry])) extrema_dict[column_name] = values return extrema_dict def get_maxima(self): """ get the maxima of the CurveDataFrame :return: dict for each column with a dict of x,y values """ return self._get_min_max(self.curve_df, maxima=True) def get_minima(self): """ get the minima of the CurveDataFrame :return: dict for each column with a dict of x,y values """ return self._get_min_max(self.curve_df, maxima=False) def usage(): """ interface usage verification """ from nirs import Nirs from testing import Testing from matplotlib import pyplot as plt # load the nirs data df, _events, _baseline = Nirs().load_nirs_data('NIRS_daten/311_d.xlsx') ts_df = Testing.get_df(df, 'T1 ', 'E1 ') ts_df['HHb'] = 100 - ts_df['HHb'] # create the interpolated data frame curve_dataframe = CurveDataFrame(ts_df) # and get the minima and maxima minima_dict = curve_dataframe.get_minima() print('## local minima at %r' % minima_dict) maxima_dict = curve_dataframe.get_maxima() print('## local maxima at %r' % maxima_dict) curve_df = curve_dataframe.get_df() column_names = curve_df.columns.tolist() for column_name in column_names: plt.plot(curve_df[column_name], label=column_name) plt.legend() plt.show() print('done!')
0f4ad94ce5b6d5619ce4cfdf106e0778cf21994b
MaxchilKH/pySimulation
/Organisms/Organism.py
1,405
3.75
4
from abc import abstractmethod, ABCMeta class Organism(metaclass=ABCMeta): def __init__(self, tile, world): self.tile = tile self.world = world self.isDead = False def kill(self): self.isDead = True @property def strength(self): return self.__strength @strength.setter def strength(self, strength): self.__strength = strength @property def initiative(self): return self.__initiative @initiative.setter def initiative(self, initiative): self.__initiative = initiative @property def world(self): return self.__world @world.setter def world(self, world): self.__world = world @property def tile(self): return self.__tile @tile.setter def tile(self, tile): self.__tile = tile @abstractmethod def action(self): pass @abstractmethod def draw(self): pass def collision(self, attacker): if attacker.strength >= self.strength: self.world.kill_organism(self) self.kill() self.world.comment("{} killed {}\n".format(type(attacker).__name__, type(self).__name__)) else: self.world.kill_organism(attacker) attacker.kill() self.world.comment("{} killed {}\n".format(type(self).__name__, type(attacker).__name__))
9474a0ab7d388a230ef9abdef461b871abe0ef66
MaxchilKH/pySimulation
/Organisms/Animals/Antilope.py
1,017
3.515625
4
from Organisms.Animals.Animal import Animal import random class Antilope(Animal): def __init__(self, tile, world): super().__init__(tile, world) self.strength = 4 self.initiative = 4 def draw(self): return "#875409" def action(self): moves = set() moves.update(self.world.get_neighbours(self.tile)) moves.update([tile for a in moves for tile in self.world.get_neighbours(a)]) moves.remove(self.tile) if not moves: return moves = [tile for tile in moves] self.move(random.choice(moves)) def collision(self, attacker): if random.randint(0, 100) >= 50 or isinstance(attacker, Antilope): super().collision(attacker) else: moves = self.world.get_free_neighbours(self.tile) if not moves: return self.world.comment("Antylopa ran from {}\n".format(type(attacker).__name__)) self.move(random.choice(moves))
27a41a40a8009d7287434b3f4e2653c9b9a965d2
menezesluiz/MITx_-_edX
/week1/exercise/exercise_happy.py
574
4.09375
4
""" Exercise: happy Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise: happy 5.0/5.0 points (graded) ESTIMATED TIME TO COMPLETE: 3 minutes Write a piece of Python code that prints out the string 'hello world' if the value of an integer variable, happy, is strictly greater than 2. Do not ask for user input Assume that variables are defined for you by our grader code. Simply write code assuming you know the values of the variables. """ happy = 5 # variável inexistente no exercício (desconsiderar) if happy > 2: print('hello world')
045ec74a9cc39d32ff4541f9c69f7bdac54ef31d
menezesluiz/MITx_-_edX
/week1/codes/V01_bindings.py
316
3.71875
4
""" Vídeo sobre variáveis e as melhores práticas para se trabalhar com elas. """ # Vídeo: Bindings x = 2 x = x * x y = x + 1 print(y) # Dessa forma, é mais fácil de se perder x = 1 y = 2 y = x x = y print(x) # A solução seria criar uma variável temporária x = 1 y = 2 temp = y y = x x = temp print(x)
00ead084fe729599aeedba61cc88fc277e7726ad
menezesluiz/MITx_-_edX
/week1/exercise/exercise-for.py
442
4.34375
4
""" Exercise: for Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise: for exercise 1 5.0/5.0 points (graded) ESTIMATED TIME TO COMPLETE: 5 minutes In this problem you'll be given a chance to practice writing some for loops. 1. Convert the following code into code that uses a for loop. prints 2 prints 4 prints 6 prints 8 prints 10 prints Goodbye! """ for i in range(2, 12, 2): print(i) print("Goodbye!")
36e8464800601f9fc4553aacc2f48369940393df
menezesluiz/MITx_-_edX
/week1/exercise/exercise04.py
2,056
4.40625
4
""" Exercise 4 Finger Exercises due Aug 5, 2020 20:30 -03 Completed Bookmark this page Exercise 4 5/5 points (graded) ESTIMATED TIME TO COMPLETE: 8 minutes Below are some short Python programs. For each program, answer the associated question. Try to answer the questions without running the code. Check your answers, then run the code for the ones you get wrong. This question is going to ask you what some simple loops print out. If you're asked what code like this prints: """ # Exemplo num = 5 if num > 2: print(num) num -= 1 print(num) # write what it prints out, separating what appears on a new line by a comma # and a space. So the answer for the above code would be: # Resposta: 5, 4 """ If a given loop will not terminate, write the phrase 'infinite loop' (no quotes) in the box. Recall that you can stop an infinite loop in your program by typing CTRL+c in the console. Note: What does +=, -=, *=, /= stand for? a += b is equivalent to a = a + b a -= b is equivalent to a = a - b a *= b is equivalent to a = a * b a /= b is equivalent to a = a / b """ # 1 num = 0 while num <= 5: print(num) num += 1 print("Outside of loop") print(num) # Minha resposta: # 0, 1, 2, 3, 4, 5, Outside of loop, 5 ou 6 # 2 numberOfLoops = 0 numberOfApples = 2 while numberOfLoops < 10: numberOfApples *= 2 numberOfApples += numberOfLoops numberOfLoops -= 1 print("Number of apples: " + str(numberOfApples)) # Minha resposta: # Infinite Loop # 3 num = 10 while True: if num < 7: print("Breaking out of loop") break print(num) num -= 1 print("Outside of loop") """ Note: If the command break is executed within a loop, it halts evaluation of the loop at that point and passes control to the next expression. Test some break statements inside different loops if you don't understand this concept! """ # Minha resposta: # Breaking out of loop, 10, 9, Outside Of loop # 5 num = 100 while not False: if num < 0: break print('num is: ' + str(num)) # Minha resposta: # Infinit loop
1156cca475eab407f874b887f625dffd6592e4be
kapilbisht/Python_Tutorial
/Hello.py
14,347
4.34375
4
print("Code with me!!!") print("*" * 10) xyz = 100 # variable store the value temporary in memory so that we can use it in our program price = 123 # integer value ratings: float = 4.5 # floating value name: str = "Kapil" # String value is_published = True # boolean value (python is case sensitive language thus True and true aren't same print(price) print(ratings) print(name) print(is_published) # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ patient_name: str = "John Smith" age: int = 20 is_newPatient: bool = True # you can set a data type help using followed by : (ex- : bool, : float etc.. print(patient_name) print(age) print(is_newPatient) # What is PEP? # PEP stands for Python Enhancement Proposal. # A PEP is a design document providing information to the Python community, # or describing a new feature for Python or its processes or environment. # The PEP should provide a concise technical specification of the feature and # a rationale for the feature. # We intend PEPs to be the primary mechanisms for proposing major new features, # for collecting community input on an issue, # and for documenting the design decisions that have gone into Python. # The PEP author is responsible for building consensus within the community and # documenting dissenting opinions. # Expression : a piece of code that produces value name: str = input("What is your name? ") # input() is used to get value from user color: str = input("What is your favorite color? ") print("{0} likes {1}".format(name, color)) # print(name + " likes " + color is # equivalent to print("{0} likes {1}".format(name, color)) # and print(f"{name} likes {color}") --> f-string literal birth_year = input("Birth year : ") print(type(birth_year)) # type() tells the type of the supplied variable. # age = 2020 - birth_year # gives you error beacause here we are subtracting string value by integer value age = 2020 - int(birth_year) # converting birth year as integer # like int() we have float() and bool() print(age) print(type(age)) print("Beginner's course") # quotes example print('Course for "beginners"') # quotes example print(''' Hi John!!! this course is for beginners. Thanks Support Team. ''') # print multi-line string ############# Strings ################################### course = 'Python for beginners' print(course[0]) # Output will be P print(course[-1]) # Output will be s. We can use -ve indexing in python print(course[-2]) # Output will be r. print(course[0:3]) # Output will be Pyt print(course[0:]) # print complete string print(course[1:]) # print string starting from index 1 print(course[:5]) # output will be Pytho print(course[:]) # print complete string name = 'jeniffer' print(name[1:-1]) # output eniffe print(name[-3:-1]) # output fe first = 'John' last = 'Smith' message = first + ' [' + last + '] is a coder' msg = f'{first} [{last}] is a coder' # formatted string print(message) print(msg) course = 'Python For Beginners' print(len(course)) print(course) print(course.capitalize()) print(course.upper()) print(course.lower()) print(course.find('P')) # output index 0 # find() method is case sensitive print(course.find('Pyt')) # output index 0 print(course.find('yth')) # output index 1 print(course.find('For')) # output index 7 print(course.find('s')) # output index 19 print(course.find('not')) # output -1 if not present in string print(course.replace('Beginners', 'absolute beginners')) print('Python' in course) # Output is True - if supplied sequence is present// search for exact match # Lists are very similar to arrays. # They can contain any types of variables, and they can contain as many variables as you wish. numbers = [1,2,3] strings = ["hello","world"] names = ["John", "Eric", "Jessica"] second_name = names[1] print(numbers) print(strings) print("The second name on the names list is %s" % second_name) # Basic Operators number = 1 + 2 * 3 / 4.0 print(number) # output 2.5 remainder = 11 % 3 print(remainder) # output 2 # Using two multiplication symbols makes a power relationship squared = 7 ** 2 cubed = 2 ** 3 print(squared) # output 49 print(cubed) # output 8 # Using operators with Strings helloworld = "hello" + " " + "world" print(helloworld) # output - hello world # Python also supports multiplying strings to form a string with a repeating sequence: lotsofhellos = "hello" * 10 print(lotsofhellos) # Using operators with lists even_numbers = [2,4,6,8] odd_numbers = [1,3,5,7] all_numbers = odd_numbers + even_numbers # Lists can be joined with addition operator print(all_numbers) # output [1, 3, 5, 7, 2, 4, 6, 8] print([1,2,3] * 3) # Output [1, 2, 3, 1, 2, 3, 1, 2, 3] # Just as in strings, # Python supports forming new lists with a repeating sequence using the multiplication operator: x = object() y = object() x_list = [x] * 10 y_list = [y] * 10 big_list = x_list + y_list print("x_list contains %d objects" % len(x_list)) print("y_list contains %d objects" % len(y_list)) print("big_list contains %d objects" % len(big_list)) # testing code if x_list.count(x) == 10 and y_list.count(y) == 10: print("Almost there...") if big_list.count(x) == 10 and big_list.count(y) == 10: print("Great!") # String Formatting # Python uses C-style string formatting to create new, formatted strings. # The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), # together with a format string, which contains normal text together with # "argument specifiers", special symbols like "%s" and "%d". name = "John" print("Hello, %s!" % name) # This prints out "Hello, John!" name = "John" age = 23 print("%s is %d years old." % (name, age)) # This prints out "John is 23 years old." # Any object which is not a string can be formatted using the %s operator as well. mylist = [1,2,3] print("A list: %s" % mylist) # This prints out: A list: [1, 2, 3] # Here are some basic argument specifiers: # # %s - String (or any object with a string representation, like numbers) # %d - Integers # %f - Floating point numbers # %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot. # %x/%X - Integers in hex representation (lowercase/uppercase) data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s." print(format_string % data) # Hello John Doe. Your current balance is $53.44. # Basic String Operation astring = "Hello World!" print(len(astring)) # output 12 print(astring.index("o")) # output 4 print(astring.count("l")) # output 3 print(astring[3:7]) # output lo w print(astring[3:7:2]) # output l print(astring[3:7:1]) # output lo w print(astring[4:8:3]) # output oo print(astring[::-1]) # output !dlroW olleH print(astring.upper()) # output HELLO WORLD! print(astring.lower()) # output hello world! print(astring.startswith("Hello")) # output True print(astring.endswith("asdfgh")) # output False s = "Strings are awesome!" # Length should be 20 print("Length of s = %d" % len(s)) # First occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a")) # Number of a's should be 2 print("a occurs %d times" % s.count("a")) # Slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" % s[1::2]) # (0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end # Convert everything to uppercase print("String in uppercase: %s" % s.upper()) # Convert everything to lowercase print("String in lowercase: %s" % s.lower()) # Check how a string starts if s.startswith("Str"): print("String starts with 'Str'. Good!") # Check how a string ends if s.endswith("ome!"): print("String ends with 'ome!'. Good!") # Split the string into three separate strings, # each containing only a word print("Split the words of the string: %s" % s.split(" ")) # Conditions # Python uses boolean variables to evaluate conditions. # The boolean values True and False are returned when an expression is compared or evaluated. x = 2 print(x == 2) # prints out True print(x == 3) # prints out False print(x < 3) # prints out True # Boolean operators # The "and" and "or" boolean operators allow building complex boolean expressions, name = "John" age = 23 if name == "John" and age == 23: print("Your name is John, and you are also 23 years old.") if name == "John" or name == "Rick": print("Your name is either John or Rick.") # The "in" operator # The "in" operator could be used to check # if a specified object exists within an iterable object container, such as a list: name = "John" if name in ["John", "Rick"]: print("Your name is either John or Rick.") # The 'is' operator # Unlike the double equals operator "==", the 'is' operator does not match the values of variables, # but the instances themselves. x = [1,2,3] y = [1,2,3] print(x == y) # Prints out True print(x is y) # Prints out False # The 'not' operator # Using 'not' before a boolean expression inverts it: print(not False) # Prints out True print((not False) == False) # Prints out False # Loops # The for loop primes = [2,4,6,8] for prime in primes: print(prime) for x in range(5): print(x) # Prints out the numbers 0,1,2,3,4 for x in range(3, 6): print(x) # Prints out 3,4,5 for x in range(3, 8, 2): print(x) # Prints out 3,5,7 # while loops count = 0 while count < 5: print(count) # Prints out 0,1,2,3,4 count += 1 # "break" and "continue" statements # break is used to exit a for loop or a while loop # continue is used to skip the current block, and return to the "for" or "while" statement. count = 0 while True: print(count) # Prints out 0,1,2,3,4 count += 1 if count >= 5: break for x in range(10): if x % 2 == 0: # Check if x is even continue print(x) # Prints out only odd numbers - 1,3,5,7,9 # "else" clause for loops # When the loop condition of "for" or "while" statement fails then code part in "else" is executed. # If break statement is executed inside for loop then the "else" part is skipped. # Note that "else" part is executed even if there is a continue statement. count = 0 while count < 5: print(count) # Prints out 0,1,2,3,4 count += 1 else: print("count value reached %d" % count) # it prints "count value reached 5" for i in range(1, 10): if i % 5 == 0: break print(i) else: print("this is not printed because for loop is terminated because of break but not due to fail in condition") # Functions def my_function(): print("Hello From My Function!") def my_function_with_args(username, greeting): print("Hello, %s , From My Function!, I wish you %s" % (username, greeting)) def sum_two_numbers(a, b): return a + b # print(a simple greeting) my_function() # prints - "Hello, John Doe, From My Function!, I wish you a great year!" my_function_with_args("John Doe", "a great year!") # after this line x will hold the value 3! x = sum_two_numbers(1, 2) print(x) # function Example def list_benefits(): return "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together" def build_sentence(benefit): return "%s is a benefit of functions!" % benefit def name_the_benefits_of_functions(): list_of_benefits = list_benefits() for benefit in list_of_benefits: print(build_sentence(benefit)) name_the_benefits_of_functions() # Classes and Objects # Classes are an encapsulation of variables and functions into a single entity. # Objects get their variables and functions from classes. # Classes are essentially a template to create your objects. # A basic example of class class MyClass: variable = "blah" def function(self): print("This is a message inside the class.") # to assign the above class(template) to an object we would do the following: myobjectx = MyClass() # Accessing Object Variables print(myobjectx.variable) # You can create multiple different objects that are of the same class(have the same variables and functions defined). # However, each object contains independent copies of the variables defined in the class. myobjecty = MyClass() myobjecty.variable = "yackity" print(myobjecty.variable) # Accessing Object Functions myobjectx.function() # Example # define the Vehicle class class Vehicle: name = "" kind = "car" color = "" value = 100.00 def description(self): desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value) return desc_str # your code goes here car1 = Vehicle() car1.name = "Fer" car1.color = "red" car1.kind = "convertible" car1.value = 60000.00 car2 = Vehicle() car2.name = "Jump" car2.color = "blue" car2.kind = "van" car2.value = 10000.00 # test code print(car1.description()) print(car2.description()) # # Dictionaries # A dictionary is a data type similar to arrays, but work with keys and values instead of indexes. # Each value stored in a dictionary can be accessed using a key, # which is any type of object(a string, a number, a list etc.) instead of using its index to address it. phonebook = {} phonebook["John"] = 12345 phonebook["Jack"] = 32165 phonebook["Jill"] = 78945 print(phonebook) # Output - {'John': 12345, 'Jack': 32165, 'Jill': 78945} # we can also initialize a dictionary in following manner phonebook = { "John" : 12345, "Jack" : 32165, "Jill" : 78945 } print(phonebook) # Output - {'John': 12345, 'Jack': 32165, 'Jill': 78945} # iterating over dictionaries # Dictionaries can be iterated over, just like list. # However, a dictionary, unlike a list, does not keep the order of the values stored in it. for name, number in phonebook.items(): print("Phone number of %s is %d" %(name, number)) # output - # Phone number of John is 12345 # Phone number of Jack is 32165 # Phone number of Jill is 78945 # Removing a value # you can one of the following notations to remove a specified index del phonebook["John"] print(phonebook) # Output - {'Jack': 32165, 'Jill': 78945} # or phonebook.pop("Jill") print (phonebook) # Output - {'Jack': 32165}
622351f3e7a0a0b374e648d439ebe4b9db74320c
r0a91/Taller1Ciencias3Grupo81UD
/Ejercicio2/almacen.py
817
3.625
4
import pila class Almacen: def __init__(self, peliculas): self.peliculas= peliculas def buscar_peliculas_por_genero(self,busqueda): #se empieza a buscar el genero entre el almacen de peliculas if self.peliculas.es_vacia(): print ("No hay mas peliculas para mostrar.") print ("_______________________________________________") else: pelicula=self.peliculas.desapilar()#obtiene la primera pelicula de toda la pila for genero in pelicula.genero: if busqueda==genero: print(pelicula.titulo) self.buscar_peliculas_por_genero(busqueda)# llama recursivamente a la funcion para seguir buscando peliculas
dff8bc261320d6c228a7cb4d9765c14acc2ca521
naemnamenmea/machine-learning-theory
/sections/regression_analysis/pca.py
6,769
3.640625
4
import numpy as np from numpy.linalg import norm def find_min(funObj, w, maxEvals, verbose, *args): """ Uses gradient descent to optimize the objective function This uses quadratic interpolation in its line search to determine the step size alpha """ # Parameters of the Optimization optTol = 1e-2 gamma = 1e-4 # Evaluate the initial function value and gradient f, g = funObj(w, *args) funEvals = 1.0 alpha = 1.0 while True: # Line-search using quadratic interpolation to find an acceptable value of alpha gg = g.T.dot(g) while True: w_new = w - alpha * g f_new, g_new = funObj(w_new, *args) funEvals += 1.0 if f_new <= f - gamma * alpha * gg: break if verbose > 1: print("f_new: %.3f - f: %.3f - Backtracking..." % (f_new, f)) # Update step size alpha alpha = (alpha ** 2) * gg / (2. * (f_new - f + alpha * gg)) # Print progress if verbose > 0: print("%d - loss: %.3f" % (funEvals, f_new)) # Update step-size for next iteration y = g_new - g alpha = -alpha * np.dot(y.T, g) / np.dot(y.T, y) # Safety guards if np.isnan(alpha) or alpha < 1e-10 or alpha > 1e10: alpha = 1. if verbose > 1: print("alpha: %.3f" % (alpha)) # Update parameters/function/gradient w = w_new f = f_new g = g_new # Test termination conditions optCond = norm(g, float('inf')) if optCond < optTol: if verbose: print("Problem solved up to optimality tolerance %.3f" % optTol) break if funEvals >= maxEvals: if verbose: print("Reached maximum number of function evaluations %d" % maxEvals) break return w class PCA: ''' Solves the PCA problem min_Z,W (Z*W-X)^2 using SVD ''' def __init__(self, k): self.k = k def fit(self, X): self.mu = np.mean(X, 0) X = X - self.mu U, s, V = np.linalg.svd(X) self.W = V[:self.k, :] return self def compress(self, X): X = X - self.mu Z = np.dot(X, self.W.transpose()) return Z def expand(self, Z): X = np.dot(Z, self.W) + self.mu return X class AlternativePCA: ''' Solves the PCA problem min_Z,W (Z*W-X)^2 using gradient descent ''' def __init__(self, k): self.k = k def fit(self, X): n, d = X.shape k = self.k self.mu = np.mean(X, 0) X = X - self.mu # Randomly initial Z, W z = np.random.randn(n * k) w = np.random.randn(k * d) f = np.sum((np.dot(z.reshape(n, k), w.reshape(k, d)) - X) ** 2) / 2 for i in range(50): f_old = f z = find_min(self._fun_obj_z, z, 10, False, w, X, k) w = find_min(self._fun_obj_w, w, 10, False, z, X, k) f = np.sum((np.dot(z.reshape(n, k), w.reshape(k, d)) - X) ** 2) / 2 print('Iteration {:2d}, loss = {}'.format(i, f)) if f_old - f < 1e-4: break self.W = w.reshape(k, d) return self def compress(self, X): n, d = X.shape k = self.k X = X - self.mu # We didn't enforce that W was orthogonal so we need to optimize to find Z z = np.zeros(n * k) z = find_min(self._fun_obj_z, z, 100, False, self.W.flatten(), X, k) Z = z.reshape(n, k) return Z def expand(self, Z): X = np.dot(Z, self.W) + self.mu return X def _fun_obj_z(self, z, w, X, k): n, d = X.shape Z = z.reshape(n, k) W = w.reshape(k, d) R = np.dot(Z, W) - X f = np.sum(R ** 2) / 2 g = np.dot(R, W.transpose()) return f, g.flatten() def _fun_obj_w(self, w, z, X, k): n, d = X.shape Z = z.reshape(n, k) W = w.reshape(k, d) R = np.dot(Z, W) - X f = np.sum(R ** 2) / 2 g = np.dot(Z.transpose(), R) return f, g.flatten() class RobustPCA(AlternativePCA): def _fun_obj_z(self, z, w, X, k): # |Wj^TZi-Xij| = sqrt((Wj^TZi-Xij)^2 + 0.0001) # |ZW-X| = ((ZW-X)**2 + 0.0001)**0.5 # f'z = 0.5((ZW-X)**2 + 0.0001)**-0.5 * 2(ZW-X)W**T n, d = X.shape Z = z.reshape(n, k) W = w.reshape(k, d) R = np.dot(Z, W) - X f = np.sqrt(np.sum(R ** 2) + 0.0001) g = np.dot(R, W.transpose()) / (np.sum(R ** 2) + 0.0001) ** 0.5 return f, g.flatten() def _fun_obj_w(self, w, z, X, k): n, d = X.shape Z = z.reshape(n, k) W = w.reshape(k, d) R = np.dot(Z, W) - X f = np.sqrt(np.sum(R ** 2) + 0.0001) g = np.dot(Z.transpose(), R) / (np.sum(R ** 2) + 0.0001) ** 0.5 return f, g.flatten() if __name__ == '__main__': import pylab as plt from prepare_data import FormData X, _, _, _ = FormData.prep_data(data="sinus") X = X.values n, d = X.shape print(X.shape) h, w = 64, 64 # height and width of each image # the two variables below are parameters for the foreground/background extraction method # you should just leave these two as default. k = 5 # number of PCs threshold = 0.04 # a threshold for separating foreground from background model = RobustPCA(k=k) model.fit(X) Z = model.compress(X) Xhat = model.expand(Z) # save 10 frames for illustration purposes # for i in range(10): # plt.subplot(1, 3, 1) # plt.title('Original') # plt.imshow(X[i].reshape(h, w).T, cmap='gray') # plt.subplot(1, 3, 2) # plt.title('Reconstructed') # plt.imshow(Xhat[i].reshape(h, w).T, cmap='gray') # plt.subplot(1, 3, 3) # plt.title('Thresholded Difference') # plt.imshow(1.0 * (abs(X[i] - Xhat[i]) < threshold).reshape(h, w).T, cmap='gray') # plt.show() # utils.savefig('q2_highway_{:03d}.jpg'.format(i)) from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target n_components = 2 pca = PCA(n_components) pca.fit(X) X_pca = pca.compress(X) colors = ['navy', 'turquoise', 'darkorange'] plt.figure(figsize=(8, 8)) for color, i, target_name in zip(colors, [0, 1, 2], iris.target_names): plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], color=color, lw=2, label=target_name) plt.title('PCA') plt.legend(loc="best", shadow=False, scatterpoints=1) plt.axis([-4, 4, -1.5, 1.5]) plt.show()
e1c3baf9c0d25e5e275398ea1a681b69d8c4669c
Iwan-Zotow/runEGS
/XcMath/voxarea.py
5,575
3.734375
4
# -*- coding: utf-8 -*- import math # # Q1 Q0 # Q2 Q3 # # rotation matrices mtxQ0 = (( 1.0, 0.0), ( 0.0, 1.0)) mtxQ1 = (( 0.0, 1.0), (-1.0, 0.0)) mtxQ2 = ((-1.0, 0.0), ( 0.0,-1.0)) mtxQ3 = (( 0.0,-1.0), ( 1.0, 0.0)) def rotate(x, y, mat): """ Given 2D matrix, rotate x, y pair and return rotated position """ return (mat[0][0]*x + mat[0][1]*y, mat[1][0]*x + mat[1][1]*y) def circ_segment_area(R, h): """ Computes the area of the circular segment Parameters ---------- R: float radius of the circle, mm h: float chord position, mm returns: float computed area of the circular segment divided by 2, sq.mm """ if R <= 0.0: raise ValueError("circ_segment_area", "circle radius is negative or 0") if h < 0.0: raise ValueError("circ_segment_area", "circle radius is negative or 0") if h >= R: return 0.0 if h == 0.0: return 0.25 * math.pi * R*R theta = math.acos(h / R) return 0.5 * ( R*R*theta - h*math.sqrt((R - h)*(R + h)) ) def circ_segmentsector_area(R, hx, hy): """ Computes half of the area of the circular segment Parameters ---------- R: float radius of the circle, mm hx: float chord X position, mm hy: float chord Y position, mm returns: float computed area of the circular segment sector, sq.mm """ Sx = circ_segment_area(R, hx) Sy = circ_segment_area(R, hy) return Sx + Sy + hx*hy - 0.25* math.pi * R*R def rotate_voxel(xmin, ymin, xmax, ymax): """ Given center position, rotate to the first quadrant Parameters ---------- xmin: float low point X position, mm ymin: float low point Y position, mm xmax: float high point X position, mm ymax: float high point Y position, mm returns: floats properly rotated voxel in the first quadrant """ xc = 0.5 * (xmin + xmax) yc = 0.5 * (ymin + ymax) if xc >= 0.0 and yc >= 0.0: # no rotation return (xmin, ymin, xmax, ymax) if xc < 0.0 and yc >= 0.0: # CW 90 rotation return (ymin, -xmax, ymax, -xmin) if xc < 0.0 and yc < 0.0: # CW 180 rotation return (-xmax, -ymax, -xmin, -ymin) # xc > 0.0 && yc < 0.0: # CW 270 rotation return (-ymax, xmin, -ymin, xmax) def check_voxel(xmin, ymin, xmax, ymax): """ Given voxel hi and low point, return true if voxel is good, false otherwise """ return xmin < xmax and ymin < ymax def vaInner(R, xmin, ymin, xmax, ymax): """ Computes intersection area Radius of the point with center of the voxel is inside the R """ if not check_voxel(xmin, ymin, xmax, ymax): raise RuntimeError("vaInner", "bad incoming voxel") #print("{0} {1} {2} {3} {4}".format(xmin, ymin, xmax, ymax, R)) # get the points in the first quadrant (xmin, ymin, xmax, ymax) = rotate_voxel(xmin, ymin, xmax, ymax) if not check_voxel(xmin, ymin, xmax, ymax): raise RuntimeError("vaInner", "bad rotated voxel") rmaxmax = math.sqrt(xmax*xmax + ymax*ymax) if rmaxmax <= R: return 1.0 # computing other two corners rminmax = math.sqrt(xmin*xmin + ymax*ymax) rmaxmin = math.sqrt(xmax*xmax + ymin*ymin) if rminmax >= R: if rmaxmin >= R: A = circ_segmentsector_area(R, xmin, ymin) else: # rmaxmin < R A = circ_segmentsector_area(R, xmin, ymin) A -= circ_segmentsector_area(R, xmax, ymin) else: if rmaxmin >= R: A = circ_segmentsector_area(R, xmin, ymin) A -= circ_segmentsector_area(R, xmin, ymax) else: # rmaxmin < R A = circ_segmentsector_area(R, xmin, ymin) A -= circ_segmentsector_area(R, xmax, ymin) A -= circ_segmentsector_area(R, xmin, ymax) return A /((ymax-ymin)*(xmax-xmin)) def vaOuter(R, xmin, ymin, xmax, ymax): """ Computes intersection area Radius of the point with center of the voxel is outside the R """ if not check_voxel(xmin, ymin, xmax, ymax): raise RuntimeError("vaOuter", "bad original voxel") # get the points in the first quadrant (xmin, ymin, xmax, ymax) = rotate_voxel(xmin, ymin, xmax, ymax) if not check_voxel(xmin, ymin, xmax, ymax): raise RuntimeError("vaOuter", "bad rotated voxel") rminmin = math.sqrt(xmin*xmin + ymin*ymin) if rminmin >= R: return 0.0 # we know we have one corner rminmax = math.sqrt(xmin*xmin + ymax*ymax) rmaxmin = math.sqrt(xmax*xmax + ymin*ymin) if rminmax >= R: if rmaxmin >= R: A = circ_segmentsector_area(R, xmin, ymin) else: # rmaxmin < R A = circ_segmentsector_area(R, xmin, ymin) A -= circ_segmentsector_area(R, xmax, ymin) else: if rmaxmin >= R: A = circ_segmentsector_area(R, xmin, ymin) A -= circ_segmentsector_area(R, xmin, ymax) else: # rmaxmin < R A = circ_segmentsector_area(R, xmin, ymin) A -= circ_segmentsector_area(R, xmax, ymin) A -= circ_segmentsector_area(R, xmin, ymax) return A /((ymax-ymin)*(xmax-xmin))
e2e4ae3acb162553475efa37669e4b14518815b1
Iwan-Zotow/runEGS
/XcMath/conversion.py
629
3.71875
4
# -*- coding: utf-8 -*- import numpy as np def mm2cm(v): """ Converts value from mm to cm Parameters ---------- v: value input value, mm returns: value in cm """ if np.isnan(v): raise ValueError("mm2cm", "Not a number") return v * 0.1 def cm2mm(v): """ Converts value from cm to cm Parameters ---------- v: value input value, cm returns: value in mm """ if np.isnan(v): raise ValueError("cm2mm", "Not a number") return v * 10.0
79d8ef07aeb2eae84c451d48f74d4f0007218e3a
L200180012/algostruk
/MODUL_5/routineswap.py
442
3.5
4
def swap(A,p,q): tmp = A[p] A[p] = A[q] A[q] = tmp def cariPosisiYangTerkecil(A, dariSini, sampaiSini): posisiYangTerkecil = dariSini #anggap ini yang terkecil for i in range(dariSini+1, sampaiSini): #cari di sisa list if A[i] < A[posisiYangTerkecil]: #kalau menemukan yang lebih kecil, posisiYangTerkecil = i #anggapan dirubah return posisiYangTerkecil
bd99265f54d83c730f9f386210f1fea3ede5177b
christinegithub/reinforcement_march7
/class.py
1,313
4
4
classroom = [ [None, "Pumpkin", None, None], ["Socks", None, "Mimi", None], ["Gismo", "Shadow", None, None], ["Smokey","Toast","Pacha","Mau"] ] row_index = 0 seat_index = 0 for row_index, row in enumerate(classroom): for seat_index, seat in enumerate(row): if seat == None: print("Row {} seat {} is free. Do you want to sit there? (y/n)".format(row_index + 1, seat_index + 1)) user_input = input() if user_input == 'y': print("What is your name?") user_name = input() classroom[row_index][seat_index] = user_name break seat_index += 1 row_index += 1 print(classroom) # Row 1 seat 1 is free. # Row 1 seat 3 is free. # Row 1 seat 4 is free. # Row 2 seat 2 is free. # Row 3 seat 3 is free. # Row 3 seat 4 is free. # Row 1 seat 1 is free. Do you want to sit there? (y/n) # user says 'n' # Row 1 seat 3 is free. Do you want to sit there? (y/n) # user says 'n' # Row 1 seat 4 is free. Do you want to sit there? (y/n) # user says 'n' # Row 2 seat 2 is free. Do you want to sit there? (y/n) # user says 'n' # Row 3 seat 3 is free. Do you want to sit there? (y/n) # user says 'n' # Row 3 seat 4 is free. Do you want to sit there? (y/n) # user says 'y' # What is your name? # user says "Tama"
2af12ab5ece3bf900831099cd069a46a6135bf8e
Mah1r2005/Python
/Sets.py
3,497
3.859375
4
s1={1,2,3,4} s0={"a","b","c"} s2={True,False} s3=set((1,2,3,4)) print(1 in s3) print(s1) #Printining the set #Duplicate not allowed #Unchanged s4={1,2,3,4,5,5,3,2,1,3,5} print(s4) #Duplicated element will no be printed print(len(s4)) #Length of the set print(type(s4)) for i in s4: print(i) #Add elements s4.add(10) print(s4) #Add set s4.update(s3) print(s4) #Add tuple or list s4.update(tuple((1,2,4,6,8,9))) print(s4) #Remove elementa s0.remove("a") print(s0) s0.discard("b") print(s0) #If not in set return error s1.pop() #Removes the last elements print(s1) s0.clear() #Clear the whole set print(s0) del s0 #Deleted th set completely #join sets s6=s1.union(s2) print(s6) print(s1.intersection_update(s2)) #keep the common elements print(s1.intersection(s2)) #Return a set that contains the items that exist in both set x, and set y: print(s1.symmetric_difference_update(s2)) #Keep the items that are not present in both sets: print(s1.symmetric_difference(s2)) #Return a set that contains all items from both sets, except items that are present in both: print(s4.union(s1)) #Union #Copy a set x=s4.copy() print(x) print(s4.difference(s1)) #Returns a set containing the difference between two or more sets print(s4.difference_update(s1)) #Removes the items in this set that are also included in another, specified set print(s4.isdisjoint(s1)) #Returns whether two sets have a intersection or not print(s4.issubset(s1)) #Returns whether another set contains this set or not print(s4.issuperset(s1)) #Returns whether this set contains another set or not s1={1,3,5} s2={2,4,6} print(s1 | s2) print(s1 & s2) print(s1 - s2) print(s1 ^ s2) print(s2 - s1) print(1 in s1) print(" ".join(str(e) for e in s1)) set1=set("mahir") print(set1) #Frozenset String = ('G', 'e', 'e', 'k', 's', 'F', 'o', 'r') Fset1 = frozenset(String) print(Fset1) print(frozenset()) print(enumerate(s1)) print(s1<=s2) #Doesnt include all elements print(s1<s2) print(s1>=s2) #Doesnt include all elements print(s1>s2) print(set("mahir")==frozenset("mahir")) #True print(frozenset('ab') | set('bc')) # tuple of vowels vowels = ('a', 'e', 'i', 'o', 'u') fSet = frozenset(vowels) print('The frozen set is:', fSet) print('The empty frozen set is:', frozenset()) # random dictionary person = {"name": "John", "age": 23, "sex": "male"} fSet = frozenset(person) print('The frozen set is:', fSet) # Frozensets # initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) # copying a frozenset C = A.copy() # Output: frozenset({1, 2, 3, 4}) print(C) # union print(A.union(B)) # Output: frozenset({1, 2, 3, 4, 5, 6}) # intersection print(A.intersection(B)) # Output: frozenset({3, 4}) # difference print(A.difference(B)) # Output: frozenset({1, 2}) # symmetric_difference print(A.symmetric_difference(B)) # Output: frozenset({1, 2, 5, 6}) # Frozensets # initialize A, B and C A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) C = frozenset([5, 6]) # isdisjoint() method print(A.isdisjoint(C)) # Output: True # issubset() method print(C.issubset(B)) # Output: True # issuperset() method print(B.issuperset(C)) # Output: True frozen_set = frozenset(('a', 'e', 'i', 'o', 'u')) print(set(frozen_set))
fd5641182de6babf5a1903469daac0fcb41e18af
Mah1r2005/Python
/Numbers.py
926
3.90625
4
#3 types of number Normal_num=4 Float=4.89988 Complex=5j x=4 y=6 z=5 print(x+y) #Sum print(x*y) #Multiply print(x**y) #Power print(x/y) #Divide print(x//y) #Divide but returns only the whole integer print(x%y) #Modulas or reminder x+=1 #Means x=x+1 (Same for other operators) print(x) x%=2 print(x) print(10000) print(2.44) print(5j) # for NaN print(float("nan")) print(float("NaN")) # for inf/infinity print(float("inf")) print(float("InF")) print(float("InFiNiTy")) print(float("infinity")) # binary 0b or 0B print("For 1010, int is:", int('1010', 2)) print("For 0b1010, int is:", int('0b1010', 2)) # octal 0o or 0O print("For 12, int is:", int('12', 8)) print("For 0o12, int is:", int('0o12', 8)) # hexadecimal print("For A, int is:", int('A', 16)) print("For 0xA, int is:", int('0xA', 16))
d525504efb47a6d52c2fcf8c3817cba176054709
Mah1r2005/Python
/Data types.py
3,960
3.515625
4
x=4 #Numbers print(x) print(type(x)) #Checking the type of the data x="mahir" #String print(x) print(type(x)) x=True #Boolean print(x) print(type(x)) x=False #Boolean print(x) print(type(x)) x = 20.5 #float print(x) print(type(x)) x = 1j #complex print(x) print(type(x)) x = ["apple", "banana", "cherry"] #list print(x) print(type(x)) x = ("apple", "banana", "cherry") #tuple print(x) print(type(x)) x = range(6) #range print(x) print(type(x)) x = {"name" : "John", "age" : 36} #dict print(x) print(type(x)) x = {"apple", "banana", "cherry"} #set print(x) print(type(x)) x = frozenset({"apple", "banana", "cherry"}) #frozenset print(x) print(type(x)) x = b"Hello" #bytes print(x) print(type(x)) x = bytearray(5) #bytearray print(x) print(type(x)) x = memoryview(bytes(5)) #memoryview print(x) print(type(x)) #Transforming data types x=5 str1=str(x) #It is now string print(str1) print(str1+str(6)) print(id(x)) print(hash(x)) x = str("Hello World") print(x) print("%s"%x) print("%a"%x) print(id(x)) #For all types print(hash(x)) print(len(x)) x = int(20) print(x) print("%d"%x) print("%c"%x) print("%e"%x) print(id(x)) print(hash(x)) x = float(20.5) print(x) print("%f"%x) print(id(x)) print(hash(x)) x = complex(1j) print(x) print(id(x)) print(hash(x)) x = list(("apple", "banana", "cherry")) print(x) print(id(x)) print(len(x)) x = tuple(("apple", "banana", "cherry")) print(x) print(id(x)) print(hash(x)) print(len(x)) x = range(6) print(x) print(id(x)) print(hash(x)) print(len(x)) x = dict(name="John", age=36) print(x) print(id(x)) print(len(x)) x = set(("apple", "banana", "cherry")) print(x) print(id(x)) print(len(x)) x = frozenset(("apple", "banana", "cherry")) print(x) print(id(x)) print(hash(x)) print(len(x)) x = bool(5) print(x) print(id(x)) print(hash(x)) x = bytes(5) print(x) print(id(x)) print(hash(x)) print(len(x)) x = bytearray(5) print(x) print(id(x)) print(len(x)) x = bytearray("5",'utf-8') print(x) print(id(x)) print(len(x)) rList = [1, 2, 3, 4, 5] x= bytes(rList) print(x) print(x) print(id(x)) print(hash(x)) print(len(x)) x = memoryview(bytes(5)) print(x) print(id(x)) print(hash(x)) print(len(x)) print(int("1000")) print(int("100",10)) #Base 10 print(ord("1")) print(hex(56)) print(bin(56)) print(oct(65)) print(list("mahir")) print(set("mahir")) print(list("mahir")) print(complex(9,5)) x = complex('3+5j') print(x) tup = (('a', 1) ,('f', 2), ('g', 3)) print(dict(tup)) print(repr(3)) x = 1 print(eval('x + 1')) print(chr(2)) number = 435 print(number, 'in hex =', hex(number)) number = 0 print(number, 'in hex =', hex(number)) number = -34 print(number, 'in hex =', hex(number)) returnType = type(hex(number)) print('Return type from hex() is', returnType) number = 2.5 print(number, 'in hex =', float.hex(number)) number = 0.0 print(number, 'in hex =', float.hex(number)) number = 10.5 print(number, 'in hex =', float.hex(number)) print('oct(0b101) is:', oct(0b101)) # hexadecimal to octal print('oct(0XA) is:', oct(0XA)) print(ord('5')) # 53 print(ord('A')) # 65 print(ord('$')) # 36 # take the second element for sort def take_second(elem): return elem[1] # random list random = [(2, 2), (3, 4), (4, 1), (1, 3)] # sort list with key sorted_list = sorted(random, key=take_second) # print list print('Sorted list:', sorted_list)
2e78c752ae5ca040e45f834444cae1076f61b758
yinxingyi/Python100day_Learning
/Day4.py
1,260
3.96875
4
# --------------------------------------------------------------- # print prime number within 0~100 # num = int(input('input a integer:')) # for number in range(0,101): # for i in range(2, number): # if number%i == 0: # print("%d is a not prime number!" %number) # break # elif i == number-1: # print("%d is a prime number!" %number) # -------------------------------------------------------------- # # num = int(input("please enter a number:")) # # for x in range(2, num+2): # for x in range(0,x): # if x !=0: # print("*", end = '') # x= x-1 # print() # # for i in range(num): # for j in range(num): # if j < num - i - 1: # print(" ", end='') # else: # print("*", end = '') # print() # # for i in range(num): # for _ in range(num - i - 1): # print(' ', end = '') # for _ in range(2*i+1): # print('*', end = '') # print() # # print out : # * # ** # *** # **** # ***** # * # ** # *** # **** # ***** # * # *** # ***** # ******* # ********* # ----------------------------------------------------------------------
386bdb2fc5eff97d6047b5a9aa10b5285bf04169
yonggyulee/gitpython
/practice02/prob04.py
431
3.65625
4
#문제4 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에 출력해보세요. 1부터 99까지만 실행하세요. count = 0 for n in range(1,100): clab = 0 clab += str(n).count('3') clab += str(n).count('6') clab += str(n).count('9') if clab > 0: print('{0} '.format(n) + '짝'*clab) count += 1 print('총 객수 : {0}'.format(count))
c142beb40fb5f0bf1527f2a5fc3172165d0d4d09
yonggyulee/gitpython
/02/07.operater_logical.py
744
4.3125
4
#일반적으로 피연산자(operand)는 True 또는 False 값을 가지는 연산 a = 20 print(not a < 20) print(a < 30 and a !=30) b = a > 1 # 다른 타입의 객체도 bool 타입으로 형변환이 가능하다 print(bool(10), bool(0)) print(bool(3.14), bool(0.)) print(bool('hello'), bool('')) print(bool([0,1]), bool([])) print(bool((0,1)), bool(())) print(bool({'k1':'v1', 'k2':'v2', 'k3':'v3'}), bool({})) print(bool(None)) # 논리식의 계산순서 t = True or bool('logical') print(t) print(True or 'logical') print(False or 'logical') print([] or 'logical') print([] and 'logical') print([0,1] or 'logical') def f(): print('hello world') a = 11 a > 10 or f() if a > 10: f() s1 = '' s = 'Hello World' s1 and print(s)
5870f29cd1de872b91906c45f7115a2aa87ecc5c
yonggyulee/gitpython
/practice01/prob06.py
579
3.6875
4
#문제6. 키보드에서 정수로 된 돈의 액수를 입력 받아 오만 원권, 만원 권, 오천 원권, 천원 권, 500원짜리 동전, 100원짜리 동전, 50원짜리 동전, 10원짜리 동전, 1원짜리 동전 각 몇 개로 변환 되는지 작성하시오. money = input("금액:") print(money, type(money)) money = int(money) value = 50000 a = 5 for i in range(10): print('%d원 : %d개' % (value, money//value)) money %= value a = 5 * ((i+1) % 2) + 2 * (i % 2) value /= a # 방법2 moneys = [ 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1]
15af66f61c1f130aa6242535ba3ac8a016958e0d
yonggyulee/gitpython
/02/03.list.py
2,468
3.734375
4
# 생성 l1 = [] l2 = [1, True, 'python', 3.14] print('\n======================sequence 타입 특징============================') # 인덱싱 (sequence 타입 특징) print(l2[0], l2[1], l2[2],l2[3]) print(l2[-4], l2[-3], l2[-2], l2[-1]) # slicing print(l2[1:4]) l3 = l2 l4 = l2[:] print(l3) print(l3 is l2) print(l4 is l2) print(l2[len(l2)::-1]) # 반복(sequence 타입 특징) l3 = l2*2 print(l3) # 연결(sequence 타입 특징) l4=l2 + [1,2,3] print(l4) # 길이(sequence 타입 특징) print(len(l4)) # in, not in(sequence 타입 특징) print(5 not in l4) print('python' in l4) print('\n======================변경가능한 객체============================') # 삭제(변경 가능한 객체) del l4[2] print(l4) #변경 가능한 객체(mutable) l5 = ['apple', 'banana', 10, 20] l5[2] = l5[2] + 90 print(l5) print('\n=====================slicing 기법============================') # 삭제 (slicing을 이용한...) l6 = [1,12,123,1234] l6[1:2] = [] print(l6) l6[0:] = [] print(l6) # 삽입(slicing을 이용한...) l7 = [1,123,1234,12345] # 중간삽입 l7[1:1] = [12] print(l7) # 마지막삽입 l7[5:] = [123456] print(l7) # 처읍삽입 l7[:0] = [0] print(l7) # 치환(slicing을 이용한...) l8 = [1, 12, 123, 1234, 12345] l8[0:2] = [10, 20] print(l8) l8[0:2] = [100] print(l8) l8[1:2] = [200] print(l8) l8[2:4] = [300, 400, 500, 600] print(l8) print('\n======================객체 함수============================') l9 = [1, 3, 4] # 중간삽입 l9.insert(1, 2) print(l9) # 마지막 삽입 l9.append(5) print(l9) # 처음 삽입 l9.insert(0, 0) print(l9) # 삭제 (값으로 삭제 동질한 객체를 삭제한다. ==) l9.remove(3) print(l9) # 없는 객체를 삭제할 경우 try: l9.remove(3) except ValueError as ve: print('없는 객체를 삭제할 경우 예외 발생') # 확장 l9.extend([-1, -2, -3, -4]) print(l9) #stack s = [] s.append(10) #push s.append(20) #push s.append(30) #push print(s) print(s.pop()) #pop print(s.pop()) #pop print(s) # que 로 사용해보기 q = [1,2] q.append(3) q.append(4) q.append(5) print(q) print(q.pop(0)) print(q.pop(0)) print(q.pop(0)) print(q) # sort l10 = [1,5,3,9,8,11] l10.sort() print(l10) l11 = [10, 2, 33, 9, 8, 4, 11] l11.sort(key=str) print(l11) l11.sort(key=int) print(l11) # cf: sorted 전역함수 l12 = [19, 35, 45, 27, 91, 55, 64] l13 = sorted(l12) print(l13) def f(i): return i % 10 l14=sorted(l12, key=f, reverse=False) print(l14)
d54e42fe882045fdcccd3a34e984f72520bc926e
machinebarker/Python_Advance_Calculator
/keling.py
120
3.609375
4
Phi = 3.14 r = float(input("Masukkan nilai jari-jari: ")) keling = 2*Phi*r print("Jadi nilai keliling: " + str(keling))
ed92b3dbb578b29762acf5dd6f6a4f738da7d690
roger0503/Guessing-game
/guessing_game.py
583
4.09375
4
import random num = random.randrange(10) Guesses = 5 for i in range(1, Guesses+1): guess = int(input("Enter your guess:")) if(guess == num): print("Your guess is correct!") break elif(guess > num and i < Guesses): print("You are close, keep trying lower") elif(guess < num and i < Guesses): print("You are close, keep trying hgher") if(i == Guesses-1): print("This is your last chance") elif(i == Guesses and guess != num): print("You Lost!") print("Correct answer was", num)
f5d16aa2f450646289b53de99b16f9cf8b899778
laueste/algorithms-ucsf-2019
/hw3/alignment/utils.py
794
3.71875
4
# Some utility classes to represent a fasta sequence and a scoring matrix class Sequence: """ A simple class for a sequence (protein or DNA) from a FASTA file """ def __init__(self, name, sequence='', header=''): self.name = name #the file name self.header = header #the name in the file following '>' self.sequence = sequence # Overload the __repr__ operator to make printing simpler. def __repr__(self): return self.name # class ScoringMatrix: # """ # A simple class for an amino acid residue # """ # # def __init__(self, type): # self.type = type # self.coords = (0.0, 0.0, 0.0) # # # Overload the __repr__ operator to make printing simpler. # def __repr__(self): # return self.type
107fb1edb7dd2a995c4c9b163b8f7ea255f1533f
melissathatblondie/snowflakePygame
/snowflake.py
2,341
3.8125
4
import pygame import random # Some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) pygame.init() # Sets the width and height of the screen [width, height] size = (700, 500) screen = pygame.display.set_mode(size) bg = pygame.image.load("gwcpic3.png") pygame.display.set_caption("Snow") color = WHITE # My SnowFlake class class SnowFlake: def __init__(self, x_location, y_location, fall_Speed, flake_size): # Attributes of the bouncing ball self.x_location = x_location self.y_location = y_location self.fall_Speed = fall_Speed self.flake_size = flake_size def fall(self, screen, color, width, height): self.fall_Speed = random.randint(1,2) color = WHITE self.y_location += self.fall_Speed pygame.draw.circle(screen, WHITE, [self.x_location, self.y_location], self.flake_size) if self.y_location > 500: self.y_location = random.randint(-40, -10) self.x_location = random.randint(0,750) # Loops until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # Speed speed = 2 # Snow List snow_list = [] for i in range(random.randint(500,700)): x = random.randint(0,700) y = random.randint(0, 500) rad = random.randint(3,6) snowball = SnowFlake(x, y, 2, rad) snow_list.append(snowball) # -------- Main Program Loop ----------- while not done: # --- Main event loop for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # --- Game logic should go here # --- Screen-clearing code goes here # Here, we clear the screen to white. Don't put other drawing commands # above this, or they will be erased with this command. # If you want a background image, replace this clear with blit'ing the # background image. screen.blit(bg, (0,0)) # --- Drawing code should go here # Begin Snow for k in snow_list: k.fall(screen, WHITE, 700, 500) # End Snow # --- Updates the screen with what I've drawn. pygame.display.flip() # --- Limits to 60 frames per second clock.tick(60) # Close the window and quit. pygame.quit() exit() # Needed when using IDLE
ee8a92f165e86d4b17ada35b224bc68db1e59528
aniljp97/DeepLearning
/Lab1/Source Code/classifcation.py
3,912
3.609375
4
""" Part 5: Run-through of exploratory data analysis, evaluation, comments, and conclusions printed to the output. Please follow through with the output. Dataset: https://www.kaggle.com/jeevannagaraj/indian-liver-patient-dataset """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import stats from sklearn.model_selection import train_test_split print("We are using a dataset of patient data targeted at the presence of cardiovascular disease.\n") df = pd.read_csv('Indian Liver Patient Dataset (ILPD).csv') print("First lets see what the data looks like:") print(df.head(), end='\n\n') print("And now some information:") df.info() print() print("Looks like column alkphos has a few missing values. Lets look closer at those:") print(df[df.isnull().any(axis=1)]) print("Since its only 4 rows, quite insignificant to the full size, lets go ahead and remove them:") df = df.drop([209,241,253,312]) df.info() print("No null values now.", end='\n\n') print("We also see that we have one attribute (gender) that is not a numerical value and is instead an object.\n" "We'll change that:") gender_dict = {"Male": 0, "Female": 1} new_gender_column = [] for g in df["gender"]: new_gender_column.append(gender_dict[g]) df["gender"] = new_gender_column df.info() print("Gender is now an int type and binary value.", end='\n\n') print("Lets look at correlations of attributes to the target and see if anything stands out:") print(abs(df[df.columns[:]].corr()['is_patient'][:-1])) print("Looks like every attribute has reasonable correlation other than 'sgpt' and 'gender'\n" "who are somewhat outliers both under 0.1. We will remove them.", end='\n\n') df = df.drop("sgpt", axis=1) df = df.drop("gender", axis=1) print("Now lets check for outliers in the attributes:") plt.title("Checking for outlier data...") df.boxplot(column=list(df.columns)) plt.show() print("We can see there are some drastic outliers that need to be removed but the outliers of some of these\n" "columns are still quite large in quantity and bunched up so we will cut off data around 1000.", end='\n\n') z_scores = stats.zscore(df) abs_z_scores = np.abs(z_scores) filtered_entries = (abs_z_scores < 3).all(axis=1) df = df[filtered_entries] plt.title("Data cut off around 1000") df.boxplot(column=list(df.columns)) plt.show() print("Now that we have done a good amount of exploratory data analysis, we can apply classification algorithms:") # get training and testing data x_train = df.drop("is_patient", axis=1) y_train = df["is_patient"] x_train_data, x_test_data, y_train_data, y_test_data = train_test_split(x_train,y_train, test_size=0.2) from sklearn.naive_bayes import GaussianNB gnb = GaussianNB() gnb.fit(x_train_data, y_train_data) print("Gaussian Naive Bayes model accuracy:", round(gnb.score(x_test_data, y_test_data) * 100, 2), end='%\n') from sklearn.svm import SVC svc = SVC() svc.fit(x_train_data, y_train_data) print("SVM model accuracy:", round(svc.score(x_test_data, y_test_data) * 100, 2), end='%\n') from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5) knn.fit(x_train_data, y_train_data) print("K-NN model accuracy:", round(knn.score(x_test_data, y_test_data) * 100, 2), end='%\n\n') print("It looks like the SVM model was generally the best model for our dataset.\n" "Naive Bayes is consistently the worst out of the bunch probably because the things\n" "that make it good for multiple class problems like text classification weren't relevant\n" "to our datasets binary classification problem. K-NN accuracy is quite varying and dependent\n" "on the k value so it could be possible to get K-NN accuracy up more with more extensive\n" "evaluation of the model.", end='\n\n')
11696c575bae8dd21f93451f2ec213d0f7518e73
sanjaykvo/substring_palindrome
/substringpalindrome.py
849
3.953125
4
""" This program will create the substring of the string and check the substring or not. if the substring is a palindrome then it will print the substring if anyone of the substring is not a palindrome it will print invalid input. """ def pal(st): if st == st[::-1]: return 1 def l(s): l1 = [] l1[:0] = s return l1 def brea(k): i = 0 c = '' for i in range(0, len(k)): c = c + k[i] if pal(c) == 1 and i > 0: alp.append(c) break return i s = str(input()) k = l(s) rk = k alp = [] for j in range(len(k)): i = brea(k) k = k[i + 1:len(k)] if i == len(k): break if len(alp) < 1 or len(alp) > len(k): print('invalid input') else: for i in range(len(alp)): print(alp[i], end=' ')
840738469fffa42ed7a25b954fac5888d1cbe6a1
mateuszlatkowski/projekt_sinwo
/algos/algorithms.py
5,308
4.21875
4
import math class Euclidean: def __init__(self): self.algorithm_name = "Euclidean Algorithm" def executes(self, a, b): '''Method for computing the greatest common divisor of two numbers (a, b)''' while(a!=b): if(a>b): a -= b else: b -= a return a def start(self): '''Method gather arguments and send them to execute alghoritm''' a = int(input('a: ')) b = int(input('b: ')) return self.executes(a, b) def __repr__(self): return self.algorithm_name def __str__(self): return self.__repr__() class LCM: def __init__(self): self.algorithm_name = "Least Common Multiply" def executes(self, a, b): """Returns the smallest positive integer that is divisible by both a and b""" Euclidean_tmp = Euclidean() return (a / Euclidean_tmp.executes(a, b)) * b def start(self): '''Method gather arguments and send them to execute alghoritm''' a = int(input('a: ')) b = int(input('b: ')) return self.executes(a, b) def __repr__(self): return self.algorithm_name def __str__(self): return self.__repr__() class Fibonacci: def __init__(self): self.algorithm_name = "Fibonacci Number" def executes(self, N): """Every number after the first two is the sum of the two preceding ones""" first = (0, 1) a, b = first number = [0] while (N + 1) > 1: number.append(b) a, b = b, (a + b) N -= 1 return number def start(self): '''Method gather arguments and send them to execute alghoritm''' N = int(input('Number: ')) return self.executes(N) def __repr__(self): return self.algorithm_name def __str__(self): return self.__repr__() class Quadratic_formula: def __init__(self): self.algorithm_name = "Quadratic formula" def executes(self, a, b, c): """Quadratic formula solving algorithm""" delta = (((b)**2 - 4*a*c)**0.5) if type(delta) is complex: zeros = None elif delta > 0: zeros = ((-b - delta)/(2*a), (-b + delta)/(2*a)) elif delta == 0: zeros = ((-b)/(2*a)) return zeros def start(self): '''Method gather arguments and send them to execute alghoritm''' a = int(input('a: ')) b = int(input('b: ')) c = int(input('c: ')) return self.executes(a, b, c) def __repr__(self): return self.algorithm_name def __str__(self): return self.__repr__() class Hanoi: def __init__(self): self.algorithm_name = "Hanoi Tower" self.steps = 0 def executes(self, N, z='A', na='C', przez='B'): """Conut hanoi tower steps for N pillars""" if N == 1: self.steps += 1 #print (z, "->", na) return self.executes(N - 1, z=z, na=przez, przez=na) self.executes(1, z=z, na=na, przez=przez) self.executes(N - 1, z=przez, na=na, przez=z) return self.steps def start(self): '''Method gather arguments and send them to execute alghoritm''' N = int(input('Tower Heigh: ')) return self.executes(N) def __repr__(self): return self.algorithm_name def __str__(self): return self.__repr__() class FermatFactorization: def __init__(self): self.name = "Fermat Algorithm" def executes(self, N): """The factorization method, the distriubtion of the number into prime factors""" if N <= 0: return 0 i = 2 e = math.floor(math.sqrt(N)) numbers = [] while i <= e: if N % i == 0: numbers.append(i) N /= i e = e = math.floor(math.sqrt(N)) else: i += 1 if N > 1: numbers.append(N) return numbers def start(self): '''Method gather arguments and send them to execute alghoritm''' N = int(input('Number: ')) return self.executes(N) def __repr__(self): return self.name def __str__(self): return self.__repr__() class BubbleSort: def __init__(self): self.name = "Bubble Sort" def executes(self, data): """Bubble sort algorithm""" for i in range(len(data)-1, 1, -1): for j in range(0, i): if data[j] >= data[j+1]: data[j+1], data[j] = data[j], data[j+1] return data def start(self): '''Method gather arguments and send them to execute alghoritm''' N = int(input('Enter table length: ')) data = [] for i in range(0, N): x = int(input('Number: '+str(i+1)+' ')) data.append(x) return self.executes(data) def __repr__(self): return self.name def __str__(self): return self.__repr__()
70a8c239ba87c9dff901ca51cffc205a96a574f0
Knasten/battle_ships
/run.py
4,095
4.125
4
import random # If player miss I will show an "-" # If player hit I will show an "X" # For water I will show "^" # Variables turns and num_ship declared here and later changed by user. # Size declared for board size here so grid 5x5 # admitted_input is used to verify row and column input from user turns = 32 num_ships = 7 size = 8 admitted_input = [str(x) for x in range(size + 1)] nl = '\n' def create_sea(board): """ This function prints the board for the user to see. Aswell as printing out numbers for each row and column. """ print(' 1 2 3 4 5 6 7 8') print(' ----------------') row_number = 1 for row in board: print("%d |%s|" % (row_number, "|".join(row))) row_number += 1 def create_ships(board, num_ships): """ This function adds ship to a random place in the list which will then be printed by create_sea func. """ for ships in range(num_ships): ship_row = random.randint(0, size - 1) ship_column = random.randint(0, size - 1) while board[ship_row][ship_column] == 'X': ship_row = random.randint(0, size - 1) ship_column = random.randint(0, size - 1) board[ship_row][ship_column] = 'X' def get_ship_location(): """ This function asks the user to enter a row and column. If row and column returned from user is not valid it will print this, and ask for a new number til the user enters a valid. """ row = input(f'Choose a row from 1 to {size}: {nl}') while row not in admitted_input or row == "": print('Your number is not valid please try again!') row = input(f'Choose a row from 1 to {size}: {nl}') column = input(f'Choose a column from 1 to {size}: {nl}') while column not in admitted_input or column == "": print('Your number is not valid please try again!') column = input(f'Choose a column from 1 to {size}: {nl}') return int(row) - 1, int(column) - 1 def count_hits(board): """ This function looks for any ship that has been hit and then returns the value to our counter. """ count = 0 for row in board: for column in row: if column == 'X': count += 1 return count # unseen_board and guess_board will be the same size # unseen_board used to verify hits and guess_board to show outcome. unseen_board = [["^" for x in range(size)]for y in range(size)] guess_board = [["^" for x in range(size)]for y in range(size)] def main(turns, num_ships): """ This function runs the game and prints out the result after each guess aswell as end result if turns go to zero or if count hit is the same as number of ships. """ round = 0 while turns > 0: print(f'Round {round}') create_sea(guess_board) row, column = get_ship_location() if guess_board[row][column] == 'X' or guess_board[row][column] == '-': print('You have already blown up theese coordinates!') elif unseen_board[row][column] == 'X': guess_board[row][column] = 'X' round += 1 print('HIT! You sank a ship!') print(f'You have {turns} left before the enemy fleet sinks you!') else: print('MISS! Try again!') guess_board[row][column] = '-' round += 1 turns -= 1 print(f'You have {turns} turns left') print('Before the enemy fleet sinks you!') if count_hits(guess_board) == num_ships: print('You have WON!') print(f'It took you {round} rounds to sink {num_ships} ships') break elif turns == 0: print('Sorry. Your crew is sleeping with the fish!') print('In theese location you could of hit the ships.') create_sea(unseen_board) break def start_game(): """ This function starts the game! """ print('Get ready! Set! Go! Battleships is starting!') create_ships(unseen_board, num_ships) main(turns, num_ships) start_game()
8d6d347432112c3884102402bf0c269bcbd2ab89
Preet2fun/Cisco_Devnet
/Python_OOP/encapsulation_privateMethod.py
1,073
4.4375
4
""" Encapsulation = Abstraction + data hiding encapsulation means we are only going to show required part and rest will keep as private """ class Data: __speed = 0 #private variable __name = '' def __init__(self): self.a = 123 self._b = 456 # protected self.__c = 789 # private self.__updatesoftware() self.__speed = 200 self.__name = "I10" def __updatesoftware(self): print("Updating software") def updatespeed(self,speed): self.__speed = speed def drive(self): print("Max speed of car is : " + str(self.__speed)) num = Data() """print(num.a, num._b, num.__c) --> we can not directly acces __C as it is define as private for class and no object of that class has access to it""" print(num.a, num._b, num._Data__c) #print(num.__updatesoftware) --> not able to access as its proivate method print(num.drive()) print(num._Data__speed) num.__speed = 300 print(num.drive()) num.updatespeed(300) print(num.drive())
10e98d3ce264b97ea09bd7ccb83261964a894b37
Preet2fun/Cisco_Devnet
/DevNet/01-programming_fundamentals/file_read_write.py
653
4.09375
4
from datetime import datetime log = "log_file.txt" """ when we use "with open" then we don't need to explicitly close open file , it will be atomically taken care """ def read_log(log): with open(log, "r") as f: print(f.read()) def write_log(log, data): with open(log, "a") as f: f.writelines("{0} : This is line has data : {1}\n".format(current_time, data)) if __name__ == "__main__": current_time = str(datetime.now()) data = input("Please provide some data : ") print("Writing some data to log file..") write_log(log, data) print("Reading log file..") read_log(log)
38cc881c104071c107379271012465907a0b3fde
Preet2fun/Cisco_Devnet
/DevNet/01-programming_fundamentals/csv_reader.py
229
3.546875
4
import csv raw_csv = open('text.csv').read() print(raw_csv) exp_csv = open('text.csv') data_read = csv.reader(exp_csv) for data in data_read: print('{} is in {} with ip : {}'.format(data[0], data[2], data[1]))
cd9c959a5bc604f523799d07470931d281d79698
paulc1600/Python-Problem-Solving
/H11_staircase.py
1,391
4.53125
5
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: Consider a staircase of size n: # # # ## # ### # #### # # Observe that its base and height are both equal to n, and # the image is drawn using # symbols and spaces. The last # line is not preceded by any spaces. # # Write a program that prints a staircase of size n. # # Function Description # Complete the staircase function in the editor below. It # should print a staircase as described above. staircase has # the following parameter(s): # o n: an integer # # --------------------------------------------------------------------- # PPC | 08/26/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # Print a staircase where the image is drawn using # symbols and spaces. def staircase(MySteps): air_fill = ' ' for step in range(MySteps): step_len = step + 1 wood_step = step_len * '#' whole_step = wood_step.rjust(MySteps, air_fill) print(whole_step) if __name__ == '__main__': n = 15 result = staircase(n)
85b96d3983eb1391604fe96f454099584335ef5a
paulc1600/Python-Problem-Solving
/H15_PowerSum_hp.py
7,709
4.0625
4
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: Find the number of ways that a given integer, X, can be # expressed as the sum of the Nth powers of unique, natural # numbers. # # For example, if X = 13 and N = 2, we have to find all # combinations of unique squares adding up to 13. The only # solution is 2^2 + 3^2 # # Function Description # Complete the powerSum function in the editor below. It should return an integer that represents the # number of possible combinations. # # powerSum has the following parameter(s): # o X: the integer to sum to # o N: the integer power to raise numbers to # # --------------------------------------------------------------------- # PPC | 08/27/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys from multiprocessing import * global nbrWays global sSetLimit # This code splits 1 huge range into mostly even partions # --------------------------------------------------------------------- def rangeSplitter(myTotal, nbrSplits, rem2end): job_ranges = [] bIdx = 0 eNbr = 0 delta = round(myTotal // nbrSplits) lint = myTotal % nbrSplits # Handle all but last partial split here for bIdx in range(nbrSplits): one_range = [] sNbr = eNbr + 1 if bIdx == 0 and rem2end == False: eNbr = eNbr + delta + lint # First split has extra records else: eNbr = eNbr + delta one_range = [sNbr, eNbr + 1] # Adjust for Python job_ranges.append(one_range) # Handle myTotal not splitting evenly / create last partial group if rem2end == True and eNbr < myTotal: sNbr = eNbr + 1 eNbr = myTotal # Last split has extra records one_range = [sNbr, eNbr + 1] # Adjust for Python job_ranges.append(one_range) return job_ranges # This code based on the original work of vibhu4agarwal # https://www.geeksforgeeks.org/find-distinct-subsets-given-set/ # --------------------------------------------------------------------- def processSubsets(myNbr, myJobQueue, myStart, myEnd, myArray, myX): global nbrWays sizePower = len(myArray) jvector = [] # Prepare vector Array One Time oneVector = 0b00000000000000000000000000000000 for jIdx in range(sizePower): myVector = oneVector + (2**jIdx) jvector.append(myVector) print() print("Call: ", myNbr, " -------------------------------------") print(" Range: ", myStart, myEnd) print(" Target for Sum: ", myX) for i in range(myStart, myEnd): # consider each element in the set (n = length arr) # Example of n = 3, i = 0:7, j = 0:2 # (1 << j) = 001, 010, 100 # i = 0 000 ___ # i = 1 001 __C # i = 2 010 _B_ # i = 3 011 _BC # i = 4 100 A__ # i = 5 101 A_C # i = 6 110 AB_ # i = 7 111 ABC subsetSum = 0 for j in range(sizePower): # Check if jth bit in the i is set. # If the bit is set, we consider jth element from arrPowers # and sum up it's value into a subset total if (i & jvector[j]) != 0: subsetSum = subsetSum + myArray[j] # Once finish with any subset -- just sum it and check it if subsetSum == myX: nbrWays = nbrWays + 1 myJobQueue.put([myNbr, nbrWays]) print("Call: ", myNbr, " ---- completed. NbrWays = ", nbrWays) return nbrWays # --------------------------------------------------------------------- # Python3 program to find all subsets of given set. Any repeated subset # is considered only once in the output # def powerSum(myX, myN): global nbrWays global sSetLimit arrPowers = [] myJobRanges = [] # Create Array of all powers of myN smaller than myX # for myN value 2 and myX value 13 would be [1, 4, 9] pos = 1 while pos ** myN <= myX: arrPowers.append(pos ** myN) pos = pos + 1 # Calculate all possible subsets print(arrPowers) sizePower = len(arrPowers) print("Need bit vector width =", sizePower) # Number subsets that give you X nbrWays = 0 # Run counter i from 000..0 to 111..1 (2**n) # For sets of unique numbers the number unique subsets # (including NULL) always 2**n. Python range statement will # drops the null subset from count. totSS = 2**sizePower print("Will create ", totSS, " subsets of Power array.") result = 0 # Parallel process above 4M subsets nbrJobs = (totSS // sSetLimit) + 1 print("Will run as ", nbrJobs, " job.") nbrCPU = cpu_count() print("System has ", nbrCPU, " cpu.") # Build queue to gather results from every subsets job (results multiple subsets) qJobResults = Queue() if nbrJobs == 1: # One job (typically X < 500) probably faster without multiprocessing print("Will run as 1 job.") ssStart = 0 ssEnd = totSS callNbr = 1 processSubsets(callNbr, qJobResults, ssStart, ssEnd, arrPowers, myX) result = nbrWays else: # More than one job (typically X > 500 or > 4M subsets) procs = [] callNbr = 0 # Must be false if nbrJobs == number of unique ranges myJobRanges = rangeSplitter(totSS, nbrJobs, False) print(myJobRanges) for oneJob in myJobRanges: callNbr = callNbr + 1 # Build Out range job parameters MyStart = oneJob[0] # Start Range MyEnd = oneJob[1] # End Range proc = Process(target=processSubsets, args=(callNbr, qJobResults, MyStart, MyEnd, arrPowers, myX)) # proc = Process(target=print("hi")) procs.append(proc) proc.start() print("Job ", callNbr, ": ", proc, proc.is_alive()) # Waite for all jobs to complete jobDone = 0 print("Job completed count = ", jobDone) while jobDone != myJobRanges: result = [] print("In loop ..") for proc in procs: print(jobDone, " | ", result, " | ", proc, proc.is_alive()) result = qJobResults.get() print("Polled Q ..") for proc in procs: print(jobDone, " | ", result, " | ", proc, proc.is_alive()) if len(result) != 0: print("Job Completed: ", result) jobDone = jobDone + 1 print("Job completed count = ", jobDone) # complete the processes for proc in procs: proc.join() print(proc, proc.is_alive()) return # -------------------------------------------------- # Driver Code # -------------------------------------------------- if __name__ == '__main__': global sSetLimit global nbrWays sSetLimit = 1024 * 8 # Test Value # sSetLimit = 1024 * 1024 * 4 # Normal Value X = 180 N = 2 TotWays = powerSum(X, N) print("X = ", X, " N = ", N, " Result = ", nbrWays)
2cc6154799ccae67f873423a981c6688dc9fb2b5
paulc1600/Python-Problem-Solving
/H22_migratoryBirds_final.py
1,740
4.375
4
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: You have been asked to help study the population of birds # migrating across the continent. Each type of bird you are # interested in will be identified by an integer value. Each # time a particular kind of bird is spotted, its id number # will be added to your array of sightings. You would like # to be able to find out which type of bird is most common # given a list of sightings. Your task is to print the type # number of that bird and if two or more types of birds are # equally common, choose the type with the smallest ID # number. # --------------------------------------------------------------------- # PPC | 09/02/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # migration def migratoryBirds(myArr): migStats = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} maxBird = 0 maxCount = 0 for birdType in myArr: migStats[birdType] = migStats[birdType] + 1 if migStats[birdType] > maxCount: maxBird = birdType maxCount = migStats[birdType] elif migStats[birdType] == maxCount and birdType < maxBird: maxBird = birdType return maxBird if __name__ == '__main__': n = 6 # ar = [1, 4, 4, 4, 5, 3] # result = migratoryBirds(ar) ar = [1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4] result = migratoryBirds(ar) # ar = [5, 5, 2, 2, 1, 1] # result = migratoryBirds(ar) print(result)
dbfbeb14f596bb7c893440d263b581ddc7047199
paulc1600/Python-Problem-Solving
/H17_kangaroo.py
2,208
3.984375
4
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: You are choreographing a circus show with various animals. # For one act, you are given two kangaroos on a number line # ready to jump in the positive direction (i.e, toward # positive infinity). # o The first kangaroo starts at location x1 and moves # at a rate of v1 meters per jump. # o The second kangaroo starts at location x2 and moves # at a rate of v2 meters per jump. # # You have to figure out a way to get both kangaroos at the # same location at the same time as part of the show. If it # is possible, return YES, otherwise return NO. # --------------------------------------------------------------------- # PPC | 08/30/2019 | Original code. # --------------------------------------------------------------------- import math import os import random import re import sys # J = (x2 - x1) / (v1 - v2) # where J is positive jump where kangaroos are together # if J is negative then starting conditions mean never catch up def kangaroo(x1, v1, x2, v2): if (v1 != v2): jump = (x2 - x1) // (v1 - v2) rem = (x2 - x1) % (v1 - v2) print("Kangaroo 1 starts at ", x1, " and jumps ", v1, " m/j.") print("Kangaroo 2 starts at ", x2, " and jumps ", v2, " m/j.") print("Magic jump is ", jump, rem) elif (x1 == x2): jump = 0 rem = 0 # Kangaroos jump in synch, and both start from same spot print("Kangaroo 1 starts at ", x1, " and jumps ", v1, " m/j.") print("Kangaroo 2 starts at ", x2, " and jumps ", v2, " m/j.") print("Magic jump is ", jump, rem) else: jump = -1 rem = 0 # Kangaroos jump in synch, and start from different spots # No jumping backward, and No partial jumps allowed if jump >= 0 and rem == 0: print("YES") else: print("NO") return if __name__ == '__main__': x1 = 0 v1 = 2 x2 = 5 v2 = 3 result = kangaroo(x1, v1, x2, v2)
49b44f2440ab260a432f2cb269e064d03712aeda
iiivvv/alg
/Хэширование/L3Z2.py
316
3.671875
4
def convert( s1 ) : return ( s1[ 0 ].split() ) s1 = [' Сегодня вечером мы с моим другом видели красивый алый закат '] b = convert( s1 ) s2 = [ ' R ' , ' k ' , ' r ' , 9 , ' m ' , ' I ' , ' S ' , 8 , ' A ' , ' O ' ] for a in zip( b , s2 ) : print( a )
02aece42d770b2fada73eeb263f196ca6d89dd54
826167518/python
/ceshi/zuqiu.py
365
4
4
#!/usr/bin/env python # -*- conding:utf-8 -*- x = str(raw_input("Enter sex m/f: ")) if x == "f" or x == "F": n = float(raw_input("Enter age : ")) if n >= 10 and n <= 12: print "Congratulations, you can join the team!!!" else: print "Unfortunately, you do not meet the requirements!" else: print "Unfortunately, you do not meet the requirements!"
41f531a819c7ece1e66b9d612375c801dd28f863
hydrotop/PythonStudy
/test/098.py
317
3.828125
4
strdata=input('정렬할 문자열을 입력하세요.') ret1=sorted(strdata) ret2=sorted(strdata,reverse=True) print(ret1) print(ret2) ret1="".join(ret1) ret2="".join(ret2) print('오름차순으로 정렬된 문자열은 <'+ret1+'>입니다.') print('내림차순으로 정렬된 문자열은 <'+ret2+'>입니다.')
9e5ab200350e382951898ec6046ca094abb8f5fa
aniszahrodl/Praktikum-Chapter-08
/LATIHAN/12.py
2,405
3.75
4
def dataBuah(): print('>>>>DAFTAR HARGA BUAH<<<<') for x,y in buah.items(): print('-',x,'(Harga: Rp.', y,')') print('') def tambah(): print('Masukkan nama buah yang ingin ditambahkan:',end='') nama=input() if nama in buah: print('Buah',nama,'sudah ada di dalam daftar') else: print('Masukkan harga satuan:',end='') harga=int(input()) buah[nama]=harga print('') global TambahLagi TambahLagi=input('Tambah data lagi? (y/n):') print('') def beli(): try: print('Buah yang ingin dibeli:',end='') A=input() print('Berapa Kg:',end='') B=int(input()) p=buah[A] Total= p*B List.append(Total) print('') global BeliLagi BeliLagi=input('Beli lagi? (y/n):') print('') except KeyError: print('Buah tidak tersedia') print('') lagi=input('Beli lagi? (y/n):') print('') def hapus(): try: print('Nama buah yang ingin dihapus:',end='') hapus=input() del buah[hapus] global hapusLagi hapusLagi=input('Ada yang ingin dihapus lagi?(y/n):') print('') except KeyError: print(hapus,'tidak ada di daftar buah') hapusLagi=input('Ada yang ingin dihapus lagi?(y/n):') print('') def menu(): print('*****MENU*****') print('A. Tambah data buah') print('B. Beli buah') print('C. Hapus data buah') pilih=input('Pilihan Menu:') print('') if pilih=='A': tambah() while TambahLagi=='y': tambah() if TambahLagi=='n': dataBuah() elif pilih=='B': dataBuah() beli() while BeliLagi=='y': beli() if BeliLagi=='n': sum=0 for i in range(len(List)): sum+=List[i] print('--------------------------') print('TOTAL HARGA: Rp.',sum) elif pilih=='C': dataBuah() hapus() while hapusLagi=='y': hapus() if hapusLagi=='n': dataBuah() print('') global kembali kembali= str(input('Kembali ke Menu? (y/n):')) List=[] buah={'apel':5000, 'jeruk':8500, 'mangga':7800, 'duku':6500} menu() while kembali=='y': menu() if kembali=='n': break
7848000793ffb7f8426d7d95f0eea4645e63b0b2
aniszahrodl/Praktikum-Chapter-08
/LATIHAN/13.py
901
3.71875
4
print(' DAFTAR NILAI MAHASISWA') print('----------------------------------------------------') nilaiMhs = [{'nim' : 'A01', 'nama' : 'Amir', 'mid' : 50, 'uas' : 80}, {'nim' : 'A02', 'nama' : 'Budi', 'mid' : 40, 'uas' : 90}, {'nim' : 'A03', 'nama' : 'Cici', 'mid' : 50, 'uas' : 50}, {'nim' : 'A04', 'nama' : 'Dedi', 'mid' : 20, 'uas' : 30}, {'nim' : 'A05', 'nama' : 'Fifi', 'mid' : 70, 'uas' : 40}] MID=[] UAS=[] nilai=[] for i in range(len(nilaiMhs)): a=nilaiMhs[i] print(a) b=a['mid'] MID.append(b) d=a['uas'] UAS.append(d) for x in range(len(MID)): nilaiAkhir=(MID[x]+(2*UAS[x]))/3 nilai.append(nilaiAkhir) Max=nilai.index(max(nilai)) p=nilaiMhs[Max] nim=p['nim'] nama=p['nama'] print('') print('Mahasiswa yang mendapat nilai akhir paling tinggi adalah:') print('- NIM:',nim) print('- Nama:',nama)
e955679387cd90ad3e5dfbbff7f941478063823d
Hajaraabibi/s2t1
/main.py
1,395
4.1875
4
myName = input("What is your name? ") print("Hi " + myName + ", you have chosen to book a horse riding lesson, press enter to continue") input("") print("please answer the following 2 questions to ensure that you will be prepared on the day of your lesson.") input("") QuestionOne = None while QuestionOne not in ("yes" , "no"): QuestionOne = str(input("have you got your own helmet? ")) if QuestionOne == "yes": print("great!") elif QuestionOne == "no": input("To rent a riding hat, you will have to pay a fee of £4 every lesson. Are you size small, medium or large? ") print("thank you") else: print("please enter yes or no") input("") QuestionTwo = None while QuestionTwo not in ("yes" , "no"): QuestionTwo = str(input("have you got your own riding shoes? ")) if QuestionTwo == "yes": print("great!") elif QuestionTwo == "no": print("To rent riding shoes, you will have to pay a fee of £5 every lesson.") else: print("please enter yes or no") input("") print("SUMMARY: For riding hat you chose: " + QuestionOne + " for riding shoes you chose: " + QuestionTwo + ".") Payment = input("To continue to payment, please type 'yes': ") if Payment == "yes": print("Thank you!") else: print("you have chosen not to go ahead with payment. see you again next time!")
93e2e4f5475a8cfc451625e077d618348447a121
chabeerabsal/python
/program.py
6,087
3.796875
4
# decimal to binary num=int(input('enter no')) binary='' while num>0: rem=num%2 binary=str(rem)+binary #print(rem) num=num//2 else: print(binary) print(1%2) # binary to decimal import math no=int(input('enter no')) power=int(input('enter no')) print(math.pow(no,power)) no=int(input('enter no')) decimal=0 i=0 while no>0: rem=no%10 value=rem*int(math.pow(2,i)) decimal=decimal+value no=no//10 i+=1 else: print(decimal) # 3 table start=1 while start<=100: if start%3==0: print(start) start+=1 #prime number no=int(input('enter a number')) div=2 while div<no: if no%div==0: print('not prime') break div+=1 else: print('prime') # nestted loop row=5 while row>=1: col = 1 while col<=row: print('*', end=(' ')) col+=1 col2=5 while col2>=row: print(row,end='') col2-=1 print() row-=1 #string s='python is very very easy' position=-1 length=len(s) print(length) count=0 while True: position=s.find('y',position+1,length) if position==-1: break print(position) count+=1 # count using for name='chabeer absal' print(name.count('a',8,11)) name=name.replace('c','a') print(id(name)) print(id(name)) print(name) # string is immutable s='python is very easy' print(s.upper()) print(s.lower()) print(s.swapcase()) print(s.title()) print(s.capitalize()) print(s[0:-1]+s[-1].upper()) mailid=input('enter your email id') i=0 while i<len(mailid): if not mailid[i]>='0' and mailid[i]<='9': print(mailid[i],end='') i+=1 print() for x in mailid: if not x>='a' and x<='z': if not mailid[i] >= '0' and mailid[i] <= '9': print(mailid[i], end='') print(x,end='') i+=1 a=[1,2,3,4,5,5,5,5,5] print(len(a)) a.append(500) print(a) print(a.count(5)) count=0 while count<=len(a): if count==5: print(count) count+=1 print(a.index(4)) list=[] for no in range(1,60): if no%2==0: list.append(no*no) print(list) l=[0,1,2,3,4,56,77,8] l.insert(3,250) l.insert(-1,2000) print(l) print(chr(65)) l1=['a','b','c'] print(id(l1)) l2=[1,2,3] l1.extend(l2) print(l1) l1.extend('chabeer') print(l1) #functions l=[10,20,30,40] l.pop() print(l) print(id(l)) l3=[20,30,40,60] print(id(l3)) l2=l.copy() print(l2) print(id(l2)) l.extend(l3) print(l) print(id(l)) l3.clear() print(l3) l.remove(20) l.reverse() print(l) s1=input('enter first number') s2=input('enter 2 number') comb='' i,j=0,0 while i<len(s1) or j<len(s2): if i<len(s1): comb=comb+s1[i]#chabeer i+=1 if j<len(s2): comb=comb+s2[j]#absal j+=1 print(comb) # input a5b6c7 #output abc567 i='a5b6c7' o='' p='' for x in i: if x.isalpha(): o=o+x else: p=p+x o=o+p print(o) #tuble t=(10,20,30,40,50,60,70,70,90) print(t.count(60)) print(t[-1]) print(t[2:5]) print(t[::2]) t1=(20,50,70,90,100,45) tt2=(964,86,879,00) print(t1+tt2) print(t1*0) print(len(t)) print(t.index(30)) print(sorted(t,reverse=True)) print(min(t)) print(max(t)) print(sum(t)) a,b,c,d=10,20,30,40 t=a,b,c,d print(t) p,q,r,s=t print(q) a=(i**i for i in range(1,6)) for value in a: print(value,end=' ') print() print(type(a)) d=0 while d<4: t=eval(input('enter')) print(t) d+=1 # dictionary d={} d[123]='chabeer' d[124]='absal' print(d) d1={1234:'chabeer',12345:'absal',12346:'absal',654:'aravinth',546:'harish'} print(d1) d1[345]='me' print(d1) del d1[345] print(d1) print(len(d1)) print(d1.get(1234)) print(d1.get(123456)) d1.pop(1234) print(d1) print(d1.popitem()) print(d1) s={10,20,30,40,50} e={20,30,40,60,70} print(e) print(s & e) print(type(s)) s.add(35) s.remove(20) print(s) a={} print(type(a)) f=s.clear() print(f) print(tuple(e)) g=[10,20,30] g[2]=37 print(g) print(dir(e)) o={345,757,976} #bublle sort # [12345]=[15246784l l=[1,0,5,6,3,8,6,9] r=len(l)-1 for n in range(0,r): if l[n]>l[n+1]: result=l[n],l[n+1]=l[n+1],l[n] print(result) def getusernamepassword(username,password): if username!='abcd': print('invalid username') username=input('enter username') password=input('enter password') elif password!='abcd': print('invalid password') username=input('enter username') password=input('enter password') else: print('correct') username=input('enter username') password=input('enter password') getusernamepassword(username,password) def display(n): print(n) n+=1 if n<=5: display(n) display(1) z=4 x=5 y=5 def chabeer(): global d d=5 return x+y+z+d ans=chabeer() print(ans) print(x+y+z+d) def division(): try: no1=int(input('enter no')) no2=int(input('enter no')) print(no1+no2) except: print('give no') finally: print('hi') division() division() def division(): try: no1=int(input('enter no')) no2=int(input('enter no')) print(no1+no2) except: print('give no') finally: print('hi') division() division() import os,sys filename=('D:/python/iam.txt') if os.path.isfile(filename): f=open(filename,'r') print('file is present') linecount=wordcount=charcount=0 for line in f: #print(line) w=line.split() wordcount=wordcount+len(w) linecount+=1 import csv with open('D:/python/student.csv','w',newline='') as file: reynolds=csv.writer(file) reynolds.writerow(['srd','snname','stuaddress']) count=int(input('enter no of students')) for i in range(count): sid=int(input('enter student id')) sname=input('enter student name') saddress=input('enter address') reynolds.writerow([sid,sname,saddress]) import re def mobileno(sentence): mobilenumber=re.compile('(91[6-9][0-9]{9})') number=mobilenumber.findall(sentence) return number sentence='my mobile no is 918234567890 and 918888888888,917345678990' number_present=mobileno(sentence) print(type(number_present)) for number in number_present: print(number)
5af4dd76f666dfc971b96135f7e31bc1d945e3cf
nurriol2/startup_scripts
/python/make.py
1,168
3.515625
4
#!/usr/bin/env python3 #module that allows access to command line input import sys import os from github import Github #module that hides typed keys; only use via command line from getpass import getpass #path to projects directory on machine path = "/Users/nikourriola/Desktop/projects/" #prompt for github username and password username = input("username: ") password = getpass("password: ") def make(): """ Create a Github repository at specified path Parameters: None Returns: None """ #project name given as first argument after calling shell script project_name = str(sys.argv[1]) #create a directory for the repo os.makedirs(path + project_name) if not os.path.isdir(path+project_name): print("Directory {} not created".format(project_name)) return #create instance of your account using username and password user_account = Github(username, password).get_user() #create a repo with project name repository = user_account.create_repo(project_name) print("Sucessfully created repository {}".format(project_name)) return if __name__ == "__main__": make()
5fc8770f4652613aa2c1ee2de68a320a0d07ffad
jeetmeena/PyFun-Backend
/stage/Help with more python lessons for beginners (Part 5).py
4,018
4.4375
4
##Variable Type ##Strings are defined either with a single quote or a double quotes veriable_name="string" #example 1 mystring = 'hello' print(mystring) mystring = "hello" print(mystring) ##python supports two types of numbers - integers and floating point numbers ver_name=4 #integer ver_name=4.0 #float ##Long integer number, use of L or l makes variable as long integer var_name = 12L ##The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, #while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. #Tuples can be thought of as read-only lists #!/usr/bin/python tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times print tuple + tinytuple # Prints concatenated lists ##Python Lists #!/usr/bin/python list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists ##Python Dictionary #Python's dictionaries are kind of hash table type. #!/usr/bin/python dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # Prints value for 'one' key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values ##Condition #if Statements The syntax of the if...else statement is − if expression: statement(s) else: statement(s) ## Example 1 Live Demo #!/usr/bin/python var1 = 100 if var1: print "1 - Got a true expression value" print var1 else: print "1 - Got a false expression value" print var1 var2 = 0 print "Good bye!" ## Example 2 #!/usr/bin/python var = 100 if var == 200: print "1 - Got a true expression value" print var elif var == 150: print "2 - Got a true expression value" print var else: print "4 - Got a false expression value" print var print "Good bye!" ##Loop ##Syntax of for Loop #for val in sequence: # Body of for ##For Example # Program to find the sum of all numbers stored in a list # List of numbers numhttps://www.programiz.com/python-programming/for-loopbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum sum = 0 # iterate over the list for val in numbers: sum = sum+val # Output: The sum is 48 print("The sum is", sum) ## Example OF While #The syntax of a while loop in Python programming language is − #while expression: # statement(s) #!/usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!" ## Function #Syntax #def functionname( parameters ): # "function_docstring" # function_suite # return [expression] # Example #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist #Example 2 #!/usr/bin/python # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 )
7b5ecddd9dd286db5182d1f9754dd30dcafc8481
wujunwei928/python_study
/before_2016/2015-07/demo1.py
1,392
3.9375
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ # 指定字符编码的上面不能有空行, 否则报错 print 'Hello Python' #老版本直接print print('测试') #新版本要print()函数, 文件中有中文的话, 文件开头要指定utf-8编码 # python中每条语句结尾的分号,可写可不写 print('hello'); # 但是如果一行中有多条逻辑语句的时候,必须以分号隔开,最后一条语句的分号可以省略 # 在python中, 一般每行语句最后的分号省略不写 print( 1+ 8);print( 3* 6) # 定义整型变量 x=y=z=10; print(x*y*z); # ** 幂运算 print( 3** 3) #3**3: 3的3次方 # Python中整除运算最终值取的是中间值的floor值 print( 7/- 3) #输出: -3 print( 7%- 3) #输出: -2 print('中文') print('hello, %s') % 'world' print('Hi, %s, you have $%d.') %('wujunwei', 10000) print('%2d-%02d') %(3,1) print('%.2f') % 3.1415926 # python函数,分支结构初探 def getScoreDesc (score): if score>=90: # python中没有switch,没有else if,elseif, print '优秀' #python中的分支关键字: if, elif, else elif score>=60 and score<90: # python中的逻辑运算符 and, or, not print '一般' # python中没有 &&, || 运算符 else: print '不及格' getScoreDesc(90) # 调用函数 #python中只有for, while循环, 没有do...while循环
df7e5dd7708411aea3f749997255bea5d5a8dd13
Beisenbek/pp2-lecture-samples-2020
/week5/today/4.py
81
3.5
4
import re text = "av" pattern = r"a+" res = re.match(pattern, text) print(res)
062f7f2539365c4e0144505720dc34cac5a22900
Beisenbek/pp2-lecture-samples-2020
/week2/dicts/4.py
72
3.59375
4
thisdict = {1:"a",2:"b"} for x, y in thisdict.items(): print(x * x, y)
e875f00f7f0f68d28aad89d0747c1bdc5e323fdc
mur6/exercises
/wordcount/wordcount.py
422
3.6875
4
from pathlib import Path import sys def wordcount(path): with path.open() as fh: lines = 0 words = 0 chars = 0 for line in fh: chars += len(line) words += len(line.split()) lines += 1 print(f"chars={chars} words={words} lines={lines} {path}") if __name__ == '__main__': for filename in sys.argv[1:]: wordcount(Path(filename))
059ab3e13f6f705db7e90b7b3d37c5e9b81a8539
anupamking01/image-processing
/distance.py
365
3.703125
4
# import math px, py = map(int, input("enter coord of p: ").split()) qx, qy = map(int, input("enter coord of q: ").split()) print("eucledian distance between 2 pixels is:",((px-qx)**2 + (py-qy)**2)**(0.5)) print("manhattan distance between 2 pixels is:",abs(px-qx) + abs(py-qy)) print("chess-board distance between 2 pixels is:",max(abs(px-qx),abs(py-qy)))
d74028fef519ab339955a57ab32d9502236c59ec
MangoMaster/chinese_pinyin_input_method
/src/char2/convert_pinyin.py
3,544
3.671875
4
import copy import json def load_table(table_path): """ Load table from table_path. Args: table_path: Path to the source table json file. Returns: table, a datastructure converted from json file. """ with open(table_path, 'r') as f: return json.load(f) def convert_pinyin(pinyin, pinyin_char_table, pinyin_pinyin_char_char_table): """ Convert pinyin to Chinese sentence. Args: pinyin: A string, a sentence of pinyin separated by space. pinyin_char_table: pinyin-char table, a dict, key->pinyin, value->[[char, log(probability)]. pinyin_pinyin_char_char_table: pinyin-pinyin-char-char table, a dict, key->str(pinyin1-pinyin2-char1-char2), value->log(probability) Returns: A string of Chinese characters converted from pinyin. """ # Dynamic programming strategy. pinyin_list = pinyin.split(' ') if not pinyin_list or pinyin_list == ['']: return "" # 'lue' should be 'lve' and 'nue' should be 'nve' in standard Chinese pinyin. pinyin_list = ['lve' if pinyin_single == 'lue' else 'nve' if pinyin_single == 'nue' else pinyin_single for pinyin_single in pinyin_list] dynamic_programming_table = [[] for _ in range(len(pinyin_list))] # dynamic_programming_table:二维数组,记录pinyin_list[:stop_index+1]的最优解 # 第一维为stop_index,第二维为list(总句,总句probability,尾字pinyin,尾字probability) pinyin_whole = pinyin_list[0] assert pinyin_whole in pinyin_char_table for char_whole, char_probability_whole in pinyin_char_table[pinyin_whole]: dynamic_programming_table[0].append( [char_whole, char_probability_whole, pinyin_whole, char_probability_whole]) for stop_index in range(1, len(pinyin_list)): pinyin_back = pinyin_list[stop_index] # Single pinyin will never fall out of pinyin_char_table assert pinyin_back in pinyin_char_table for char_back, char_probability_back in pinyin_char_table[pinyin_back]: # Pushes one sentence for every char_back max_sentence = [ "", float("-inf"), pinyin_back, char_probability_back] for sentence_front, sentence_probability_front, pinyin_front, char_probability_front in dynamic_programming_table[stop_index - 1]: pinyin_char_pair = '-'.join( (pinyin_front, pinyin_back, sentence_front[-1], char_back)) # log(probability), so * => + , / => - if pinyin_char_pair in pinyin_pinyin_char_char_table: sentence_probability = ( sentence_probability_front + pinyin_pinyin_char_char_table[pinyin_char_pair] - char_probability_front) else: # Add a punishment to increase accuracy sentence_probability = sentence_probability_front + char_probability_back - 2 if sentence_probability > max_sentence[1]: max_sentence[0] = sentence_front + char_back max_sentence[1] = sentence_probability assert max_sentence[0] != "" dynamic_programming_table[stop_index].append(max_sentence) max_sentence = ("", float("-inf")) for dp_node in dynamic_programming_table[-1]: if dp_node[1] > max_sentence[1]: max_sentence = (dp_node[0], dp_node[1]) assert max_sentence[0] != "" return max_sentence[0]
2b73a75901607565c0aeaf785bdbc16b79d29a81
Teju-mestry/PracticePython
/Exercise-Solution-Functions-Medium.py
349
4
4
# Define a function that adds two numbers and returns the result def returnSum(numberOne, numberTwo): return(numberOne + numberTwo) # Declare two numbers numberOne = 10 numberTwo = 20 # Declare a variable that would store the result of the returned function additionResult = returnSum(numberOne, numberTwo) print(additionResult) # Output => 30
20aae63f1956a2211f853bf1d509205904db4451
Teju-mestry/PracticePython
/Marks apprecition.py
1,202
3.96875
4
import operator x = int(input("how many students are present in class?")) name = [] marks = [] dic ={} if x>=3: for i in range(0,x) : n = input("Name of student {} = ".format(i+1)) name.append(n) m = int(input("Marks of student {} = ".format(i+1))) marks.append(m) dic.update({name[i]:marks[i]}) else: print("Number of student must be atleast 3") dics = dict( sorted(dic.items(), key=operator.itemgetter(1),reverse=True)) tup = ("$500","$300","$100") print("Congratulations! {}.You got first rank in class with {} marks And you rewarded with {}.".format(list(dics.keys())[0],list(dics.values())[0],tup[0])) print("Congratulations! {}.You got second rank in class with {} marks And you rewarded with {}.".format(list(dics.keys())[1],list(dics.values())[1],tup[1])) print("Congratulations! {}.You got third rank in class with {} marks And you rewarded with {}.".format(list(dics.keys())[2],list(dics.values())[2],tup[2])) for i in range(0,x): if list(dics.values())[i] >= 950 : print("{} your work is appreciable.Keep it up.".format(list(dics.keys())[i])) input("Press enter")
bcb7617ed059bbed6382b21a51ea43de2a406f10
maxfer1221/rpi-bluetooth-tests
/findmyphone.py
443
3.515625
4
import bluetooth target_name = "AL HydraMotion" target_address = None nearby_devices = bluetooth.discover_devices() print(nearby_devices) for bdaddr in nearby_devices: if target_name == bluetooth.lookup_name( bdaddr ): target_address = bdaddr break if target_address is not None: print("found target bluetooth device with address ", target_address) else: print("could not find target bluetooth device nearby")
594d1a8d21079af653535af2c0617d866d2537e5
xingleigao/study
/python/base-knowloage/for/test2.py
167
3.65625
4
#!/usr/bin/python #coding =utf-8 fruits = ['banana','apple','mango'] for index in range(len(fruits)): print('当前水果 : %s'%fruits[index]) print ('Good bye!')
251aac02f6cc42c6b3146adc6bf2a8d314e32d9a
xingleigao/study
/python/base-knowloage/tuple/del.py
129
3.640625
4
#!/usr/bin/python # codingg = utf-8 top = ('physics','chemistry',1997,2000) print(top) del top print('After deleting top:',top)
ea9baf6807a757adca26d6e0d8d295afbd41166c
xingleigao/study
/python/base-knowloage/function/tests7.py
278
4.09375
4
#!/usr/bin/python # coding = utf-8 #可写函数说明 def printinfo( arg1, *vartuple ): "打印任何传入的参数" print('输出:') print(arg1) for var in vartuple: print(var) return #调用printinfo函数 printinfo( 10 ) printinfo( 70, 60, 50)
428daa8b1f6ad9dac313e849435390ce05155f2e
xingleigao/study
/python/base-knowloage/tuple/test1.py
139
3.734375
4
#!/usr/bin/python top1 = ('physics','chemistry',1997,2000) top2 = (1,2,3,4,5,6,7) print('top1[0]:',top1[0]) print('top2[1:5]:',top2[1:5])
c2524e59714f938836553a0c964ab7936ca2058e
xingleigao/study
/python/base-knowloage/if/elif.py
208
3.75
4
#!/usr/bin/python #coding = urf-8 num = int(input()) if num ==3: print('boss') elif num ==2: print('user') elif num ==1: print('worker') elif num <0: print ('error') else: print ('rodman')
27279a639ce31e647b7d18a6e05f1678c494d5cf
SerialSata/ITEA-PythonBasic
/lect 4 work.py
3,856
4.15625
4
# import random # # MAX_TRIES = 5 # secret = random.randint(1, 10) # tries = 0 # # is_guessed = False # # while tries < MAX_TRIES: # try: # guess = int(input('You have 5 tries. Guess a number: ')) # except ValueError: # print("Please, provide a number between 1 and 10") # continue # tries += 1 # if secret == guess: # print("You're right! Congratulations!") # # is_guessed = True # break # if secret < guess: # print("Little less") # else: # print("Little more") # else: # print('You are looser!') # # if not is_guessed: # # print ('You are looser!') # =================================================== # import random # # min_limit = 1 # max_limit = 10 # MAX_TRIES = 5 # tries = 0 # # print("I want to guess a number between 1 and 10, let's try!") # while tries < MAX_TRIES: # tries += 1 # random_guess = random.randint(min_limit, max_limit) # print(random_guess) # guess = input("Am i right? Input 'yes', '>' or '<'") # if guess == 'yes': # print('Woohoo! I win!') # break # elif guess == '<': # max_limit = random_guess # elif guess == '>': # min_limit = random_guess # else: # print("i didn't understand!") # guess = input("Am i right? Input '>' or '<'") # else: # print("Too bad :( But ok, let's try one more time!") # =================================================== # import copy # l = [1,2,[1,2,3]] # l1 = l[:] # l1 = list(l) # l1 = copy.deepcopy(l) # print(list(range(10))) # print(list(range(2,10,2))) # =================================================== # for i in range(100000): # if i*i >=50: # break # print(i, i*i) # for index, value in enumerate("hello"[3:8], 2): #2 - Начало нумерации # print(index, value) # L = [1,2,3,4,5] # x=input() # for i in L: # if i == x: # print ('yes') # break # else: # print ('no') # L = [x*x for x in range(10) if x%2] # print (L) # =================================================== ''' ДЗ 1. сделать автомат с разменом монет на циклах 2. найти произведение элементов списка, минимальный и максимальный элемент списка 3. найти 2 одинаковых элемента в списке 4. поменять местами мин и макс элементы списка 5. Сдвиг на 1 элемент в списке, циклический сдвиг ''' import random L = [] for i in range(10): L.append(random.randint(1, 100)) print('List: ', L) print("========= Composition of all list members =========") composition = 1 for i in L: composition *= i print('Composition: ', composition) print("========= Find min & max =========") min_elem = max_elem = L[0] iterator = min_place = max_place = 0 for i in L: if i < min_elem: min_elem = i min_place = iterator if i > max_elem: max_elem = i max_place = iterator iterator += 1 print('Min element: ', min_elem, '; Max element: ', max_elem) print("========= Сhange places in list for min max elements =========") L[min_place] = max_elem L[max_place] = min_elem print(L) print("========= Move for 1 list element to left =========") for i in range(len(L)): if i == 0: continue else: L[i - 1] = L[i] L.pop(len(L) - 1) print(L) print("========= Cycling all list members =========") CYCLE_COUNT = int(input("Input needed cycles count: ")) z = 0 print('Initial list: ', L) while z < CYCLE_COUNT: first_elem = L[0] for i in range(len(L)): if i == 0: continue else: L[i - 1] = L[i] L.pop(len(L) - 1) L.append(first_elem) print(L) z += 1
3963af4f201ab605c818b0307db4611ae722015c
noorulislam770/guass_seidel
/simple.py
8,258
4.125
4
import math def main(): get_equations() def get_equations(): eq1 = ["5x1","-2x2","3x3","-1"] eq2 = ["-3x1","9x2","1x3","2"] eq3 = ["2x1","-1x2","7x3","3"] print("steps to enter equations : ") print("Enter each coeff of x1 x2 and so on as ") print("1 -1 2 0 0 1 and write 0 if there is no coeff " ) print("and add a comma after every row like : ") print("1 2 -1 ,1 0 2,9 23 9") equat = input("Please Enter all the equation in above manner : ") equat = equat.lstrip() equat = equat.rstrip() equat_row = equat.split(",") # eq1 = ["1x1","-2x2","5x3","1"] # print(equat_row) equations_elems = [row.split(" ") for row in equat_row] print(equations_elems) for row in equations_elems: for i in range(len(equations_elems)): row[i] = row[i] + "x" + str(i+1) print(equations_elems) # eq2 = ["-3x1","9x2","1x3","2"] # eq3 = ["9x1","-1x2","7x3","3"] equations = equations_elems strictly_daignoally = reorder_eq(equations) print("Rows Rearranged after performing Row Operations.") print(strictly_daignoally) calculate(strictly_daignoally) # 22 109 2 42 6 23,100 2 3 44 3 23,23 7 7 4 99 4,12 4 66 3 -1 34,32 45 9 145 9 34 def reorder_eq(equations): fullcoeffients = [extract_coeffs(equation) for equation in equations] coeffients = fullcoeffients print(coeffients,"coeffeints inside reorder_eq") new_coeffs=[] for coeff in coeffients: new_coeffs.append(coeff[0:-1]) coeffients = new_coeffs # [[-4, 5], [1, 2]] print(coeffients," INSIDE ") i = 0 reordered_matrix = coeffients print(reordered_matrix, "Re-ordered matrix ") # [[-4, 5], [1, 2]] for c in reordered_matrix: print("coeffient ", c)# [-4 5], [1 2] # print("index ", i) coeffient = c if reordered_matrix.index(coeffient) == i and coeffient[i] != 0: # print (True) num_index = 0 for num in coeffient: if math.fabs(num) > abs_of_rest(c,num_index): if c.index(num) == len(c): # print("inside of if last ") reordered_matrix.remove(c) reordered_matrix.append(c) else: # print("inside of if not last ") reordered_matrix.remove(c) reordered_matrix.insert(coeffient.index(num),c) else: for num in coeffient: if math.fabs(num) > abs_of_rest(c,c.index(num)): if c.index(num) == len(c): # print("inside of if last ") reordered_matrix.remove(c) reordered_matrix.append(c) else: # print("inside of if not last ") reordered_matrix.remove(c) reordered_matrix.insert(coeffient.index(num),c) # for i in range # reordered_matrix = [[reordered_matrix.append(equation[-1]) if (equation[i] == reordered_matrix[i]) ] for i in range (len(reorder_eq) - 1) for equation in equations ] temp_reordered_list = [] for re in reordered_matrix: temp_row = [] # print(re) for temp in fullcoeffients: # print(temp[0:-1]) if re == temp[0:-1]: temp_row = re temp_row.append(temp[-1]) temp_reordered_list.append(temp_row) # print(temp_row) reordered_matrix = temp_reordered_list return reordered_matrix def extract_coeffs(equation): print(equation,"equation inside extract_coeff() method") # temp_eqs = [equation[0].split("x")[0],equation[1].split("x")[0],equation[2].split("x")[0],equation[3]] # temp_eqs = [] temp_eqs = [] for elem in equation: if elem.find("x") != -1: e = elem.split("x")[0] temp_eqs.append(e) else: temp_eqs.append(elem) print("Temp Eqs",temp_eqs) # this will generate theese values and pass to the calling function # Temp Eqs ['0', '-2', '5', '1'] # Temp Eqs ['-3', '9', '1', '2'] # Temp Eqs ['9', '-1', '7', '3'] return [int(eq) for eq in temp_eqs] # return def abs_of_rest(row,index): newlist = [] for x in range(len(row)): if x != index: newlist.append(row[x]) total = 0 for num in newlist: total += math.fabs(num) # print(total) return total # 1 1 1 1,2 2 2 2,23 2 3 3 # 1 1 8 1 1,9 2 2 2 1,3 15 3 3 1 1,2 3 4 20 3 # 1 1 8 1 1 8,9 2 2 2 1 8,3 15 3 3 1 1 2,2 3 4 20 3 4,3 4 3 5 23 4 def calculate(matrix): print("inside calculate method") print(matrix," matrix") roeq = [e for e in matrix[-1]]; functions = [] rownum = 0 print("Matrix",matrix) for row in matrix: print(row,"this is row") columnnum = 0 leftofeq = 0 rightofeq = [] for coeff in row: # print("Row",row) # print(coeff,"coeffs") if rownum == columnnum: leftofeq = coeff elif columnnum == len(row)-1: # print("inside elif") rightofeq.insert(0,coeff) else: rightofeq.append(coeff*(-1)) # print(rightofeq,"rightofeq") # print(leftofeq,"leftofeq") columnnum += 1; # print("loop Done") completeeq = [num/leftofeq for num in rightofeq ] # completeeq.insert(0,roeq[rownum]/leftofeq) # print("completeeq") # print(completeeq) functions.append(completeeq) rownum += 1 # print("================ function = ==============") # print(functions); startCalculating(functions) def startCalculating(equations): print("\n\n\n +++++++++++++++++ inside the calculating function ++++++++++++++++") matrixlen = len(equations) variables = [0 for matrixlen in equations] print(equations,"Equations \n\n") # print(variables) # [[0.1111111111111111, -0.1111111111111111, 0.7777777777777778], # [-0.2222222222222222, -0.3333333333333333, 0.1111111111111111], [1.0, 0.2, -0.4]] # [[0.1111111111111111, -0.1111111111111111, 0.7777777777777778] # [0, 0, 0] # [1, 2, 3] answer_array = [] notdone = True while notdone: if len(answer_array) > 0: if variables == answer_array[-matrixlen*2:-matrixlen]: notdone = False if notdone == False: break counter = 0 print("equations") print(equations) for equation in equations: result = equation[0] #1 print(result,"result") tempeqs = equation[1:] tempvariables = [v for v in variables] print(variables,"normal variables") tempvariables.pop(equations.index(equation)) print(tempeqs,"temp eqs") # print(tempvariables,"temp vars") for i in range(matrixlen-1):#0,1,2 print(i) result += tempvariables[i] * tempeqs[i]#0.2 + 0 * 0.4 + 0 * .6\ 0.2 + 0.2 * 0.2 + 0* -1 # print() # print(result,"result") variables[equations.index(equation)] = result #[0]=0.4 answer_array.append(result)#[0.4] counter += 1; # print(variables, "variables") # print(counter) # print(answer_array) tempasnarray = [] for i in range(0,len(answer_array),matrixlen): tempasnarray.append(answer_array[i:i+matrixlen]) # print(tempasnarray) # print(answer_array) for i in range(len(variables)): spaces = 21 * " " print("x",i+1,end=spaces) print() bars = (len(variables) * 22) * "-" print(bars) counterrrr = 0 for row in tempasnarray: for i in range(len(row)): print(row[i],end=" , ") print() counterrrr += 1 print(variables) print(counterrrr) if __name__ == "__main__": main()
a3b8127727aab91acb49a0c57c81aa5bf8b7ea4a
atishay640/python_core
/comparison_oprators.py
363
4.28125
4
# Comparison operators in python # == , != , > , < >= ,<= a= 21 b= 30 c= a print(a==b) print(c==a) print(a>=b) print(a<=b) print(a<b) print('------------------------------------') # Chaining comparison operators in python # 'and' , 'or' , and 'not' print(a == b and b == c) print(a == b or a == c) print(not a == 21) print(True and True ) print(not False)
fd7715910c9fee1405c6599869252b112b098520
atishay640/python_core
/dictionary.py
891
4.4375
4
# Dictionary in python # It is an unordered collection # Used 'key'-'value' pairs to store values. # it is identified with {} print("**********dictionary in python") students_dic = {1 : 'Atishay' ,2 : 'Vikas' ,3 : 'Aakash' } print(students_dic) print("**********fetch value in python") print(students_dic[2]) print("**********nested list in dictionary in python") students_dic[4] = ['107 Simran sun' , 'indore' ,'mp'] print(students_dic) print("********** fetch nested list element in dictionary in python") print(students_dic[4][1]) print("********** modify nested list element in dictionary in python") students_dic[4][2] = 'M.P.' print(students_dic[4][2]) print("********** dictionary methods in python") print("********** keys()") print(students_dic.keys()) print("********** values()") print(students_dic.values()) print("********** items()") print(students_dic.items())
22e758582061d1f3f911afd3008c87b9e8c00bf3
atishay640/python_core
/variable_assignment.py
360
3.96875
4
# Variable assignment # # # # # # # # # # # # a = 5 print(a) print("-----------") print (a+a) print("-----------") a = 15 ; print(a) print("-----------") a=a + a print (a) print("----Power-------") print(5**5) print("-----Yearly Income calcultor------") income = 15000 months_in_a_year = 12 yearly_income = income * months_in_a_year print(yearly_income)
2599892f0d1edf3a23907bad202b1d1b0f10328f
atishay640/python_core
/polymorphism.py
922
4.15625
4
# Inheritance in python class Person: def __init__(self,name,mob_no,address): self.name = name self.mob_no = mob_no self.address = address def eat(self): print('I eat food') class Employee(Person): def __init__(self,name,mob_no,address,company_name): Person.__init__(self,name,mob_no,address) self.company_name = company_name def eat(self): print('I eat healthy and lit food') class Student(Person): def __init__(self,name,mob_no,address,school): Person.__init__(self,name,mob_no,address) self.school = school def eat(self): print('I eat spicy and junk food') person = Person("Atishay Sharma" , 8899779988 , 'Indore') student = Student("Rahul Rai",4565656665 , "Indore",school='NDPS') employee = Employee("Priyanka" , 898989889 ,"Mhow", company_name='GWL') for human in [person,student,employee]: human.eat()
e98c5729c38f3e6394f06efad7125981324ef230
Anamican/design-patterns
/strategy/python/sorting_using_func_object.py
585
3.65625
4
# Sort by name def sort_by_name(sort_list): return sorted(sort_list, key=lambda dct: dct['name']) # Sort by price def sort_by_price(sort_list): return sorted(sort_list, key=lambda dct: dct['price']) products = [ {'name': 'Mobie', 'price': 12}, {'name': 'Camera', 'price': 20}, {'name': 'Flask', 'price': 5}, {'name': 'Coffee mug', 'price': 10}, {'name': 'Laptop', 'price': 40}, ] # Choose the strategy sort = sort_by_name # Execute strategy print(sort(products)) # Choose the strategy sort = sort_by_price # Execute strategy print(sort(products))
fcbcbde6b50cbfd2fb5c3ad21153c3c6a55981ac
jha-prateek/ML_basics
/gradientDescent.py
1,220
3.859375
4
from numpy import genfromtxt data = genfromtxt("data.csv", delimiter=",") N = float(len(data)) def get_error(m, b): error = 0 for points in data: x = points[0] y = points[1] error = error + (y - ((m * x) + b)) ** 2 return error/N def gradient_descent(m_cur, b_cur, learningRate): m_sum = 0 b_sum = 0 # Evaluating Slope for every point in Space and Summing up for points in data: x = points[0] y = points[1] m_sum += (((m_cur * x) + b_cur) - y) * x b_sum += (((m_cur * x) + b_cur) - y) m_sum = m_sum * (2 / N) b_sum = b_sum * (2 / N) new_m = m_cur - (learningRate * m_sum) new_b = b_cur - (learningRate * b_sum) return new_m, new_b def learning_iterations(number): m_learn = 0 b_learn = 0 for i in range(number): m_learn, b_learn = gradient_descent(m_learn, b_learn, 0.0001) return m_learn, b_learn ei = get_error(0,0) n_m, n_b = learning_iterations(500) print "After 500 Iterations" print "New Value of Slope: {0}\nNew Value of Intercept: {1}".format(n_m, n_b) ef = get_error(n_m, n_b) print "Initial Error: {0}\nFinal Error: {1}".format(ei, ef) print "Score: {0}".format(1 - ef/ei)
cc6d670c6fcb735d6786dc77a655ccef7c769962
kaanf/password_generator
/passwordGenerator.py
1,533
3.65625
4
import random import os chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789!$%&/#*=" class colors: BLUE = '\033[94m' CYAN = '\033[96m' WARNING = '\033[93m' GREEN = '\033[92m' FAIL = '\033[91m' ENDC= '\033[0m' # Choose an option def optionMenu(): g_password = generatePassword() choice = input(colors.GREEN + "Do you want to save the password? (Y/N) > " + colors.ENDC) if (choice == "Y" or choice == "y"): os.system("echo " + g_password + " >> passwords.txt") print() print(colors.CYAN + "Password saved succesfully." + colors.ENDC) print() main() elif (choice == "N" or choice == "n"): return optionMenu() else: print("Wrong input. Try again.") # Generate new password def generatePassword(): password_len = int(input(colors.CYAN + "Enter password length: " + colors.ENDC)) password = "" for x in range(0, password_len): password_char = random.choice(chars) password = password + password_char print(colors.WARNING + "Password: " + colors.ENDC, password) return password # Main menu def main(): try: print() print(colors.BLUE + "Hey. Please choose an option:" + colors.ENDC) print("1. Generate new password") print("2. Show my passwords") print() choice = input("Your choice > ") except Exception: pass if __name__ == '__main__': main() while "1": optionMenu()
0d0892bf443e39c3c5ef078f2cb846370b7852e9
JakobLybarger/Graph-Pathfinding-Algorithms
/dijkstras.py
1,297
4.15625
4
import math import heapq def dijkstras(graph, start): distances = {} # Dictionary to keep track of the shortest distance to each vertex in the graph # The distance to each vertex is not known so we will just assume each vertex is infinitely far away for vertex in graph: distances[vertex] = math.inf distances[start] = 0 # Distance from the first point to the first point is 0 vertices_to_explore = [(0, start)] # Continue while heap is not empty while vertices_to_explore: distance, vertex = heapq.heappop(vertices_to_explore) # Pop the minimum distance vertex off of the heap for neighbor, e_weight in graph[vertex]: new_distance = distance + e_weight # If the new distance is less than the current distance set the current distance as new distance if new_distance < distances[neighbor]: distances[neighbor] = new_distance heapq.heappush(vertices_to_explore, (new_distance, neighbor)) return distances # The dictionary of minimum distances from start to each vertex graph = { 'A': [('B', 10), ('C', 3)], 'C': [('D', 2)], 'D': [('E', 10)], 'E': [('A', 7)], 'B': [('C', 3), ('D', 2)] } print(dijkstras(graph, "A"))
bf1be45cd079f5cfec0d919ac02f25561447e90f
daehyun1023/Python
/LeeJehwan/scraper/1.THEORY/1.1.Lists_in_Python.py
101
3.75
4
days = ["Mon", "Tue", "Wed", "Thu", "Fri"] print(days) days.append("Sat") days.reverse() print(days)
730813969c03631faf3a7cc53472800540584152
AndresF97/Adventure_Game
/Adventure_game.py
3,136
3.859375
4
import time import random def print_pause(message_to_print): print(message_to_print) time.sleep(2) def intro(): print_pause('Welcome to New Jersey, some people say that you can find the portal to hell \n') print_pause('luckly for you that your grandfather is a archyologist. \n') print_pause('You make your way into the New Jersey forrest were many trange creaters have been sighted! \n') print_pause('your father always told you to never go there, but your adventure spirit drives you to the unknown \n') def Cave(): print_pause('You\'ve entered the cave with the key that you stole from your father.') print_pause('You make your way into the ruins, you pull out the key') response = input('Would you like to put in the key "yes" or "no" \n') if 'yes' in response : print_pause('You have enetered the skull shape key in the hole\n' 'THE WALLS HAVE STARTED TO MOVE, all the bricks started to crumble\n') print_pause('the smell of sulfur starts to take over the room \n') Hell_Portal() else: print_pause('Your adventures spirit has died down, you put your head down in shame\n') print_pause('GAME OVER!') again = input ('would you like to play again "yes" or "no"\n') if 'yes' in again: intro() Cave() Hell_Portal() else: print_pause('Thank you for playing!') def Hell_Portal(): demons = random.choice(['little demon with small claws','Big demon with small t-rexc claws thats spits fire','fat demon that laughs like santa claus']) guns = random.choice (['1911 colt pistol','assult rifle','double-barrel shootgun']) power = random.choice(['in poor condition','in great condition','a broken condition']) print_pause(f'The portal opens, a {demons} comes out you grabe your trusty {guns} you check to see if its good condition') print_pause(f'Your gun is in {power}\n') gun_condition = power if 'poor' in gun_condition: print_pause('You use your gun. it is in poor condition''fourtunaley your gun worked, but it only shoot once. It wasnt very effective\n' 'your gun broken......the demon approches you. He attacks you everything goes black.\n') elif 'great' in gun_condition: print_pause('You use your weapon... it was very effective. The Demon falls to its feet, you moved forward to you destiny') print_pause('You win!\n') again = input ('would you like to play again "yes" or "no"\n') if 'yes' in again: intro() Cave() Hell_Portal() else: print_pause('Thank you for playing!') elif 'broken' in gun_condition: print_pause('Your weapon has failed immidiatly, the demon has attacked you....EVERYTHING GOES DARK!!!!!\n') print_pause('GAME OVER \n') again = input ('would you like to play again "yes" or "no"\n') if 'yes' in again: intro() Cave() Hell_Portal() else: print_pause('Thank you for playing!') def play_game(): intro() Cave() play_game()
a6c88fb61ffcaa9709941f272d9b311720e97768
pawsey18/day-2-3-exercise
/main.py
445
3.953125
4
# 🚨 Don't change the code below 👇 age = input("What is your current age?") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 int_as_age = int(age) remaining_years = 90 - int_as_age remaining_days = remaining_years * 365 remaining_weeks = remaining_years * 52 remaining_months = remaining_years * 12 print(f'You have {remaining_days} days, {remaining_weeks} weeks and {remaining_months} months left.')