blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
29240ab6e69652738d220283183acb439879ada0
utsav-195/python-assignment
/problem1.py
1,003
3.875
4
def validate(password): condition = [0, 0, 0, 0, 1] # for testing all the four criterias for i in password: if ord(i) >= ord('A') and ord(i) <= ord('Z'): # checking for capital alphabet condition[0] = 1 elif ord(i) >= ord('a') and ord(i) <= ord('z'): # charcking for small alphabet condition[1] = 1 elif i.isdigit(): # checking for digit condition[2] = 1 elif i == '$' or i == '#' or i == '@': # checking for special symbols condition[3] = 1 else: # if character other then the mentioned conditionsL condition[4] = 1 # print(condition) if 0 in condition: print("not valid") else: if len(password) >= 6 and len(password) <= 12: print("valid") else: print("Password too long!!") return def main(): s = raw_input("Enter password: ") validate(s) if __name__ == '__main__': main()
f1c745b6786930254c938f7be7afbab341253872
roguishmountain/dailyprogrammer
/challenge228.py
536
3.75
4
lwords = ['billowy', 'biopsy', 'chinos', 'defaced', 'chintz', 'sponged', 'bijoux', 'abhors', 'fiddle', 'begins', 'chimps', 'wronged'] for word in range(len(lwords)): bInOrder = True bRInOrder = True for char in range(len(lwords[word])-1): if lwords[word][char] > lwords[word][char+1]: bInOrder = False elif lwords[word][char] < lwords[word][char+1]: bRInOrder = False if bInOrder: print lwords[word], 'IN ORDER' elif bRInOrder: print lwords[word], 'REVERSE IN ORDER' else: print lwords[word], 'NOT IN ORDER'
6e39b7628ea2e62d8a0da616c94ccb8195d73cc6
MalachiBlackburn/CSC121new
/functions.py
1,597
4.0625
4
def addition(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) add=first+second print(first, "+", second, "=", add) def subtraction(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) sub=first-second print(first, "-", second, "=", sub) def multiplication(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) mult=first*second print(first, "*", second, "=", mult) def division(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) div=first/second print(first, "/", second, "=", div) def integerdivision(): first=int(input("Enter your first number: ")) second=int(input("Enter your second number: ")) intdiv=first//second print(first, "//", second, "=", intdiv) def torus(): majorradius=float(input("Enter your major radius: ")) minorradius=float(input("Enter your minor radius: ")) if majorradius <= minorradius: print("Major radius must be larger than the minor radius") torus() else: torusminor=(math.pi)*((minorradius)*(minorradius)) torusmajor=(2*math.pi)*(majorradius) torusfinal= (torusminor)*(torusmajor) print("The volume of the torus is:", torusfinal) def square(): side=int(input("Enter the length of one side of the square: ")) squarearea=side*side print("The area of the square is: ", squarearea)
ed0df19d54dd286b6996146454fa108b3d73adf3
tinayating/Leetcode
/Python/121. Best Time to Buy and Sell Stock.py
465
3.53125
4
import math class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) == 0: return 0 minPrice, maxProfit = prices[0], -math.inf for p in prices: minPrice = min(p, minPrice) profit = p - minPrice maxProfit = max(profit, maxProfit) return maxProfit
195d83bbefa65c664cbbbc9446984ba007e3d81c
valerio-oliveira/edx_cd50_python_javascript
/03_python/loops.py
78
3.734375
4
# a basic loop #for i in [0,1,2,3,4,5]: for i in range(10,15): print (i)
46af2af08a021f4a646df6debfe9a6fd28843d0d
awstown/PHYS200
/Chapter12/Chapter12.py
1,983
4.0625
4
# -*- coding: utf-8 -*- # Chapter 12 Exercises: 12.1, 12.2, 12.3 # Dwight Townsend # Phys 400 - Spring 2012 - Cal Poly Physics # imports import random # Exerise 12.1 def sumall(*args): return sum(args) print sumall(1, 3, 5, 7, 9) # Exercise 12.2 def sort_by_length(words): t = [] for word in words: t.append((len(word), random.random(), word)) t.sort(reverse=True) res = [] for length, rand, word in t: res.append(word) return res print sort_by_length(['hello','world', 'it', 'is', 'hot', 'in', 'here']) # Exercise 12.3 english = 'Buddhism can be confusing to begin with, especially if you come from a Christian, Islamitic or Jewish background. You may be unfamiliar with concepts such as karma, rebirth, emptiness and the practice of meditation. On top of that, the presentation of Buddhism in the various traditions can vary quite a bit, so if you read materials from different traditions, it is easy to lose track.' german = 'Buddhismus kann verwirrend sein, zu beginnen, besonders wenn Sie aus einer christlichen, jdischen oder islamitischen Hintergrund kommen. Sie drfen nicht vertraut sein mit Begriffen wie Karma, Wiedergeburt, "Leere" und die Praxis der Meditation. Hinzu kommt, dass kann der Prsentation des Buddhismus in den verschiedenen Traditionen variieren ziemlich viel, wenn Sie also Materialien von' french = 'Le bouddhisme peut tre source de confusion, pour commencer, surtout si vous venez d\'un chrtien, fond Islamitic ou juive. Vous pouvez ne pas tre familiers avec des concepts tels que le karma, la renaissance, vide et la pratique de la mditation.' def histogram(s): d = dict() for c in s: d[c] = d.get(c,0) + 1 return d def most_frequent(string): d = histogram(string) t = [] for key, val in d.items(): t.append((val, key)) t.sort(reverse=True) res = [] for occur, letter in t: res.append(letter) print res most_frequent(german)
537ddca25824fd995727cbb026fecefa5bdcaf8b
wkomari/Lab_Python_04
/data_structures.py
1,383
4.40625
4
#lab 04 # example 1a groceries = ['bananas','strawberries','apples','bread'] groceries.append('champagne') print groceries # example1b groceries = ['bananas','strawberries','apples','bread'] groceries.append('champagne') # add champagne to the list of groceries groceries.remove('bread') # remove bread from the list of groceries print groceries # example 1c groceries = ['bananas','strawberries','apples','bread'] groceries.append('champagne') # add champagne to the list of groceries groceries.remove('bread') # remove bread from the list of groceries groceries.sort() print groceries # example 2a print 'Dictionary would be used as the data type' dict = {'Apples':'7.3','Bananas':'5.5','Bread':'1.0','Carrot':'10.0','Champagne':'20.90','Strawberries':'32.6'} print 'Apple is', dict['Apples'] dict['Strawberries'] = 63.43 print 'The price of Strawberries in winter now is', dict['Strawberries'] # updated strawberries price dict['chicken'] = 6.5 print dict # prints all entries in the dictionary print 'Hehe customers we have chicken now in stock at', dict['chicken'] #example3 in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries') always_in_stock = ('Apples','Bananas','Bread','Carrot','Champagne','Strawberries') print 'Come to shoprite! We always sell:\n', always_in_stock[0:6] for i in always_in_stock: print i #example4
39c80f04366d2381fa04b4b851cca2ba58a1cb26
Only8Bytes/Python-Programs
/Final Project.py
1,837
3.703125
4
import operator def palindrome(a): if str(a) == str(a)[::-1]: return "yes" return "no" def nearPrime(a): val = 0 for i in range(2, int(a) - 1): if (int(a)/i) % 1 == 0 and int(a)/i != i: val += 1 if val > 2: return "no" return "yes" def upNum(a): a = list(a) val = None for x in a: if val == None or int(x) >= val: val = int(x) else: return "no" return "yes" def downNum(a): a = list(a) val = None for x in a: if val == None or int(x) <= val: val = int(x) else: return "no" return "yes" def upDownNum(a): a = list(a) val = None i = -1 for x in a: i += 1 if val == None or int(x) >= val: val = int(x) elif downNum(str.join("", a[i:len(a)])) == "yes": return "yes" else: return "no" return "no" def getScore(a, pal, nprime, nice): val = int(a) if pal: val *= 2 if nprime: val *= 2 if nice: val *= 3 return val Scores = {} Nums = str.split(input("Enter an integer: "), ",") for num in Nums: pal = False nprime = False nice = False if palindrome(num) == "yes": pal = True if nearPrime(num) == "yes": nprime = True if upNum(num) == "yes" or downNum(num) == "yes" or upDownNum(num) == "yes": nice = True score = getScore(num, pal, nprime, nice) if num not in Scores: Scores[num] = score else: Scores[str(num) + "Dupe"] = score SortedScores = sorted(Scores.items(), key = operator.itemgetter(1)) for x in SortedScores: print(str(x[0]) + "," + str(x[1]))
566a189b7b5fff577335764813be64f9dabfaaee
jayson-s/csci1030u
/Test1_Question4.py
278
3.546875
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 19 11:12:52 2017 @author: Jayson """ def drawParallelogram(numRows, numCols): for rows in range(numRows, 0, -1): print(' ' * (numRows - rows) + '*' * (numRows)) drawParallelogram(10, 8)
3c4f2f635ffb56ddec52a1ea4b0fb59fc9dafad5
jayson-s/csci1030u
/Test2_Question1a.py
769
3.796875
4
#Name: Jayson Sandhu #Student ID: 100659589 #Question 1a import math class Rectangle: def __init__(self, width, length): self.width = width self.length = length def getLength(self): return self.length def getWidth(self): return self.width def getArea(self): return self.width * self.length def getPerimeter(self): return self.width * 2 + self.length * 2 class Circle: def __init__(self,radius): self.radius = radius def getRadius(self): return self.radius def getArea(self): return math.pi * pow(self.radius,2) def getPerimeter(self): return 2 * math.pi * self.radius def main(): if __name__ == "__main__": main()
fcd2821ec8109d3270d9c73e4c06ace969bb7782
jayson-s/csci1030u
/Jayson_Lab6.py
5,276
3.921875
4
#Jayson Sandhu, 100659589 #Declare Variables and Initialize with values partyNames = ['Krogg', 'Glinda', 'Geoffrey'] partyHP = [180, 120, 150] partyAttack = [20, 5, 15] partyDefense = [20, 20, 15] partyDead = [False, False, False] bossAttack = 25 bossDefense = 25 bossHP = 500 round = 1 class Character: """ Character This class represents all of the data and behaviour of a character in our game. """ def __init__(self, name, hp, xpGained, attack, defense, magic=0): """ __init__(self, name, hp, attack, defense, magic) This constructor initializes all of the instance variables of our class @arg self The character object being initialized @arg name The name of the character @arg hp The remaining hitpoints of the character @arg xp The amount of xp that has been collected so far, which is initialized to 0 @arg xpGained The XP that would be gained by defeating the character @arg attack The attack power of the character @arg defense The defense power of the character @arg magic The magic power of the character (optional, default: 0) @arg level The current level of the character, which is initialized to 1 """ self.name = name self.hp = hp self.xp = 0 self.xpGained = xpGained self.maxhp = hp self.attackpower = attack self.defensepower = defense self.magic = magic self.level = 1 #Output round sequences while the HP for the Boss is greater than 0 while (bossHP > 0 or partyHP == 0): print ("Round", round) round = round + 1 print ("Krogg does", partyAttack [0], " points of damage to Boss") bossHP = bossHP - partyAttack [0] print ("Geoffrey does", partyAttack [2], " points of damage to Boss") bossHP = bossHP - partyAttack [2] partyHP  = partyHP + 5 isPartyDead(partyHP[]) #Once Boss HP is less than 0, output the following statements based in which case is true if (bossHP <= 0): print ("The boss is dead. You are victorious!") else: print ("Your whole party is dead. You lose.") def isPartyDead(party[]): """ isPartyDeadDead(party[]) This function returns True if the party is dead @arg party[] The Party's HP in the array we want to check """ if (party[] <= 0): return true else: return false def isDead(partyHP[]): """ isDead(partyHP[]) This function returns True if the character is dead @arg partyHP[] The character's HP in the party we want to check """ i=0 if partyHP[i] <= 0: return True else: return False def attack(self, otherCharacter): """ attack(self, otherCharacter) This function simulates an attack from this character ('self') to 'otherCharacter'. The other character's HP is updated with the damage taken. @arg self The character that is attacking @arg otherCharacter The target of the attack """ if self.isDead(): print(self.name, 'cannot attack because he/she is dead.') else: damage = self.attackpower - otherCharacter.defensepower otherCharacter.hp -= damage if otherCharacter.hp < 0: otherCharacter.hp = 0 print(self.name, 'does', damage, 'points of damage to', otherCharacter.name) def heal(self, party): """ heal(self, party) This function simulates a healing spell. The HP of the entire party is updated. @arg self The character that is healing @arg party The list of party members being healed """ if self.isDead(): print(self.name, 'cannot heal because he/she is dead.') else: for partyMember in party: if not partyMember.isDead(): partyMember.hp += self.magic if partyMember.hp > partyMember.maxhp: partyMember.hp = partyMember.maxhp print(self.name, 'heals', self.magic, 'hp for', partyMember.name) def __str__(self): """ __str__(self) This function returns a string representation of our character @arg self The character that is being represented @return The string representation of the character """ return self.name + ' has ' + str(self.hp) + ' HP.' return self.name + ' has ' + str(self.maxhp) + ' max HP.' return self.name + ' has ' + str(self.attackpower) + ' attack power.' return self.name + ' has ' + str(self.defensepower) + ' defense power.' return self.name + ' has ' + str(self.magic) + ' magic points.' return self.name + ' has gained ' + str(self.xpGained) + ' XP.'
fcbe70e27eaba61f35abb918ffcb7cc55bd11066
nhan1361992/python
/helloworld.py
137
3.671875
4
print ("begin") arrs = [] for i in range(20,35) : if ((i%7 == 0) and (i%5 != 0)) : arrs.append(str(i)) print(','.join(arrs))
84e31e9c440bdcc0b6e101ee8739a721f388ce07
GurmanBhullar/hactoberfest-Projects-2020
/Hackerrank-Python/designerdoormat.py
512
3.890625
4
# Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: # Mat size must be X. ( is an odd natural number, and is times .) # The design should have 'WELCOME' written in the center. # The design pattern should only use |, . and - characters. n, m = map(int, input().split()) for i in range(1, n, 2): print((".|."*i).center(m, "-")) print(("WELCOME").center(m, "-")) for i in range(n-2, -1, -2): print((".|."*i).center(m, "-"))
555913911bc903f7d407f39009ac136e3e281f72
GurmanBhullar/hactoberfest-Projects-2020
/Hackerrank-Python/Find angle MBC.py
210
3.96875
4
from math import acos, degrees, sqrt AB = int(input()) BC = int(input()) AC = sqrt(AB*AB + BC*BC) BM = AC / 2 angel = round(degrees(acos((BC * BC + BM * BM - BM * BM) / (2.0 * BM * BC)))) print(str(angel)+'°')
075c6e5733adf3dec09c3337f42806a51ed524ad
mohamed-minawi/KNN-LLS
/KNN.py
1,310
3.84375
4
import numpy as np class KNN(object): def __init__(self): pass def train(self, Data, Label): """ X is N x D where each row is an example. Y is 1-dimension of size N """ # the nearest neighbor classifier simply remembers all the training data self.train_data = Data self.train_labels = Label def predict(self, test_data, l='L1', k=1): """ X is N x D where each row is an example we wish to predict label for """ num_test = test_data.shape[0] # lets make sure that the output type matches the input type Ypred = np.zeros(num_test, dtype=self.train_labels.dtype) # loop over all test rows for i in range(num_test): # find the nearest training example to the i'th test example if l == 'L1': # using the L1 distance (sum of absolute value differences) distances = np.sum(np.abs(self.train_data - test_data[i, :]), axis=1) else: distances = np.sqrt(np.sum(np.square(self.train_data - test_data[i, :]),axis=1)) closelabels = self.train_labels[distances.argsort()[:k]] count = np.bincount(closelabels); Ypred[i] = np.argmax(count) print(k,": Test ", i," done ") return Ypred
db7b6be5a8c25fff421436696ad1d332fa367a66
CamiloSaboA-csv/problemas_HackerRank
/Strings_Making_Anagrams.py
352
3.609375
4
def makeAnagram(a, b): # Write your code here from collections import Counter a,b=list(sorted(a)),list(sorted(b)) a_count=Counter(a) b_count=Counter(b) x=((b_count-a_count)+(a_count-b_count)).values() x=sum(x) return x a,b= 'faacrxzwscanmligyxyvym','jaaxwtrhvujlmrpdoqbisbwhmgpmeoke' #a,b='aaaaaaabc','aaaaabde' x=100000000 x=makeAnagram(a,b) print(x)
262ec8a9fc2241422d79720605e903e873c25d4e
BLOODMAGEBURT/exercise100
/data-structure/sort-search/5.9.插入排序.py
1,522
3.96875
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: 5.9.插入排序 Description : Author : Administrator date: 2019/10/12 0012 ------------------------------------------------- Change Activity: 2019/10/12 0012: ------------------------------------------------- """ def insertion_sort(alist): size = len(alist) # 先循环获取从第二项到最后一项 for i in range(1, size): current_value = alist[i] for j in range(i - 1, -1, -1): # 将值依次与前方的数字做比较, 如果比前一项小,则前一项往后移一位,直到比前一项大为止 if alist[j] > current_value: alist[j + 1] = alist[j] # 需要注意如果比第一项大的时候 if j == 0: alist[0] = current_value else: alist[j + 1] = current_value break return alist def insertion_sort2(alist): """ 使用while的方式 :param alist: :return: """ for index in range(1, len(alist)): current_value = alist[index] position = index while position > 0 and alist[position - 1] > current_value: alist[position] = alist[position - 1] position -= 1 alist[position] = current_value return alist if __name__ == '__main__': alist = [45, 20, 15, 30, 25, 10] print(insertion_sort2(alist))
b1ab6571086c0867dabdfee9970348aee716dbe5
BLOODMAGEBURT/exercise100
/exercise/exercise5.py
532
3.9375
4
# -*- coding: utf-8 -*- def sort_method(alist): """ 给一个list排序,从小到大 :param alist: :return: """ assert isinstance(alist, list) new_list = sorted(alist) return new_list if __name__ == '__main__': print(sort_method([2, 7, 5, 10, 4])) """ 按学生年龄大小排队,从小到大 """ students = [('burt', 20), ('tom', 23), ('jean', 21), ('jack', 19)] sorted_students = sorted(students, key=lambda x: x[1]) print('sorted_students:', sorted_students)
3fb4a522861fca51b2f54d48c9cc9c28120280aa
BLOODMAGEBURT/exercise100
/exercise/exercise12.py
988
3.921875
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: exercise12 Description : Author : burt date: 2018/11/7 ------------------------------------------------- Change Activity: 2018/11/7: ------------------------------------------------- """ import math def count_su(x, y): """ 计算x,y之间有多少个素数 素数定义:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数 :param x: :param y: :return: """ prime_num = [] for i in range(x, y): count = 0 for j in range(2, int(math.sqrt(i)) + 1): if i % j == 0: count += 1 break if count == 0: prime_num.append(i) return prime_num, len(prime_num) if __name__ == '__main__': result = count_su(100, 200) print(result[0], '共有%d个' % (result[1],))
4712a8abf07cb2927fbb8695e3764f0590e87dd9
BLOODMAGEBURT/exercise100
/exercise/exercise7.py
583
3.75
4
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: exercise7 Description : Author : burt date: 2018/11/6 ------------------------------------------------- Change Activity: 2018/11/6: ------------------------------------------------- """ def list_copy(): """ 复制alist 到 blist 中 :return: """ if __name__ == '__main__': list_a = [1, 2, 3, 4] list_b = list_a[:] list_a.append(5) print('list_a是:{}-------list_b是:{}'.format(list_a, list_b))
2539e1965cf3e3df19acc8c1e7a9f65c734a4c12
gelisa/sandbox
/working-with-spark/run_spark.py
2,129
3.8125
4
# run_spark.py """ a sandbox to test spark and learn how it works to run it: put some (at least a couple) text files to the data folder type in command line: python run_spark.py or <path to spark home folder>/bin/spark-submit run_spark.py to understand very basics of spark read: http://mlwhiz.com/blog/2015/09/07/Spark_Basics_Explained/ it is very good """ # this is to run with spark: python run_spark.py from pyspark import SparkConf from pyspark import SparkContext # import python packages import os import numpy as np # import my custom class import custom_class # set up spark environment conf = SparkConf() sc = SparkContext(conf=conf) # text files shoud be here folder = 'data/' # init a list to put filenames in there to work with the files a_list = [] for datafile in os.listdir(folder): a_list.append(os.path.join(folder,datafile)) # create a spark rdd from the list of file names sp_filenames = sc.parallelize(a_list) # now I use map to create a python class for every file (see custom_class.py for details) sp_classes = sp_filenames.map(custom_class.Custom_class) # now we apply a method function to every class. # If this function creates or updates a class attribute it has to return an object itself # so that spark has access to it (rdd's are immutable: you have to create a new rdd) # we'll have [obj1, obj2, obj3 ...] classes_wt_count = sp_classes.map(lambda x: x.count_lines()) # so no we want calculate some stats for every file. # we use flatMap which returns seveal items of output for one item of inpet # we'll have [stat1(dbj1), stat2(ojb1), stat1(obj2) ...] dicts = classes_wt_count.flatMap(lambda x: x.get_stats()) # now instead of having a long list of key value pair we want to get [key1: list1, key2: list2 ] # key is a name of stat and each list is a list of the stats for each object dicts_collected = dicts.groupByKey().mapValues(list) # now we calculate mean and standard deviation for every stat stats = dicts_collected.map(lambda x: (x[0], np.mean(x[1]),np.std(x[1]))) # for spark to do the actual calculation we have to call an action # for example collect() print(stats.collect())
30850c4f1d5a5d986941cd04d8e17178e15a835d
johnabfaria/bambus.py
/main.py
771
3.8125
4
import pic_it import tweet_it import txt_it import drop_it import pin import time """ This is the main program that will use pin to id inputer from raspberry pi using RPi.GPIO If input from IR motion sensor is positive, camera will be activated, photo snapped and saved locally Photo will be tweeted and then uploaded to dropbox A text message using Twilio will be sent to contact list with twitter link and dropbox direct link """ #while True(): for z in range(15) print("Sensor null, run = {0}".format(z)) if pin.status: time_snap = "{0}:{1}".format(time.localtime().tm_hour, time.localtime().tm_min) name = "Bambus_pije_o: " + time pic_it.snap(name) tweet_it.send(name) drop_it.upload(name) txt_it.go(name) time.sleep(5)
fe957545e1dc512e5d3a2a28defc654281ae82ee
YunYouJun/python-learn
/primer/first_program.py
437
3.984375
4
def isEqual(num1, num2): if num1 < num2: print(str(num1) + ' is too small!') return False elif num1 > num2: print(str(num1) + ' is too big!') return False else: print('Bingo!') return True from random import randint num = randint(1, 100) print('Guess what I think?') bingo = False while bingo == False: answer = input() if answer: isEqual(int(answer), num)
87de1f7da5274947664161b3e54d2913720b59e9
Om-Jaiswal/Python
/Python_Programs/FizzBuzz.py
643
4.03125
4
# for number in range(1,101): # if number % 3 == 0 and number % 5 == 0: # print("FizzBuzz") # elif number % 3 == 0: # print("Fizz") # elif number % 5 == 0: # print("Buzz") # else: # print(number) print("Welcome to FizzBuzz!") Fizz = int(input("Enter a number for fizz :\n")) Buzz = int(input("Enter a number for buzz :\n")) print("Here's the solution") for number in range(1,101): if number % Fizz == 0 and number % Buzz == 0: print("FizzBuzz") elif number % Fizz == 0: print("Fizz") elif number % Buzz == 0: print("Buzz") else: print(number)
c0549fa722759a574c69585d0e0767c47d8d1be1
Om-Jaiswal/Python
/Python_Programs_OPP/Dash_Square.py
326
3.5
4
import turtle as t from turtle import Screen tim = t.Turtle() tim.shape("turtle") def dash_line(): for _ in range(15): tim.forward(10) tim.penup() tim.forward(10) tim.pendown() for _ in range(4): dash_line() tim.right(90) screen = Screen() screen.exitonclick()
5f168aeaf97ebb2100fafcbaef59928522f86d70
sha-naya/Programming_exercises
/reverse_string_or_sentence.py
484
4.15625
4
test_string_sentence = 'how the **** do you reverse a string, innit?' def string_reverser(string): reversed_string = string[::-1] return reversed_string def sentence_reverser(sentence): words_list = sentence.split() reversed_list = words_list[::-1] reversed_sentence = " ".join(reversed_list) return reversed_sentence example_1 = string_reverser(test_string_sentence) print(example_1) example_2 = sentence_reverser(test_string_sentence) print(example_2)
4196ac75509c5eff3227c1e8bff9ad00cc83ddd0
frfanizz/PressureChess
/pressurechess.py
5,374
3.75
4
import sys from pieces import * ''' Considerations: allow buring pieces ''' class tile: """ (Board) tile objects """ def __init__(self, piece, hp = 6): """ Tile classs constructor :param self tile: the current object :param piece piece: the current object :param hp int: the current object """ self.piece = piece self.hp = hp def lose_hp(self): """ Decrements self's hp :param self tile: the current object :returns boolean: True if hp was decremented, False o.w. """ if self.hp > 0: self.hp = self.hp - 1 return True else: # self.hp = 0 return False def get_piece(self): """ Returns self's piece :param self tile: the current object :returns piece: the piece of the current object """ return self.piece def set_piece(self, piece): """ Sets self's piece to piece :param self tile: the current object :param piece piece: a piece object :returns: """ self.piece = piece def toString(self): """ Returns a string representation of self :param self tile: the current object :returns str: a string representation of self """ if self.piece is None: return " " + str(self.hp) else: return " " + self.piece.toString() + str(self.hp) class board: """ The chess board, which is an 8x8 array of tiles """ def __init__(self, tiles): """ Board class constructor :param self board: the current object :param tiles [tile]: an array of tiles :returns: """ self.tiles = tiles # TODO: add curr player to move?? # TODO: def is_in_check(self) def print_board(self): """ Prints the board in a visually athstetic way :param self board: the current object :returns: """ print(self.toString()) def toString(self): """ Returns a string representation of the board in a visually athstetic way :param self board: the current object :returns str: The board in a string representation """ retString = "\n +---+---+---+---+---+---+---+---+\n" for row in range(len(self.tiles)-1, -1, -1): retString += str(row+1) + " " for tile in range(len(self.tiles[row])): retString += "|" + self.tiles[row][tile].toString() + "" retString += "|\n +---+---+---+---+---+---+---+---+\n" retString += " a b c d e f g h \n" return retString class position: """ The position on the board, where rank = row (1 : 0), and file = col (a : 0) """ def __init__(self, pos_rank, pos_file): """ Position class constructor :param self position: the current object :param pos_rank int: the rank (row) number from 0 to 7 :param pos_file int: the file (colum) number from 0 to 7 :returns: """ self.pos_rank = pos_rank # row self.pos_file = pos_file # column def get_rank(self): """ Return self's rank :param self position: the current object :returns int: self's rank """ return self.pos_rank def get_file(self): """ Return self's file :param self position: the current object :returns int: self's file """ return self.pos_file def rank_to_string(self): """ Return self's rank in a string format from 1 to 8 :param self position: the current object :returns str: self's rank in a string format """ return str(self.pos_rank + 1) def file_to_string(self): """ Return self's rank in a string format from a to h :param self position: the current object :returns str: self's rank in a string format """ return chr(ord("a")+self.pos_file) def toString(self): """ Return self in a string format (file followed by row) :param self position: the current object :returns str: self in a string format """ return self.file_to_string() + self.rank_to_string() board_std = [ [tile(rook(0)), tile(knig(0)), tile(bish(0)), tile(quee(0)), tile(king(0)), tile(bish(0)), tile(knig(0)), tile(rook(0))], [tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0)), tile(pawn(0))], [tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None)], [tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None)], [tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None)], [tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None), tile(None)], [tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1)), tile(pawn(1))], [tile(rook(1)), tile(knig(1)), tile(bish(1)), tile(quee(1)), tile(king(1)), tile(bish(1)), tile(knig(1)), tile(rook(1))] ] def main(argv): """ Main application class :param argv [str]: the terminal/command line inputs :returns: """ field = board(board_std) print(field.toString()) if __name__ == "__main__": main(sys.argv)
2e61bac1d6b08105532a2c34e96b98e5e6886b0f
rabahbedirina/HackerRankContests
/CatsandaMouse.py
207
3.65625
4
def catAndMouse(x, y, z): X = abs(x - z) Y = abs(y-z) if X < Y: cat = "Cat A" elif X > Y: cat = "Cat B" else: cat = "Mouse C" return cat catAndMouse(x, y, z)
0e599494c99b1d05d0162c5cf66b98f0b0301be1
rabahbedirina/HackerRankContests
/Big Sorting.py
526
3.625
4
def bigSorting(unsorted): for i in range(n): unsorted[i] = int(unsorted[i]) print(unsorted) list_sorted = sort(unsorted) print(list_sorted) for j in range(n-1): print(str(list_sorted[j])) return str(list_sorted[-1]) n = 6 unsorted = ['31415926535897932384626433832795', '1', '3', '10', '3', '5'] print(bigSorting(unsorted)) # unsorted = [31415926535897932384626433832795, 1, 3, 10, 3, 5] # print(bigSorting(unsorted)) # TypeError: sequence item 0: expected str instance, int found
a336bb76c0bce019135ea4a775ab09f434a5b01d
skyrusai/code_training
/others/FizzBuzz.py
327
3.96875
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 09:44:32 2018 @author: shenliang-006 """ for l in range(101): if l==0: continue if l%3==0: if l%5==0: print("FizzBuzz") else: print("Fizz") elif l%5==0: print("Buzz") else: print(l)
e2584e9dda14afad7ca6aa5eebf4f23d56ac01f9
ardieorden/electrical_circuits
/circuit_initial.py
6,626
3.671875
4
import cmath import numpy as np import matplotlib.pyplot as plt from sympy import Symbol, simplify, Abs from sympy.solvers import solve from scipy.signal import sawtooth # We set our unknowns: vo, vr, ir, ic and il vo = Symbol("V_O") vr = Symbol("V_R") ir = Symbol("I_R") ic = Symbol("I_C") il = Symbol("I_L") r = Symbol("R") # resistance omega = Symbol("\omega") # angular frequency c = Symbol("C") # capacitance l = Symbol("L") # inductance eq1 = (vr + vo - 1, ir - ic - il, vr - ir*r, # what does 1j mean? (1j represents the imaginary number i) vo - ic/(1j*omega*c), vo - 1j*omega*l*il) # what does the following line do? sol = solve(eq1, (vo, vr, ir, ic, il)) vos = simplify(sol[vo]) """ The system of equations is solved for the 5 specified variables. Subsequently, the variable vo is simplified. """ # compare the output of the following line if vos = sol[vo] print "Simplified: " + str(vos) print "Unsimplified: " + str(sol[vo]) """ When 'vos=sol[vo]' instead of 'vos=simplify(sol[vo])', the output is still the same because the expression is already simplified after solving. """ numvalue = {c: 10**-6, l: 10**-3} # what does subs() do? is vos.subs(c=10**-6, l=10**-3) allowed? Try it. vosnum = vos.subs(numvalue) flist = [vosnum.subs({r: 100.0*3**s}) for s in range(0, 4)] omega_axis = np.linspace(20000, 43246, 100) """ 'subs()' substitutes a variable expression with an actual number. Using 'numvalue = {c: 10**-6, l: 10**-3}', the result of the substitution is i*omega/1000. """ # what does 121 in the following line mean? # what are the other possible parameters of subplot()? plt.subplot(121) """ '121' indicates the position of the subplot. The three numbers represent numrows, numcols, fignum. fignum ranges from 1 to numrows*numcols. """ # describe (python type, dimensions, etc) of the input parameter/s of zip() below # what does zip(*a) do if a is a 2-D list or numpy array? plt.plot(omega_axis, zip(*[[abs(f.subs({omega: o})) for o in omega_axis] for f in flist])) """ The input parameter is a 2-D list. It is a list of output voltages within another list. When there is an asterisk before the arguments (e.g. zip(*a) where a is 2-D), it outputs a list of tuples. """ plt.xlim(20000, 43246) plt.ylim(0, 1) plt.xlabel('$\omega$') plt.ylabel('$V_O$') plt.xticks([20000, 30000, 40000]) # Replicate Fig. 2.6, right pane following the code for Fig. 2.6, left pane """Code shown below.""" plt.subplot(122) plt.plot(omega_axis, zip(*[[cmath.phase(f.subs({omega: o})) for o in omega_axis] for f in flist])) plt.xlim(20000, 43246) plt.ylim(-1.5, 1.5) plt.xlabel('$\omega$') plt.ylabel('$\phi$') plt.xticks([20000, 30000, 40000]) plt.tight_layout() plt.savefig('fig2.6.png', dpi=300) plt.show() def vsaw(t, T=1.0): """Output a sawtooth wave over a given time array t. In order to create a sawtooth wave, I utilized 'scipy.signal.sawtooth()'. The instructions call for a period T = 1.0. However, 'sawtooth()' has a period T = 2pi. To get around this, the argument for the 'sawtooth()' function must be multiplied by 2pi. """ return sawtooth(t*2*np.pi) omegares = 1./np.sqrt(np.prod(numvalue.values())) alist = (1/np.sqrt(256)) * vsaw(np.arange(256)/256.0) blist = np.sqrt(256) * np.fft.fft(alist) def plot3(fac, w): # add a docstring for this function """Plots the output voltage of a sawtooth voltage input. Parameters ---------- fac : Ratio of input fundamental frequency to the resonance frequency w : Resistor value Returns ------- Output voltage V_out vs. t/T plot showing the filtered sawtooth input. """ omegai = fac * omegares # How were the limits of arange() in the following line chosen? """ To be able to multiply 'volist' correctly with 'blist' for the subsequent inverse Fourier transform, both arrays must be of the same size. Since 'blist' is a numpy array of size 256, 'volist' must also be the same """ volist = np.concatenate(([complex(vosnum.subs({omega: omegai*s, r: w}).evalf()) for s in np.arange(1, 129)], [0.0], [complex(vosnum.subs({omega: omegai*s, r: w}).evalf()) for s in np.arange(-127, 0)])) vtrans = np.fft.ifft(blist * volist) plotlist = np.array([[(k+1)/256., vtrans[k%256]] for k in range(768)]) plt.plot(plotlist[:,0], plotlist[:,1]) # what does the following line do? plt.axhline(0, color='black') """'axhline()' creates a horizontal axis line.""" # add labels """Labels shown below.""" plt.xlabel('$t/T$') plt.ylabel('$V_O(t)$') fname = 'fig2.7and8_f' + str(fac) + 'r' + str(w) + '.png' plt.savefig(fname, dpi=300) plt.show() plot3(1, 2700.0) plot3(1/3., 200.0) plot3(3.0, 5.0) eq2 = (ir * (r + 1/(1j*omega*c) + 1j*omega*l) + vo - 1, ir - (1j*omega*c + 1/(1j*omega*l)) * vo) sol2 = solve(eq2, [vo, vr, ir, ic, il]) vos2 = simplify(sol2[vo]) irs = simplify(sol2[ir]) # why should irs be passed to Abs() before squaring? """ 'irs' was first passed through an absolute value before squaring to ensure that the square is solely real-valued. """ power = (r**2) * (Abs(irs)**2) flist3 = [Abs(vos2.subs(numvalue).subs({r: 10.0*3**s})) for s in range(0, 3)] omega_axis = np.linspace(10000, 70000, 1000) lines = plt.plot(omega_axis, zip(*[[abs(f.subs({omega: o})) for o in omega_axis] for f in flist3])) # what does plt.setp() do? """'plt.setp' changes the properties of an artist object""" plt.setp(lines[0], lw=2, label="$R = 10 \Omega$") plt.setp(lines[1], ls='--', label="$R = 30 \Omega$") plt.setp(lines[2], ls='-.', label="$R = 90 \Omega$") # add labels and ticks """Labels and ticks shown below.""" plt.xlabel('$\omega$') plt.ylabel('|$V_O$|') plt.xticks([10000, 30000, 50000, 70000]) plt.tight_layout() plt.minorticks_on() plt.legend(loc=0) plt.savefig('fig2.9.png', dpi=300) plt.show() # replicate fig. 2.10 """Code shown below.""" flist4 = [power.subs(numvalue).subs({r: 10.0}) for s in range(0,1)] lines = plt.plot(omega_axis, zip(*[[f.subs({omega: o}) for o in omega_axis] for f in flist4])) plt.xlabel('$\omega$') plt.ylabel('$P/P_0$') plt.xticks([10000, 30000, 50000, 70000]) plt.tight_layout() plt.minorticks_on() plt.savefig('fig2.10.png', dpi=300) plt.show()
18fae6895c6be30f0a3a87531a2fafe965a3c89f
pkdoshinji/miscellaneous-algorithms
/baser.py
1,873
4.15625
4
#!/usr/bin/env python3 ''' A module for converting a (positive) decimal number to its (base N) equivalent, where extensions to bases eleven and greater are represented with the capital letters of the Roman alphabet in the obvious way, i.e., A=10, B=11, C=12, etc. (Compare the usual notation for the hexadecimal numbers.) The decimal number and the base (N) are entered in the command line: baser.py <base> <decimal number to convert> ''' import sys #Character set for representing digits. For (base N) the set is characters[:N] characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+/' #Usage guidelines def usage(): print('[**]Usage: baser.py <base> <number to convert>') print(f' <base> must be less than or equal to {len(characters)}') print(f' <number> must be a nonnegative integer') #Get the most significant digit (MSD) of the decimal number in (base N) def getMSD(base, number): MSD = 1 while True: if (base ** MSD) > number: return MSD MSD += 1 #Convert the decimal number to (base N) def convert(MSD, base, number): result = '' for i in range(MSD - 1, -1, -1): value = number // (base ** i) result += chars[value] number = number % (base ** i) return result def main(): #Input sanitization try: base = int(sys.argv[1]) except: usage() exit() try: number = int(sys.argv[2]) except: usage() exit() if base > len(characters): usage() exit(0) if number == 0: print(0) exit(0) if number < 0: usage() exit(0) global chars chars = characters[:base] #Get the (base N) character set print(convert(getMSD(base, number), base, number)) #Convert and output if __name__ == '__main__': main()
60a99e1a6a1a8ab2c8a5827d36b891fdafb5035f
DimitrisParris/Bootcamp-AFDE
/Exercises in Python/ex.8(part2).py
290
3.703125
4
num = input("Give sequence of numbers:") sum = 0 for i in range(len(num)): if i%2 == 0 and i<(len(num)-1): a = int(num[i])*int(num[i+1]) sum+=a if len(num)%2 !=0 and i==(len(num)-1): sum += int(num[-1]) print("This is the sum of the sequence:", sum)
653e3c2184e36a5a05ea9e77d7f8214e4be9d770
DimitrisParris/Bootcamp-AFDE
/Exercises in Python/ex.2(part 2).py
410
3.703125
4
number=input('Give 8-bit number:') num=str(number) if len(num)!=8: print('Not an 8-digit number. False. Check again.') else: neo=num[:7] print(neo) sum=0 for i in neo : if int(i)==1: sum+=1 if sum%2==0 : print('sum even') else : print('sum odd') if (int(num[-1])%2)==(sum%2): print('Parity OK') else: print('Parity not OK')
5d9d9ee735c83028145dda4bbc9a615cab916d6c
DSJ-23/DS_Algorithms
/valid_parenthesis.py
1,039
3.890625
4
from stack import Stack class Solution: def isValid(self, s): valid = Stack() for p in s: if p == "(" or p == "[" or p =="{": valid.add(p) # elif p == ")" or p == "]" or p == "}": print(valid.get_stack()) return True a= Solution() print(a.isValid("()[]{")) # print(Solution.isValid("()[]")) class Solution: def isValid(self, s: str) -> bool: result = [] print(s) for i in s: if i == "(" or i == "[" or i == "{": result.append(i) else: if result != []: if i == ")" and result[-1] == "(": result.pop() if i == "]" and result[-1] == "[": result.pop() if i == "}" and result[-1] == "{": result.pop() else: return False if len(result) > 0: return False return True
7c53f978351f9de8b446810c5fbd0d87160806cf
DSJ-23/DS_Algorithms
/DS/queue.py
316
3.5
4
class Queue: def __init__(self): self.data = [] def push(self, x: int) -> None: self.data.append(x) def pop(self): return self.data.pop(0) def peek(self): return self.data[0] def empty(self): return bool(self.data == [])
28b99002de36b734fe2f53b72ac863075f594ebc
DSJ-23/DS_Algorithms
/all_duplicates.py
549
3.578125
4
class Solution: def findDuplicates(self, nums): for i in range(1, len(nums) +1): if i in nums and nums.count(i) == 1: nums.remove(i) elif i in nums and nums.count(i) > 1: self.remove_nums(nums, i) else: continue return nums def remove_nums(self, list_nums, number): while list_nums.count(number) != 1: list_nums.remove(number) return list_nums eg = [4,3,2,7,8,2,3,1] a = Solution() print(a.findDuplicates(eg))
d7cae30b5df626903234bce52cde315a602603cb
DSJ-23/DS_Algorithms
/binary_search.py
495
3.671875
4
a = list(range(1001)) def binary_search(nums, num): lower = 0 upper = len(nums) - 1 mid = 0 while lower <= upper: mid = (lower + upper)//2 # print(nums[mid]) if nums[mid] > num: upper = mid -1 elif nums[mid] < num: lower = mid + 1 else: return mid return -1 # for i in range(1001): # if binary_search(a, i) != i: # print('oh no') # else: # print('yes')
becb9a7d85b964a23e2a9e416b3654a2a4e8b7d5
tomchor/scivis
/plots/ex0/ex0.py
665
3.9375
4
import numpy as np from matplotlib import pyplot as plt # Create some made up simple data y1=[1,4,6,8] y2=[1,2,3,4] # Create a new figure with pre-defined sizes and plot everything plt.figure(figsize=(3,4)) plt.plot(y1) plt.plot(y2) plt.savefig('bad_ex.pdf') plt.close('all') # Create another figure with defined sizes plt.figure(figsize=(3,4)) # Plot with curve labels plt.plot(y1, label='Speed for runner 1') plt.plot(y2, label='Speed for runner 2') # Put axis labels plt.xlabel('Distance (m)') plt.ylabel('Speed (m/s)') # Inlcude title plt.title('Better version') # legend() is necessary for the curve labels to appear plt.legend() plt.savefig('good_ex.pdf')
c901957b592edc23c8b162ab5483e8f005bf3de2
cbrandao18/python-practice
/math-practice.py
564
4.0625
4
import math numbers = [5, 8, 27, 34, 71, 6] n = len(numbers) def getSum(numbers): summation = 0 for num in numbers: summation = summation + num return summation def getSD(numbers): avg = getSum(numbers)/n numerator = 0 for num in numbers: numerator = numerator + (num - avg)**2 sd = math.sqrt(numerator/(n-1)) return sd print "The sum of the numbers is "+ str(getSum(numbers)) print "The average of the numbers is "+ str(getSum(numbers)/n) print "The standard deviation of the numbers is "+ str(getSD(numbers))
fe03952ad6982e0e51a9218b01dc9231df641b41
cbrandao18/python-practice
/celsius-to-f.py
226
4.1875
4
def celsiusToFahrenheit(degree): fahrenheit = degree*1.8 + 32 print fahrenheit celsiusToFahrenheit(0) celsiusToFahrenheit(25) n = input("Enter Celsius you would like converted to Fahrenheit: ") celsiusToFahrenheit(n)
edeff33f8b00a449bab826aa2b05a50108ea335f
luciengaitskell/csci-aerie
/csci0160/3-data/athome3_sorting_algos.py
6,579
4.15625
4
""" Sorting Algos Handout Due: October 7th, 2020 NOTES: - Reference class notes here: https://docs.google.com/document/d/1AWM3nnLc-d-4nYobBRuBTMuCjYWhJMAUx2ipdQ5E77g/edit?usp=sharing - Do NOT use online resources. - If you are stuck or want help on any of them, come to office hours! Completed by Lucien Gaitskell (LUC) EXERCISES 1. Suppose we have 243 identical-looking boxes each containing a drone ready to ship, but we remember that one box is missing instructions! This box will weigh a little less than the rest and there is a scale that can compare weights of any two sets of boxes. Assuming the worst case scenario, what is the minimum number of weighings needed to determine which box has the missing instructions? Hint: review the Tower of Hanoi stuff from class 2. Implement the following sorting algos (Insertion Sort, Merge Sort, and Quick Sort) in Python. Use comments to denotate which pieces of code refer to the recursive process of divide, conquer, and combine. Include 3-5 test cases for each algo. Hint: review the pseudocode from the lecture notes 3. In terms of time complexity, which one is more efficient - Merge Sort or Quick Sort? What about space memory efficiency? """ # LUC: Exercise 1 """ As this is the worst case scenario, all the boxes have to be weighed in some form. As only two boxes can be weighed at once, one option is to compare pairs of boxes. Two boxes will be paired and only compared against each other. If the weighing scale could compare more than two boxes, than I would use a binary search approach. """ # LUC: Exercise 2 def insertion_sort(l): """ LUC """ # Validate input if len(l) < 1 or not isinstance(l, list): return l current = 1 # Set element to compare while current < len(l): # Run until selected element is beyond range val = l[current] # Get value of selected value to insert swap_idx = current # Set initial index to compare for swap while val < l[swap_idx-1] and swap_idx>0: # If selected value is less than next swap element swap_idx -= 1 # Decrement swap position for i in reversed(range(swap_idx, current)): # Shift up each element after swap position l[i+1] = l[i] l[swap_idx] = val # Swap selected element to swap position current += 1 # Increment comparison index (could increment a second time if swap occurred) return l assert insertion_sort([]) == [] assert insertion_sort([1]) == [1] assert insertion_sort([2,1,5]) == [1, 2, 5] assert insertion_sort([2,1,5,3,4]) == [1, 2, 3, 4, 5] assert insertion_sort([5,4,3,2,1]) == [1, 2, 3, 4, 5] assert insertion_sort([9,2,56,2,1]) == [1, 2, 2, 9, 56] def merge_sort(l): """ LUC """ if len(l) <= 1: # Single or empty array -> already sorted return l pivot = int(len(l) / 2) # DIVIDE sublist1 = merge_sort(l[:pivot]) # CONQUER s1idx = 0 sublist2 = merge_sort(l[pivot:]) # CONQUER s2idx = 0 for i in range(len(l)): # COMBINE if ( (not s2idx < len(sublist2)) # If at end of sublist 2 or (s1idx < len(sublist1) and sublist1[s1idx] < sublist2[s2idx]) # or if sublist 1 has remaining elements and selected element is smaller than in list two ): l[i] = sublist1[s1idx] s1idx += 1 else: l[i] = sublist2[s2idx] s2idx += 1 return l assert merge_sort([2,1,4,6]) == [1, 2, 4, 6] assert merge_sort([7,3,10,4]) == [3, 4, 7, 10] assert merge_sort([7]) == [7] assert merge_sort([]) == [] import math DEBUG = False def quick_sort(l, start=0, end=None): """ LUC :param l: Input list, to sort :param start: First index of range to operate on :param end: Last index of range to operate on (last element is end-1) :return: Sorted list """ if DEBUG: print("\n\nStarting {}".format(l)) if end is None: end = len(l) if DEBUG: print("Operating idx {}->{}-1".format(start, end)) if end - start <= 1: # Empty or single lists are sorted if DEBUG: print("Ended") return l # Select pivot pidx = math.ceil((end-start)/2) + start - 1 pval = l[pidx] if DEBUG: print("Pivot: {} (idx {})".format(pval, pidx)) # Move pivot to end l[pidx] = l[end-1] l[end-1] = pval pidx = end-1 while True: if DEBUG: print("Loop {}".format(l)) #if DEBUG: print(l[start:end]) left = start # Move left selector from start until reaching a value greater than or equal to pivot while l[left] < pval and left <= end-2: left += 1 if DEBUG: print("Left:", left) right = end - 2 # Move right selector from second to last until reaching a value less than or equal to pivot while l[right] > pval and right >= start: right -= 1 if DEBUG: print("Right:", right) #if DEBUG: input() if left >= right: # selectors have crossed l[pidx] = l[right+1] l[right+1] = pval if DEBUG: print("Crossed swap {}".format(l)) if DEBUG: print("Recurse...") quick_sort(l, start, left) # Operate on left sublist quick_sort(l, left+1, end) # Operate on right sublist return l else: # intermediate swap # swap values at left and right selectors tmp = l[left] l[left] = l[right] l[right] = tmp if DEBUG: print("Intermediate swap {}".format(l)) assert quick_sort([10,3,6,4,11]) == [3,4,6,10,11] assert quick_sort([10,8,3,6,20,4]) == [3, 4, 6, 8, 10, 20] assert quick_sort([10,5,3,2,8,3,6,20,4]) == [2, 3, 3, 4, 5, 6, 8, 10, 20] assert quick_sort([10,8,3,6,20,4,18]) == [3,4,6,8,10,18,20] assert quick_sort([]) == [] assert quick_sort([1]) == [1] assert quick_sort([2,1]) == [1,2] # LUC: Question 3 """ Quick Sort can be the most efficient, with a potential for O(n). On average, the time complexity is O(nlogn), which is the same as the consistent values of Merge Sort. However, the inefficient quadratic cases for Quick Sort are very unlikely and therefore lead it to be more efficient the majority of the time. Merge Sort also requires O(n) memory, due to the nature of copying elements into new arrays and merging them afterwards. On the other hand, Quick Sort operates on a single list, in place. Therefore the algorithm only requires O(logn) memory complexity as the recursive operation will have a call stack of size ~logn. """
a07ada7c787f741ef1884b2a455b69fdab98f28c
Nawod/Hactoberfest2021-1
/Python/Guess_Number_Game.py
1,416
4.03125
4
import random import sys print('GUESS THE NUMBER') #function for genarate random numbers according to the levels def level(lvl): global randNo if lvl == 'E': randNo = random.randint(1,10) print('Guess a number between 1 & 10..') elif lvl == 'N': randNo = random.randint(1,20) print('Guess a number between 1 & 20..') elif lvl == 'H': randNo = random.randint(1,30) print('Guess a number between 1 & 30..') else: sys.exit('Invalid Input') return randNo #function for take the guessed numbers def guessNo(randNo): print('.......') print('You have only 3 chances') for i in range(0,3): global guess guess = int(input('Enter your guessed number : ')) if guess < randNo : print('The number Is Too Low') elif guess > randNo: print('The number Is Too High') else: break try: #get level to generate a randome no print('Select a level') print('(Enter the level first letter)') lvl = input('Easy\t- E\nNormal\t- N\nHard\t- H\n') randNo = level(lvl) guessNo(randNo) #Checking the input number and random number if guess == randNo: print('Congradulations! You guessed the number') else: print('Wrong guess!\nMy number was '+str(randNo)) except (ValueError): print("Enter a number only")
8040f07a2775078bcdc058cd58e49ef3c9fc2f96
lydxlx1/icpc
/src/codeforces/_1131F.py
883
3.5625
4
"""Codeforces 1131F Somehow, recursive implementation of Union-Find Algorithm will hit stack overflow... """ from sys import * n = int(stdin.readline()) parent, L, R, left, right = {}, {}, {}, {}, {} for i in range(1, n + 1): parent[i] = i L[i] = R[i] = i left[i] = right[i] = None def find(i): root = i while parent[root] != root: root = parent[root] while i != root: j = parent[i] parent[i] = root i = j return root def union(i, j): i, j = find(i), find(j) parent[i] = j # j is the new root a, b, c, d = L[i], R[i], L[j], R[j] L[j], R[j] = a, d right[b], left[c] = c, b for i in range(n - 1): u, v = stdin.readline().split(' ') union(int(u), int(v)) ans = [] root = L[find(1)] for i in range(n): ans.append(root) root = right[root] print(' '.join([str(i) for i in ans]))
c49b8274518bd59b4ba0fdfc75e6370afaec562b
lydxlx1/icpc
/src/adventofcode/2021_04.py
2,430
3.53125
4
import sys import math def readln_str(): return input().split(" ") def readln_int(): return [int(i) for i in readln_str()] class Board: def __init__(self, A): self.A = A self.visited = [ [False for _ in range(len(A[0]))] for _ in range(len(A))] def place(self, num): A = self.A for i in range(len(A)): for j in range(len(A[0])): if A[i][j] == num: self.visited[i][j] = True return def win(self): visited = self.visited for i in range(len(visited)): if all(visited[i]): return True for j in range(len(visited[0])): if all(visited[i][j] for i in range(len(visited))): return True return False def unmarked_sum(self): ans = 0 A, visited = self.A, self.visited for i in range(len(A)): for j in range(len(A[0])): if not visited[i][j]: ans += A[i][j] return ans def part1(): lines = [line.strip() for line in fin.read().strip().split("\n") if line.strip() != ''] seq = [int(token) for token in lines[0].split(",")] puzzles = [] i = 1 while i < len(lines): A = [] for _ in range(5): row = [int(token) for token in lines[i].split(" ") if token.strip() != ""] A.append(row) i += 1 puzzles.append(Board(A)) def doit(): for i in seq: for puzzle in puzzles: puzzle.place(i) if puzzle.win(): return i * puzzle.unmarked_sum() return None print(doit()) def part2(): lines = [line.strip() for line in fin.read().strip().split("\n") if line.strip() != ''] seq = [int(token) for token in lines[0].split(",")] puzzles = [] i = 1 while i < len(lines): A = [] for _ in range(5): row = [int(token) for token in lines[i].split(" ") if token.strip() != ""] A.append(row) i += 1 puzzles.append(Board(A)) ans = None for i in seq: for puzzle in puzzles: if not puzzle.win(): puzzle.place(i) if puzzle.win(): ans = i * puzzle.unmarked_sum() print(ans) with open('in.txt', 'r') as fin: # part1() part2()
36f9546b9a292d58f205ff22c9895fa65b0a70d9
Meldanen/kcl
/scientific_programming/algorithm_optimisation/pathing.py
10,269
3.578125
4
from itertools import chain import math from algorithmType import AlgorithmType import numpy as np def getAdjustedImageArray(image, algorithmType, size=None): """ Returns an image with the best path based on the selected method :param image: The image from which we'll look for the best path :param size: The image's size :param algorithmType: The algorithm type (i.e. dynamic) :return: an image that includes the best path """ validateAlgorithmType(algorithmType) validateImage(image) return getImageWithBestPath(image, size, algorithmType) def getImageWithBestPath(image, size, algorithmType): """ Returns an image with the best path based on the selected method :param image: The image from which we'll look for the best path :param size: The image's size :param algorithmType: The algorithm type (i.e. dynamic) :return: an image that includes the best path :raises: NotImplementedError if the algorithm type is not one of the implemented ones """ if algorithmType is algorithmType.BRUTE_FORCE: return getImageWithBestPathBruteForce(image, size) elif algorithmType is algorithmType.DYNAMIC: return getImageWithBestPathDynamic(image) raise NotImplementedError def getImageWithBestPathDynamic(image): """ Returns an image with the best path :param image: The image from which we'll look for the best path :return: an image with the best path """ if not isinstance(image, np.ndarray): image = np.array(image) costArray, backtrack = getCostAndBacktrackArrays(image) rows, columns = image.shape imageWithBestPath = np.zeros((rows, columns), dtype=np.int) j = np.argmin(costArray[-1]) for i in reversed(range(rows)): imageWithBestPath[i, j] = 1 j = backtrack[i, j] return imageWithBestPath def getCostAndBacktrackArrays(image): """ Computes the cost array which contains the best path and a backtrack array to trace the steps :param image: The image from which we'll look for the best path :return: a cost array for the best path and the backtrack array """ rows, columns = image.shape cost = image.copy() backtrack = np.zeros_like(cost, dtype=np.int) cost[0, :] = 0 for i in range(1, rows): for j in range(0, columns): # Make sure we don't try to use a negative index if we're on the left edge if j == 0: previousCosts = cost[i - 1, j:j + 2] costOfCurrentPaths = abs(image[i - 1, j:j + 2] - image[i, j]) indexOfBestNode = np.argmin(previousCosts + costOfCurrentPaths) backtrack[i, j] = indexOfBestNode + j costBetweenTheTwoNodes = abs(image[i - 1, indexOfBestNode + j] - image[i, j]) previousCost = cost[i - 1, indexOfBestNode + j] cost[i, j] = previousCost + costBetweenTheTwoNodes else: previousCosts = cost[i - 1, j - 1:j + 2] costOfCurrentPaths = abs(image[i - 1, j - 1:j + 2] - image[i, j]) indexOfBestNode = np.argmin(previousCosts + costOfCurrentPaths) backtrack[i, j] = indexOfBestNode + j - 1 costBetweenTheTwoNodes = abs(image[i - 1, indexOfBestNode + j - 1] - image[i, j]) previousCost = cost[i - 1, indexOfBestNode + j - 1] cost[i, j] = previousCost + costBetweenTheTwoNodes return cost, backtrack def getImageWithBestPathBruteForce(image, size): """ Creates all the possible paths and then finds the best one :param image: The image from which we'll look for the best path :param size: The image's size :return: an image with the best path """ size = getSize(image, size) validateSize(size) rows, columns = size paths = None for i in range(columns): if paths is None: paths = getAllPossiblePathsBruteForce(image, 0, i, rows - 1) else: paths = chain(paths, getAllPossiblePathsBruteForce(image, 0, i, rows - 1)) bestPath = getBestPathBruteForce(image, paths) return convertBestPathToImageWithBestPathBruteForce(image, bestPath, rows, columns) def convertBestPathToImageWithBestPathBruteForce(image, bestPath, rows, columns): """ Converts the best path to an image with the best path Not entirely sure if we need to return a different type depending on the initial one but I included it just in case :param image: The image from which we'll look for the best path :param bestPath: The best path :param rows: The image's rows :param columns: The image's columns :return: an image with the best path """ if isinstance(image, np.ndarray): return getImageWithBestPathForNumpyArray(bestPath, rows, columns) return getImageWithBestPathForPythonList(bestPath, rows, columns) def getImageWithBestPathForPythonList(bestPath, rows, columns): """ Converts the best path to an python list with the best path :param bestPath: The best path :param rows: The image's rows :param columns: The image's columns :return: an image with the best path """ imageWithBestPath = [[0] * columns for _ in range(rows)] for i in range(rows): for j in range(columns): if (i, j) in bestPath: imageWithBestPath[i][j] = 1 return imageWithBestPath def getImageWithBestPathForNumpyArray(bestPath, rows, columns): """ Converts the best path to a numpy array with the best path :param bestPath: The best path :param rows: The image's rows :param columns: The image's columns :return: an image with the best path """ imageWithBestPath = np.zeros((rows, columns), dtype=np.int) for i in range(rows): for j in range(columns): if (i, j) in bestPath: imageWithBestPath[i, j] = 1 return imageWithBestPath def getBestPathBruteForce(image, paths): """ Evaluates all paths in the image to find the best one :param image: The image from which we'll look for the best path :param paths: All the possible paths :return: The best path """ bestScore = math.inf bestPath = None for path in paths: score = 0 for i, j in path: # Stop if we reached the last node if i + 1 < len(path): x = path[i][0] y = path[i][1] w = path[i + 1][0] z = path[i + 1][1] value1 = image[x][y] value2 = image[w][z] score += abs(value1 - value2) if score < bestScore: bestScore = score bestPath = path return bestPath def getAllPossiblePathsBruteForce(image, i, j, rows, current_path=None): """ Calculates all the possible paths in the image :param image: The image from which we'll look for the best path :param i: The current row :param j: The current column :param rows: The total rows :param current_path: The current path :return: a list with all possible paths """ if current_path is None: current_path = [(i, j)] if i == rows: yield current_path else: for x, y in getPossibleNeighbors(image, i, j): if (x, y) not in current_path: for path in getAllPossiblePathsBruteForce(image, x, y, rows, current_path + [(x, y)]): yield path def getPossibleNeighbors(image, i, j): """ Finds the possible neighbours from the current point :param image: The image from which we'll look for the best path :param i: The current row :param j: The current column :return: """ for x, y in getAdjacentCells(i, j): if 0 <= x < len(image[0]) and 0 <= y < len(image): yield (x, y) def getAdjacentCells(i, j): """ Returns the direction of movement from the current node :param i: The current row :param j: The current column :return: The direction of movement from the current node """ yield (i + 1, j - 1) yield (i + 1, j) yield (i + 1, j + 1) def validateAlgorithmType(algorithmType): """ :param algorithmType: The solution method (i.e. dynamic) :raises ValueError: if the algorithm type is invalid """ if algorithmType is None or not isinstance(algorithmType, AlgorithmType): raise TypeError("Please use a valid algorithm type") def validateImage(image): """ :param image: The image from which we'll look for the best path :raises ValueError: if the image is invalid """ if image is None or len(image) == 0: raise ValueError("Image is empty or null") def validateSize(size): """ :param size: The image's size :raises ValueError: if the size is invalid """ if size is None or size[0] <= 0 or size[1] <= 0: raise ValueError("Dimensions must be greater than zero") def getSize(image, size): """ Get the size of the image :param image: The image from which we'll look for the best path :param size: If it's provided, we assume the user knows what they are doing :return: the size of the image """ if size is not None: return size if isinstance(image, np.ndarray): return getNumpyArraySize(image) return getPythonListSize(image) def getNumpyArraySize(image): """ Get the size of the image for numpy arrays :param image: The image from which we'll look for the best path :return: the size of the image """ return image.shape def getPythonListSize(image): """ The size of the image for python lists. If the length of a sublist is inconsistent (i.e. [[1,2,3], [1,2], [1,2,3]]) we raise an exception :param image: The image from which we'll look for the best path :return: the size of the image :raises ValueError: For inconsistent image dimensions """ rows = len(image) columns = None for column in image: if columns is None: columns = len(column) if len(column) != columns or columns != rows: raise ValueError("Image dimensions are inconsistent") return rows, columns
4b01cbf0895f080bfee152a52c3bcceed8b2df6e
nicoleta23-bot/instructiunea-if-while-for
/prb2.py
151
3.921875
4
import math n=int(input("dati numarul natural nenegativ n=")) s=0 for i in range (1,n+1): s+=(math.factorial(i)) print("suma 1!+2!+...n!= ",s)
1a7fcc21c19fe743f7517e5221b4de3fe871cf7c
tbgdwjgit/python3
/baseTest/first.py
6,425
4.15625
4
__author__ = 'Test-YLL' # -*- coding:utf-8 -*- import os print("Hello Python interpreter!") print("中文也没问题!") print('翻倍'*3) print('45+55') print(45+55) #注释 ''' 多行 print("Hello World") print('What is your name?') # ask for their name myName = input() print('It is good to meet you, ' + myName) print('The length of your name is:') print(len(myName)) print('What is your age?') # ask for their age myAge = input() print('You will be ' + str(int(myAge) + 1) + ' in a year.') 变量名只能包含以下字符: • 小写字母(a~z) • 大写字母(A~Z) • 数字(0~9) • 下划线(_) 名字不允许以数字开头。 ''' ''' 列表 ''' # letters =[2,22,'2cd',5] # print(letters[1]) # #append()和 extend()的区别 # letters.append('vvv') # letters.extend(['mmm']) # letters.extend('mmm') # letters.insert(3,'55') # print(letters) # letters.remove('55') # print(letters) # del letters[0] # print(letters) # print(letters.pop(1)) # print(letters.pop(1)) # print(letters.pop(0)) # print(letters) # letters.sort()#改变你提供的原始列表,而不是创建一个新的有序列表 # print(letters) # letters.reverse() # print(letters) ''' 集合 [] 能创建一个空列表 {} 会创建一个空字典 空集输出为 set() ''' print(set()) s_test ={1,2,3,4} s_test.add('a') print(s_test) """ 控制流 """ # print('What is your name?') # name = input() # print('What is your age?') # age = input() # # if name == 'Alice': # print('Hi, Alice.') # elif int(age) < 12: # print('You are not Alice, kiddo.') # else: # print('You are neither Alice nor a little kid.') # while True: # print('Who are you?') # name = input() # if name != 'Joe': # continue # print('Hello, Joe. What is the password? (It is a fish.)') # password = input() # if password == 'swordfish': # break # print('Access granted.') # print('My name is') # for i in range(5): # print('Jimmy Five Times (' + str(i) + ')') # import random # for i in range(5): # print(random.randint(1, 10)) # # import sys # sys.exit() ''' 函数 ''' # def hello(name): # print('Hello ' + name) # # hello('Alice') # hello('Bob') def printMyNameBig(): print(" CCCC A RRRRR TTTTTTT EEEEEE RRRRR ") print(" C C A A R R T E R R ") print("C A A R R T EEEE R R ") print("C AAAAAAA RRRRR T E RRRRR ") print(" C C A A R R T E R R ") print(" CCCC A A R R T EEEEEE R R") print() # for i in range(2): # printMyNameBig(); '''类''' class Dog(): '''一次模拟小狗的简单尝试''' def __init__(self, name, age): """初始化属性name和age""" self.name = name self.age = age #特殊方法是 __str__(),它会告诉 Python 打印(print)一个对象时具体显示什么内容。 def __str__(self): msg = "Hi, I'm a " + self.name + " " + str(self.age) + " ball!" return msg def sit(self): """模拟小狗被命令时蹲下""" print(self.name.title() + " is now sitting.") def roll_over(self): """模拟小狗被命令时打滚""" print(self.name.title() + " rolled over!") d = Dog('jack',10) # d.sit() # print(d) '''继承''' # class Car(): # """一次模拟汽车的简单尝试""" # # def __init__(self, make, model, year): # self.make = make # self.model = model # self.year = year # self.odometer_reading = 0 # # def get_descriptive_name(self): # long_name = str(self.year) + ' ' + self.make + ' ' + self.model # return long_name.title() # # def read_odometer(self): # print("This car has " + str(self.odometer_reading) + " miles on it.") # # def update_odometer(self, mileage): # if mileage >= self.odometer_reading: # self.odometer_reading = mileage # else: # print("You can't roll back an odometer!") # # def increment_odometer(self, miles): # self.odometer_reading += miles # # class ElectricCar(Car): # """电动汽车的独特之处""" # # def __init__(self, make, model, year): # """初始化父类的属性""" # super().__init__(make, model, year) # # my_tesla = ElectricCar('tesla', 'model s', 2016) # print(my_tesla.get_descriptive_name()) ''' 文件处理 os.getcwd()取当前目录 os.path.dirname(os.getcwd())取当前目录上一级目录 ''' import re def transformCodec(re_data):#ascii (gbk) 转 unicode try: re_data = re_data.decode('gbk') except Exception as error: print(error) print('delete illegal string,try again...') pos = re.findall(r'decodebytesinposition([\d]+)-([\d]+):illegal',str(error).replace(' ','')) if len(pos)==1: re_data = re_data[0:int(pos[0][0])]+re_data[int(pos[0][1]):] re_data = transformCodec(re_data) return re_data return re_data textFile = open(os.path.pardir +'\\readme.txt') # textFile ='C:\\Users\\Test-YLL\\PycharmProjects\\python3\\test.txt' # textFile =u'test.txt' print(textFile) print(os.path.dirname(os.getcwd()) +'\\readme.txt') textFile = os.path.dirname(os.getcwd()) +'\\readme.txt' # with open('test.txt') as file_object: with open(textFile) as file_object: contents = file_object.read() print(contents) # print(os.getcwd()) # print(os.path.dirname(os.getcwd())) # textFile =os.path.dirname(os.getcwd())+r'\readme.txt' # print(textFile) # with open(textFile,'rb') as file_object: # # with open(textFile,'r', encoding='gbk') as file_object: # # contents = file_object.read() # contents = transformCodec( file_object.read()) #转码 # print(contents) ''' Python数据可视化:Matplotlib pip install matplotlib pip install pandas pip install xlrd ''' # a = 5 # matplotlib.lines # from matplotlib.pyplot import plot # plot(a, a**2) # import matplotlib.pyplot as plt # import pandas as pd # # import seaborn as sns # import numpy as np # # # 0、导入数据集 # df = pd.read_excel('first.xlsx', 'Sheet1') # # var = df.groupby('BMI').Sales.sum() # fig = plt.figure() # ax = fig.add_subplot(111) # ax.set_xlabel('BMI') # ax.set_ylabel('Sum of Sales') # ax.set_title('BMI wise Sum of Sales') # var.plot(kind='line') # # plt.show()
ebc8d4374db54e557755d67cfe9d39631575fb3e
chm7374/linera_algebra_final
/linear_algebra_final/main.py
3,078
3.625
4
import numpy as np import fractions def create_matrix(): print("2x2 matrix:\n[ m11 m12 ]") print("[ m21 m22 ]") m11 = float(input("Enter the value of m11: ")) m12 = float(input("Enter the value of m12: ")) m21 = float(input("Enter the value of m21: ")) m22 = float(input("Enter the value of m22: ")) mat = np.matrix([[m11,m12], [m21, m22]]) mat_array = np.array([[m11,m12], [m21, m22]]) print(mat) print("\nExponential of Matrix: ") print(np.dot(np.array([[m11,m12],[m21,m22]]), np.array([[m11,m12],[m21,m22]]))) return mat, mat.trace(), mat_array def transpose_matrix(mat): mat_trs = np.matrix.getT(mat) print(mat_trs) return mat_trs def invert_matrix(mat): mat_inv = np.matrix.getI(mat) print(mat_inv) return mat_inv def determinant_matrix(mat): mat_det = np.linalg.det(mat) print(str(round(mat_det, 4))) return mat_det def rref(A, tol=1.0e-12): m, n = A.shape i, j = 0, 0 jb = [] while i < m and j < n: # Find value and index of largest element in the remainder of column j k = np.argmax(np.abs(A[i:m, j])) + i p = np.abs(A[k, j]) if p <= tol: # The column is negligible, zero it out A[i:m, j] = 0.0 j += 1 else: # Remember the column index jb.append(j) if i != k: # Swap the i-th and k-th rows A[[i, k], j:n] = A[[k, i], j:n] # Divide the pivot row i by the pivot element A[i, j] A[i, j:n] = A[i, j:n] / A[i, j] # Subtract multiples of the pivot row from all the other rows for k in range(m): if k != i: A[k, j:n] -= A[k, j] * A[i, j:n] i += 1 j += 1 # Finished return A, jb def eigen_matrix(mat): eigval_mat, eigvec_mat = np.linalg.eig(mat) print(eigval_mat) print("\nEigenvectors of Matrix: ") print(eigvec_mat) # The main function is the first thing the program will run when started. if __name__ == '__main__': # Makes it so the output is printed as fractions instead of decimals. np.set_printoptions(formatter={'all': lambda x: str(fractions.Fraction(x).limit_denominator())}) print("Matrix Equation Solver Thingy!\nby Cameron MacDonald | chm7374\n") mat, mat_trace, mat_array = create_matrix() print("\nTranspose of matrix: ") mat_trs = transpose_matrix(mat) print("\nInverse of matrix: ") mat_inv = invert_matrix(mat) print("\nDeterminant of matrix: ", end="") mat_det = determinant_matrix(mat) print("\nReduced row matrix: ") rref_mat, j = rref(mat) print(rref_mat) print("\nRank of Matrix:", np.linalg.matrix_rank(mat)) str_trace = str(mat_trace)[2:] str_trace = str_trace[:1] print("Trace of Matrix:", str_trace) np.set_printoptions(precision=5) print("\nEigenvalues of Matrix: ") eigen_matrix(mat_array)
5c9d24c0cc24a7f0346fe7cee3239a467c51dd6d
zainiftikhar52422/Perceptron-learning-gates-given-theta
/perceptron learning And gate.py
1,127
3.71875
4
import random def andGate(): # Or gate Learning # in and gate you can increase decimal points as much as you want weight1=round(random.uniform(-0.5,0.5), 1) # to round the out to 1 decimal point weight2=round(random.uniform(-0.5,0.5), 1) # to round the out to 1 decimal point print("Weighted intialization",weight1,weight2) thetha=0.2 alpha=0.1 flage=True # flage will be false when convergence reaches output=1 andGate=((0,0,0),(0,1,0),(1,0,0),(1,1,1)) while(flage==True): flage=False for examp in andGate: value=(examp[0]*weight1)+(examp[1]*weight2) if(value>=thetha): #if perceptoron excited output=1 else: output=0 if((output-examp[2])!=0): weight1=round(weight1+(alpha*(examp[2]-output)*examp[0]),1) # to round the out to 1 decimal point weight2=round(weight2+(alpha*(examp[2]-output)*examp[1]),1) # to round the out to 1 decimal point flage=True print(weight1,weight2) for i in range(5): andGate()
3009d64a201ffd4616985588111ec747f510925c
m-blue/prg105-Ex-16.1-Time
/Time.py
331
4.09375
4
class Time(): """ This will hold an object of time attributes: hours, minutes, seconds """ def print_time(hour, minute, sec): print '%.2d:%.2d:%.2d' % (hour, minute, sec) time = Time() time.hours = 4 time.minutes = 30 time.seconds = 45 print_time(time.hours, time.minutes, time.seconds)
2cee626ca8bbdd1c78751e9df019279d323d1e06
Philngtn/pythonDataStructureAlgorithms
/Arrays/ArrayClass.py
1,291
4.15625
4
# # # # # # # # # # # # # # # # # # # # # # # # # Python 3 data structure practice # Chap 1: Implementing Class # Author : Phuc Nguyen (Philngtn) # # # # # # # # # # # # # # # # # # # # # # # # class MyArray: def __init__(self): self.length = 0 # Declare as dictionary self.data = {} # Convert the class object into string def __str__(self): # convert all the class object to dictionary type {length, data} return str(self.__dict__) def get(self,index): return self.data[index] def push(self, item): self.data[self.length]= item self.length +=1 def pop(self): lastitem = self.data[self.length - 1] del self.data[self.length - 1] self.length -= 1 return lastitem def delete(self, index): deleteditem = self.data[index] # Shifting the data to one slot for i in range(index, self.length -1): self.data[i] = self.data[i+1] # Delete the last array slot del self.data[self.length - 1] self.length -= 1 return deleteditem newArray = MyArray() newArray.push("Hello. ") newArray.push("How") newArray.push("are") newArray.push("you") newArray.push("!") newArray.delete(1) print(newArray)
e96d19e436a77fcca9e16e143a81ea58eee15997
Philngtn/pythonDataStructureAlgorithms
/String.py
3,163
4
4
# # # # # # # # # # # # # # # # # # # # # # # # # Python 3 data structure practice # Chap 0: String # Author : Phuc Nguyen (Philngtn) # # # # # # # # # # # # # # # # # # # # # # # # # Strings in python are surrounded by either single quotation marks, or double quotation marks. print("Hello World") print('Hello World 2') # You can assign a multiline string to a variable by using three quotes: a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' print(a) ##################### Strings are Arrays ###################### a = "Hello, World" print(a[1]) # Output: e # Looping Through a String for x in "philngtn": print(x) # Output: philngtn # String Length print(len(a)) # Check String txt = "The best things in life are free!" print("free" in txt) # Check NOT in String txt = "The best things in life are free!" print("expensive" not in txt) ##################### Slicing Strings ###################### b = "Hello, World2" print(b[2:5]) # Output: llo, # Slice From the Start b = "Hello, World3" print(b[:5]) # Output: Hello, # Slice To the End b = "Hello, World!" print(b[2:]) # Negative Indexing # Use negative indexes to start the slice from the end of the string: b = "Hello, World!" print(b[-5:-2]) # From: "o" in "World!" (position -5) to, but not included: "d" in "World!" (position -2): ##################### Modify Strings ###################### # The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) # Lower Case a = "Hello, World!" print(a.lower()) # Remove Whitespace # The strip() method removes any whitespace from the beginning or the end: a = " Hello, World! " print(a.strip()) # returns "Hello, World!" # Replace String a = "Hello, World!" print(a.replace("H", "J")) # Split String a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!'] ##################### String Concatenation ###################### a = "Hello" b = "World" c = a + b print(c) ##################### String Format ###################### # The format() method takes the passed arguments, formats them, # and places them in the string where the placeholders {} are: age = 36 txt = "My name is John, and I am {}" print(txt.format(age)) quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price)) # You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) ##################### Escape Characters ###################### # To insert characters that are illegal in a string, use an escape character. txt = "We are the so-called \"Vikings\" from the north." # \' Single Quote # \\ Backslash # \n New Line # \r Carriage Return # \t Tab # \b Backspace # \f Form Feed # \ooo Octal value # \xhh Hex value
9fb22d73c2c5983d48283c648ab5ef1527cb4c1e
Philngtn/pythonDataStructureAlgorithms
/LinkedList/LinkedListClass.py
3,734
4.03125
4
# # # # # # # # # # # # # # # # # # # # # # # # # Python 3 data structure practice # Chap 3: Linked List # Author : Phuc Nguyen (Philngtn) # # # # # # # # # # # # # # # # # # # # # # # # from typing import NoReturn class Node: def __init__(self, data): self.value = data self.next = None def __str__(self): return str(self.__dict__) class LinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def __str__(self): return str(self.__dict__) def append(self,value): newNode = Node(value) if (self.length == 0): self.head = newNode self.tail = self.head self.length += 1 else: self.tail.next = newNode self.tail = newNode self.length += 1 def prepend(self, value): newNode = Node(value) if (self.length == 0): self.head = newNode self.tail = self.head self.length += 1 else: newNode.next = self.head self.head = newNode self.length += 1 def insert(self, value, location): newNode = Node(value) temp = self.head count = 0 if (self.length == 0): self.head = newNode self.tail = self.head self.length += 1 return 0 while (True): if location > self.length: self.append(value) break elif location == 0: self.prepend(value) break else: if (count != (location - 1)): temp = temp.next count += 1 else: newNode.next = temp.next temp.next = newNode self.length +=1 return 0 def remove(self,location): temp = self.head count = 0 while(True): if location > self.length or location < 0: return print("Error: location should be within length: " + str(self.length)) if (count != (location-1)): temp = temp.next count += 1 else: temp2 = temp.next temp.next = temp2.next temp2 = None self.length -= 1 return 0 def reverse(self): temp = self.head # set the tail at the beginning self.tail = self.head temp2 = temp.next if (self.length == 0): return "Empty list" if (self.length == 1): return 0 while (temp2 != None): temp3 = temp2.next temp2.next = temp temp = temp2 temp2 = temp3 self.head.next = None # set the head at the end of reverse list self.head = temp def printList(self): temp = self.head while temp != None: print(temp.value, end= ' ') temp = temp.next print() print('Length = ' + str(self.length)) myLinkedList = LinkedList() myLinkedList.append(22) myLinkedList.append(223) myLinkedList.append(221) myLinkedList.prepend(2123) myLinkedList.prepend(88) myLinkedList.prepend(53) myLinkedList.insert(1,22) myLinkedList.insert(42,0) myLinkedList.insert(1,4) myLinkedList.remove(4) myLinkedList.remove(99) print("--------------------") print("Linklist:") myLinkedList.printList() print("--------------------") print("Revered Linklist:") myLinkedList.reverse() myLinkedList.printList()
280fbe40b133e0b47f101f5855014fdb1fcb8815
Philngtn/pythonDataStructureAlgorithms
/Algorithm/Sorting/BubbleSort.py
338
4.0625
4
def bubble_sort(array): count = len(array) while(count): for i in range(len(array) - 1) : if(array[i] < array[i+1]): temp = array[i] array[i] = array[i + 1] array[i + 1] = temp count -= 1 a = [1,2,4,61,1,2,3] bubble_sort(a) print(a)
875635c71286360aef3af5b485e87d195974fa32
sepej/162P
/Lab6/main.py
478
3.859375
4
# Joseph Sepe CS162P Lab 6B from helper import * def main(): employees = [] # get number of employees to enter print("How many employees work at the company?") num_employees = get_integer(5, 10) # create an employee and add it to the list for num_employees for i in range(num_employees): new_employee = create_employee() employees.append(new_employee) display_employees(employees) exit() if __name__ == '__main__': main()
bc1fb8b5ec979d6031e2dfaf934defff52e6d45b
sepej/162P
/Lab1/functions.py
4,197
4.03125
4
# Display instructions def display_instructions(): print('\nWelcome to Tic-Tac-Toe\nTry to get 3 in a row!') # Reset board, rewrites the board list with '' def init_board(board): for idx, value in enumerate(board): board[idx] = '' # Get the player name, Returns X or O # Adds the possibility of letting players type their own names in. def player_name(player): if player == 0: return 'X' else: return 'O' def player_char(player): if player == 0: return 'X' else: return 'O' # Display the board def show_board(board): for idx, value in enumerate(board): if value == '': value = str(idx+1) if (idx+1) % 3 == 0: print('[' + value + ']') else: print('[' + value + ']', end='') print('') # Returns the valid move def valid_moves(board): validMoves = [] for idx, value in enumerate(board): if value == '': validMoves.append(idx+1) return validMoves # Enter the player's move def get_move(board, player): # Print player's name, calling function print("\nIt's " + player_name(player) + "'s turn\n") show_board(board) # Get a list of valid moves for the current board valid = valid_moves(board) # Enter the players move into the list while True: print("Move: ") choice = input() choice_int = int(choice) if choice_int in valid: board[choice_int-1] = player_char break else: print("Please choose a valid move") show_board(board) # Check win condition, returns true or false def check_win(board): # Check two squares, if they are the same then check the next in the sequence if board[4] == board[0] and board[4] != '': if board[4] == board[8]: # Player won, change the array to display a line where they won. board[0] = '\\' board[4] = '\\' board[8] = '\\' show_board(board) return True if board[4] == board[2] and board[4] != '': if board[4] == board[6]: board[2] = '/' board[4] = '/' board[6] = '/' show_board(board) return True if board[4] == board[1] and board[4] != '': if board[4] == board[7]: board[1] = '|' board[4] = '|' board[7] = '|' show_board(board) return True if board[0] == board[3] and board[0] != '': if board[0] == board[6]: board[0] = '|' board[3] = '|' board[6] = '|' show_board(board) return True if board[8] == board[5] and board[8] != '': if board[8] == board[2]: board[2] = '|' board[5] = '|' board[8] = '|' show_board(board) return True if board[8] == board[7] and board[8] != '': if board[8] == board[6]: board[6] = '-' board[7] = '-' board[8] = '-' show_board(board) return True if board[4] == board[3] and board[4] != '': if board[4] == board[5]: board[3] = '-' board[4] = '-' board[5] = '-' show_board(board) return True if board[0] == board[1] and board[0] != '': if board[0] == board[2]: board[0] = '-' board[1] = '-' board[2] = '-' show_board(board) return True return False # Check draw, if no win's then return true def check_draw(board): if check_win(board) == False: return True # Play again question def play_again(): return yes_no("Do you want to play again? (y/n)") # Passes in the question and then returns true or false for yes or no def yes_no(question): valid = ['y', 'n'] while True: print(question) choice = input() choice = choice.lower() if choice in valid: if choice == 'y': return True else: return False else: print("Please type y or n")
8557893e7488d2eb1993bbaf96b4e87a88a91bc4
sepej/162P
/Lab6/Sepe_Lab6A/employee.py
460
3.671875
4
from person import * class Employee: # init employee class composition def __init__(self, first_name = "", last_name = "", age = None): self.__person = Person(first_name, last_name, age) # return employee name def get_employee_name(self): return self.__person.get_first_name() + " " + self.__person.get_last_name() # return employee age def get_employee_age(self): return self.__person.get_age()
6470b470180117635b5e5515ee39d08951ca1118
Spencer-Weston/DatatoTable
/datatotable/typecheck.py
4,509
4.125
4
""" Contains type checks and type conversion functions """ from datetime import datetime, date from enum import Enum def set_type(values, new_type): """Convert string values to integers or floats if applicable. Otherwise, return strings. If the string value has zero length, none is returned Args: values: A list of values new_type: The type to coerce values to Returns: The input list of values modified to match their type. String is the default return value. If the values are ints or floats, returns the list formatted as a list of ints or floats. Empty values will be replaced with none. """ if new_type == str: coerced_values = [str(x) for x in values] elif new_type == int or new_type == float: float_values = [float(x) for x in values] if new_type == int: coerced_values = [int(round(x)) for x in float_values] else: coerced_values = float_values else: raise ValueError("{} not supported for coercing types".format(new_type.__name__)) return coerced_values def _set_type(values, new_type): """Transforms a list of values into the specified new type. If the value has zero length, returns none Args: values: A list of values new_type: A type class to modify the list to Returns: The values list modified to the new_type. If an element is empty, the element is set to None. """ new_vals = [] for i in values: if len(i) > 0: # Some values may have len(0); we convert them to None to put into sql db new_vals.append(new_type(i)) else: new_vals.append(None) return new_vals def get_type(values): """Return the type of the values where type is defined as the modal type in the list. Args: values: A list or value to get the type for. Returns: The modal type of a list or the type of the element. Can be integer, float, string, datetime, or none """ if hasattr(values, "__len__") and (type(values) != type): # Checks if the object is iterable val_types = [] for i in values: val_types.append(_get_type(i)) type_set = set(val_types) if len(type_set) == 1: return type_set.pop() elif len(type_set) == 2 and {None}.issubset(type_set): # None value allowance return type_set.difference({None}).pop() elif len(type_set) <= 3 and {int, float}.issubset(type_set): diff = type_set.difference({int, float}) if not bool(diff) or diff == {None}: return float else: return str else: # All other possible combinations of value must default to string return str elif isinstance(values, Enum): # For enum objects, pass the value to the get_type function (right choice? IDK) return _get_type(values.value) else: return _get_type(values) def _get_type(val): """Return the type of the value if it is a int, float, or datetime. Otherwise, return a string. Args: val: A value to get the type of Returns: The type of the value passed into the function if it is an int, float, datetime, or string Raise: Exception: An exception raised if the val is not int, float, datetime, None, or string. """ if isinstance(val, int): return int elif isinstance(val, float): return float elif isinstance(val, datetime): return datetime elif isinstance(val, date): return date elif isinstance(val, str): return str elif isinstance(val, bool): return bool elif val is None: return None elif is_python_type(val): # Handles types that are passed explicitly return val else: raise Exception("Val is not an int, float, datetime, string, Bool, or None") def is_int(x): """Return true if X can be coerced to a integer. Otherwise, return false.""" try: int(x) # Will raise ValueError if '.2'; will not raise error if .2 return True except ValueError: return False def is_float(x): """Return true if X can be coerced to a float. Otherwise, return false.""" try: float(x) return True except ValueError: return False def is_python_type(x): if x in [int, float, datetime, str, bool, None]: return True else: return False
f371d7904f943099dd17d251df171b63592d8c9c
hhost-madsen/prg105-drawingObject
/House.py
633
3.515625
4
import turtle bob = turtle.Turtle() alice = turtle.Turtle() def square(t): for i in range(4): t.fd(100) t.lt(90) square(bob) square(alice) def square(t, length): for i in range(4): t.fd(length) t.lt(90) square(bob, 100) def polygon(t, n, length): angle = 360 / n for i in range(n): t.fd(length) t.lt(angle) bob.lt(90) bob.fd(100) bob.rt(90) polygon(bob, 3, 100) bob.rt(90) bob.fd(100) bob.lt(90) bob.fd(40) bob.lt(90) bob.fd(50) bob.rt(90) bob.fd(20) bob.rt(90) bob.fd(50) turtle.done()
d3c36626dce89bafc3df9b8e63adaab05bdd4c30
etx77/protostar-write-up
/alpha.py
170
4.0625
4
#!/usr/bin/env python import string # this program is generate string to calculate return address text = "" for c in string.ascii_uppercase: text += c*4 print text
9d7b65b56e55b02b6ff598018da15c9ce16ac4e2
yitu257/pythondemo
/filterSquareInteger.py
902
3.765625
4
#过滤出1~100中平方根是整数的数: import math def is_sqr(x): return math.sqrt(x)%1==0 templist=filter(is_sqr,range(1,101)) newlist=list(templist) print(newlist) # 通过字典设置参数 site = {"name": "菜鸟教程", "url": "www.runoob.com"} print("网站名:{name}, 地址 {url}".format(**site)) print(globals()) #a=input("input:") #print(a) v=memoryview(bytearray("abcdef",'utf-8')) print(v[1]) print(v[-1]) print(v[-2]) print(v[1:4]) print(v[1:4].tobytes()) print(v) lst_t=("a",77,"bbcc",("user1","name","sex","age")) print(lst_t[:2]) print(lst_t[:-3:-1]) print(lst_t[:3:2]) print(lst_t[::2]) print(lst_t[::-2]) dict = "abcd efgh"; print(dict) print(repr(dict)) print(str(dict)) RANGE_NUM = 100 for i in (math.pow(x,2) for x in range(RANGE_NUM)): # 第一种方法:对列表进行迭代 # do sth for example print(i)
ba97831c540e5109dd1cfe338c885f4004b191b8
avshrudai1/recommedation_engine_chrome
/main.py
1,044
3.625
4
# importing the module import pandas as pd import csv import numpy from googlesearch import search # taking input from user val = input("Enter your command: ") #splitting the command to subparts K = val.split() T = len(K) def queryreform(): search_name = 'Brooks' with open('tmdb_5000_movies.csv', 'r') as file: output = re.findall(f'{search_name}.*', file.read()) for row in output: items = row.split(',') print(items[0], '>>' ,items[1]) def similar(): def searchit(): from googlesearch import search for i in search(query, tld="co.in", num=1, stop=10, pause=2): print(i) #splitting the cases based on command length if T == 0: print("Error: no commands!") elif T == 1: query = "allintext:" query = query.append(#columns) searchit() print(x) elif T == 2: query = "allintext:" query = query.append(#columns) searchit() elif T == 3: query = "allintext:" query = query.append(#columns searchit() else: print("Error: Too many commands!")
b9bdcf609dd73187034012475399c0eda465fb79
yarlagaddalakshmi97/python-solutions
/python_set1_solutions/set1-4a.py
173
3.5
4
''' a) The volume of a sphere with radius r is 4/3pr3. What is the volume of a sphere with radius 5? Hint: 392.7 is wrong! ''' r=5 volume=(4/3)*3.142*(r*r*r); print(volume)
5ab66decbeb7f56a685d621d6eb7695d6021ac47
yarlagaddalakshmi97/python-solutions
/python_practice/cmd-args1.py
470
4.0625
4
from sys import argv if(len(argv)<3): print("insufficient arguments..can't proceed..please try again..") elif argv[1]>argv[2] and argv[1]>argv[3]: print("argument 1 is largest..") elif argv[1]>argv[2] and argv[1]<argv[3]: print("argument 3 is largest..") elif argv[2]>argv[1] and argv[2]>argv[3]: print("argument 2 is largest..") elif argv[2] > argv[1] and argv[3] > argv[2]: print("argument 3 is largest..") else: print("the numbers are same..")
1b2b5047eaa337f94083a7b09e7b8103cc8170ca
yarlagaddalakshmi97/python-solutions
/python_practice/nested for loop.py
792
4.0625
4
''' for i in range(1,10): for j in range(1,i+1): print(i,end=" ") print("\n") for i in range(1,10): for j in range(1,i): print(j,end=" ") print("\n") for i in range(1,10): for j in range(1,i): print("*",end=" ") print("\n") for i in range(1,5): for j in range(1,5): print("*",end=" ") print("\n") ''' ''' n=int(input("enter a number:\n")) for i in range(1,n+2): for j in range(1,i): print("*",end=" ") print("\n") ''' ''' i=1 while(i<=5): print(i) i=i+1 ''' ''' i=1 while(i<=5): print(i) if(i==3): print("you have reached the limit....") print("bye") break i=i+1 ''' i=1 while(i<=5): print(i) i = i + 1 if(i==3): print(i) continue
9c3f2d4f7813d13d83db9c1b19108ac1dc2260ed
yarlagaddalakshmi97/python-solutions
/python_set3_solutions/set3-8.py
617
4.0625
4
''' 8.Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there? (i.e) "Abhor" or "Aux" or "Aadil" should return "True" Banana should return "False" ''' def abecedarian(words): for i in words: for j in (0,len(i)): if ord(i[j])>ord[j+1]: print(i[j]) break elif i[j]==i[len[i]-1]: return i else: continue words = input("enter words:\n").split(" ") print(words) print(abecedarian(words))
0606f08dfe5a4f9f41b38c60330ed5de7852c64e
yarlagaddalakshmi97/python-solutions
/python_practice/factorial.py
101
3.578125
4
def fact(n): if n>0: return 1 else: return n*fact(n-1) res=fact(7) print(res)
e3814888ad456dbcd5e9fc3ae048ff8395dfad80
yarlagaddalakshmi97/python-solutions
/python_set2_solutions/set2-6.py
790
4
4
''' 6.Implement a function that satisfies the specification. Use a try-except block. def findAnEven(l): """Assumes l is a list of integers Returns the first even number in l Raises ValueError if l does not contain an even number""" ''' ''' try: list1 = list(input("enter list of integers..:\n")) num = 0 for l in list1: if int(l) % 2 == 0 and num == 0 and int(l)!=0: print(l) num = l if num == 0: raise ValueError except ValueError: print("list does not contain an even number") ''' list1=list(input("enter list\n")) def findAnEven(l): for i in l: if int(i) % 2 == 0: return i else: raise ValueError try: print(findAnEven(list1)) except ValueError: print("no even numbers in list")
94c4554eea473193dff5415d66e7fe3253fd7d36
yarlagaddalakshmi97/python-solutions
/python_set2_solutions/set2-4.py
229
4.03125
4
''' 4.Write a program that computes the decimal equivalent of the binary number 10011? ''' string1='10011' count=len(string1)-1 number=0 for char in string1: number=number+(int(char)*(2**count)) count-=1 print(number)
7842f4fb35ab747fba9c8207b7eb4f1ec7a20a92
MDLR29/python_class
/entrenamiento.py
243
3.828125
4
np=int(input(" usuarios a evaluar: ")) lm=1 sumed=0 while lm<=np : genero=input(" cual es tu genero: ") edad=int(input("escriba su edad: ")) lm = lm + 1 sumed=sumed+edad promedio=sumed/np print("el promedioes: ",promedio)
b515031a176de8d788207e9a53fafa3ae2e86559
wnsdud4206/stockauto
/test2.py
809
3.5625
4
# from datetime import datetime # t_now = datetime.now() # t_9 = t_now.replace(hour=9, minute=0, second=0, microsecond=0) # t_start = t_now.replace(hour=9, minute=5, second=0, microsecond=0) # t_sell = t_now.replace(hour=15, minute=15, second=0, microsecond=0) # t_exit = t_now.replace(hour=15, minute=20, second=0,microsecond=0) # today = datetime.today().weekday() # print('t_now: ' + str(t_now)) # print('t_9: ' + str(t_9)) # print('t_start: ' + str(t_start)) # print('t_sell: ' + str(t_sell)) # print('t_exit: ' + str(t_exit)) # print('week: ' + str(today)) def test_1(): global myText myText = "awesome-text" print("hello, world - 1 " + myText) test_1() def test_2(): print("hello, world - 2 " + myText) test_2() # myList = ["a", "b", "c"] # print(len(myList)) # print(1 <= 1)
8e17ae60197afe42c01addf2cf79aafcae6cd01e
Abhra-Debroy/Udacity-ML-Capstone
/utilties.py
6,889
3.6875
4
## Disclaimer : Reuse of utility library from Term 1 course example ########################################### # Suppress matplotlib user warnings # Necessary for newer version of matplotlib import warnings warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib") # # Display inline matplotlib plots with IPython from IPython import get_ipython get_ipython().run_line_magic('matplotlib', 'inline') ########################################### import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd import numpy as np from sklearn.decomposition import PCA from sklearn.mixture import GaussianMixture from sklearn.metrics import silhouette_score from sklearn.cluster import KMeans,MiniBatchKMeans from sklearn.model_selection import learning_curve from sklearn.metrics import roc_auc_score # my_pca function was taken from class notes and altered def my_pca(data, n_components = None): ''' Transforms data using PCA to create n_components, and provides back the results of the transformation. INPUT: n_components - int - the number of principal components , default is None OUTPUT: pca - the pca object after transformation data_pca - the transformed data matrix with new number of components ''' pca = PCA(n_components) data_pca = pca.fit_transform(data) return pca, data_pca def plot_pca(pca): ''' Creates a scree plot associated with the principal components INPUT: pca - the result of instantian of PCA i OUTPUT: None ''' n_components=len(pca.explained_variance_ratio_) ind = np.arange(n_components) vals = pca.explained_variance_ratio_ plt.figure(figsize=(10, 6)) ax = plt.subplot(111) cumvals = np.cumsum(vals) ax.bar(ind, vals) ax.plot(ind, cumvals) for i in range(n_components): ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), va="bottom", ha="center", fontsize=12) ax.xaxis.set_tick_params(width=0) ax.yaxis.set_tick_params(width=2, length=12) ax.set_xlabel("Principal Component") ax.set_ylabel("Explained Variance (%)") plt.title('Explained Variance vs Principal Component') def pca_results(good_data, pca): ''' Create a DataFrame of the PCA results Includes dimension feature weights and explained variance ''' # Dimension indexing dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)] # PCA components components = pd.DataFrame(np.round(pca.components_, 4), columns = list(good_data.keys())) components.index = dimensions # PCA explained variance ratios = pca.explained_variance_ratio_.reshape(len(pca.components_), 1) variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance']) variance_ratios.index = dimensions # Return a concatenated DataFrame return pd.concat([variance_ratios, components], axis = 1) def features_of_component(pca, component, column_names): ''' Map weights for the component number to corresponding feature names Input: pca : the pca object after transformation component (int): component number to map to feature column_names (list(str)): column names of DataFrame for dataset Output: df_features (DataFrame): DataFrame with feature weight sorted by feature name ''' weight_array = pca.components_[component] df_features = pd.DataFrame(weight_array, index=column_names, columns=['Weight']) variance = pca.explained_variance_ratio_[component].round(2)*100 df_features= df_features.sort_values(by='Weight',ascending=False).round(2) return variance, df_features def get_minikmeans_score(data, nu_clusters, batch_size=50000): ''' returns the kmeans score regarding SSE for points to centers INPUT: data - the dataset you want to fit kmeans to center - the number of centers you want (the k value) OUTPUT: score - the SSE score for the kmeans model fit to the data ''' #instantiate kmeans kmeans = MiniBatchKMeans(n_clusters=nu_clusters, batch_size=batch_size, random_state=42) # Then fit the model to your data using the fit method model = kmeans.fit(data) # Obtain a score related to the model fit score = np.abs(model.score(data)) # both inertia_ and score gives same output #inertia = model.inertia_ return score def get_minikmeans_silhouette_score(data, nu_clusters, batch_size=50000, sample_size =50000): ''' returns the kmeans silhouette_score ts to centers INPUT: data - the dataset you want to fit kmeans to center - the number of centers you want (the k value) OUTPUT: score - silhouette_score for the kmeans model fit to the data ''' #instantiate kmeans kmeans = MiniBatchKMeans(n_clusters=nu_clusters, batch_size=batch_size, random_state=42) # Then fit the model to your data using the fit method #kmeans.fit(data) #cluster_labels = kmeans.labels cluster_labels = kmeans.fit_predict(data) # Obtain a score related to the model fit s_score = silhouette_score(data, cluster_labels,sample_size=sample_size, metric='euclidean',random_state=42) return s_score def draw_learning_curves(estimator, x, y, training_num): ''' Draw learning curve that shows the validation and training auc_score of an estimator for training samples. Input: X: dataset y: target estimator: object type that implements the “fit” and “predict” methods training_num (int): number of training samples to plot Output: None ''' train_sizes, train_scores, validation_scores = learning_curve( estimator, x, y, train_sizes = np.linspace(0.1, 1.0, training_num),cv = None, scoring = 'roc_auc') train_scores_mean = train_scores.mean(axis = 1) validation_scores_mean = validation_scores.mean(axis = 1) plt.grid() plt.ylabel('AUROC', fontsize = 14) plt.xlabel('Training set size', fontsize = 14) title = 'Learning curves for ' + str(estimator).split('(')[0] plt.title(title, fontsize = 15, y = 1.03) plt.plot(np.linspace(.1, 1.0, training_num)*100, train_scores_mean, 'o-', color="g", label="Training score") plt.plot(np.linspace(.1, 1.0, training_num)*100, validation_scores_mean, 'o-', color="y", label="Cross-validation score") plt.yticks(np.arange(0.45, 1.02, 0.05)) plt.xticks(np.arange(0., 100.05, 10)) plt.legend(loc="best") print("") plt.show() print("Roc_auc train score = {}".format(train_scores_mean[-1].round(2))) print("Roc_auc validation score = {}".format(validation_scores_mean[-1].round(2)))
358c68067412029677c59023d1f4b35af58c54ff
yuniktmr/String-Manipulation-Basic
/stringOperations_ytamraka.py
1,473
4.34375
4
#CSCI 450 Section 1 #Student Name: Yunik Tamrakar #Student ID: 10602304 #Homework #7 #Program that uses oython function to perform word count, frequency and string replacement operation #In keeping with the Honor Code of UM, I have neither given nor received assistance #from anyone other than the instructor. #---------------------- #-------------------- #method to get number of words in string def wordCount(a): b = a.split(" ") count = 0 for word in b: count = count + 1 print("The number of words is {}".format(count)) #method to get the most repititive word def mostFrequentWord(b): c = b.split(" ") dict = {} #mapping word with its wordcount. for word in c: dict[word] = c.count(word) max = 0 for word in dict: if (dict[word] > max): max = dict[word] for word in dict: if(dict[word] == max): print('The word with max occurence is', word) #method to replace the words in the string def replaceWord(a, d ,c): words = a.split(" ") wordCheck = False for word in words: if d == word: wordCheck = True if wordCheck: print("\nOriginal is ",a) print("The new string after replacement is ",a.replace(d,c)) else: print("Word not found") #main method to call the functions a= input("Enter a word\n") wordCount(a) mostFrequentWord(a) b = input("\nEnter a word you want to be replaced. Separate them with a space\n") c = b.split(" ") #invoke the replaceWord method replaceWord(a, c[0], c[1])
189da51101c163022df6d8b417da004cba11c649
annamunhoz/learningpython
/exercise01.py
476
4
4
# Exercise 01: create a python program that takes 2 values # and then select between sum and sub. Show the result. print("Submit your first number") first_number = float(input()) print("Submit your second number") second_number = float(input()) print("Choose the basic arithmetic: type SUM for sum or SUB for subtraction") arithmetic = input() if arithmetic == "SUM": print(first_number + second_number) else: print(first_number - second_number)
904398e1e75159b8047dc94757e5a7ac0dfb16e8
wxb-gh/py_test
/demo3.py
363
3.796875
4
# coding:gbk colours = ['red', 'green', 'blue'] names = ['a', 'b', 'c'] for colour in colours: print colour for i, colour in enumerate(colours): print i, ' -> ', colour for colour in reversed(colours): print colour for colour in sorted(colours, reverse=True): print colour for name, colour in zip(names, colours): print name, '->',colour
7345117ef887ad5049d57e2688e1ce8d5601f001
AndrewsDutraDev/Algoritmos_2
/Tabelas/Teste.py
886
3.53125
4
from Tabelas import Table tamanho_tabela = 5 tabela = Table(tamanho_tabela) # Inicializa a tabela com tamanho 3 tabela.insert("xyz", "abc") #Insere um valor e uma key tabela.insert("dfg","dfb") #Insere um valor e uma key tabela.insert("ffg","dfb") #Insere um valor e uma key tabela.insert("hfg","dfb") #Insere um valor e uma key tabela.insert_sort("abc","dfb") #Insere um valor e uma key de maneira ordenada print('Size: '+str(tabela.size())) #Retorna o tamanho da tabela print(tabela.search('lin_bin', "ffg")) # Faz o search pela key passando como primeiro parâmetro o tipo de busca. 'bin' para binária e '' para linear. Retorna a posição print(tabela.__repr__()) #Retorna a tabela #print(tabela.search_bin("ffg", 0, tamanho_tabela)) #Pesquisa diretamente usando a busca binária. Retorna a posição #print(tabela.search('', 'ffg')) #print(tabela.destroy()) #Destrói a tabela
5ccf9390ee5678a3c21acbd019df5673c7ff08a5
AndrewsDutraDev/Algoritmos_2
/Recursão/recursao2.py
1,623
3.734375
4
# Busca Encadeada Recursiva def busca_encadeada(): if (len(lista) == 0): return else: if (lista[0] == produto): return cont else: cont = cont + 1 return busca_encadeada(lista[1:], produto, cont) # Busca Linear Recursiva def busca_linear_recursiva(lista, produto, cont): if (len(lista) == 0): return else: if (lista[0] == produto): return cont else: cont = cont + 1 return busca_linear_recursiva(lista[1:], produto, cont) # Ordenação para busca binária em tabela def ordena(lista2): cont = 1 for i in range(len(lista2) - 1, 0, -1): for j in range(i): if lista2[j] > lista2[j + 1]: (lista2[j], lista2[j + 1]) = (lista2[j + 1], lista2[j]) return lista2 #Função que executa os dois tipos de listas def busca(lista, tipo, produto): if (tipo == 'bin'): listaOrd = ordena(lista) return busca_linear_recursiva(listaOrd, produto, cont) else: return busca_linear_recursiva(lista, produto, cont) #Função de busca binária def search_bin(lista, produto, inicio, fim): #função para buscar de forma binária if len(lista): mid = ((inicio + fim) // 2) if lista[mid] == produto: return mid + 1 if (produto < lista[mid]): return self.search_bin(lista, produto, inicio, mid - 1) else: return self.search_bin(lista, produto, mid + 1, fim) return cont = 1 lista = [5,3,1,2,8] tipo = 'lin' produto = 2 print(busca(lista, tipo, produto))
3b2a0f4b8f0a7c1f9e480ded60b1a2aaf2c75603
taniarebollohernandez/progAvanzada
/ejercicio7.py
85
3.6875
4
n = float(input('Inserta un numero positivo: ')) print('suma',int(((n*(n+1)/2))))
124e7250acd99e2668d71cf4717f0b54db63f7ab
taniarebollohernandez/progAvanzada
/ejercicio5.py
792
4.03125
4
#In many jurisdictions a small deposit is added to drink containers to encourage peopleto recycle them. In one particular jurisdiction, drink containers holding one liter or less have a $0.10 deposit, and drink containers holding more than one liter have a $0.25 deposit. Write a program that reads the number of containers of each size from the user. Your program should continue by computing and displaying the refund that will be received for returning those containers. Format the output so that it includes a dollar sign and always displays exactly two decimal places. poquitos = float(input('¿cuantos envases de 1 litro o menos tiene?')) muchos = float(input('¿cuantos envases de mas de 1 litro tiene?')) print('Tu reembolso total es de $', 0.10 * poquitos + 0.25 * muchos)
de52a7dc06b7dcd402a07e8d76a00f487f5e84b8
kazimuth/python-mode-processing
/examples/misc/triflower/triflower.pde
999
3.65625
4
""" Adapted from the TriFlower sketch of Ira Greenberg """ # # Triangle Flower # by Ira Greenberg. # # Using rotate() and triangle() functions generate a pretty # flower. Uncomment the line "# rotate(rot+=radians(spin))" # in the triBlur() function for a nice variation. # p = [None]*3 shift = 1.0 fade = 0 fillCol = 0 rot = 0 spin = 0 def setup(): size(200, 200) background(0) smooth() global fade,spin fade = 255.0/(width/2.0/shift) spin = 360.0/(width/2.0/shift) p[0] = PVector (-width/2, height/2) p[1] = PVector (width/2, height/2) p[2] = PVector (0, -height/2) noStroke() translate(width/2, height/2) triBlur() def triBlur(): global fillCol,rot fill(fillCol) fillCol+=fade rotate(spin) # another interesting variation: uncomment the line below # rot+=radians(spin) rotate(rot) p[0].x+=shift p[0].y-=shift p[1].x-=shift p[1].y-=shift p[2].y+=shift triangle (p[0].x, p[0].y, p[1].x, p[1].y, p[2].x, p[2].y) if p[0].x<0: # recursive call triBlur()
f6a909d7e0d878aaf314109c6b594bc80964da83
LucasFerreira06/ExercicioProva4Dupla
/Questao2.py
1,306
3.921875
4
def adicionarSorteado(sorteados): numAdd = random.randint(0, 100) sorteados.append(numAdd) print(sorteados) def adicionarAluno(alunos, matricula, nome): alunos[matricula] = nome def exibirAlunos(alunos): for chave, valor in alunos.items(): print("Matricula:", chave, "Aluno:", valor) def buscarAluno(alunos, matricula): for achado, nome in alunos.items(): if(achado == matricula): print("Matricula encontrado! ->", achado, "Aluno:", nome) def Menu(): contador = 0 while(contador == 0): escolha = eval(input("1 para adicionar um numero a lista, 2 para adicionar um aluno a lista, 3 para exibir os alunos, 4 para buscar aluno e 5 para sair.")) if(escolha == 1): adicionarSorteado(sorteados) elif(escolha == 2): matricula = eval(input("Digite a matricula para adicionar: ")) nome = input("Digite o nome do aluno: ") adicionarAluno(alunos, matricula, nome) elif(escolha == 3): exibirAlunos(alunos) elif(escolha == 4): matricula = eval(input("Digite a matricula a ser buscada: ")) buscarAluno(alunos, matricula) else: contador = 1 Menu()
48c6bbe599a6444304766b3f23a51a43adb8103a
PrashantMittal54/Data-Structures-and-Algorithms
/String/Look-and-Say Sequence String.py
927
4.09375
4
# Look-and-Say Sequence # To generate a member of the sequence from the previous member, read off the digits of the previous member # and record the count of the number of digits in groups of the same digit. # # For example, 1 is read off as one 1 which implies that the count of 1 is one. As 1 is read off as “one 1”, # the next sequence will be written as 11 where 1 replaces one. Now 11 is read off as “two 1s” as the count # of “1” is two in this term. Hence, the next term in the sequence becomes 21. def next_number(s): idx = 0 output = [] while idx < len(s): count = 1 while idx+1 < len(s) and s[idx] == s[idx+1]: count += 1 idx += 1 output.append(str(count)) output.append(s[idx]) idx += 1 return ''.join(output) s = "1" print(s) n = 8 for i in range(n-1): s = next_number(s) print(s)
5e1c85a492b786dcb674a436f3bb7fb9ad6f8559
PrashantMittal54/Data-Structures-and-Algorithms
/LinkList/Deletion.py
1,778
3.796875
4
# Deletion by Value and Position class Node: def __init__(self, data): self.data = data self.next = None class Linklist: def __init__(self): self.head = None def delete_node_at_pos(self, pos): cur = self.head if pos == 0: self.head = cur.next cur = None return count = 0 prev = None while cur and count != pos: prev = cur cur = cur.next count += 1 if not cur: return None prev.next = cur.next cur = None def delete_node(self, key): cur = self.head if cur and cur.data == key: self.head = cur.next # cur.data = None cur = None return prev = None while cur: prev = cur cur = cur.next if cur and cur.data == key: prev.next = cur.next # cur.data = None cur = None return else: return print('Node does not exist') def append(self, data): new_node = Node(data) curr = self.head if curr is None: self.head = new_node return while curr.next: curr = curr.next curr.next = new_node def print_list(self): curr = self.head while curr: print(curr.data) curr = curr.next llist = Linklist() llist.append("A") llist.append("B") llist.append("C") llist.append("D") llist.print_list() llist.delete_node("B") llist.print_list() llist.delete_node("E") llist.delete_node_at_pos(1) llist.print_list()
19013fbbb00b4c43c334ccf48a52b13c278932ee
PrashantMittal54/Data-Structures-and-Algorithms
/LinkList/Move Tail to Head.py
1,023
3.859375
4
class Node: def __init__(self, data): self.data = data self.next = None class Linklist: def __init__(self): self.head = None def append(self, data): new_node = Node(data) curr = self.head if curr is None: self.head = new_node return while curr.next: curr = curr.next curr.next = new_node def print_list(self): curr = self.head while curr: print(curr.data) curr = curr.next def move_tail_to_head(self): if not self.head: return curr = self.head prev = None while curr.next: prev = curr curr = curr.next curr.next = self.head self.head = curr prev.next = None llist = Linklist() llist.append("A") llist.append("B") llist.append("C") llist.append("D") # llist.print_list() llist.move_tail_to_head() llist.print_list()
db4df4d10e3392349cb74bb36f5614c794e59eff
PrashantMittal54/Data-Structures-and-Algorithms
/Array/Arbitrary Precision Increment Array.py
353
3.65625
4
def plus_one(A): A[-1] += 1 carry = 0 for x in range(1,len(A)+1): if (A[-x] + carry) == 10: carry = 1 A[-x] = 0 else: A[-x] += carry break if A[0] == 0: A[0] = 1 A.append(0) return A print(plus_one([2,9,9])) print(plus_one([9,9,9]))
5ee72868552ba9c802f653357564b241c00ca020
bsspirit/mytool
/src/md5_rdict.py
282
3.875
4
# -*- coding: utf-8 -*- #读字典文件 def dict_read(file): lines = [] f = open(file,"r") line = str(f.readline()) lines.append(line.split(',')) while line: line = f.readline() lines.append(line.split(',')) f.close() return lines
e5098b5399a500afcf7d5c140b2a5aed46d613f7
hdjewel/Markov-Chains
/lw_markov.py
3,792
3.765625
4
#!/usr/bin/env python from sys import argv import random, string def make_chains(corpus): """Takes an input text as a string and returns a dictionary of markov chains.""" # read lines --- we don't need to read the lines. We are reading it as one long string # strip newlines, punctuation, tabs and make lower case exclude = string.punctuation exclude2 = "\n" + "\t" new_corpus = "" #created new string because corpus string is immutable for char in corpus: if char in exclude: continue elif char in exclude2: # new_corpus += "" -- doesn't work because it took away all the spaces at new lines new_corpus += " " #works, but creates double space at new lines. Should not be a problem #because we will split at a space else: new_corpus += char new_corpus = new_corpus.lower() # create list of words on line list_of_words = new_corpus.split() # create a dictionary where key = tuple of two words (prefix) and value = a list # of words that follow the prefix. d = {} # for i in range(len(list_of_words)): # Wendy thinks the following two lines will throw an IndexError for i in range( (len(list_of_words) - 2) ): #Wendy's version to avoid IndexError # print 0.01, IndexError # if IndexError: # break # else: prefix = (list_of_words[i], list_of_words[i+1]) suffix = list_of_words[i+2] """ if prefix not in d: add the prefix as a key to d and setting suffix as the prefix's value else append suffix to the value of the prefix in d """ if prefix not in d: d[prefix] = [suffix] #intializes the suffix as a list else: d[prefix].append(suffix) # make a key of the last 2 words and it's value = first word of the text return d def make_text(chains): """Takes a dictionary of markov chains and returns random text based off an original text.""" # so to build our text the first prefex and suffix are random # then we build our text from the suffix to a new prefix # random_prefix = random.sample(chains.keys(), 1) random_prefix = random.choice(chains.keys()) # get random suffix from the list random_suffix = random.choice(chains[random_prefix]) markov_text = "" # and the loop control is at this time arbitrary # for i in range(4): for word in random_prefix: markov_text += word + " " markov_text += random_suffix """ take the second value of the random_prefix make it the first value and make the suffix the second value of the new key the last word is handled how in our dictionary?? --- we add to the dictionary (in make_chains) as key, the last two words in the list, and as it's value, the first word in the list. """ #get new random prefix print 2, random_prefix print 2.0, chains[random_prefix] print 2.1, random_suffix print 2.2, markov_text # markov_text = random_prefix + random_prefix01... return "Here's some random text." def main(): script, filename = argv # args = sys.argv # print 1, args[1] # print 1.0, type(args[1]) # Change this to read input_text from a file # input_text = open(args[1]) input_text = open(filename) # content = input_text.read() # input_text = input_text.read().replace(\n) input_text = input_text.read() # print 1.1, input_text # print 1.2, type(input_text) # do read chain_dict = make_chains(input_text) random_text = make_text(chain_dict) # print random_text if __name__ == "__main__": main()
5649dabbf39457cb906368ebc3591f964108713c
ijoshi90/Python
/Python/hacker_rank_staricase.py
460
4.3125
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 30-Oct-19 at 08:06 """ # Complete the staircase function below. """def staircase(n): for stairs in range(1, n + 1): print(('#' * stairs).rjust(n)) """ def staircase(n): for i in range(n-1,-1,-1): for j in range(i): print (" ",end="") for k in range(n-i): print("#",end="") print("") if __name__ == '__main__': staircase(6)
cc0dbeccd0b265b09bf10f8aa12881d5e245acae
ijoshi90/Python
/Python/loop_while.py
534
3.78125
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 20 20:47:00 2019 @author: akjoshi """ import time # While Loop x = 5 y = 1 print (time.timezone) while x >=1: print (time.localtime()) time.sleep (1) print ("X is "+ str (x)) x-=1 while y <= 5: time.sleep(1) print ("Y is "+str(y)) y+=1 # While Loop i=0 while i <=10: i=i+1 if i == 5: break print ("I is "+str(i)) j = 0 while j < 6: j += 1 if j == 3: continue print ("J is "+str(j))
035e8af4d681ae42fa9ce31a9a22f2430aaa1531
ijoshi90/Python
/Python/array_operations.py
579
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 25 18:21:20 2019 @author: akjoshi """ from array import * arr = array('i', []) l = int (input ("Enter the length : ")) print ("Enter elements") for i in range (l): x = int (input("Enter the " + str (i) + " value : ")) arr.append(x) key = int (input ("Enter value to search : ")) for i in range (l): if key == arr[i]: print (str(key) + " is in position " + str(i)) else: print ("element is not in array") print (arr.index(key)) # Sum of Array new_arr = [1,2,3,4,5,6,7,8,9,10] print(max(new_arr))
e3b10157dafc23d144d1a2db892f055a8f2d608f
ijoshi90/Python
/Python/prime_or_not.py
391
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 24 16:40:46 2019 @author: akjoshi """ # Prime or not number = int (input ("Enter a number to print prime numbers between 0 and number : ")) for num in range(2,number + 1): # prime numbers are greater than 1 if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)
4c951106721a49a06d1e6a95f6461e5d8da18c44
ijoshi90/Python
/Python/dictionary.py
1,448
3.875
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 18:05:09 2019 @author: akjoshi """ #dictionary dictionary_car = { "Brand" : "BMW", "Model" : "X1", "Year" : "2020", "Owner" : "Sanaksh" } print (dictionary_car) # Accessing this_dictionary = dictionary_car["Model"] print (this_dictionary) print (dictionary_car["Year"]) print (dictionary_car.get("Owner")) dictionary_car["Owner"]="Adi Shankara" print (dictionary_car.get("Owner")) for x in dictionary_car: print (x + " : " +dictionary_car[x]) for x in dictionary_car.values(): print (x) for x, y in dictionary_car.items(): print (x, y) if "Brand" in dictionary_car: print ("Brand is present") if "BMW" in dictionary_car.values(): print ("BMW is there") print ("Length of dictionary : "+str(len(dictionary_car))) # Adding to dictionary dictionary_car["Type"]="Petrol" print (dictionary_car) # Removing from dictionary dictionary_car.pop("Year") print (dictionary_car) # del del dictionary_car["Model"] print (dictionary_car) # Copying a dictionary new_dictionary=dictionary_car.copy() print (new_dictionary) new_dictionary=dict(dictionary_car) print (new_dictionary) dictionary_car.clear() print (dictionary_car) # Copying a dictionary new_dictionary=dictionary_car.copy() print (new_dictionary) del dictionary_car # dict() : Constructor dictionary = dict(brand="BMW",model="3 Series") print (dictionary)
75aabcea6f84ac4f13a725080c9858954074472c
ijoshi90/Python
/Python/maps_example.py
1,385
4.15625
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 19-12-2019 at 11:07 """ def to_upper_case(s): return str(s).upper() def print_iterator(it): for x in it: print(x, end=' ') print('') # for new line #print(to_upper_case("akshay")) #print_iterator("joshi") # map() with string map_iterator = map(to_upper_case, 'abc') print(type(map_iterator)) print_iterator(map_iterator) # Map iterator with tuple map_iterator = map(to_upper_case, (1, "ab", "xyz")) print_iterator(map_iterator) # Map with list map_iterator = map(to_upper_case, [1, 2, "Aksh"]) print_iterator(map_iterator) # Converting map to list, tuple or set map_iterator = map(to_upper_case, ['a,b', 'b', 'c']) my_list = list(map_iterator) print (type(my_list)) print(my_list) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_set = set(map_iterator) print(type(my_set)) print(my_set) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_tuple = tuple(map_iterator) print(type(my_tuple)) print(my_tuple) # Map with list_numbers = [1, 2, 3, 4] mapite = map(lambda x: x * 2, list_numbers) print(type(mapite)) for i in mapite: print(i) # Map with multiple arguments list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8) mapitnow = map(lambda x,y : x * y, list_numbers, tuple_numbers) for each in mapitnow: print("From multiple arguments in lambda : {}".format(each))
00e0422cf41f40f287b9d72f42881b3afcb93ce1
ijoshi90/Python
/Python/bubble_sort_trial.py
364
3.984375
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 09-01-2020 at 10:15 """ list = [1, 3, 8, 9, 2, 5, 2, 3, 6, 5, 8, 10, 19, 12, 14, 7, 20] def bubble (list): for i in range(len(list)): for j in range(i+1, len(list)): if list [i] > list [j]: list [i], list [j] = list [j], list[i] bubble(list) print(list)
6fc2d2631238c25c2d2e30ed887c4abbe8a0083c
ijoshi90/Python
/Python/set.py
851
4.03125
4
# -*- coding: utf-8 -*- """ Created on Tue Aug 6 20:40:20 2019 @author: akjoshi """ # Set Example thisset = {"1 apple", "2 banana", "3 cherry","4 kiwi"} print(thisset) for i in thisset: print (i) print ("5 banana" in thisset) print ("2 banana" in thisset) thisset.add("5 Strawberry") print (thisset) thisset.update(["6 Raspberry","7 Blueberry"]) print (thisset) print ("Set length : "+str(len(thisset))) # Remove will raise error if item is not there thisset.remove("7 Blueberry") print (thisset) # Discard will not raise error if item is not there thisset.discard("4 kiwi") print(thisset) # Pop removes last item x=thisset.pop() print (x) print (thisset) # Del deletes the set completely del (thisset) #print (thisset) # Set constructor thisset = set(("apple", "banana", "cherry")) # note the double round-brackets print(thisset)
3f28a1970aa458cfde8700646e1adecf1bb63634
ijoshi90/Python
/Python/string_operations.py
421
4
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 17-12-2019 at 14:43 """ string = "Hello, World!" # Strings as array print (string[2]) # Slicing print (string[2:5]) # Negative indexing - counts from the end print (string[-5:-2]) # Replace print (string.replace("!","#")) print((string.replace("Hello", "Well Hello"))) #Split print(string.split(",")) print(string) # Join print(",".join(string))
2733ce9698980790023690e311fd8ab37e46fb8f
ijoshi90/Python
/Python/iterator.py
383
3.859375
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 18-12-2019 at 15:18 """ # Iter in tuple mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) # Iter in strings string = "Akshay" myit1 = iter(string) print(next(myit1)) print(next(myit1)) print(next(myit1)) next(myit1) next(myit1) print(next(myit1))
bbcdeafd4fdc92f756f93a1a4f990418d295c643
ijoshi90/Python
/Python/variables_examples.py
602
4.375
4
""" Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 26-Sep-19 at 19:24 """ class Car: # Class variable wheels = 2 def __init__(self): # Instance Variable self.mileage = 20 self.company = "BMW" car1 = Car() car2 = Car() print ("Wheels : {}".format(Car.wheels)) # Override the value of wheels with 4 Car.wheels = 4 print (car1.company, car1.mileage, car1.wheels) print (car2.company, car2.mileage, car2.wheels) # Changing values of Car 2 car2.company = "Mini" car2.mileage = "25" car2.wheels = "3" print (car2.company, car2.mileage, car2.wheels)
d17f55a72be36d93dd6c5dc553d312e5c26beda4
romilpatel-developer/CIS2348_projects
/Homework 4/pythonProject24/main.py
1,398
3.671875
4
# Romilkumar Patel # 1765483 # Homework 4 (Zybooks 14.13) # Global variable num_calls = 0 # TODO: Write the partitioning algorithm - pick the middle element as the # pivot, compare the values using two index variables l and h (low and high), # initialized to the left and right sides of the current elements being sorted, # and determine if a swap is necessary def partition(user_ids, i, k): pivot = user_ids[k] # pivot is the middle item in the list index = i - 1 for j in range(i, k): if user_ids[j] <= pivot: index += 1 user_ids[index], user_ids[j] = user_ids[j], user_ids[index] user_ids[index+1], user_ids[k] = user_ids[k], user_ids[index+1] return index+1 # TODO: Write the quicksort algorithm that recursively sorts the low and # high partitions. Add 1 to num_calls each time quisksort() is called def quicksort(user_ids, i, k): if i < k: piv = partition(user_ids, i, k) quicksort(user_ids, i, piv-1) quicksort(user_ids, piv+1, k) if __name__ == "__main__": user_ids = [] user_id = input() while user_id != "-1": user_ids.append(user_id) user_id = input() # Initial call to quicksort quicksort(user_ids, 0, len(user_ids) - 1) num_calls = int(2 * len(user_ids) - 1) # Print number of calls to quicksort print(num_calls) # Print sorted user ids for user_id in user_ids: print(user_id)