blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e5e25b43cf9409c1e8cdb2b3f8cd58b857dc1b75
guojixu/interview
/leetcode/25. K 个一组翻转链表.py
2,559
3.53125
4
class ListNode: def __init__(self, val): self.val = val self.next = None def toList(): s = input().split() head = ListNode(-1) p = head for val in s: p.next = ListNode(val) p = p.next return head def my_reverse_1(head): if head == None or head.next == None: return head p = my_reverse_1(head.next) head.next.next = head head.next = None return p def my_reverse_2(head): if head == None or head.next == None: return None new_head = None while p != None: tmp = p p = p.next tmp.next = new_head new_head = tmp return new_head # # def reverse(head, tail): # if head == None or head.next == None: # return head # # pre = tail.next # # p = head # # while pre != tail: # next = p.next # p.next = pre # pre = p # p = next # # return tail, head def k_reverse(head, k): if head == None or head.next == None: return None tail = head for i in range(k): if tail == None: return head tail = tail.next new_head = reversed(head, tail) head.next = k_reverse(tail, k) return new_head def reverseKGroup(head,k): if head == None or head.next == None: return head tail = head for i in range(k): if tail == None: return head tail = tail.next newHead = my_reverse_22(head, tail) head.next = reverseKGroup(tail, k) return newHead def reverse(head, tail): new_head = None p = None while head != tail: p = head.next head.next = new_head new_head = head head = p return new_head def my_reverse_22(head, tail): if head == None or head.next == None: return head p = head new_head = tail while p != tail: tmp = p p = p.next tmp.next = new_head new_head = tmp return new_head def my_reverse_2(head, tail): if head == None or head.next == None: return None pre = head new_head = None while p != tail: tmp = p p = p.next tmp.next = new_head new_head = tmp return new_head def showList(head): p = head while p != None: print(p.val) p = p.next if __name__ == '__main__': head = toList() k = int(input()) # k_reverse(root, k) showList(head.next) new_head = reverseKGroup(head.next, k) showList(new_head)
372bd3212fc4b7a349fff024e03a224be5f79369
RRaffay/CleverHangmanRaffay
/CleverHangman.py
7,682
3.796875
4
''' @author: Rana Raffay ar534 ''' import random def handleUserInputDebugMode(): ''' THis function asks the user if they want to play in debug mode or play mode and then returns a boolean where true means they want to play debug and false means play mode ''' debugOrNo = input("Do you want to play in (d)ebug mode or (p)lay mode?: ") if debugOrNo == 'd': return True else: return False def handleUserInputWordLength(): ''' this asks the user to input how long they want the word to be and returns it as an integer ''' length = input("How long should the word be? ") return int(length) def createTemplate(currTemplate, letterGuess, word): ''' This function creates a template for a word based on the letter guessed and whether or not it was in the word or not ''' lstCurrTemp = list(currTemplate) for i in range(len(word)): if word[i] == letterGuess: lstCurrTemp[i] = letterGuess strNewTemp = ''.join(lstCurrTemp) return strNewTemp def getNewWordList(currTemplate, letterGuess, wordList, DEBUG): ''' This function takes the current available words and determines what the new list of words is based on the templates created by calling createTemplate Also if DEBUG is true, it prints out certain statistics that help the user see the possible keys and the word ''' len1 = len(wordList) tempDict = {} for word in wordList: temp = createTemplate(currTemplate, letterGuess, word) if temp not in tempDict: tempDict[temp] = [] tempDict[temp].append(word) wordLst = [(key,tempDict[key]) for key in tempDict] debugLst = wordLst[:] debugLst = sorted(debugLst,key = lambda x: x[0]) maxLst = (0,[]) for word in wordLst: if len(word[1]) > (len(maxLst[1])): maxLst = (word[0],word[1]) elif len(word[1]) == (len(maxLst[1])): count1 = word[0].count("_") count2 = maxLst[0].count("_") if count1>count2: maxLst = (word[0],word[1]) if len(maxLst[1])!=0: word = random.choice(maxLst[1]) if DEBUG: for key in debugLst: print(key[0] + " : " + str(len(key[1]))) ''' if len(key[1]) > (len(maxLst)): maxLst = (key[0],key[1]) ''' print("# keys = " + str(len(debugLst))) print("word is: " + word) print("Number of possible words: " + str(len(maxLst[1]))) tup = (maxLst[0],maxLst[1]) return tup def processUserGuessClever(guessedLetter, hangmanWord, missesLeft): ''' This function takes the guessed letter and template version of the word and how many misses are left and determines whether or not the user missed It returns a list with the updated misses and a boolean of whether or not the user missed ''' miss = True if guessedLetter not in hangmanWord: missesLeft -= 1 miss = False else: miss = True return [missesLeft,miss] def handleUserInputDifficulty(): ''' This function asks the user if they would like to play the game in (h)ard or (e)asy mode, then returns the corresponding number of misses allowed for the game. ''' print("How many misses do you want? Hard has 8 and Easy has 12.") userInput = input("(h)ard or (e)asy> ") if userInput == 'h' or userInput == 'H': return 8 else: return 12 def createDisplayString(lettersGuessed, missesLeft, hangmanWord): ''' Creates the string that will be displayed to the user, using the information in the parameters. ''' retString = "letters not yet guessed: " alphabet = 'abcdefghijklmnopqrstuvwxyz' alpha_list = list(alphabet) for let in alpha_list: if let in lettersGuessed: alpha_list[alpha_list.index(let)] = " " retString += ''.join(alpha_list) ''' for let in lettersGuessed: retString = retString + (let + " ") ''' retString += ("\n") retString += ("misses remaining = " + str(missesLeft) + "\n") for let in hangmanWord: retString += (let + " ") return retString def handleUserInputLetterGuess(lettersGuessed, displayString): ''' Prints displayString, then asks the user to input a letter to guess. This function handles the user input of the new letter guessed and checks if it is a repeated letter. ''' print(displayString) letter = True while letter: inLetter = input("Input a letter> ") if inLetter in lettersGuessed: print("you already guessed that") else: letter = False return inLetter def runGame(filename): ''' This function sets up the game, runs each round, and prints a final message on whether or not the user won. True is returned if the user won the game. If the user lost the game, False is returned. file = os.path("lowerwords.txt") f = open(file) wordsClean = [w.strip() for w in f.read().split()] print(wordsClean[0:30]) ''' all_words = [] words = open(filename,'r') for line in words: x = line.split() for y in x: all_words.append(y) DEBUG = handleUserInputDebugMode() wordLength = handleUserInputWordLength() missesLeft = handleUserInputDifficulty() mL = missesLeft firstWord = [] for word in all_words: if len(word) == int(wordLength): firstWord.append(word) fWord = random.choice(firstWord) hangmanWord = ["_"] * int(wordLength) count = 0 lettersGuessed = [] wordList = firstWord while missesLeft > 0 and "_" in hangmanWord: count+=1 displayString = createDisplayString(lettersGuessed, missesLeft, hangmanWord) guessedLetter = handleUserInputLetterGuess(lettersGuessed, displayString) lettersGuessed.append(guessedLetter) hangmanWord = ''.join(hangmanWord) newWordLst = getNewWordList(hangmanWord, guessedLetter, wordList, DEBUG)#wordList was firstWord wordList = newWordLst[1] hangmanWord = newWordLst[0] missLeftAndMiss = processUserGuessClever(guessedLetter, hangmanWord, missesLeft) #was newWordLst before missesLeft = missLeftAndMiss[0] miss = missLeftAndMiss[1] if not miss: print("You missed: " + guessedLetter + " not in word") if missesLeft == 0: print("you're hung \n word is: " + random.choice(wordList)) print("You made "+ str(count) + " guesses with " + str(mL) + " misses" ) return False elif "_" not in hangmanWord: print("you guessed the word: " + hangmanWord) print("you made " + str(count) + " guesses with " + str(mL - missesLeft) + " misses") return True if __name__ == "__main__": ''' Running Hangman.py should start the game, which is done by calling runGame, therefore, we have provided you this code below. ''' wins = 0 games = 0 play = True while play: result = runGame('lowerwords.txt') if result == True: wins += 1 games += 1 userInput = input("Do you want to play again? (y)es or (n)o ") if userInput == 'n': play = False print("You won " + str(wins) + " game(s), and lost " + str(games-wins) + " game(s)")
5426d815fdd76ecbbd0a7c92d631f444e3cd4eed
JohnGorter/NIKO_Demos
/guessnumber/game.py
2,683
3.5
4
from random import randint from .decorators import log from .userinput import ask_number, ask_number_attempts class Game: def __init__(self, name): self.name = name def start(self): pass def showName(self): print("Welkom bij het spel: " + self.name) class GuessNumber(Game): def __init__(self, use_hints = False, numberofnumbers = 10): super().__init__("GuesNumbers") self.numbercount = numberofnumbers self.hints = use_hints def game_over(self, won): # NEW: als er geen geheim getal is if won: # NEW: print gewonnen! print("U heeft het spel gewonnen!") # NEW: anders else: # NEW: print verloren print("Helaas, u heeft het spel verloren!") def play_round(self, getal): ''' dfjglkfdjgdjk ''' geradengetal = -1 aantalpogingen = 0 # zolang geradengetal niet gelijk is aan geheimgetal is en aantalpogingen < 3 while geradengetal != getal and aantalpogingen < 3: # vraag om een getal, geef de gebruiker drie kansen om een goed getal op te geven geradengetal = ask_number_attempts(10) # geef een hint if geradengetal != getal and self.hints: print("Het getal is " + ("lager" if getal < geradengetal else "hoger")) # hoog aantalpogingen op aantalpogingen += 1 # als geradengetal gelijk is aan geheimgetal if geradengetal == getal: # schrijf goed zo gewonnen! print("Goed zo, gewonnen! Het getal was inderdaad " + str(getal)) # anders else: # schrijf helaas, het getal was geheimgetal print("Helaas het getal was " + str(getal)) return geradengetal == getal def start(self): # maak een lijst met geheimegetallen = [1,2,3] geheimegetallen = [randint(0,9) for i in range(self.numbercount)].copy() #// # haal het volgende getal van de lijst en onthoud deze in geheimgetal geheimgetal = geheimegetallen.pop() # schrijf introductietekst print(f"Welkom bij raad een getal onder de 10, raad {len(geheimegetallen)+1} getallen") # zolang er een geheim getal is en een speelronde succesvol is afgerond.... while geheimgetal != None and self.play_round(geheimgetal): # haal het volgende getal van de lijst en onthoud deze in geheimgetal geheimgetal = None if len(geheimegetallen) == 0 else geheimegetallen.pop() # druk het resultaat van het spel af... self.game_over(geheimgetal == None)
c73dc06bbea712cda5277a0980daa75c091c4d7d
lixuanhong/LeetCode
/RangeSumQueryMutable.py
1,765
3.921875
4
""" Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8 Note: The array is only modifiable by the update function. You may assume the number of calls to update and sumRange function is distributed evenly. """ """ 思路:用segment tree来查找区间值, time complexity O(lgN) """ class NumArray(object): def __init__(self, nums): #construct the segment tree self.nums = nums n = len(nums) if n == 0: return None self.tree = [0] * 2 * n for i in range(n, 2 * n): self.tree[i] = self.nums[i - n] for i in range(n - 1, 0, -1): self.tree[i] = self.tree[2*i] + self.tree[2*i + 1] def update(self, i, val): #Besides update the child, also update the parent i += len(self.nums) #the value of the parent equals to the sum of left tree and right tree self.tree[i] = val while i > 0: left = i right = i if i % 2 == 0: right = i + 1 else: left = i - 1 self.tree[i/2] = self.tree[left] + self.tree[right] i /= 2 def sumRange(self, i, j): i += len(self.nums) j += len(self.nums) sum = 0 while i <= j: if i % 2 != 0: sum += self.tree[i] i += 1 if j % 2 != 1: sum += self.tree[j] j -= 1 i /= 2 j /= 2 return sum
5d393bbafcdb99e1122afd4d20a72b7160498acf
Silzhar/Ejercicios-Python
/ejercicios.py
490
3.78125
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 24 16:44:08 2018 @author: Yamabushi """ lista=[] mayor=0 menor=0 total=int(input('Total de números :')) for x in range(total): n=int(input('Número :')) lista.append(n) if n>mayor: mayor=n else: if n<mayor: menor=n lista.sort() print(lista) print('El número mayor es :',mayor) print('El número menor es :',menor)
87feac8b22d078cd62625e536e60ac02c31a4f61
imguozr/LC-Solutions
/1362_Closest_Divisors.py
542
3.59375
4
import math from typing import List class Solution: """ I dont know what the algorithm is... """ def closestDivisors(self, num: int) -> List[int]: def helper(n): s = int(math.sqrt(n) // 1) for v1 in range(s, 1, -1): v2 = n // v1 if not n % v1 and not n % v2: return [v1, v2] return [1, n] div1 = helper(num + 1) div2 = helper(num + 2) return div1 if div1[1] - div1[0] < div2[1] - div2[0] else div2
a61c2112da95d2bc07af7e5d7def7898c4b91ecc
CN-TU/py_lstm-tweets
/text_processing.py
641
3.625
4
#import re #import nltk #from nltk.corpus import stopwords #nltk.download('stopwords') # ******* FUNCTIONS ******* def tokenize_sentences(sentences): words = [] for sentence in sentences: w = extract_words(sentence) words.extend(w) words = sorted(list(set(words))) return words def extract_words(sentence): #ignore_words = stopwords.words('english') if include_stopwords else [] ignore_words = [] #words = re.sub("[^\w]", " ", sentence).split() words = sentence.split() words_cleaned = [w.lower() for w in words if w not in ignore_words] return words_cleaned
40f77967f3ca07b01e512df4e4a0520d911cb270
null-Exception1/Textify
/textify.py
2,834
3.875
4
import os class Canvas: def __init__(self,width,height,background_char): self.width = width self.height = height self.display = [background_char]*(width*height) self.xborder = "" self.yborder = "" def render(self): """ Prints display, with formatting. Returns none. """ display = self.display print(self.xborder*(self.width+2)) for i in range(self.height): print(self.yborder + "".join(display[self.width*i:self.width*(i+1)]) + self.yborder) print(self.xborder*(self.width+2)) def render_val(self): """ Returns canvas display, with formatting """ display = "" display += self.xborder*(self.width + 2) + "\n" for i in range(self.height): display += self.yborder+"".join(self.display[self.width*i:self.width*(i+1)])+ self.yborder + "\n" display += self.xborder*(self.width + 2) + "\n" return display def rect(self,background_character,y,x,width,height,line_width=0,line_width_character=" "): """ Fills a square at given coordinates, x and y, to extent of the given width and height with background_character as the background. Returns none. """ if line_width==0: for i in range(x,x+width): for j in range(y,y+height): self.display[(i*self.width)+j] = background_character elif line_width>0: for i in range(x-line_width,x+width+line_width): for j in range(y-line_width,y+height+line_width): self.display[(i*self.width)+j] = line_width_character for i in range(x,x+width): for j in range(y,y+height): self.display[(i*self.width)+j] = background_character def addborders(self,x_axis,y_axis): """ Make a border for the canvas (outline, will not affect display in any way.) x axis is for horizontal bordering of canvas y axis is for vertical bordering of canvas Leave empty string if the particular axis is not needed Variables will be set, no value will be returned from this function. """ self.xborder = x_axis self.yborder = y_axis def draw_image(self,x,y,image): """ Draw a 2d array representing your image returns nothing """ height = len(image) width = len(image[0]) for i in range(x,x+width): for j in range(y,y+height): self.display[(i*self.width)+j] = image[i-x][j-y]
7627b10e8cb84de503747ce1c7a0a359462adc21
Oracy/curso_em_video
/Exercicios/025.py
130
3.90625
4
name = str(input('What is your name? ')).strip() check = "silva" in name.lower() if check: print('true') else: print('false')
7a8c08862984ed216f3d5976b71b5d308b77499f
evertonulisystem/Iterasys-series
/src/tabuada.py
269
3.828125
4
def tabuada(num): for cont in range(1,11): print('{0} x {1} = {2}'.format(num, cont, num * cont)) def calcular_contador(num, cont): return num * cont if __name__ == '__main__': num = int(input('Informa o numero para tabuada: ')) tabuada(num)
3d0b2b55382941bc88892777292d26ab07a27c29
spirosmastorakis/CS249
/db.py
1,407
3.5625
4
class Author(object): def __init__(self, id, name, affiliation): self.id = id self.name = name self.affiliation = affiliation self.candidate_papers = set() def __str__(self): return ', '.join([str(self.id), self.name, self.affiliation, str(len(self.candidate_papers))]) def add_candidate_paper(self, paper_id): self.candidate_papers.add(paper_id) def get_last_name(self): return self.name.split(' ')[-1] @staticmethod def get_last_name_static(name): return name.split(' ')[-1] class Paper(object): def __init__(self, id, title, year, conference_id, journal_id, keywords): self.id = id self.title = title self.year = year self.conference_id = conference_id self.journal_id = journal_id self.keywords = set(keywords) self.candidate_authors = [] self.num_candidate_authors = 0 def __str__(self): return ', '.join([str(self.id), self.title, str(self.year), str(self.conference_id), str(self.journal_id), str(self.keywords), str(self.num_candidate_authors)]) def add_candidate_author(self, author_info): # author_info = (author_id, name, affiliation) self.candidate_authors.append(author_info) self.num_candidate_authors += 1
e77178ce30a2f5a0714bf731eaf7b6ad1dc6d735
hartex/stepik-algo
/src/huffman/encoding.py
1,285
3.515625
4
from collections import Counter import heapq from leaf import Leaf from node import Node def huffman_tree(n): queue = [(freq, Leaf(ch)) for ch, freq in Counter(n).items()] heapq.heapify(queue) if len(queue) == 1: _, leaf, = heapq.heappop(queue) codes = {leaf.char: "0"} return codes while len(queue) > 1: freq1, left, = heapq.heappop(queue) freq2, right, = heapq.heappop(queue) elem = (freq1 + freq2, Node(left, right)) heapq.heappush(queue, elem) [(_freq, root)] = queue codes = {} root.walk(codes, "") return codes def encode(n): codes = huffman_tree(n) encoded_str = "".join([codes[i] for i in n]) return codes, encoded_str def test(n_iter=100): import random import string for i in range(n_iter): length = random.randint(1, 32) s = "".join(random.choice(string.ascii_letters) for _ in range(length)) _, encoded = encode(s) print(encoded) def main(): n = input() codes, encoded_str = encode(n) print("{} {}".format(len(codes.keys()), len(encoded_str))) for i in codes: print("{}: {}".format(i, codes[i])) print(encoded_str) # test() # Examples # abacabad if __name__ == "__main__": main()
92006152a011d600c2e99e10235e35f4b80436bb
Temujin18/income_pred
/misc/cube_perm.py
3,051
3.515625
4
from itertools import permutations, count import itertools import profile # import numpy as np # import pandas as pd import collections # from sympy.utilities.iterables import multiset_permutations import timeit # def perms(n): # """ # Returns permutations of n that is a perfect cube. # Really slow. Don't bother. # """ # n = str(n) # int_list = list(map(int,(''.join(x) for x in permutations(n)))) # result = [num for num in int_list if (round(num**(1/3)))**3 == num] # return set(result) #permutation elements are treated unique based on position, not by values. duplicates possible, therefore set(). # def perms_v2(n): # """ # Permutations using numpy and sympy. # Still very slooow. Don't bother. # """ # n = list(map(int, list(str(n)))) # n = np.array(n) # permutations = [p for p in multiset_permutations(n)] # return permutations # SOLUTION # Abandon use of permutations in solution due to O(k*n!) complexity: # https://stackoverflow.com/questions/25735762/big-o-notation-for-the-permutations-of-a-list-of-words # Class for incrementing counts of cubes and storing cubed numbers in a list # Based on https://stackoverflow.com/questions/8483881/defaultdict-and-tuples class Cubes(object): __slots__ = ('count', 'cubes') # slots for memory and access time gains def __init__(self): self.count = 0 self.cubes = [] def __iadd__(self, num): self.count += 1 self.cubes.append(num) return self def cube_perms(num_perms=5): """ Returns smallest cubed number based on num of permutations """ cubed_counts = collections.defaultdict(Cubes) result = None for i in count(start=1): cubed_num = i**3 perm = ''.join(sorted(str(cubed_num))) # encountered cubed_num sorted into single string if result is not None and len(perm) > len(str(result)): return result # return result if result exists and shorter than current perm cubed_counts[perm] += cubed_num # count each 'permutation' and add cubed_num to list of cubes if cubed_counts[perm].count == num_perms: if not has_more_cubes(perm, i): smallest_cube = min(cubed_counts[perm].cubes) if result is None or smallest_cube < result: result = smallest_cube # check if cubed number only has cube roots equal to num_perms # Based on https://codereview.stackexchange.com/questions/107508/project-euler-62-cubic-permutations-logic def has_more_cubes(perm, i): max_possible = int(int(''.join(perm[::-1]))**(1/3.)) #reverse of perm is highest num suspected to be perfect cube return any( ''.join(sorted(str(p**3))) == perm for p in range(i+1, max_possible)) # return True if there exists a perfect cube beyond i+1. profile.run('print(f"ANSWER: {cube_perms()}")') # t = timeit.Timer('cube_perms()','from cube_perm import cube_perms') # runs = t.repeat(100,1) # print(min(runs)) # method runs at around 0.23 s
909c5dcf6f993a41879fa1ca436dcde6780a7821
NamJaeyong/pythonNam
/control.py
1,989
3.828125
4
number = 1 if number ==1: print('참참참') number1 = 100 number2 = 200 number3 = 300 number4 = 400 a = number1 > number2 b = number3 < number4 if a: print('True') else: print('False') if a and b: print('True') else: print('False') list1 = ['a', 'b'] if 'a' in list1: print('a가 있읍니다.') else: if 'b' in list1: print ('b가 있읍니다.') else: print('a와 b가 모두 없읍니다.') if 'a' in list1: print('a가 있읍니다.') elif 'b' in list1: print('b가 있읍니다.') else: print('a와 b가 모두 없읍니다.') list11 = ['a', 'b'] if 'a' in list11: pass else: print('a가 없습니다.') if 'a' in list11: print('있습니다.') print('진짜 있습니다.') else: print('없습니다.') if 'a' in list11: print('있습니다.'); print('진짜 있습니다.') else: print('없습니다.') treehit = 0 while treehit < 100: treehit = treehit + 1 print("나무를 %d번 찍었습니다." %treehit) if treehit == 100: print("아부지~~나무 넘어가유~~~") num1 = 0 while num1 < 10: num1 += 1 print(num1) if num1 == 5: break num2 = 0 while num2 < 10: num2 += 1 if num2 % 2 == 0: continue print (num2) n = 0 while n <4: n += 1 print('*' * n ) list1111 = [1, 2, 3, 4, 5, 6, 7, 8 ,9, 10] for x in list1111: print(x) if x == 5: break list22222 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for x in list22222: if x % 2 ==0: continue print(x) a = range(0, 10) print(a[9]) a = range(0, 10, 1) print(a[9]) a = range(0, 10, 2) print(a[1]) a = [1, 2, 3, 4] result = [] for num in a: result.append(num*3) print(result) a = [1, 2, 3, 4] result = [num * 3 for num in a] print (result) a = [1, 2, 3, 4] result = [num * 3 for num in a if num % 2 == 0] print(result) a = 'mutzangesazachurum' count = 0 for x in a: if x in 'aeiou': count += 1 print(count)
4fe4bbc0db9abbaadb67e1a54dbfbfdf77f1aaee
higor-gomes93/curso_programacao_python_udemy
/Sessão 4 - Exercícios/ex46.py
272
4.125
4
''' Faça um programa que leia um número inteiro positivo de três dígitos (de 100 a 999). Gere outro número formado pelos dígitos invertidos do número lido. ''' entrada = input("Digite um numero com 3 digitos: ") saida = entrada[::-1] print(f"O inverso eh {saida}")
d202844348e6096fb7336249cc2492ba3bb8b354
mikegleen/modes
/src/once/x025_find_dups.py
407
3.71875
4
""" Find duplicated columns in a CSV file. Input is the CSV file produced by csv2xml.py using title_and_briefdes.yml """ import csv import sys TESTCOL = 1 infile = open(sys.argv[1]) reader = csv.reader(infile) origdict = dict() for row in reader: target = row[TESTCOL] if target in origdict: print(f'dup: {origdict[target]} {row[0]}') else: origdict[target] = row[0]
8d3f56001aa921522ba152292875f17dcfab6c7d
Collins-Kibet/Neural-Networks-and-Handwriting-Recognition
/rbf_net.py
10,183
4.1875
4
'''rbf_net.py Radial Basis Function Neural Network Collins Kibet CS 251: Data Analysis Visualization, Spring 2021 ''' import numpy as np import kmeans import scipy.linalg class RBF_Net: def __init__(self, num_hidden_units, num_classes): '''RBF network constructor Parameters: ----------- num_hidden_units: int. Number of hidden units in network. NOTE: does NOT include bias unit num_classes: int. Number of output units in network. Equals number of possible classes in dataset TODO: - Define number of hidden units as an instance variable called `k` (as in k clusters) (You can think of each hidden unit as being positioned at a cluster center) - Define number of classes (number of output units in network) as an instance variable ''' # prototypes: Hidden unit prototypes (i.e. center) # shape=(num_hidden_units, num_features) self.prototypes = None # sigmas: Hidden unit sigmas: controls how active each hidden unit becomes to inputs that # are similar to the unit's prototype (i.e. center). # shape=(num_hidden_units,) # Larger sigma -> hidden unit becomes active to dissimilar inputs # Smaller sigma -> hidden unit only becomes active to similar inputs self.sigmas = None # wts: Weights connecting hidden and output layer neurons. # shape=(num_hidden_units+1, num_classes) # The reason for the +1 is to account for the bias (a hidden unit whose activation is always # set to 1). self.wts = None # num_hidden_units defined as k "clusters" self.k = num_hidden_units # define num_classes as an instance variable self.num_classes = num_classes def get_prototypes(self): '''Returns the hidden layer prototypes (centers) (Should not require any changes) Returns: ----------- ndarray. shape=(k, num_features). ''' return self.prototypes def get_num_hidden_units(self): '''Returns the number of hidden layer prototypes (centers/"hidden units"). Returns: ----------- int. Number of hidden units. ''' return self.k def get_num_output_units(self): '''Returns the number of output layer units. Returns: ----------- int. Number of output units ''' return self.num_classes def avg_cluster_dist(self, data, centroids, cluster_assignments, kmeans_obj): '''Compute the average distance between each cluster center and data points that are assigned to it. Parameters: ----------- data: ndarray. shape=(num_samps, num_features). Data to learn / train on. centroids: ndarray. shape=(k, num_features). Centroids returned from K-means. cluster_assignments: ndarray. shape=(num_samps,). Data sample-to-cluster-number assignment from K-means. kmeans_obj: KMeans. Object created when performing K-means. Returns: ----------- ndarray. shape=(k,). Average distance within each of the `k` clusters. Hint: A certain method in `kmeans_obj` could be very helpful here! ''' #c_data = np.zeros(shape=(self.k)) avg_dist = np.zeros(self.k) for i in range(self.k): c_data = data[cluster_assignments == i] avg_dist[i] = (np.mean(kmeans_obj.dist_pt_to_centroids(centroids[i], c_data))) return avg_dist def initialize(self, data): '''Initialize hidden unit centers using K-means clustering and initialize sigmas using the average distance within each cluster Parameters: ----------- data: ndarray. shape=(num_samps, num_features). Data to learn / train on. TODO: - Determine `self.prototypes` (see constructor for shape). Prototypes are the centroids returned by K-means. It is recommended to use the 'batch' version of K-means to reduce the chance of getting poor initial centroids. - To increase the chance that you pick good centroids, set the parameter controlling the number of iterations > 1 (e.g. 5) - Determine self.sigmas as the average distance between each cluster center and data points that are assigned to it. Hint: You implemented a method to do this! ''' #prototypes kmeans_obj = kmeans.KMeans(data) kmeans_obj.cluster_batch(k = self.k, n_iter = 5) #prototypes self.prototypes = kmeans_obj.get_centroids() #sigmas self.sigmas = self.avg_cluster_dist(data, self.prototypes, kmeans_obj.get_data_centroid_labels(), kmeans_obj) def linear_regression(self, A, y): '''Performs linear regression CS251: Adapt your SciPy lstsq code from the linear regression project. CS252: Adapt your QR-based linear regression solver Parameters: ----------- A: ndarray. shape=(num_data_samps, num_features). Data matrix for independent variables. y: ndarray. shape=(num_data_samps, 1). Data column for dependent variable. Returns ----------- c: ndarray. shape=(num_features+1,) Linear regression slope coefficients for each independent var AND the intercept term NOTE: Remember to handle the intercept ("homogenous coordinate") ''' #Ahat Ahat = np.column_stack((A, np.ones((A.shape[0], 1)))) #Calculate lstsq using scipy c,_,_,_ = scipy.linalg.lstsq(Ahat, y) return c def hidden_act(self, data): '''Compute the activation of the hidden layer units Parameters: ----------- data: ndarray. shape=(num_samps, num_features). Data to learn / train on. Returns: ----------- ndarray. shape=(num_samps, k). Activation of each unit in the hidden layer to each of the data samples. Do NOT include the bias unit activation. See notebook for refresher on the activation equation ''' hidden_act = np.zeros(shape= (data.shape[0],self.k)) gamma = 1/(2*self.sigmas*self.sigmas+(1e-8)) for i in range(self.k): hidden_act[:,i] = np.exp(- gamma[i] * np.sum(np.square(data - self.prototypes[i,:]), axis = 1)) return hidden_act def output_act(self, hidden_acts): '''Compute the activation of the output layer units Parameters: ----------- hidden_acts: ndarray. shape=(num_samps, k). Activation of the hidden units to each of the data samples. Does NOT include the bias unit activation. Returns: ----------- ndarray. shape=(num_samps, num_output_units). Activation of each unit in the output layer to each of the data samples. NOTE: - Assumes that learning has already taken place - Can be done without any for loops. - Don't forget about the bias unit! ''' output_act = np.column_stack((hidden_acts, np.ones(hidden_acts.shape[0]))) @ self.wts return output_act def train(self, data, y): '''Train the radial basis function network Parameters: ----------- data: ndarray. shape=(num_samps, num_features). Data to learn / train on. y: ndarray. shape=(num_samps,). Corresponding class of each data sample. Goal: Set the weights between the hidden and output layer weights (self.wts) using linear regression. The regression is between the hidden layer activation (to the data) and the correct classes of each training sample. To solve for the weights going FROM all of the hidden units TO output unit c, recode the class vector `y` to 1s and 0s: 1 if the class of a data sample in `y` is c 0 if the class of a data sample in `y` is not c Notes: - Remember to initialize the network (set hidden unit prototypes and sigmas based on data). - Pay attention to the shape of self.wts in the constructor above. Yours needs to match. - The linear regression method handles the bias unit. ''' self.wts = np.empty([self.k+1, self.num_classes]) #set weights using linear regression for i in range(self.num_classes): self.wts[:,i] = self.linear_regression(self.hidden_act(data),y == i) def predict(self, data): '''Classify each sample in `data` Parameters: ----------- data: ndarray. shape=(num_samps, num_features). Data to predict classes for. Need not be the data used to train the network Returns: ----------- ndarray of nonnegative ints. shape=(num_samps,). Predicted class of each data sample. TODO: - Pass the data thru the network (input layer -> hidden layer -> output layer). - For each data sample, the assigned class is the index of the output unit that produced the largest activation. ''' #output = self.prototypes @ self.wts output = self.output_act(self.hidden_act(data)) y_pred = np.argmax(output, axis = 1) return y_pred def accuracy(self, y, y_pred): '''Computes accuracy based on percent correct: Proportion of predicted class labels `y_pred` that match the true values `y`. Parameters: ----------- y: ndarray. shape=(num_data_sams,) Ground-truth, known class labels for each data sample y_pred: ndarray. shape=(num_data_sams,) Predicted class labels by the model for each data sample Returns: ----------- float. Between 0 and 1. Proportion correct classification. NOTE: Can be done without any loops ''' #proportion of predicted class labels y_pred that match true values of y correct = y == y_pred acc = np.sum(correct)/len(y) return acc
be7de4114806715fb2a16b49d0096dcfca7244b2
dmurr/holbertonschool-higher_level_programming
/0x11-python-network_1/9-starwars.py
417
3.5625
4
#!/usr/bin/python3 # Takes in a string and sends a search request to the Star Wars API if __name__ == "__main__": import requests from sys import argv url = 'https://swapi.co/api/people/' r = requests.get(url, params={'search': argv[1]}) obj = r.json() print('Number of results: {}'.format(obj['count'])) results = obj.get('results') for d in results: print(d.get('name'))
4de82bd9f181ee36fe734dfa6c3b26fcc76367fb
birendra7654/recursion
/generate_all_balance_paenthesis.py
659
3.75
4
res = [] def generate_balance_parenthesis(open, close, op): if open == 0 and close == 0: res.append(op) return if open == close: op1 = op + '(' return generate_balance_parenthesis(open-1, close, op1) if open == 0: op1 = op + ")" return generate_balance_parenthesis(open, close-1, op1) else: op1 = op + "(" op2 = op + ")" generate_balance_parenthesis(open-1, close, op1) generate_balance_parenthesis(open, close - 1, op2) if __name__ == "__main__": n = 3 open = n close = n op = "" generate_balance_parenthesis(open, close, op) print(res)
6bad4b8bccef7069fba0df335c638c76651c9059
Near-River/leet_code
/131_140/134_gas_station.py
2,236
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ here are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1. Note: The solution is guaranteed to be unique. """ class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ # solution one # length = len(gas) # # def doCircuit(tank, index, target): # tank += gas[index] - cost[index] # if tank < 0: return False # index = index + 1 if index < length - 1 else 0 # if index == target: return True # return doCircuit(tank, index, target) # # for i in range(length): # if gas[i] < cost[i]: continue # if doCircuit(tank=0, index=i, target=i): return i # return -1 # solution two """ 问题变化为找到某个节点,在它之前的路段剩余油量为负, 而从它开始到整个队列结束剩余油量均不为负。 所需时间复杂度为O(N) """ # The solution is guaranteed to be unique: the aim is to find start gas station tank = 0 start, left = -1, 0 for i in range(len(gas)): temp = gas[i] - cost[i] tank += temp if temp >= 0: if start == -1: start = i left = temp else: left += temp else: left += temp if left < 0: start = -1 if tank < 0: return -1 return start if __name__ == '__main__': solution = Solution() print(solution.canCompleteCircuit([4], [6])) print(solution.canCompleteCircuit([2, 4], [3, 4])) print(solution.canCompleteCircuit([2], [2])) print(solution.canCompleteCircuit([2, 2], [4, 0]))
32507d726c8988d1366333163b23ea9085825f99
Lucas01iveira/curso_em_video-Python
/Exercício_31.py
276
3.75
4
def calcula_preco (d): if d <= 200: return d*(0.5) return d*(0.45) def main(): distancia = int(input('Informe a distância, em km, ao destino desejado: ')) p = calcula_preco(distancia) print ('O preço da sua viagem é R$ {:.2f}'.format(p)) main()
a3539607bf4bef819299a7b77c756bf279fca6a6
calexhaynes/python_tests
/tuple_function.py
1,872
4.3125
4
""" Several useful functions for doing things with tuples that I'm writing """ def tuple_value_change_with_kwargs( a_tuple=(2, 3, 4, 5), an_int=6 ): print a_tuple, an_int print a_tuple[1:] print a_tuple * 2 print (an_int,) + a_tuple[1:] new_tuple= (an_int,) + a_tuple[1:] return new_tuple def find_tup_lengths(tuples) : """ Returns the length of tuples that have ben input. e.g. Start with: find_tup_lengths( [(1, 2, 3), (5, 6), (1, 10, 100, 1000)]) find_tup_lengths( [(1, 2, 3), (5, 6), (1, 10, 100, 1000)]) >> [3, 2, 4] """ print tuples returndef find_tup_lengths(tuples) : """ Returns the length of tuples that have ben input. e.g. Start with: find_tup_lengths( [(1, 2, 3), (5, 6), (1, 10, 100, 1000)]) find_tup_lengths( [(1, 2, 3), (5, 6), (1, 10, 100, 1000)]) >> [3, 2, 4] """ print tuples def find_tup_lengths(tuples) : """ Returns the length of tuples that have ben input. e.g. Start with: find_tup_lengths( [(1, 2, 3), (5, 6), (1, 10, 100, 1000)]) find_tup_lengths( [(1, 2, 3), (5, 6), (1, 10, 100, 1000)]) >> [3, 2, 4] """ print tuples list_tup = [] print type(tuples) for tup in tuples: print tup list_tup.append(len(tup)) print (len(tup)) return list_tup
3e078c8dce0335f0dbacbeafd098cab50eef5175
S-ign/LearnCode
/PythonApplication2.py
4,640
4.03125
4
import sys class UserInfo(object): #initializes class variables def __init__(self): self.username = "" self.age = 0 self.userid = 0 #Gracefully closes application by typing exit in any prompt def check_input(self): Exit_List = ["exit", "Exit", "EXit", "EXIt", "EXIT", "exIT", "eXIT"] if self.username in Exit_List: exit(0) elif self.age in Exit_List: exit(0) elif self.userid in Exit_List: exit(0) elif self.username == "": print("Field can not be left blank") self.get_username() elif self.age == "": print("Field can not be left blank") self.get_age() elif self.userid == "": print("Field can not be left blank") self.get_userid() #Checks if input is a number for age and userid def is_number(self, test): try: int(test) return True except ValueError: return False #Checks if input is above 1 and makes sure integers are inputed def is_possitive(self, num): try: if num == self.age: if int(self.age) < 1: print("Please enter a possitive integer above 1") self.get_age() if num == self.userid: if int(self.userid) < 1: print("Please enter a possitive integer above 1") self.userid except ValueError: if num == self.age: print("Please enter a valid age (1-85)") self.get_age() elif num == self.userid: print("Please enter a valid ID (1-999999)") self.get_userid() #Checks if input is in desired range 1-999999 def in_range(self, num): if num == self.age: if int(num) < 1 or int(num) > 85: print("Please enter a valid age (1-85)") self.get_age() elif num == self.userid: if int(num) < 1 or int(num) > 9999999: print("Please enter a valid ID (1-999999)") self.get_userid() #Gets input from user for username def get_username(self): self.username = input("Please enter your username: ") self.check_input() return self.username #Gets input from user for age def get_age(self): self.age = input("Please enter your age (1-85): ") self.check_input() self.is_possitive(self.age) self.in_range(self.age) return self.age #Gets input from user for userid def get_userid(self): self.userid = input("Please enter your userID (1-999999): ") self.check_input() self.is_possitive(self.userid) self.in_range(self.userid) return self.userid #Create a new instance of UserInfo Class user_report = UserInfo() #Save the user_report.username() data to variable "name" #Makes user input a string and not a number try: name = int(user_report.get_username()) while name == int(user_report.username): print("Please do not use numbers") name = int(user_report.get_username()) except ValueError: name = user_report.username #Save the user_report.age() data to variable "age" #Checks if user input is_number() if user_report.is_number(user_report.get_age()) == True: age = int(user_report.age) else: print("Please enter a valid age (1-85)") while user_report.is_number(user_report.get_age()) == False: print("Please enter a valid age (1-85)") else: age = int(user_report.age) #Save the user_report.userid() data to variable "userid" #Checks if user input is_number() if user_report.is_number(user_report.get_userid()) == True: userid = int(user_report.userid) else: print("Please enter a valid ID (1-999999)") while user_report.is_number(user_report.get_userid()) == False: print("Please enter a valid ID (1-999999)") else: userid = int(user_report.userid) print("You are %s, aged %s, next year you will be %s, with a user id %s, the next user id is %s." % (name, age, age + 1, userid, userid + 1))
0dbe9ece2371caf494ba786e47a0bdf99c9ab060
adrian123454321/Robot
/mapas/Programa/robot.py
872
3.703125
4
#claserobot #comportamiebtos #mover #rotar #recoger class Robot(object): def __init__(self,x,y,,direccion): self.x=x self.y=y self.monedas=0 self.direccion="UP" self.mapa=None def mover(self): if self.direccion=="UP": self.y-=1 elif self.dereccion=="RIGHT": self.x+=1 elif self.direccion=="DOWN": self.y+=1 else self.x-=1 def rotar(self): if self.direccion=="UP": self.direccion="RIGHT" elif self.direccion=="RIGHT": self.direccion="DOWN" elif self.direccion=="DOWN": self.direccion="LEFT" else self.direccion=="UP": def recoger(self): if self.contar_monedas(self.x,self.y)>0: self.moneda+=1 self.mapa.quitar_moneda(x,y) def representar(self): if self.direccion=="UP": return "^" elif self.direccion"RIGHT": return">" elif self.direccion=="DOWN": return"v" elif self.direccion=="LEFT"
8d795ecbd122e9011a6afa8d3636e5db46751771
BotoniLucas/Curso_Python
/Exerc_Python/desafios28a35.py
2,270
4
4
'''# desafio 28 import random from time import sleep adv = random.randrange(0, 5, 1) #ou randint user = int(input('Qual número de 1 a 5 o computador escolheu? ')) print('Processando...") sleep(2) # espera 2 segundos print(f'O número do computador foi {adv}') if user == adv: print('Você acertou!') else: print('Você errou') ''' '''# desafio 29 vel = float(input('Qual a velocidade do carro? ')) if vel >80: print(f'Você ultrapassou o limite de 80km/h, sua multa é de R${(vel-80)*7 :.2f}') else: print('Você está dentro do limite') ''' ''' # desafio 30 n = int(input('Digite um número inteiro: ')) if n%2 == 0: print('O número é par') else: print('O número é ímpar') ''' ''' # desafio 31 d = float(input('Digite a distância da viagem em Km: ')) if d <=200: print(f'O preço da viagem é de R${d*0.5 :.2f}') else: print(f'O preço da viagem é R${d*0.45 :.2f}') ''' ''' # desafio 32 from datetime import date ano = int(input('Digite o ano. Para o ano atual digite 0: ')) if ano == 0: ano = date.today().year if (ano%4==0) and (ano%100)!=0 or (ano%400)==0: # também pode usar and e or como & e barra reta print(f'O ano de {ano} é bissexto: ') else: print(f'O ano de {ano} não é bissexto: ') ''' '''# desafio 33 a = float(input('Digite o primeiro número: ')) b = float(input('Digite o segundo número: ')) c = float(input('Digite o terceiro número: ')) # para o menor menor = a if b < a and b < c: menor = b if c < a and c < b: menor = c # para o maior maior = a if b > a and b > c: maior = b if c > a and c > b: maior = c print(f'O maior é {maior :.2f} e o menor é {menor :.2f}') ''' '''# desafio 34 sal = float(input('Digite o salário: ')) if sal>1250: print(f'O novo salário é de {sal*1.1 :.2f}') else: print(f'O novo salário é de {sal*1.15 :.2f}') ''' # desafio 35 n1 = float(input('Digite o comprimento da primeira reta: ')) n2 = float(input('Digite o comprimento da segunda reta: ')) n3 = float(input('Digite o o comprimento da terceira reta: ')) if n1 < n2 + n3 and n2 < n1 + n3 and n3 < n1 + n2: print(f'Os segmentos {n1}, {n2} e {n3} podem formar um triângulo') else: print(f'Os segmentos {n1}, {n2} e {n3} não podem formar um triângulo')
feb0ee6804828771a5b5161486b37836b778967a
codud0954/megait_python_20201116
/10_string/ex01/ex01.py
1,476
4.0625
4
# 문자열 더하기 a = "I like" b = " Python" c = a + b print(c) # 문자열 곱하기 print(b * 5) print("=" * 50) # 문자열의 길이 구하기 print(len(c)) # 문자열의 index print(c[0]) print(c[len(c) - 1]) # 마지막 문자 print(c[-1]) # 마지막 문자 # 문자열 index로 값 변경하기 => 바꿀 수 없다. # c[-1] = 'm' # 문자열 슬라이싱 [index:index] # I like Python => "like" print(c[2:6]) # like # Python만 뽑아내기 print(c[7:]) # Python # 특정 문자 개수 세기 print("i의 개수는", c.count("i")) # 찾는 문자의 첫번째 index (1) print("y의 인덱스는", c.find('y')) print("a의 인덱스는", c.find('a')) # 없는 문자를 찾는 경우 -1 # 찾는 문자의 첫번째 index (2) print("y의 인덱스는", c.index('y')) #print("a의 인덱스는", c.index('a')) # 없는 문자를 찾는 경우 에러 # 문자열 치환 # I like Python => You like Python c = c.replace("I", "You") print(c) # 문자열 나누기 words = c.split() # 아무 파라미터를 넣지 않으면 기본으로 공백 기준으로 문자열을 자른다. print(words) fruits = "grape:apple:orange:peach" fruit_list = fruits.split(':') print(fruit_list) # 문자 입력받기 # a, b = input("2개의 숫자를 입력하세요:").split() # print(a, b) # words = input("2개의 숫자를 입력하세요:").split() # print(words) a, b = [1, 2] print(a, b)
53eaed018ae2e19bdc049f108f80325d954aa85a
Rob-Rychs/py
/py-scripts/decryptmessage.py
1,151
3.5625
4
#!/usr/bin/python #process an image find the hidden morse code then process actual answer #need to automate this task import sys import Image from math import * im = Image.open("PNG.png") x,y = im.size # get dimension of image (width * height) pixels = im.load() # get pixels as 2d matrix in "pixels" count = 0 morse = { '.-':'A','-...':'B','-.-.':'C','-..':'D', '.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J', '-.-':'K','.-..':'L','--':'M','-.':'N','---':'O', '.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T', '..-':'U','..-':'V','.--':'W','-..-':'X','-.--':'Y', '--..':'Z','.----':'1','..---':'2','...--':'3','....-':'4','.....':'5', '-....':'6','--...':'7','---..':'8','----.':'9','-----':'0', } list =[] for i in range(y): for j in range(x): if pixels[j,i] == 1: count += 1 if count == 1: # No offset for 1st number list.append(i*100 + j) anonymous = i*100 + j else: list.append(i*100 + j -anonymous) anonymous = i*100 + j print "Hidden Message : ", string ='' for asci in list: if asci == 32: sys.stdout.write(morse[string]) string = '' else: string += chr(asci) print ""
d7473d43a471a292f7bb6a58a217c90d35fc3947
advancedpythonprogramming/hands-on-activities
/AC_solutions/chapter_06/AC06_1/AC06_1.py
3,539
3.78125
4
import unittest from bank import Bank, ATM class Test_ATM(unittest.TestCase): def setUp(self): self.bank = Bank("Seguritas") self._id1 = "18.375.852-2" self.name1 = "John Dupre" self.password1 = 2345 self._id2 = "13.432.113-k" self.name2 = "Emma Cashter" self.password2 = 5912 self.bank.add_user(self._id1, self.name1, self.password1) self.bank.add_user(self._id2, self.name2, self.password2) self.atm = ATM(self.bank) def test_credentials(self): # first case: _id y password right self.atm.login(self._id1, self.password1) _idingresado = self.bank.actual_user._id self.assertEqual(self._id1, _idingresado) # second case: _id right but password incorrect self.atm.login(self._id1, 1234) self.assertIsNone(self.bank.actual_user) # tercer case: _id no está en la bank database self.atm.login("10.000.000-1", 1234) self.assertIsNone(self.bank.actual_user) def test_balance(self): self.atm.withdraw_money(self._id1, self.password1, 20000) balance = self.bank.actual_user.balance # the user must have balance 0, ya que nunca ha depositado self.assertEqual(0, balance) # the test fails, you can see that the balance results in # -20.000 when it should be 0 def test_amount_updated(self): self.atm.login(self._id1, self.password1) # deposit of 10.000 self.bank.deposit(self.bank.actual_user, 10000) # withdrawal of 5.000 self.atm.withdraw_money(self._id1, self.password1, 5000) balance = self.bank.actual_user.balance # balance must end up in 5000 self.assertEqual(5000, balance) def test_account_tercero(self): # Will try to transfer to an account that does not exist self.atm.login(self._id1, self.password1) self.bank.deposit(self.bank.actual_user, 10000) self.atm.transfer_money( self._id1, self.password1, "1.000.000-3", 5000) self.assertIsNone(self.bank.third_person) # Indeed the destination user is not created and it is not found def test_amounts_updated(self): self.atm.login(self._id1, self.password1) # account 1 receives 15.000 self.bank.deposit(self.bank.actual_user, 15000) # 5.000 transfered from account 1 to account 2 self.atm.transfer_money(self._id1, self.password1, self._id2, 3000) # we should prove that account 1 balance = 12.000 and account # 2 balance = 3.000 amountUser = self.bank.actual_user.balance amountThird = self.bank.third_person.balance self.assertEqual(amountUser, 12000) self.assertEqual(amountThird, 3000) # Here the test fails def test_verify_error(self): # what if the third user does not exist self.atm.login(self._id1, self.password1) # account 1 receives a 10.0000 deposit self.bank.deposit(self.bank.actual_user, 10000) # lets transfer to a non existing account self.atm.transfer_money( self._id1, self.password1, "1.000.000-3", 5000) # lets verify that the transference is not performed amountUser = self.bank.actual_user.balance self.assertEqual(amountUser, 10000) # we can see that anyway the 5.000 is substracted despite the # error the test fails if __name__ == "__main__": unittest.main()
332a9926f3ac29da87fc42c012670ccecefec615
sgouda0412/Coding-Questions
/codewars/python/find_parity_outlier.py
458
3.734375
4
def find_outlier(integers): if integers[0] % 2 == 0 and integers[1] % 2 == 0: isEven = True elif integers[0] % 2 == 1 and integers[1] % 2 == 1: isEven = False else: if integers[2] % 2 == 0: isEven = True else: isEven = False for num in integers: if isEven and num % 2 == 1: return num elif not isEven and num % 2 == 0: return num return None
4106c5c4aa4c36c4d30e8601c4909615579b1e53
hudsonchromy/kattis
/rollcall.py
344
3.625
4
import operator names = [] firstNames = [] while True: try: newName = list(input().split()) names.append(newName) firstNames.append(newName[0]) except EOFError: break names = sorted(names, key = operator.itemgetter(1,0)) for name in names: if(firstNames.count(name[0]) > 1): print(name[0] + " " + name[1]) else: print(name[0])
a71e22eec0d355d38f537a767ad03bf63ba0a377
sherms77/Python-challenges
/HackerRank/Python if-Else/fb/ifElse_hr_refactored(fb2).py
808
3.71875
4
# refactored code given by someone by fb user from Amigoscode import math, os, random, re, sys ''' 240321: # don't know how to execute code in vs code # guessing I have to wrap in a function # will just run the code as is in HR # ran in HR - works # NEXT STEP: Understand and explain code. ''' # 290321: no rule for constraint? # 290321: i think the constraint rule is applied through the even_condtions variables even_condition1= [i for i in range(2,6)] # range will stop at 5 even_condition2= [i for i in range(6,21)] if __name__ == '__main__': n = int(input().strip()) if n%2 == 0 and n > 20: print('Not Weird') elif n%2 == 0 and n in even_condition1: print('Not Weird') elif n%2 == 0 and n in even_condition2: print('Weird') else: print('Weird')
8f2baaeb7b09effc095767877c0a2769656395e4
pspatel2/MSiA422_Assignments
/HW2/hw2_ppm8265.py
7,505
3.640625
4
''' MSiA 422 Homework 2 -- Written by Parth Patel ******************************************************************************* THIS SCRIPT IS PRIMARILY TO SATISFY THE PROVIDED TEST CASES PLEASE REFER TO THE SUBMITTED JUPYTER NOTEBOOK FILE FOR COMPLETE DOCUMENTATION AND RESULTS The jupyter notebook code better utilizes the class structure so the code is not syntactically identical but functionally they are ******************************************************************************* Directions: Write a a class that offers 2 functions that works exactly like the sorted() built-in function in python ''' ''' Define the class that has bubble and merge sorting methods # The class has two methods defined: - bubble_sort() implements a bubble sort algorithm on inputted list and returns a sorted version of the inputted list. - merge_sort() applies a merge sort algorithm and returns a sorted version of the inputted list. ''' #imports below are not used in this script (are used in the notebook) #these were kept because code was pulled from the notebook and reworked to work with the test case #not all 'unnecessary' reminants from the notebook were removed import time ##used (in the notebook) for returning time measure when a given sort function is called on its own import timeit ##used (in the notebook) ffor coparing the two sort functions for reporting performance import matplotlib.pyplot as plt ##used (in the notebook) for generating performance comparison plot import random ##used (in the notebook) for random generation of data for performance comparison and test cases #class will inherit the base object class class MySorted(object): ''' A class that offers 2 sorting functions (bubble and merge algorithms) which receives inputs exactly like the sorted() built-in function in python. instance attributes (unused) & method inputs iterable of objects: any list of objects (of the same type, e.g. list of numbers, list of strings, list of lists) key: A custom key function can be supplied to customize the sort order, e.g. for sorting list can provide key str.lower(); defaults to None so do not supply anything unless desired reversed: A flag field that allows the order of sort to be defined. E.g. if descending order sort is desired supply True. If ascending order is desired supply True or do not provide the arg as it is defaulted to True ''' def __init__(self,a_list=[],key_in=lambda x:x,reverse=False): self.list_in = a_list self.key = key_in if reverse == True or reverse == False: self.rev_flag = reverse else: raise ValueError("Reversed field supplied must be True or False") #class method for implementing a bubble sort algorithm to the supplied list def bubble_sorted(self,iterable=[],key=lambda x:x,reverse=False): ''' Inputs: iterable of objects: any list of objects (of the same type, e.g. list of numbers, list of strings, list of lists) key: A custom key function can be supplied to customize the sort order, e.g. for sorting list can provide key str.lower(); defaults to None so do not supply anything unless desired reverse: A flag field that allows the order of sort to be defined. E.g. if descending order sort is desired supply True. If ascending order is desired supply True or do not provide the arg as it is defaulted to True Performs: a bubble sort algorithm on inputted list applying the key & reverse fields Outputs: A tuple contains the following: (sorted list, number of comparison performed during sorting, number of swaps performed during sorting, time elapsed) ''' #counters for time, comparison, and swaps not used in this script; see jupyter notebook for these ouputs start_time = time.time() nComp = 0 #used in the jupyter notebook nSwap = 0 if reverse == False: for pass_num in range(len(iterable) - 1, 0, -1): for i in range(pass_num): nComp += 1 if key(iterable[i]) > key(iterable[i + 1]): iterable[i],iterable[i + 1] = iterable[i + 1] ,iterable[i] nSwap+=1 end_time = time.time() else: for pass_num in range(len(iterable) - 1, 0, -1): for i in range(pass_num): nComp += 1 if key(iterable[i]) < key(iterable[i + 1]): iterable[i],iterable[i + 1] = iterable[i + 1] ,iterable[i] nSwap+=1 end_time = time.time() return iterable #class method for implementing a merge sort algorithm to the supplied list def merge_sorted(self,a_list,key=lambda x:x,reverse=False): ''' Inputs: iterable of objects: any list of objects (of the same type, e.g. list of numbers, list of strings, list of lists) key: A custom key function can be supplied to customize the sort order, e.g. for sorting list can provide key str.lower(); defaults to None so do not supply anything unless desired reverse: A flag field that allows the order of sort to be defined. E.g. if descending order sort is desired supply True. If ascending order is desired supply True or do not provide the arg as it is defaulted to True Performs: a merge sort algorithm on inputted list applying the key & reverse fields Outputs: A tuple contains the following: (sorted list, number of comparison performed during sorting, number of swaps performed during sorting, time elapsed) ''' #counters for time, comparisons, and swaps not used in this script; see jupyter notebook for these ouputs nComp = 0 nSwap = 0 lft_comp = 0 rgt_comp = 0 lft_swap = 0 rgt_swap = 0 start_time = time.time() if len(a_list) > 1: mid = len(a_list) // 2 left_half = a_list[:mid] right_half = a_list[mid:] self.merge_sorted(left_half,key,reverse) self.merge_sorted(right_half,key,reverse) i = 0 j = 0 k = 0 if reverse == False: while i < len(left_half) and j < len(right_half): nComp += 1 if key(left_half[i]) < key(right_half[j]): nSwap+=1 a_list[k] = left_half[i] i = i + 1 else: a_list[k] = right_half[j] j = j + 1 k = k + 1 else: while i < len(left_half) and j < len(right_half): nComp += 1 if key(left_half[i]) > key(right_half[j]): nSwap+=1 a_list[k] = left_half[i] i = i + 1 else: a_list[k] = right_half[j] j = j + 1 k = k + 1 while i < len(left_half): a_list[k] = left_half[i] i = i + 1 k = k + 1 while j < len(right_half): a_list[k] = right_half[j] j = j + 1 k = k + 1 end_time = time.time() return(a_list)
58906c17be7141adb7b8df1e8368b485d31cea41
haekyu/python_honey
/Day 07 - 보충, dict, 재귀, sorting/merge_sort.py
1,855
4.1875
4
def merge_sort(lst): # Base case (!!!! 중요 !!!!) if len(lst) <= 1: return lst # Divide (left_lst, right_lst) middle_idx = int(len(lst) / 2) left_lst = lst[:middle_idx] right_lst = lst[middle_idx:] # Sort (left_lst sorting, right_lst sorting) left_lst = merge_sort(left_lst) right_lst = merge_sort(right_lst) # Merge (!!!! 중요 !!!! append 잘 하면 됨, 아래 함수 참고) merged_lst = merge(left_lst, right_lst) return merged_lst def merge(left_lst, right_lst): # If an input lst is empty, return the other lst # No need to merge if len(left_lst) == 0: return right_lst elif len(right_lst) == 0: return left_lst # Initialize variables left_idx = 0 right_idx = 0 merged_lst = [] # Merge left_lst and right_lst while (left_idx < len(left_lst)) or (right_idx < len(right_lst)): # Check whether we want left or right value to insert want_left = False left_val = left_lst[left_idx] right_val = right_lst[right_idx] if left_val < right_val: want_left = True # Insert left value if want_left == True if want_left: merged_lst.append(left_val) left_idx += 1 # Insert right value if want_left == False else: merged_lst.append(right_val) right_idx += 1 # Check if all values of one of the list are scanned if left_idx == len(left_lst): merged_lst = merged_lst + right_lst[right_idx:] break if right_idx == len(right_lst): merged_lst = merged_lst + left_lst[left_idx:] break return merged_lst lst = [5, 1, 2, 6, 2, 1, 3, 0] sorted_lst = merge_sort(lst) print('before sorting:', lst) print('after sorting:', sorted_lst)
cc9b505c42f3ecc77fb94787642b5493eb8d8770
no-timing/CODE
/CA.py
3,387
3.71875
4
''' Cipher: CA Principle: Stream Cipher Types: one dimension, two dimension(moore neighbourhood) Programmer: TSM Date: 2017-09-01 Function: Encrypt(plaintext, key) Decrypt(ciphertext, key) ''' #加密函数 def Encrypt(plaintext, key): dimension = int(key[0]) key = int(key[2:]) if(dimension==1): ciphertext = OneDEncrypt(plaintext, key) elif(dimension==2): ciphertext = TwoDEncrypt(plaintext, key) else: print("!dimension 参数错误") return False return ciphertext #一维CA加密 def OneDEncrypt(plaintext, key): ciphertext = ['\0',]*6400 tempPlaintext = ['\0',]*6400 tempCiphertext = ['\0',]*6400 #处理原始明文字符串 num = 0; #有效明文字数 for i in range(0,len(plaintext)): if(97<=ord(plaintext[i])<=122): #原始明文为小写字母 tempPlaintext[num] = plaintext[i] num += 1 elif(65<=ord(plaintext[i])<=90): #原始明文为大写字母 tempPlaintext[num] = chr(ord(plaintext[i])+32) num += 1 #原始明文字母转换为0/1流 plaintextStream = "" for i in range(0,num): tempStream = str(bin(ord(tempPlaintext[i]))) tempStream = tempStream[2:] plaintextStream = plaintextStream + tempStream #加密规则 key = int(key) ruleStr = str(bin(key)) ruleStr = "0"*(10-len(ruleStr))+ruleStr[2:] #根据规则加密 ciphertextStream = RuleEncrypt(ruleStr, plaintextStream) for i in range(0,int(len(ciphertextStream)/7)): tempC = ciphertextStream[i*7:(i+1)*7] tempC = ''.join(tempC) tempCiphertext[i] = chr(int(tempC,2)) #转换密文字符串 num = 0 for i in range(0,len(plaintext)): if(97<=ord(plaintext[i])<=122): ciphertext[i] = tempCiphertext[num] num += 1 elif(65<=ord(plaintext[i])<=90): ciphertext[i] = chr(ord(tempCiphertext[num])-32) num += 1 else: ciphertext[i] = plaintext[i] ciphertext = ciphertext[:len(plaintext)] ciphertext = ''.join(ciphertext) return ciphertext #规则加密函数 def RuleEncrypt(ruleStr, plaintextStream): ciphertextStream = ['\0',]*len(plaintextStream) for i in range(0,len(plaintextStream)): tempStream = plaintextStream[i-1] + plaintextStream[i] + plaintextStream[(i+1)%len(plaintextStream)] ciphertextStream[i] = ruleStr[int(tempStream,2)] return ciphertextStream #二维CA加密 def TwoDEncrypt(plaintext, key): ciphertext = [([0] * len(plaintext)) for i in range(len(plaintext))] #加密规则 ruleStr = str(bin(key)) ruleStr = "0"*(8-len(ruleStr))+ruleStr[2:] X = input("请输入自定义X(0/1):") for i in range(0,len(plaintext)): for j in range(0,len(plaintext)): ciphertext[i][j] = (int(ruleStr[0])*int(X))^(int(ruleStr[1])*plaintext[i][j])^(int(ruleStr[2])*plaintext[(i-1)%len(plaintext)][j])^(int(ruleStr[3])*plaintext[(i+1)%len(plaintext)][j])^(int(ruleStr[4])*plaintext[i][(j-1)%len(plaintext)])^(int(ruleStr[5])*plaintext[i][(j+1)%len(plaintext)]) return ciphertext #测试数据 #print(OneDEncrypt('hello','23')) #plaintext = [[0,0,1],[0,0,0],[0,1,0]] #print("Plaintext:") #print(plaintext) #ciphertext = TwoDEncrypt(plaintext,14) #print("Ciphertext:") #print(ciphertext)
70c2c0baa62bbfaf74c1058f3e769e4011167428
610968110/ai_01_python-
/01_基础/py_02_函数.py
1,225
3.90625
4
def test(string="李四"): # 缺省参数,这里默认赋值了李四,缺省参数必须在末尾 """ 这里是文档注释 :param string: 字符串 :return: null """ print(string) test("张三") # -------------------------- 全局变量的操作 -------------------------- print("-" * 25, "全局变量的操作", "-" * 25) num = 1 def test1(): global num # 告诉后面num均为全局变量 print("num -> %d" % num) test1() # -------------------------- 返回多个值 -------------------------- print("-" * 25, "返回多个值", "-" * 25) def test2(): return 1, 2, "3" # 返回的是元祖,()省略了 # test2_ = test2() (one, two, three) = test2() print(one, two, three) # -------------------------- 多值参数 -------------------------- print("-" * 25, "多值参数", "-" * 25) def t(*args, **args_map): # *列表 **字典 print(args) print(args_map) list_ = [1, 2, 3] map_ = {"a": 1, "b": 2, "c": 3} t(list_, map_) # 错误,全赋值到列表里了 print("~~~~~~~~~~~~~") t(_list=list_, _map=map_) # 错误,全赋值到字典里了 print("~~~~~~~~~~~~~") t(*list_, **map_) # 正确 不知道为什么字典的key必须是string才行
de6beb5bf2125caa4fada7f5aff0e6eeb72d8552
shazamct/datetime-python
/main.py
704
3.671875
4
import datetime import pytz #printing today today = datetime.date.today() print(today) #finding age birthday = datetime.date(2000, 5, 30) Age = (today - birthday) print(Age) #adding a fixed time period time_period = datetime.timedelta(hours=10) Age = Age+time_period print(Age) print(today.month) print(today.weekday()) #monday =0 , sunday=6 #hours mins and secs print(datetime.time(7, 2, 20, 15)) #datetime.date(Y,M,D) #datetime.time(h,m,s,ms) #datetime.datetime(both above) print(datetime.datetime.now()+time_period) #timezones date_today = datetime.datetime.now(tz=pytz.UTC) date_india = date_today.astimezone(pytz.timezone('Asia/Kolkata')) print(date_india)
8822c907a10de53c51bd71411f0ae872007fbd57
MahrukhKhaan/IDLE-based-LMS
/win0_0.py
1,244
3.5
4
from tkinter import * class AdminLogin(Frame): def __init__(self, parent): Frame.__init__(self, parent) Frame.config(self, width=500,height=500,bg='misty rose') Frame.pack(self, side=LEFT) self.parent=parent labelmain= Label(self,text='Admin Login',width=20,font=("bold",18),bg='misty rose').place(x=90,y=30) labelpass= Label(self,text='Password',width=10,font=("bold",10),bg='floral white').place(x=80,y=180) self.varpass=StringVar() entrypass= Entry(self,textvariable=self.varpass).place(x=240,y=180) backbutton = Button(self, text="Back",command= lambda: self.back()) backbutton.place(x=430, y=10) Nextbutton = Button(self, text="Next",command= lambda: self.Next(), width=10) Nextbutton.place(x=340, y=220) def back(self): import win0 self.parent.CurrentPage=win0.LoginPage(self) self.parent.CurrentPage.tkraise() def Next(self): if str(self.varpass.get())=='CISD': import win0_00 self.parent.CurrentPage=win0_00.MainMenu(self) self.parent.CurrentPage.tkraise() else: print('Incorrect Password')
2289d3636cf909bb0ee1c39b31e210b064864fa0
zdravkob98/Fundamentals-with-Python-May-2020
/Dictionaries - Lab/01. Bakery.py
162
3.828125
4
elements = input().split() my_dict = {} for element in range(0 , len(elements) , 2): my_dict[elements[element]] = int(elements[element + 1]) print(my_dict)
d8c47a104a2dfb1590b05a2fae27e065a05c6f64
shivamptl18/Password-Generator
/passwordCreator.py
574
4.125
4
def pwd(): isupper = 0 islower = 0 y = '' x = input('Please enter a password. It must be 8 characters long ' + '\n contains 1 uppercase letter ' + '\n contains 1 lowercase letter ' + '\n contains a digit ' + '\n password: ') if len(x) >= 8: for i in x: if i.isupper() == True: isupper = 1 if i.islower() == True: islower = 1 while(y != x): y = input('Please retype the password: ') return x print(pwd())
38bde22805340ddb5de6049cacbd943b476e077c
HarounH/numal-col726
/assignment1/code1.py
6,497
3.71875
4
''' Code for numerical algorithms - assignment 1. @authors Haroun H ''' from __future__ import print_function import sys,os,pdb from matplotlib import pyplot as plt import numpy as np ''' @params f : Unary function that takes a float input and returns a float a,b: lower and upper range of integration h : step size for integration @returns ans: integral of f from a to b ''' def trapezoidal_rule(f, a, b, h): # Doing it as stably as possible xl = a xu = xl + h ans = 0 while xu<b: ans += h*(f(xl) + f(xu)) # Multiply by h here to avoid overflow? xl += h xu += h ans *= 0.5 return ans ''' @params f : fn: float*float -> float n : number of values at step size of h h : step size y0: boundary condition for y at 0 @return x,y : sequence of function values at points in the range(0:nh:h) ''' def euler_method(f, n, h, y0): x = [] y = [] xk = 0 yk = y0 for k in range(0,n): x.append(xk) y.append(yk) yk += h*f(xk, yk) xk += h return x,y ''' Newton's method for computing sqrt(2) ''' def newton_method(): correct_value = 1.41421356237 mdoa = 12 # maximum number of digits of accuracy ndoa = 0 # Number of digits of accuracy xk = 1 k = 0 ns = [] ks = [] xks = [xk] while ndoa<mdoa: k += 1 xk = 0.5*(xk + (2.0/xk)) xks.append(xk) # Figure out how many digits of accuracy we have while (abs(xk - correct_value) < (10**(1-ndoa))): print(str(ndoa) + ' digits of accuracy in ' + str(k) + ' iterations') ndoa += 1 ns.append(ndoa) ks.append(k) print('calculated value:' + str(xk)) plt.scatter(ns, ks, label='observations (in steps)', color='blue') plt.scatter(ns, [np.exp(k) for k in ks], label='e^observations', color='red') m,b = np.polyfit(ns, [np.exp(k) for k in ks], 1) plt.plot(ns, [m*n + b for n in ns], label='line through e^observations', color='red') # plt.plot([ns[0], ns[-1]], [np.exp(ks[0]), np.exp(ks[-1])], label='straight line through exp(observations)', color='green') plt.ylabel('#steps') plt.title('Number of steps vs number of digits of accuracy') plt.legend(loc='upper left') plt.plot() plt.show() plt.scatter(ns, ks, label='observations', color='blue') # plt.plot([ns[0], ns[-1]], [np.exp(ks[0]), np.exp(ks[-1])], label='straight line through exp(observations)', color='green') plt.xlabel('#digits of accuracy') plt.ylabel('#steps') plt.title('Number of steps vs number of digits of accuracy') plt.legend(loc='best') plt.plot() plt.show() def pi_instability(): f = lambda y0: lambda x: np.pi*y0/(y0 + (np.pi - y0)*(np.exp(x**2))) xs = np.linspace(0,10,100) pi8 = np.round(np.pi, 8) pi9 = np.round(np.pi, 9) f8 = f(pi8) f9 = f(pi9) y_pi8s = [f8(x) for x in xs] y_pi9s = [f9(x) for x in xs] y_true = [np.pi for x in xs] plt.plot(xs,y_pi8s,label='8 digits of np.pi') plt.plot(xs,y_pi9s,label='9 digits of np.pi') plt.plot(xs,y_true,label='all digits of np.pi') plt.xlabel('x') plt.ylabel('y') plt.title('y vs x') plt.legend(loc='best') plt.show() def qutb_minar_to_gurugram(): b = np.array([1,2]) a0 = np.array([[2,-4],[-2.998, 6.001]]) a1 = np.array([[2,-4],[-2.998, 6.0]]) s0 = np.linalg.solve(a0,b) s1 = np.linalg.solve(a1,b) print('s0:' + str(s0)) print('s1:' + str(s1)) def polynomial(): print('original roots:' + str(np.roots([1, -102, 201, -100]))) print('original roots:' + str(np.roots([1, -102, 200, -100]))) def evalpolynomial(coeffs, x): ans = 0 n = len(coeffs) for i in range(0, len(coeffs)): ans += coeffs[i]*(x**(n-i)) return ans print('value at 1:' + str(evalpolynomial([1, -102, 201, -100], 1.0))) print('value at 1:' + str(evalpolynomial([1, -102, 200, -100], 1.0))) def analyse_root_formula(): def quadratic_roots(a,b,c): normal0 = (-b + np.sqrt(b**2 - 4*a*c))/(2*a) normal1 = (-b - np.sqrt(b**2 - 4*a*c))/(2*a) new = -2*c/(b**2 + np.sqrt(b**2 -4*a*c)) return normal0, normal1, new a = 1 c = 1 blo = 10 bhi = 1000 bstep = 1 bs = [] roots0 = [] roots1 = [] rootsn = [] for b in range(blo, bhi, bstep): r0,r1,rn = quadratic_roots(a,b,c) roots0.append(r0) roots1.append(r1) rootsn.append(rn) bs.append(b) plt.plot(bs, roots0, label='usual formula') # plt.plot(bs, roots1, label='roots1') plt.plot(bs, rootsn, label='new formula') plt.legend(loc='best') plt.xlabel('b') plt.ylabel('root') plt.title('Roots v/s b for a=' + str(a) + ', c=' + str(c)) plt.axis([blo-100, bhi+100, min(min(roots0) , min(rootsn)), -1*min(min(roots0) , min(rootsn))]) plt.show() def integration_by_parts(): I0 = 1 - (1.0/np.e) sequence1 = [I0] sequence2 = [I0] for k in range(1, 21): print('k=' + str(k)) Ik = 0 if k%2==0: # update sequence2 Ik = (1.0/np.pi) - (k*(k-1)/(np.pi**2))*sequence2[-1] sequence2.append(Ik) # update sequence 1 anyway Ik = 1.0 - k*sequence1[-1] sequence1.append(Ik) print('Sequence1:') for ik in sequence1: print(ik) print('Sequence2:') for ik in sequence2: print(ik) plt.plot([0.0,20.0], [0.0, 0.0], color='black') plt.plot([0.0,20.0], [1.0, 1.0], color='black') plt.plot([0.0,20.0], [-1.0, -1.0], color='black') # plt.plot(list(range(0,21)), sequence1, label='step size 1') plt.plot(list(range(0,21,2)), sequence2, label='step size 2') plt.xlabel('k') plt.ylabel('Ik') plt.title('Ik vs k') plt.legend(loc='best') plt.axis([0, 20, -5.0, 5.0]) plt.show() def deviation_analysis(xs): xbar = np.mean(xs) n = len(xs) s0 = 0 s1 = 0 for x in xs: s0 += (x-xbar)**2 s1 += (x**2) - (xbar**2) s0 /= n s1 /= n print('for ' + str(xs)) print('mu:' + str(xbar)) print('s0: ' + str(s0)) print('s1: ' + str(s1)) def main(): # Tut1: Part1 Q1 - integrate sin x using trapezoidal rule. # for h in [0.1, 0.01]: # print('h=' + str(h) + ' integral=' + str(trapezoidal_rule(np.sin, 0, np.pi, h))) # Tut1: Part1 Q2c - solve differential equation # x,yapprox = euler_method((lambda xk,yk: (2*xk*yk - 2*xk*xk + 1)), 10, 0.1, 1) # yexact = [ (np.exp(xk**2) + xk) for xk in x ] # plt.plot(x, yapprox, label='Approximation by Euler') # plt.plot(x, yexact, label='using solution to DE') # plt.xlabel('x') # plt.ylabel('y') # plt.title('Experiment with differential equation') # plt.legend(loc='best') # plt.show() # Tut1: Part1 Q3c # newton_method() # Tut1: Part2 Q1 # pi_instability() # Tut1: Part2 Q1 # qutb_minar_to_gurugram() # Tut1: Part2 Q3 # analyse_root_formula() #Tut1: Part3 Q3 # integration_by_parts() #Tut1: Part3 Q4 deviation_analysis([1-11e-12] + ([1.0+1e-12]*9)) if __name__ == '__main__': main()
730c1b8b34b4279537fd19871d7b73a48194b8b0
MoritaDataLand/Natural_Language_Processing
/spam_classification.py
2,094
3.53125
4
# -*- coding: utf-8 -*- """ @channel Morita DataLand @author Morita Tarvirdians @email tarvirdians.morita@gmail.com @desc simple text categorization project for NLP tutorial """ import pandas as pd import matplotlib.pyplot as plt import re from nltk.corpus import stopwords from nltk.stem import PorterStemmer # read dataset (csv -> pandas dataframe) df = pd.read_csv("spam_text_message_data.csv") print(df.head()) df["Category"].replace({'ham': 0 ,'spam': 1}, inplace=True) print(df.head(10)) # gain insight from data data = {'category': ['spam', 'ham'], 'number': [len(df.loc[df.Category==1]), len(df.loc[df.Category==0])] } df_count = pd.DataFrame(data,columns=['category', 'number']) print (df_count) df_count.plot(x ='category', y='number', kind = 'bar') plt.show() # cleaning dataset stemmer = PorterStemmer() corpus = [] for w in range(len(df['Message'])): msg = df['Message'][w] msg = re.sub("[^a-zA-Z]", " ", msg) msg = msg.lower() msg = msg.split() msg = [stemmer.stem(word) for word in msg if not word in set(stopwords.words('english'))] msg = " ".join(msg) corpus.append(msg) # create word vector from sklearn.feature_extraction.text import TfidfVectorizer tf = TfidfVectorizer() tf.fit(corpus) # print(tf.vocabulary_) X = tf.transform(corpus).toarray() Y = df['Category'] # train test split from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.20, random_state = 0) # train model from sklearn.naive_bayes import MultinomialNB model = MultinomialNB().fit(X_train, y_train) y_pred = model.predict(X_test) # compute metrics from sklearn.metrics import confusion_matrix confusion_m = confusion_matrix(y_test, y_pred) print(confusion_m) from sklearn.metrics import accuracy_score, precision_score, recall_score acc = accuracy_score(y_test, y_pred) rec = recall_score(y_test, y_pred) prec = precision_score(y_test, y_pred) print("acc", acc, "\n") print("prec", prec, "\n") print("rec", rec, "\n")
8728e0b89bd3e252c0da7407bf874ff1c87b2ebe
RRoundTable/Data_Structure_Study
/sort/QuickSort.py
621
3.703125
4
import random import time N=100 lstNumbers=list(range(N)) random.seed(1) random.shuffle(lstNumbers) print(lstNumbers) def quickSort(lstNum, pivot = 0): if len(lstNum) <= 1 : return lstNum pivot_value = [] less = [] greater = [] for iter in range(len(lstNum)): if pivot == iter : pivot_value.append(lstNum[iter]) elif lstNum[iter] > lstNum[pivot]: greater.append(lstNum[iter]) elif lstNum[iter] < lstNum[pivot]: less.append(lstNum[iter]) return quickSort(less) + pivot_value + quickSort(greater) print(quickSort(lstNumbers))
9703a03c651f4c9907685bd800311ac05352ab4e
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_137/158.py
2,153
3.703125
4
#!/usr/bin/python # coding: UTF-8 def check_mine_and_draw(R, C, M): free_space = R * C - M min_space = 4 extra_R = 0 extra_C = 0 if free_space == 1: return draw_mine(R, C, extra_C, free_space) if R == 1 or C == 1: if free_space >= 2: return draw_mine(R, C, extra_C, free_space) else: return "Impossible" else: for i in range(max(R, C)*2): # print "it " + str(i) + " extra_R " + str(extra_R) + " extra_C " + str(extra_C) min_space = 4 + extra_R * 2 + extra_C * 2 # print min_space if free_space < min_space: return "Impossible" max_space = (2 + extra_R) * (2 + extra_C) # print max_space if min_space <= free_space <= max_space: return draw_mine(R, C, extra_C, free_space) if i % 2 == 0: if 2 + extra_C < C: extra_C += 1 else: if 2 + extra_R < R: extra_R += 1 def draw_mine(R, C, extra_C, free_space): pict = "" draw = 0 if R == 1: drawable = free_space elif C == 1: drawable = 1 else: drawable = 2 + extra_C for r in range(R): if free_space - drawable > 0: if C != 1 and free_space - drawable == 1: draw = drawable - 1 else: draw = drawable free_space -= draw else: draw = free_space free_space = 0 pict += "."*draw + "*"*(C-draw) + "\n" return "c" + pict[1:len(pict)-1] # print check_mine_and_draw(5, 1, 4) # txtfile = open('C-small-attempt2.in').read() txtfile = open('C-large.in').read() # txtfile = open('test_c.txt').read() cases = txtfile.split('\n') case_num = int(cases[0]) obj = open("c_large_ans.out", "w") for a in range(case_num): inputs = cases[a+1].split() R = int(inputs[0]) C = int(inputs[1]) M = int(inputs[2]) # print 'Case #'+str(a+1)+':\n'+check_mine_and_draw(R, C, M) print >> obj, 'Case #'+str(a+1)+':\n'+check_mine_and_draw(R, C, M)
af66245e43d10d4b2e8e3ddb3e0377b15c1589ec
edwardrh/Oregon-State-University-Coursework
/Engineering Courses/Computer Science Courses/Fall 2014 - Summer 2015/Fall 2014/Computer Science Orientation/Code/Assignments/assign3.py
736
4.0625
4
terminate = False; while not terminate: operation = input("Enter a number operation (+, -, /, *, **, %): "); num1 = int(input("Enter your 1st number: ")); num2 = int(input("Enter your 2nd number: ")); game_over = False; while not game_over: if operation == "+": print(num1 + num2); elif operation == "-": print(num1 - num2); elif operation == "/": print(num1 / num2); elif operation == "*": print(num1 * num2); elif operation == "**": print(num1 ** num2); elif operation == "%": print(num1 % num2); game_over = True; if game_over: entry = input("Would you like to play again? (0 - no, 1 - yes): "); if entry == "0": terminate = True; print("Thank you for using this calculator.");
d3ab5cfe7bb1ff17169b2b600d21ac2d7fabbf70
adamsjoe/keelePython
/Week 8 Assignment/scratchpad.py
1,193
4.125
4
while not menu_option: menu_option = input("You must enter an option") def inputType(): global menu_option def typeCheck(): global menu_option try: float(menu_option) #First check for numeric. If this trips, program will move to except. if float(menu_option).is_integer() == True: #Checking if integer menu_option = 'an integer' else: menu_option = 'a float' #Note: n.0 is considered an integer, not float except: if len(menu_option) == 1: #Strictly speaking, this is not really required. if menu_option.isalpha() == True: menu_option = 'a letter' else: menu_option = 'a special character' else: inputLength = len(menu_option) if menu_option.isalpha() == True: menu_option = 'a character string of length ' + str(inputLength) elif menu_option.isalnum() == True: menu_option = 'an alphanumeric string of length ' + str(inputLength) else: menu_option = 'a string of length ' + str(inputLength) + ' with at least one special character'
689afb258e00543db1e8dcc9876aadf23b5d6162
fuyangchang/Practice_Programming
/LearnPythonHardWay/ex21.py
839
4.15625
4
# -*- coding: utf-8 -*- def add(a, b): print "addition %d + %d" % (a, b) return a + b def subtract(a, b): print "subtraction %d - %d" % (a, b) return a - b def multiply(a, b): print "multiplification %d * %d" % (a, b) return a * b def divide(a, b): print "division %d / %d" % (a, b) return a / b print "Let's do calculations only with functions!" age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) print "age: %d, height: %d, weight: %d, iq: %d" % (age, height, weight, iq) # bonus point questions print "There is a problem." what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) print "result:", what, "Can you calculate by hands?" calculation = age + (height - weight * (iq / 2)) print calculation cal2 = divide(add(24, 34), subtract(100.0, 1023.0)) print cal2
777ee1f0e553a56b1b445cb9ffb8bb4c9f33333b
george-webb-oxb/grad-code-challenge-python
/main.py
1,655
4.03125
4
# Graduate Coding Challenge - Python # Here are a series of small coding challeneges in cpp for you to try! # There is no right or wrong answer, just give it a go! # Don't worry about not finishing it. # Don't google a solution to the questions! # You can search for small things like "what does this function return". # Leave all the code you write, even the debug stuff :)! # Just comment it out if you need to run the app. # Each question has a URL to an explanation of what we are asking :) # Python -> You shouldn't need to import anything but you can import # standard libray stuff if you need. # Replit -> You can edit what happens when you hit run in the .replit file # Have fun! import unordered_numbers as data # ----------------------------------------------------------------------------- print("Hello!") # 1. Write a function that takes in a list of unordered numbers # (unordered_numbers.h) and returns a list of ordered numbers # (ascending order) using a merge sort. # Don't use an sort function from python (that makes it too easy) # Merge Sort: https://www.bbc.co.uk/bitesize/guides/zjdkw6f/revision/5 # 2. Write a function to show your sorting works on your ordered numbers # (e.g. Prints "Passed" to the terminal on an expected result). # 3. Write a function that performs a binary search to return # the index of a given number (if it exists!). # Binary Search: https://www.bbc.co.uk/bitesize/guides/zjdkw6f/revision/3 # (Try not to read the pseudoode at the end of the page....) # 4. Write a function to show your binary search works # (e.g. Prints "Passed" to the terminal on an expected result).
5449867deba06c667cc012e5dba8712812ea3ade
juelianzhiren/python_demo
/1.py
2,914
3.625
4
def describe_pet(pet_name, animal_type="dog"): """显示宠物的信息""" print("\nI have a " + animal_type + "."); print("My " + animal_type + "'s name is " + pet_name.title() + "."); describe_pet(pet_name="willie") describe_pet(animal_type="hamster", pet_name="harry") def get_formatted_name(first_name, last_name, middle_name=""): if middle_name: full_name = first_name + " " + middle_name + " " + last_name; else: full_name = first_name + " " + last_name; return full_name.title(); musician = get_formatted_name("jimi", "hendrix"); print(musician); print(get_formatted_name("john", "hooker", "lee")); print("\n"); def build_person(first_name, last_name, age=""): """返回一个字典,其中包含一个人的信息""" person = {"first": first_name, "last": last_name}; if age: person["age"]=age; return person; musician = build_person("jimi", "hendrix", 28); print(musician); while True: print("\nPlease tell me your name:"); print("(enter 'q' at any time to quit)"); f_name=input("First name:"); if f_name=="q": break; l_name=input("Last_name:"); if l_name=="q": break; formatted_name=get_formatted_name(f_name, l_name); print("\nHello, " + formatted_name + "!"); def greet_users(names): """向列表中的每位用户都发出简单的问候""" for name in names: msg = "Hellow, " + name.title() + "!"; print(msg); usernames=["hannah", "ty", "margot"]; greet_users(usernames); # 首先创建一个列表,其中包含一些要打印的设计 unprinted_designs = ["iphone case", "rebot pendant", "dodecahedron"]; completed_models=[]; # 模拟打印每个设计,直到没有未打印的设计为止 # 打印每个设计后,都将其移动到表completed_models中 while unprinted_designs: current_design = unprinted_designs.pop(); #模拟根据设计制作3D打印模型的过程 print("Printing model " + current_design); completed_models.append(current_design); print("\nThe following models have been printed:"); for completed_model in completed_models: print(completed_model); print(completed_models) print("\n"); def print_models(unprinted_designs, completed_models): """模模拟打印每个设计,直到没有未打印的设计为止 打印每个设计后,都将其移动到表completed_models中""" while unprinted_designs: current_design = unprinted_designs.pop(); #模拟根据设计制作3D打印模型的过程 print("Printing model:" + current_design); completed_models.append(current_design); def show_completed_models(completed_models): """显示打印好的模型""" print("\nThe following models have been printed:"); for completed_model in completed_models: print(completed_model); unprint_designs = ["iphone case", "robot pendant", "dodecahedron"]; completed_models = []; print_models(unprint_designs[:], completed_models); show_completed_models(completed_models); show_completed_models(unprint_designs)
6e33424f205ccc13aabe3f81e79d915763f23f98
samuelcm/estrutura_sequencia
/temperatura.py
436
4.09375
4
#Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius. F = float(input("Qual a temperatura em Farenheit neste momento?")) C = (5 * (F-32) / 9) C = round(C,2) print("A temperatura em Celsius neste momento é ", C) if C > 30.: print ("Tá quente. Vá para a praia") if C < 30 and C > 20: print("A temperatura está boa") else: print("Tá frio. Volte para a cama")
4dc2eb4a93dee8976bf5a2a632e179e0f08fdc63
Preflyer/MITPython
/MITx_6.00.1/Week 2.2 Lecture.py
819
3.90625
4
### Week 2 ### Lecture 3 def __str__(self): res = '' # Change 1 for b in self.buckets: for t in b: res = res + str(t[0]) + ':' + str(t[1]) + ',' return '{' + res[:-1] + '}' # Change 2 ### Lecture 4 def stdDevOfLengths(L): """ L: a list of strings returns: float, the standard deviation of the lengths of the strings, or NaN if L is empty. """ if L == []: return float('NaN') values = [] if L != []: for string in L: char = len(string) values.append(char) mean = sum(values)/float(len(values)) total = 0.0 for i in values: total += (i-mean)**2 return (total/len(values))**0.5 return (tot/len(X))**0.5
6035f30816124e159edb804044efcfc1baa91608
arzutp/programlamaLab
/29-30 nisan.py
4,740
4.09375
4
#normalize/gauss ( #random - mean - std - normalize - mean +-std - main+-2*std - mean3std #buble sortta-selection-intersal sıralıycaz oran tutucaz hangisinin daha iyi oldugu bulunur #(normalize=x-mean)/std import random from math import sqrt def get_n_random_integer(n): #sayılar #random.seed(100) #aynı deger uretmek ıcın saate gore numbers=[] for i in range(n): s=random.randint(0,100) numbers.append(s) return numbers sayilar=get_n_random_integer(5) print("sayilar",sayilar) def get_mean_for_n_integer(numbers): #ortalamasını bulduk toplam=0 tane=0 for sayi in numbers: toplam=toplam+sayi tane=tane+1 return toplam/tane ortalama=get_mean_for_n_integer(sayilar) print("ortalaması",ortalama) def get_std_for_n_integer(numbers): #standart sapamasını bulduk toplam=0 tane=0 ortalama=get_mean_for_n_integer(numbers) #ortalamaya gore farkı alınarak ve kareleri alınarak bulunur for sayi in numbers: toplam=toplam+(sayi-ortalama)**2 tane=tane+1 var_1=toplam/(tane-1) std_1=sqrt(var_1) return std_1 standartSapma=get_std_for_n_integer(sayilar) print("standart sapmasi",standartSapma) def normalizasyon(numbers): new_numbers=[] ortalama=get_mean_for_n_integer(numbers) standartSapma=get_std_for_n_integer(numbers) for x in numbers: #sayıyı ortalamadan cıkarıp standart sapmaya boldu new_x=(x-ortalama)/standartSapma new_numbers.append(new_x) return new_numbers normalize=normalizasyon(sayilar) print("yeni normalize liste",normalize) def get_mean_one_std_neighbor_ratio(numbers): #standart sapmanın ortalamaya yakınlıkları tane=0 toplamKacSayi=0 ortalama=get_mean_for_n_integer(numbers) standart=get_std_for_n_integer(numbers) low=ortalama-standart high=ortalama+standart for x in numbers: toplamKacSayi+=1 if(x>low and x<high): tane+=1 return tane/toplamKacSayi a=get_mean_one_std_neighbor_ratio(sayilar) print(a) #sayilar_2=[75,32,25,14,47] #insertion sort def insertion(numbers): #insertion amacı swap sayısını azaltmak sayilar_2=numbers length_1=len(sayilar_2) karsilastirma_sayisi=0 yerdegistirme=0 #swap print(sayilar_2) for i in range(1,length_1): for j in range(i,0,-1): karsilastirma_sayisi+=1 if (sayilar_2[j]<sayilar_2[j-1]): #degistirme yerdegistirme+=1 temp=sayilar_2[j-1] sayilar_2[j-1]=sayilar_2[j] sayilar_2[j]=temp #print("sıralanmıs hali",sayilar_2) return sayilar_2 sayilar_1=get_n_random_integer(10) sayilar_2=insertion(sayilar_1) print("siralanmis",sayilar_2[0]) print("karsilastırma sayısı",sayilar_2[2]) print("yer degistirme sayisi",sayilar[1]) def get_mean_of_swap_in_insertion(numTrials,numInt): #yer degistirme sayılarını karsılastırcaz liste halinde swap_sayilari=[] for i in range(numTrials): sayilar_1=get_n_random_integer(numInt) sayilar_2=insertion(sayilar_1) s_1=sayilar_2[2] swap_sayilari.append(s_1) mean_1=get_mean_for_n_integer(swap_sayilari) std_1=get_std_for_n_integer(swap_sayilari) return int(mean_1),int(std_1) print(get_mean_of_swap_in_insertion(10,10)) def bubble(arr): n=len(arr) karsilastirma_sayisi=0 yerdegistirme=0 #swap for i in range(n): karsilastirma_sayisi+=1 for j in range(0,n-i-1): if(arr[j]>arr[j+1]): yerdegistirme+=1 arr[j],arr[j+1]=arr[j+1],arr[j] return yerdegistirme,karsilastirma_sayisi sayilar_1=get_n_random_integer(10) print("sıralanmamıs",sayilar_1) swap_sayisi=bubble(sayilar_1) print("sıralanmıs",sayilar_1) print("yer degistirme sayisi",swap_sayisi) #print("karsilastirma sayisi",swap_sayisi[1]) def get_mean_of_swap_in_bubble(numTrials,numInt): #yer degistirme sayılarını karsılastırcaz liste halinde swap_sayilari=[] for i in range(numTrials): sayilar_1=get_n_random_integer(numInt) s_1=bubble(sayilar_1) swap_sayilari.append(s_1[0]) mean_1=get_mean_for_n_integer(swap_sayilari) std_1=get_std_for_n_integer(swap_sayilari) return numInt,int(mean_1),int(std_1) random.seed(100) result_1=get_mean_of_swap_in_insertion(10,10) random.seed(100) result_2=get_mean_of_swap_in_bubble(10,10) print("insertion",result_1) print("bubblesort",result_1)
91281da323723f21d151601b238298326653e6b5
guilhermepirani/100daysofcode
/day002/lifeinweeks/life_in_weeks.py
617
3.984375
4
'''Create a program using maths and f-Strings that tells us how many days, weeks, months we have left if we live until 90 years old. It will take your current age as the input and output a message with our time left in this format: You have x days, y weeks, and z months left.''' # 🚨 Don't change the code below 👇 age = input("What is your current age?") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 years = 90 - int(age) months = round(years * 12) weeks = round(years * 52) days = round(years * 365) print(f'You have {days} days, {weeks} weeks, and {months} months left.')
528728e2e2c84079736e6841bf4c27eef3b8a423
Divyangana-12/hacktoberfest2021
/Turtle.py
577
4.0625
4
import turtle t = turtle.Turtle() # Conditional Statements a = input("Would u ike to draw a shape? them say yes or no:") if a == 'yes': t = turtle.Pen() s = turtle.Screen() colors = ['red', 'purple', 'blue', 'green', 'orange', 'white', 'yellow'] s.bgcolor('black') t.speed('fastest') turtle.bgcolor('black') for x in range(360): t.pencolor(colors[x % 6]) t.width(x / 100 + 1) t.forward(x) t.left(59) t.speed(15) elif a == 'no' or 'NO' or 'No' or 'nO': print("okay!!") else: print("Better luck!!")
424363d0f557872637459c496dc856262e559b74
Amna-A/cisco-course-labs-my_solutions
/mod5lab2.py
597
4
4
''' a function that behaves like the split() method''' def mysplit(strng): new_list=[] temp="" if strng.isspace(): return new_list for ch in strng: if ch!=" ": temp+=ch else: new_list.append(temp) temp="" no_space_final_list = [item for item in new_list if not item == ""] return no_space_final_list print(mysplit("To be or not to be, this is a question")) print(mysplit("To be or not to be,this is a question")) print(mysplit(" ")) print(mysplit(" abc ")) print(mysplit(""))
a3edf56307ad4a507b871cc543925f123884a351
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/series/5baaa8e000e64b26a6a702ef3e088498.py
503
3.65625
4
def slices(digits, k): # Raise ValueError if length argument is larger than number of digits # or if length argument is zero if (len(digits) < k or k < 1): raise ValueError("Error: Length argument does not fit the series.") # Add list of k digits to series until no more k digit long slices left series = [] i = 0 while i <= len(digits) - k: series.append([int(digit) for digit in digits[i:i+k]]) i += 1 return(series)
72cf11b2c3e83d7584bfa22a35432e834664c915
hardvester/small-coding-challenges
/small_coding_challenges/chapter3_stacks_and_queues/3_2_stack_with_min.py
1,189
3.796875
4
class StackMin: def __init__(self): self.items = [] self.min = [] def push(self, data): if not len(self.min): self.min.append(data) elif data <= self.min[-1]: self.min.append(data) self.items.append(data) def pop(self): if self.items == []: raise Exception('Stack empty') if self.peep() == self.min[-1]: self.min.pop() self.items.pop() def isEmpty(self): return self.items == [] def peep(self): if self.isEmpty(): raise Exception('Stack is empty') return self.items[len(self.items) - 1] def get_min(self): if self.isEmpty(): raise Exception('Stack is empty') return self.min[-1] # trying to implement a stack where I am going to inherit the original stack implementation and extend the way how the stack is treated if __name__ == "__main__": stack = StackMin() stack.push(5) stack.push(6) stack.push(4) stack.push(4) stack.push(5) stack.pop() stack.pop() stack.pop() stack.pop() stack.pop() print(stack.get_min())
be08f8d01473391cfa0b57c3f0e5cb7a129e0def
hzz2020/python_case
/case1:rename/class/烤地瓜.py
1,008
3.59375
4
# class SweetPotato(): def __init__(self): # 被烤的时间 self.cook_time = 0 # 烤的状态 self.cook_static = '生的' # 调料列表 self.condiments = [] def cook(self, time): """烤地瓜的方法""" self.cook_time += time if 0 <= self.cook_time < 3: self.cook_static = '生的' elif 3 <= self.cook_time < 5: self.cook_static = '半生不熟' elif 5 <= self.cook_time < 8: self.cook_static = '熟了' elif self.cook_time >= 8: self.cook_static = '烤糊了' def __str__(self): return f'这个地瓜烤了{self.cook_time}分钟,状态是{self.cook_static},调料有{self.condiments}' def add_condiment(self, condiment): """添加调料""" self.condiments.append(condiment) digua1 = SweetPotato() print(digua1) digua1.cook(2) print(digua1) digua1.cook(4) print(digua1) digua1.add_condiment("酱油") print(digua1)
c23ad0a3fcc2f7d39161952bbed0ca5b2c9cd11a
dongruibin/MachineLearning
/comStudy/ClassTest/SelfUse.py
775
4.09375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #明确self的使用 #首先self只有在类的方法中才会有,独立的函数或方法不必带有self的。 #self在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数。 #self名称不是必须的,在python中self不是关键字,可以将self改为myname #一样没有问题。 #self是指类实例对象本身(注意:不是类本身) class Person: def __init__(self,name):#构造方法为__init__是两根"_"这样的下划线 self.name=name def sayhello(self): print 'My name is :',self.name #self是指向实例的,如果指向类,存在多个对象,就没有办法指了 if __name__=='__main__': p=Person("dong") p1=Person('ding') print p
64ad765768914ac1ea5e81fe5629be24e774a2d2
grahamhord/exercises
/goldbach.py
3,416
4.09375
4
""" Sum of 2 primes exercise Goal: Create a function to verify Goldbach's conjecture for a range between two given positive integers """ #Create a list of primes up to ubound (inclusive) def primes(ubound): """ Creates a list of prime integers between 0 and ubound (inclusive) Returns list ubound must be integer higher than 2 """ if not isinstance(ubound,int) or ubound<=2: raise ValueError('Primes: upper bound (ubound) must be an integer higher than 2') def check(i): """ Check if i is prime Returns boolean Checks all integers 1-i exclusive to see if there are any other factors for i. If none are found, i is prime. """ for x in range(2,i): if i % x == 0: return False return True output = [2] [output.append(i) for i in range(3, ubound+1, 2) if check(i)] return output def goldbach(ubound,lbound = 4,gb1 = True): """ Check all even integers between 4 and ubound (inclusive) to verify Goldbachs first conjecture: Every even integer greater than 2 can be written as the sum of two primes Set gb1 = False to verify Goldbachs second conjecture: Every integer greater than 5 can be written as the sum of three primes Uses a brute force approach to find satisfying equation for each integer in range. Raises a value error if an exception to Goldbach is found. """ if not isinstance(ubound,int) or not isinstance(lbound,int): raise ValueError('Goldbach: ubound and lbound must be integers') if lbound>=ubound: raise ValueError('Goldbach: ubound must be greater than lbound') def solvegb(i): """ Checks possible pairs/trios to find an equation that satisfies Goldbach's conjecture. Raises a value error if any exceptions to the conjecture are found. Otherwise returns satisfying equation as string. Uses a series of subsets of primes that include only viable integers For example: if i = 10, subset1 = [7,5,3,2] For the first prime (7), subset2 is (subset1 <= (10-7)) or [3,2] """ output = '' subset = [x for x in prime[::-1] if x <= i] for n in subset: if output: break subset2 = [x for x in subset if x <= (i-n)] for m in subset2: if gb1 and (m+n) == i: output = f'{i} = {n} + {m}' break elif not gb1: if output: break subset3 = [x for x in subset2 if x <= (i-n-m)] for l in subset3: if (m+n+l) == i: output = f'{i} = {n} + {m} + {l}' break if not output: raise ValueError(f'FAILURE: NO EQUATION FOUND FOR {i}') return output lbound = max(lbound,(6 - (2*gb1))) ubound = max(ubound,(7 - (2*gb1))) prime = primes(ubound) return [solvegb(i) for i in range(lbound, ubound + 1, 1 + gb1)] gb = goldbach(100) #gb = goldbach(100, gb1=False) #gb = goldbach(1000, lbound=500, gb1=False) [print(x) for x in gb] #print(primes(1000))
7a1419c0be015d0580fd31f42072beac3bce2e1c
BackGraden/Data-Structures-and-Algorithm
/Coursera Stanford Algorithms/Course 2/week3/Algorithm implementation/Bst.py
1,376
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Oct 12 15:09:14 2019 @author: qinzhen """ import numpy as np class BST(): def __init__(self, data): self.data = data self.lchild = None self.rchild = None def search(self, data): if (self.data == data): return data elif (data < self.data): if (self.lchild != None): return self.lchild.search(data) else: return None else: if (self.rchild != None): return self.rchild.search(data) else: return None def insert(self, data): if (data < self.data): if (self.lchild != None): self.lchild.insert(data) else: self.lchild = BST(data) else: if (self.rchild != None): self.rchild.insert(data) else: self.rchild = BST(data) def in_order(self): if (self.lchild != None): self.lchild.in_order() print(self.data) if (self.rchild != None): self.rchild.in_order() ####测试 lst = np.random.randint(0, 100, 30) Bst = BST(0) for i in lst: Bst.insert(i) Bst.in_order() lst = np.random.randint(0, 100, 5) for i in lst: print(i, Bst.search(i))
99649a5001635903aeda17a75e830e0431c5699e
tartlet/CS303E
/Tempgrams.py
933
3.71875
4
"""n1 = eval(input("First Num? ")) n2 = eval(input("Second Num? ")) k = 1 while k <= n1 and k <= n2: if n1 % k == 0 and n2 % k == 0: gcd = k k += 1 print("GCD is", gcd) """ #GCD Program #Future Tuition: """current1 = 10000 yearcount = 0 ncurrent = 10000 nextyear = 0 while nextyear <= 2*current1: nextyear = ncurrent * 1.07 ncurrent = nextyear yearcount += 1 print("It took", yearcount, "years for tuition to double") print("The tuition is now", format(ncurrent, ".2f"))""" #DIsplay 50 prime numbers count = 0 number = 2 numPerLine = 10 print("The first 50 prime numbers are") while count < 50: prime = True div = 2 while div <= number/2: if number % div == 0: prime = False break div += 1 if prime == True: print(format(number, "5d"), end = '') count += 1 if count % numPerLine == 0: print() number += 1
2bc599504b41033eb452a154c37b5557c0429029
mambalong/Algorithm_Practice
/0221_maximalSquare.py
1,049
3.703125
4
''' 221. Maximal Square Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4 ''' ''' 思路动态规划,dp[i][j] 表示以当前格子为右下角,最大的正方形的边长。 dp 方程:dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 base case: 当 i 或者 j 等于 0 时,dp 值等于对应格子的值。 ''' class Solution: def maximalSquare(self, matrix): if matrix == []: return 0 max_side = 0 nr, nc = len(matrix), len(matrix[0]) dp = [[0] * nc for _ in range(nr)] for i in range(nr): for j in range(nc): if matrix[i][j] == '1': if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 max_side = max(max_side, dp[i][j]) return max_side * max_side
535a0b6f019d180f33fd7a68d676308c41d55f82
DrCesar/python-opengl-renderer
/opengl/models/vectors.py
1,325
3.8125
4
class V3(object): def __init__(self, x, y, z=0): self.x = x self.y = y self.z = z def __add__(self, other): if isinstance(other, (int, float)): return V3(self.x + other, self.y + other, self.z + other) elif isinstance(other, V3): return V3(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): if isinstance(other, (int, float)): return V3(self.x - other, self.y - other, self.z - other) elif isinstance(other, V3): return V3(self.x - other.x, self.y - other.y, self.z - other.z) def __mul__(self, other): if isinstance(other, (int, float)): return V3(self.x * other, self.y * other, self.z * other) elif isinstance(other, V3): return V3( self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x ) def __matmul__(self, other): if isinstance(other, V3): return V3(1, 2, 1) def __len__(self): return 3 def __getitem__(self, index): return (self.x, self.y, self.z)[index] return 0 def __str__(self): return 'V3(%s, %s, %s)' % (self.x, self.y, self.z)
77ca98d4d699be49862d8aca1ddacb47b0748e81
jquahian/robosim
/linear_interp.py
2,146
3.6875
4
import numpy as np import time def generate_linear_path(waypoints, intermediate_point_dist): """function takes a list of waypoints and generates a list of points to form a linear path between them. The order of the waypoints matters. intermediate points will be generated between waypoint n and n+1. Function will take any number of waypoints. Args: waypoints (array): array of cartesian points where each point is given as an array [x, y, z] (mm) intermediate_point_dist (float): distance to space the intermediate points between waypoints (mm) Returns: array of arrays: each item in the array is a cartesian point in the form [x, y, z] (mm) """ start_time = time.time() linear_coordinates = [] for i in range(len(waypoints)): if i < len(waypoints) - 1: point_1 = np.array(waypoints[i]) point_2 = np.array(waypoints[i + 1]) vector_p1_p2 = np.subtract(point_2, point_1) print(f'vector: {vector_p1_p2}') segment_length = np.linalg.norm(vector_p1_p2) print(f'segment is {segment_length} mm \n') # determine number of intermediate points spaced some distance between the waypoints num_points = int(segment_length // intermediate_point_dist) # generate the intermediate points for j in range(num_points): linear_point = np.multiply(vector_p1_p2, j/num_points) linear_point = np.add(linear_point, point_1) linear_coordinates.append(linear_point) elapsed_time = round(start_time - time.time(), 7) linear_coordinates.append(np.array(waypoints[-1])) print(f'linear solve: {len(linear_coordinates)} points generated between {len(waypoints)} waypoints in {elapsed_time} s') return linear_coordinates # # example useage and for testing # point_a = [393.67, -227.585, 428.274] # point_b = [480., 40., 400.] # point_c = [393.67, 0, 428.274] # waypoints = [point_a, point_b, point_c] # generate_linear_path(waypoints, 10)
b37c462177a88f93275138810eb52e6d118ec3d1
juliovt-07/Exercicios-Python
/Condicional 4.py
269
4.0625
4
#programa que leia um número e, #caso ele seja positivo, calcule e mostre: #• O número digitado ao quadrado #• A raiz quadrada do número digitado n = int(input("Digite um número: ")) if n%2 == 0: print(f"{n} É Positivo") else: print(f"{n} É Negativo")
1c488ccf257818ae41918e13037565886814597d
ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
/trie/trie.py
3,549
3.8125
4
class TrieNode: def __init__(self, key, parent = None, children: dict = {}): self.key = key self.parent = parent self.children:dict = {} self.endchar: bool = False class Trie: def __init__(self): self.root: TrieNode = TrieNode(None) def insert(self, string: str): current: TrieNode = self.root for character in string: if character not in current.children: current.children[character] = TrieNode(character, current) current = current.children[character] current.endchar = True def contains(self, string: str)->bool: current: TrieNode = self.root for character in string: if character not in current.children: current = None break current = current.children[character] if current is None: return False return current.endchar def delete(self, string: str): current: TrieNode = self.root for character in string: if character not in current.children: current = None break current = current.children[character] if current is None: return current.endchar = False parent: TrieNode = current.parent while parent is not None and not current.endchar and len(current.children) == 0: del(parent.children[current.key]) current = parent parent = current.parent def prefix(self, prefix: str)->list: current: TrieNode = self.root for character in prefix: if character not in current.children: current = None break current = current.children[character] if current is None: return words: list = [] self.helper(current, words, prefix) return words def helper(self, node: TrieNode, words: list, currentWord: str): if node is None: return if node.endchar: words.append(currentWord) for key in node.children: self.helper(node.children[key], words, currentWord + key) def allWords(self)->list: words: list = [] self.helper(self.root, words, "") return words def count(self)->int: return self.countHelper(self.root) def countHelper(self, node: TrieNode)->int: if node is None: return 0 sum: int = 0 if node.endchar: sum += 1 for character in node.children: sum += self.countHelper(node.children[character]) return sum trie = Trie() trie.insert("javascript") trie.insert("java") trie.insert("scala") trie.insert("scale") trie.insert("scalable") trie.insert("perl") print("Contains 'javascript' : ", trie.contains("javascript")) print("Contains 'java' : ", trie.contains("java")) print("Contains 'ruby' : ", trie.contains("ruby")) #trie.delete("java") trie.delete("javascript") print("Contains 'javascript' : ", trie.contains("javascript")) print("Contains 'java' : ", trie.contains("java")) print("Contains 'ruby' : ", trie.contains("ruby")) print(trie.prefix("scal")) # ['scala', 'scalable', 'scale'] print(trie.prefix("java")) # ['java'] print("All words", trie.allWords()) # All words ['java', 'scala', 'scalable', 'scale', 'perl'] print("Count : ", trie.count())
ad3189f3c124b726a44f0148c6695b67e055d598
antonyngayo/react-upload
/server/db.py
1,094
3.609375
4
#!/usr/bin/python3 from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, TIMESTAMP, func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import text Base = declarative_base() class User(Base): __tablename__ = "person" id = Column('id', Integer, primary_key=True, autoincrement=True) username = Column('username', String, unique=True) last_login_date = Column(TIMESTAMP(timezone=False), server_default=func.now(), nullable=False) engine = create_engine('sqlite:///users.db', echo=True) Base.metadata.create_all(bind=engine) Session = sessionmaker(bind=engine) # Creating a session object to help in creating, updating, deleting objects in database session = Session() # Adding user # user = User() # user.id = 1 # user.username = "Anthony" # session.add(user) # session.commit() users = session.query(User).all() for user in users: print(f"The username is {user.username} and id: {user.id} and they last logged in at: {user.last_login_date}") session.close()
9c6bd6328135ff5600e18657cfd5781212a38464
qualityland/Python_for_Everybody
/c03/try_except.py
235
3.78125
4
sh = input("Enter hours:") sr = input("Enter rate:") try: h = float(sh) r = float(sr) except: print("Hours and rate need to be numbers.") quit() p = h * r if h > 40 : p = p + (h - 40) * r * 0.5 print("Pay:", p)
b1dc9e505c919a677e4ad516ba5eb32f5820c244
zumbipy/PythonExercicios
/EstruturaDeRepeticao/estruturaderepeticao-09.py
672
3.640625
4
# Telegram: @ZumbiPy __ _ ___ # /_ / __ ____ _ / / (_) _ \__ __ # / /_/ // / ' \/ _ \/ / ___/ // / # /___/\_,_/_/_/_/_.__/_/_/ \_, / # E-mail: zumbipy@gmail.com /___/ """ 09 - Faça um programa que imprima na tela apenas os números ímpares entre 1 e 50. """ # ================================================================================ # Logica do Programa. # ================================================================================ for i in range(1, 50): # Quando resto de uma divisao por 2 for 0 ele e par se nao e ímpar. if i % 2 != 0: print(i) print("=" * 72) # ou for i in range(1, 50, 2): print(i)
a6d1b81892043537d9e7950abd99006fde7290ce
migboi/Miguel-Dam-2019
/Diseño_de_interfaces/pythonProjects/Testeo con doctest/lopez_boils.py
394
4.125
4
import math def volume (r:float,h:float,R:float)-> float: """ this function calculing the volume of a truncate cone. Volume=h*pi/3*(R2+r2+R*r) h,r,R never cant less menor or equal 0 >>> volume(2,2,2) 25.133 >>> volume(2,3,2) 37.699 """ return round(h*math.pi/3*(math.pow(R,2)+math.pow(r,2)+(R*r)),3) help(volume)
85f66fa854b48936d948dd47d48b8b7f6dc3bde6
skymoonfp/python_learning
/Python_code/exc_def2.py
1,111
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 定义乘积函数 def product(*numbers): s = 1 for n in numbers: s = s * n return s # 测试 print('product(5)=', product(5)) print('product(5,6)=', product(5, 6)) print('product(5,6,7)=', product(5, 6, 7)) print('product(5,6,7,9)=', product(5, 6, 7, 9)) if product(5) != 5: print('测试失败!') elif product(5, 6) != 30: print('测试失败!') elif product(5, 6, 7) != 210: print('测试失败!') elif product(5, 6, 7, 9) != 1890: print('测试失败!') else: try: product() print('测试成功!') except TypeError: print('测试成功!') # 定义输出格式函数 def print_input(*numbers): if len(numbers) == 1: print('product(%s)=%s' % (numbers[0], product(*numbers))) else: # print('product%s=%f' %(''.join(repr(numbers)),product(*numbers))) print('product%s=%s' % (numbers, product(*numbers))) # 输入数据 numbs = map(float, input('Enter numbers:').split()) print_input(*numbs) print('\n') input('Please press Enter to exit!')
72624c9864bb7a168eebf67df196b88239e980f2
Jaysparkexel/DFS-1
/Problem2.py
2,356
3.59375
4
# Time Complexity : O(MxN) (Where M is no of row and N is no of column) # Space Complexity : O(1) # Did this code successfully run on Leetcode : Yes # Three line explanation of solution in plain english: # - Instead of running dfs on each 1 we can run it on each 0. # - Chage value of 1 to some big number and add location of 0 in teh queue. # - If neighbour is greater than current value + 1 that means, that neighbour was 1 in the original matrix. So, update it's value with minimum distance. class Solution(object): def updateMatrix(self, matrix): """ :type matrix: List[List[int]] :rtype: List[List[int]] """ # Initialize queue and find length of row and column queue = [] maxrow = len(matrix) maxcol = len(matrix[0]) # Initizlize direction drow = [-1, 1 , 0, 0] dcol = [0, 0, 1 , -1] # Parse through every cell for i in range(maxrow): for j in range(maxcol): # If the cell is 0 than we will append it to queue, because that will serve as our starting point. if matrix[i][j] == 0: queue.append((i, j)) # Convert all the 1 into +infinite. else: matrix[i][j] = float("+inf") # Run the loop untill queue is not empty while queue: # Pop the first element current = queue.pop(0) (row, col) = current # Try all 4 direction for j in range(4): # Update row and column according to direction nrow = row + drow[j] ncol = col + dcol[j] # If neighbour's row and column is not out of bound and it's value is greater than current cell value + 1 we go in. This is possible only when neighbour cell was 1. if 0 <= nrow and nrow < maxrow and 0 <= ncol and ncol < maxcol and matrix[nrow][ncol] > matrix[row][col] + 1: # Update new row and column value to the current cell value plus 1. matrix[nrow][ncol] = matrix[row][col] + 1 # add new row and column value into the queue queue.append((nrow, ncol)) # Return the answer return matrix
e9141c08d4b798f1210e73c80c134ebe641699dd
polyglotm/coding-dojo
/coding-challange/leetcode/medium/2743-count-substrings-without-repeating-character/2743-count-substrings-without-repeating-character.py
988
3.625
4
# leetcode/medium/2743. Count Substrings Without Repeating Character # 2743-count-substrings-without-repeating-character # URL: https://leetcode.com/problems/count-substrings-without-repeating-character/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference class Solution: def numberOfSpecialSubstrings(self, s: str) -> int: count = 0 for i in range(len(s)): char_set = set(s[i]) count += 1 for j in range(i + 1, len(s)): if s[j] in char_set: break else: char_set.add(s[j]) count += 1 return count s = "abcd" assert Solution().numberOfSpecialSubstrings(s) == 10 # Output: 10 s = "ooo" assert Solution().numberOfSpecialSubstrings(s) == 3 # Output: 3 s = "abab" assert Solution().numberOfSpecialSubstrings(s) == 7 # Output: 7 s = "bddqc" assert Solution().numberOfSpecialSubstrings(s) == 9
c8d038805c0df46208b529412bc5a744c342d5c9
antaladrien/Python-beginner-exercises
/day-10/main.py
724
4
4
def format_name(f_name, l_name): if f_name == "" or l_name == "": return "You didn't provide valid inputs." formated_f_name = f_name.title() formated_l_name = l_name.title() f"Result: {formated_f_name} {formated_l_name}" formatted_name = format_name(input("Your first name: "), input("Your last name: ")) print(formatted_name) print(format_name(input("What is your first name? "), input("What is your last name? "))) length = len(formatted_name) def format_name(f_name, l_name): if f_name == "" or l_name == "": return "You didn't provide valid inputs." formated_f_name = f_name.title() formated_l_name = l_name.title() return f"Result: {formated_f_name} {formated_l_name}"
490df0d7db0b04a2a245b0148617be04d2eaad53
fernandoim/wpcli_utilidades
/busca_palabras_clave.py
1,608
3.5625
4
""" Devuelve una lista de palabras clave a partir de una o varias palabras clave indicadas como argumentos. Este listado de palabras clave se basa en las sugerencias de Google. """ import requests, json import sys # -*- coding: utf-8 -*- def muestra_ayuda(): """ Muestra la ayuda del script.""" print("Recibe una o más palabras y devuelve un listado con sugerencias de palabras clave.") numero_de_parametros = len(sys.argv) palabras = sys.argv[1:numero_de_parametros] busqueda = "" for palabra in palabras: if palabra == "-h": muestra_ayuda() sys.exit(0) else: busqueda = busqueda + " " + palabra tambusqueda = len(busqueda) busqueda = busqueda[1:tambusqueda] URL="http://suggestqueries.google.com/complete/search?client=firefox&q=" + busqueda cabecera = {'User-agent':'Mozilla/5.0'} respuesta = requests.get(URL, headers=cabecera) resultado = json.loads(respuesta.content.decode('utf-8')) primera_ronda = resultado.pop(1) palabras_clave = primera_ronda for i in range(1,3): for elemento in palabras_clave: URL="http://suggestqueries.google.com/complete/search?client=firefox&q=" + elemento cabecera = {'User-agent':'Mozilla/5.0'} respuesta = requests.get(URL, headers=cabecera) resultado = json.loads(respuesta.content.decode('utf-8')) temporal = resultado.pop(1) temporal += palabras_clave palabras_clave = list(set(temporal)) print("Localizadas " + str(len(palabras_clave)) + " palabras clave derivadas de " + busqueda + ":") for palabra_clave in palabras_clave: print(palabra_clave)
343f1824ad9e1ff26126d72ed9915a213b890fa2
kemingy/daily-coding-problem
/src/max_subarray.py
740
3.921875
4
# Given an array of integers and a number k, where 1 <= k <= length of the array, # compute the maximum values of each subarray of length k. from collections import deque def max_subarray(array, k): assert 1 <= k <= len(array) dq = deque() for i, n in enumerate(array[:k]): while dq and n >= array[dq[-1]]: dq.pop() dq.append(i) for i, n in enumerate(array[k:], k): yield array[dq[0]] while dq and dq[0] <= i - k: dq.popleft() while dq and n >= array[dq[-1]]: dq.pop() dq.append(i) yield array[dq[0]] if __name__ == '__main__': print(list(max_subarray([100, 1, 78, 60, 57, 89, 56], 3)))
ce9b393b008c1d620e4d98c21ba15c8058e29b94
Lhotse867745418/Python3_Hardway
/ex30.py
811
4.25
4
#------------------------------------------------------------------------------- # Name: what if # Purpose if-elif-elsestatement # # Author: lhotse # # Created: 19/03/2018 # Copyright: (c) Administrator 2018 # Licence: #------------------------------------------------------------------------------- people = 30 cats = 30 dogs = 15 if people < cats: print("too many cats! the world is doomed") elif people > cats: print("not many cats! the world is saved!") else: print("every one will have one cat!" ) if people < dogs: print("the world is drooled on!") elif people > dogs: print("the world is dry!") else: print("the amount of people is same as dogs!") def main(): pass if __name__ == '__main__': main()
7bf0c452c446aa9db9bc41b25a6e51ce90f12a8c
abhra04/SortingVisualizer
/quickSort.py
1,858
3.59375
4
""" Algorithm: Select a pivot - > start iteration from the begining -> compare the value with pivot -> if less than pivot swap with border -> at the end replace border with pivot-> recurse of the subarray left and right of pivit Compleity -> O(nlogn) (Average) O(n2) (Worst Case) """ import time def getMid(arr,left,right,drawData,play): pivot = arr[right] border = left drawData(arr, getColorArray(len(arr), left, right, border, border,False)) time.sleep(1/play) for i in range(left,right): if arr[i] < pivot: drawData(arr, getColorArray(len(arr), left, right, border, border,True)) time.sleep(1/play) arr[border],arr[i] = arr[i],arr[border] border = border + 1 drawData(arr, getColorArray(len(arr), left, right, border, border,False)) time.sleep(1/play) drawData(arr, getColorArray(len(arr), left, right, border, border,True)) time.sleep(1/play) arr[border],arr[right] = arr[right],arr[border] return border def quickSort(arr,left,right,drawData,play): if left>=right: return mid = getMid(arr,left,right,drawData,play) quickSort(arr,left,mid - 1 ,drawData , play) quickSort(arr,mid + 1,right,drawData,play) def getColorArray(dataLen, head, tail, border, currIdx, isSwaping): colorArray = [] for i in range(dataLen): #base coloring if i >= head and i <= tail: colorArray.append('pink') else: colorArray.append('orange') if i == tail: colorArray[i] = 'blue' elif i == border: colorArray[i] = 'red' elif i == currIdx: colorArray[i] = 'yellow' if isSwaping: if i == border or i == currIdx: colorArray[i] = 'green' return colorArray ''' Testing: arr = [7,5,7,9,4,2] print(arr) quickSort(arr,0,len(arr) -1 , 0,0) print(arr) '''
79143b8a0bf4007c214bd333e0e1e0903843634b
10486/labs
/lab7/lab7.py
670
3.96875
4
# Во входном файле имеется строка символов, которая заканчивается # точкой. Напишите рекурсивную программу, которая определяет количество # цифр в заданной последовательности. def counter(string): numbers = [str(x) for x in range(10)] + ['A', 'B', 'C', 'D', 'E', 'F'] if len(string) == 1: return int(string in numbers) else: if string[0] in numbers: return counter(string[1:]) + 1 return counter(string[1:]) with open('input.txt', 'r') as f: print(counter(f.read()))
22b9ae49be573442350a93d631206d725c47632f
sneharnair/Stack-1
/Problem-1_Daily_temperatures.py
1,479
3.671875
4
# APPROACH 1: Stack solution # Time Complexity : O(n), n: length of T # Space Complexity : O(n), due to size of stack # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : None # # # Your code here along with comments explaining your approach # 1. Use stack to put those indices of lower temperature # 2. If we find a greater temperature than the top of stack, pop if off and write the difference in the indices (curr - stack's top element) -> number of days in it's # corresponding result. # 3. Keep resolving this till this new temperature is greater than the top of stack. Then move forward # 4. At end of array, there will be some unresolved indices in stack. Place 0 in their corressponding result. class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: if len(T) < 1 or T is None or len(T) > 30000: return [] stack, result = [], [0 for _ in range(len(T))] stack.append(0) for ind in range(1, len(T)): if T[ind] < 30 or T[ind] > 100: return [] else: while len(stack) > 0 and T[ind] > T[stack[-1]]: top_ind = stack.pop() result[top_ind] = ind - top_ind stack.append(ind) while stack: ind = stack.pop() result[ind] = 0 return result
8b326209faddcd6ea0387d22c0a67278ee4a7065
WeiqiangZhang/SQuEaL
/database_project/starter/reading.py
3,457
4.03125
4
# Functions for reading tables and databases import glob from database import * # a table is a dict of {str:list of str}. # The keys are column names and the values are the values # in the column, from top row to bottom row. # A database is a dict of {str:table}, # where the keys are table names and values are the tables. # YOU DON'T NEED TO KEEP THE FOLLOWING CODE IN YOUR OWN SUBMISSION # IT IS JUST HERE TO DEMONSTRATE HOW THE glob CLASS WORKS. IN FACT # YOU SHOULD DELETE THE PRINT STATEMENT BEFORE SUBMITTING # print(file_list) # Write the read_table and read_database functions below def read_table(csv): '''(str) -> Table REQ: A valid file name that can be found REQ: The file has to have at least one header >>>read_table('books.csv').get_dict() {'book.year': ['1979', '2014', '2015', '2014'], 'book.title': ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma'], 'book.author': ['Douglas Hofstadter', 'Randall Munroe', 'Randall Munroe', 'Andrew Hodges']} ''' # Create a Table object return_value = Table() # Open the file my_file = open(csv, 'r') # read every line of the file file_list = my_file.readlines() # Create a holder list new_list = [] j = 0 title_num = 0 # Go through every line of the file for next_line in file_list: # Check if the line is empty or not if (next_line.strip() != ''): # Make each string seperated by , an element next_line = next_line.split(',') # Get rid of any spaces in the elements for i in range(len(next_line)): next_line[i] = next_line[i].strip() # Append the list to the holder list new_list.append(next_line) for title in new_list[title_num]: # Call set_header using the headers return_value.set_header(title) # Go through every header for title in new_list[title_num]: # Go through every rows for i in range(1, len(new_list)): # Call set_table to make a Table object using the header and # rows of that header return_value.add_elements(title, new_list[i][j]) j += 1 # Close the file my_file.close() # Return the Table object return return_value def read_database(): '''() -> Database Read all the files and make the file name the key and Table object of that file the value REQ: The files has to have at least one header each >>>read_database().get_dict() {'imdb': <database.Table object at 0x02860E50>, 'oscar-film': <database.Table object at 0x0295E3F0>, 'oscar-actor': <database.Table object at 0x0295EF10>, 'boxoffice': <database.Table object at 0x02930290>, 'seinfeld-foods': <database.Table object at 0x02A24750>, 'olympics-locations': <database.Table object at 0x0295E450>, 'books': <database.Table object at 0x029302B0>, 'seinfeld-episodes': <database.Table object at 0x02A1B8B0>, 'olympics-results': <database.Table object at 0x0295E430>} ''' # Make a Database object return_value = Database() # Read every file file_list = glob.glob('*.csv') for file in file_list: # Add each Table in the Database return_value.add_tables(file.replace('.csv', ''), read_table(file)) # Return the Database return return_value
0b21ce64bf126145094e25e19457f33e5b326afa
evilnsm/learn-python
/Project Euler/023.py
1,126
3.8125
4
#coding:utf-8 ''' 完全数是指真因数之和等于自身的那些数。例如,28的真因数之和为1 + 2 + 4 + 7 + 14 = 28,因此28是一个完全数。 一个数n被称为亏数,如果它的真因数之和小于n;反之则被称为盈数。 由于12是最小的盈数,它的真因数之和为1 + 2 + 3 + 4 + 6 = 16,所以最小的能够表示成两个盈数之和的数是24。通过数学分析可以得出,所有大于28123的数都可以被写成两个盈数的和;尽管我们知道最大的不能被写成两个盈数的和的数要小于这个值,但这是通过分析所能得到的最好上界。 找出所有不能被写成两个盈数之和的正整数,并求它们的和。 ''' import math def is_abundant(n): d = 1 for x in xrange(2,int(math.sqrt(n))+1): if n%x == 0: d += (x + n/x) if x*x == n: d -= x return d > n ab = [x for x in xrange(12,28123-11) if is_abundant(x)] absum = set([x+y for x in ab for y in ab if x+y < 28123]) non_absum = 0 for n in xrange(1,28123): if n not in absum: non_absum += n print non_absum
dbd4dfee42d9e2f62cd98c0e38700e1ac0a7e2f4
lovebc/lovelab
/code/peter_global_trends/randomize.py
488
3.65625
4
##### Randomizing choices ##### ##### Modules ##### import random ########## def randomize_choices (choices): # Lists index_list_choices=[] rand_choices=[] # Choices made for x in range(0, len(choices)): index_list_choices.append(x) for y in range(0, len(choices)): a=random.randint(0, (len(index_list_choices)-1)) b=index_list_choices[a] rand_choices.append(choices[b]) del index_list_choices[a] return rand_choices ##########
40746b8b2bfdc50f6b278a64cd6cc1e9952e975f
ynfle/interview-practice-problems
/problems/Python/2-merge-sort.py
571
4.125
4
# merge sort def merge(arr1: list, arr2: list) -> list: raise NotImplementedError len1, len2 = len(arr1), len(arr2) result = [] for i in range(len1 + len2): result.append() def merge_sort(arr: list) -> list: length = len(arr) if length == 1: return arr left = merge_sort(arr[:length//2]) right = merge_sort(arr[length//2:]) return merge(left, right) if __name__ == "__main__": arr = [21, 3, 1, 4, 5, 6] arr2 = arr[:] merge_sort(arr) arr2 = sorted(arr2) assert arr, arr2 print(arr == arr2)
7c786385666e9682ba376560cf8a991695c1b53d
aabhishek-chaurasia-au17/python_practice
/list/list-exercise/Count_occurrences.py
490
4.09375
4
# Python | Count occurrences of an element in a list """ Input : lst = [15, 6, 7, 10, 12, 20, 10, 28, 10] x = 10 Output : 3 10 appears three times in given list. Input : lst = [8, 6, 8, 10, 8, 20, 10, 8, 8] x = 16 Output : 0 """ def Count_element(a,x): count = 0 for i in a: if i == x: count += 1 return count if __name__=="__main__": lst = [15, 6, 7, 10, 12, 20, 10, 28, 10] x = 10 print(Count_element(lst,x))
a6937e1ee984628795d36c77c3ea879f74f1b196
theme716/small-routine
/insect/8.eight_day/3.互斥锁、信号量.py
990
3.890625
4
# 互斥锁 ''' from threading import Thread,Lock num = 0 #创造一个互斥锁 lock = Lock() # 在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。 def add(): global num for i in range(1000000): # 上锁姿势:一 # lock.acquire() # 上锁 # num += 1 # lock.release() # 解锁 # 上锁姿势:二 with lock: num += 1 t1 = Thread(target=add) t2 = Thread(target=add) t1.start() t2.start() t1.join() t2.join() print(num) ''' # 信号量 ''' from threading import Thread,BoundedSemaphore import time def foo(i): bs.acquire() #上锁 time.sleep(1) print(i) bs.release() #解锁 bs = BoundedSemaphore(3) #同时执行的线程数 for i in range(10): t = Thread(target=foo,args=(i,)) t.start() '''
768ddcf21ed63b2df61f6a66a652f81364afa626
mewturn/hackerrank
/Algorithms/Implementation/checkpangram.py
377
4.03125
4
# Original Problem: https://www.hackerrank.com/challenges/pangrams/problem def checkPangram(inp): inp_set = set(inp.lower()) # Set to lower-case alphabets = set('abcdefghijklmnopqrstuvwxyz') # Check that all of the alphabets are in the input set for elem in alphabets: if elem not in inp_set: return "not pangram" return "pangram"
f82b545053b2d89f2619e94712a68d9b2be45fdd
p-heebong/Manchester-Differential-Manchester-Endcoding
/code/manchester.py
2,221
3.6875
4
import matplotlib.pyplot as plt print('1.Manchester') print('2.Differential-Manchester') print('') choice = int(input('무엇을 출력하시겠습니까?: ')) str = input("비트를 입력하세요: ") num = len(str) x = list() y = list() for i in range(num): y.append(int(str[i])) if choice == 1: yaxis = list() for i in range(0, num): if y[i] == 1: yaxis.append(-1) yaxis.append(1) if y[i] == 0: yaxis.append(1) yaxis.append(-1) x = [] for i in range(2 * num): x.append(i) x = x * 2 x.sort() x.remove(x[0]) x.append(2 * num) m = [] for i in yaxis: m.extend([i, i]) yaxis = m zero = list() for i in range(0, 4 * num): zero.append(int(0)) plt.plot(x, yaxis, linewidth=4.0) plt.plot(x, zero, linewidth=1.0) plt.plot([0, 0, 0], [0, 1.5, -1.5]) plt.grid() plt.title("Manchester") plt.show() if choice==2: yaxis = list() for i in range(num - 1): if i == 0: if y[i] == 1: yaxis.append(1) yaxis.append(-1) elif y[i] == 0: yaxis.append(-1) yaxis.append(1) if y[i + 1] == 0: if yaxis[-1] == -1: yaxis.append(1) yaxis.append(-1) elif yaxis[-1] == 1: yaxis.append(-1) yaxis.append(1) if y[i + 1] == 1: if yaxis[-1] == -1: yaxis.append(-1) yaxis.append(1) elif yaxis[-1] == 1: yaxis.append(1) yaxis.append(-1) m = [] for i in yaxis: m.extend([i, i]) yaxis = m for i in range(2 * num): x.append(i) x = x * 2 x.sort() x.remove(x[0]) x.append(2 * num) zero = list() for i in range(0, 4 * num): zero.append(int(0)) plt.plot(x, yaxis, linewidth=5.0) plt.plot(x, zero, linewidth=1.0) plt.plot([0, 0, 0], [0, 1.5, -1.5]) plt.grid() plt.title("Differential-Manchester") plt.show()
5e1088eff63c2523880f76d607e2a0e7a8e0ed56
exeburgos/Loan-Calculator
/creditcalc.py
6,016
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 28 09:45:39 2020 @author: exebu """ import sys import math import argparse def periods(principal, payment, interest): interest = interest / 12 / 100 per = math.ceil(math.log(payment / (payment - interest * principal), (1 + interest))) final(per) return per def payment(principal, periods, interest): interest = interest / 12 / 100 pay = principal * interest * pow(1 + interest, periods) / (pow(1 + interest, periods) - 1) print('Your annuity payment = {}!'.format(math.ceil(pay))) return math.ceil(pay) def principal(payment, periods, interest): interest = interest / 12 / 100 prin = payment * ((1 + interest) ** periods - 1) / (interest * ((1 + interest) ** periods)) print('Your loan principal = {}!'.format(str(math.ceil(prin)))) return math.ceil(prin) def overpayment(periods, payment, principal): over = periods * payment - principal print('Overpayment =' + str(over)) def differentiated_payments(principal, periods, interest): over = 0 interest = interest / 12 / 100 for monthly in range(1, periods + 1): dp = (principal / periods) + interest * (principal - ((principal * (monthly - 1)) / periods)) print('Month {0}: payment is {1}'.format(monthly, math.ceil(dp))) over += math.ceil(dp) print('\nOverpayment =' + str(over- args.principal)) def final(result): if result < 12: print('It will take {0} month{1} to repay the loan'.format(result % 12, 's' if result % 12 != 1 else '')) elif result % 12 == 0: print('It will take {0} year{1} to repay the loan'.format(result // 12, 's' if result // 12 != 1 else '')) else: print('It will take {0} year{1} and {2} month{3} to repay the loan'.format(result // 12, 's' if result // 12 != 1 else '', result % 12, 's' if result % 12 != 1 else '')) def input_verifier(): arguments = sys.argv args = [element.split('=') for element in arguments[1:]] count = 0 for element in args[1:]: if element[0] == '--interest': count +=1 break if count == 0: print('Incorrect parameters.') sys.exit() elif len(args) < 4: print('Incorrect parameters.') sys.exit() elif args[0][1] not in ['diff', 'annuity']: print('Incorrect parameters.') sys.exit() elif args[0][1] not in ['diff', 'annuity'] and '--payment' in args[:][0]: print('Incorrect parameters.') sys.exit() for element in args[1:]: if int(element[1]) < 0: print('Incorrect parameters.') sys.exit() def check_input(): global args if not args.type: print('Incorrect parameters') elif args.type == 'diff' and args.payment: print('Incorrect parameters') elif not args.interest: print('Incorrect parameters') argu = sys.argv arguments = [element.split('=') for element in argu[1:]] for element in arguments[1:]: if float(element[1]) < 0: print('Incorrect parameters.') sys.exit() parser = argparse.ArgumentParser(description="Loan Calculator") parser.add_argument("--type", type=str, help="The type of loan", choices=['diff', 'annuity']) parser.add_argument("--interest", type=float, help="the annual interest rate without % sign ") parser.add_argument("--principal", type=int, help="The borowed ammount") parser.add_argument("--payment", type=int, help="The monthly payment") parser.add_argument("--periods", type=int, help="The number of months") args = parser.parse_args() if args: check_input() if args.type == 'annuity': if args.payment and args.periods and args.interest: prin = principal(args.payment, args.periods, args.interest) overpayment(args.periods, args.payment, prin) elif args.payment and args.principal and args.interest: per = periods(args.principal, args.payment, args.interest) overpayment(per, args.payment, args.principal) elif args.principal and args.interest and args.periods: pay = payment(args.principal, args.periods, args.interest) overpayment(args.periods, pay, args.principal) elif args.type == 'diff': if args.interest and args.principal and args.periods: differentiated_payments(args.principal, args.periods, args.interest) else: input_verifier() selection = input('''What do you want to calculate? type "n" for number of monthly payments, type "a" for annuity monthly payment amount, type "p" for loan principal, type "d" for differentiated loan:''') if selection == 'n': P = int(input('Enter the loan principal:')) a = int(input('Enter the monthly payment:')) i = float(input('Enter the loan interest:')) result = periods(P, a, i) final(result) overpayment(result, a, P) elif selection == 'a': P = int(input('Enter the loan principal:')) n = int(input('Enter the number of periods:')) i = float(input('Enter the loan interest:')) result = math.ceil(payment(P, n, i)) print('Your monthly payment = {0}!'.format(result)) overpayment(n, result, P) elif selection == 'p': a = float(input('Enter the annuity payment:')) n = int(input('Enter the number of periods:')) i = float(input('Enter the loan interest:')) result = math.ceil(principal( a, n, i)) print('Your monthly payment = {0}!'.format(result)) overpayment(n, a, result) else: P = int(input('Enter the loan principal:')) n = int(input('Enter the number of periods:')) i = float(input('Enter the loan interest:')) differentiated_payments(P, n, i)
4d708a8ffeecaf499df2bcc9fe4911758a602774
why1679158278/python-stu
/python资料/day8.17/day13/exercise01.py
842
3.796875
4
""" 情景:手雷爆炸,可能伤害敌人(头顶爆字)或者玩家(碎屏)。 变化:还可能伤害房子、树、鸭子.... 要求:增加新事物,不影响手雷. 画出架构设计图 体会:开闭原则 增加新攻击目标,手雷不改变. 封装: 继承: 多态: """ # --------------架构师---------------- class Grenade: def explode(self,target): print("手雷爆炸") target.damage() class AttackTarget: def damage(self): pass # --------------程序猿---------------- class Enemy(AttackTarget): def damage(self): print("头顶爆字") class Player(AttackTarget): def damage(self): print("碎屏") # --------------测试---------------- g = Grenade() g.explode( Enemy() ) g.explode( Player() )
f7ffd074a2c1cb42f8c10d52afc7435ec4ab8d58
Jiaqi07/CodeInPlaceFinalProject
/main.py
2,701
3.59375
4
import cv2 from simpleimage import SimpleImage from matplotlib import pyplot as plt DEFAULT_FILE = 'images/ocean.jpg' def show(filename): image = SimpleImage(filename) image.show() def grayscale(filename): image = SimpleImage(filename) width = image.width height = image.height grayimg = SimpleImage.blank(width, height) for pixel in image: intensity = .2989 * pixel.red + .587 * pixel.green + .114 * pixel.blue pixel.red = intensity pixel.blue = intensity pixel.green = intensity grayimg.set_pixel(pixel.x, pixel.y, pixel) grayimg.show() def hist(filename): img = cv2.imread(filename, 0) histr = cv2.calcHist([img], [0], None, [256], [0, 256]) plt.plot(histr) plt.xlabel("Intensity") plt.ylabel("Pixel Count") plt.title("Intesity to Pixel Count Diagram") plt.show() def flip(filename): image = SimpleImage(filename) width = image.width height = image.height direction = input('Horizontal or Vertical? (H or V): ') if direction.lower() == 'v': flippedimg = SimpleImage.blank(width, height) for y in range(height): for x in range(width): pixel = image.get_pixel(x, y) flippedimg.set_pixel(width - (x + 1), y, pixel) flippedimg.show() elif direction.lower() == 'h': flippedimg = SimpleImage.blank(width, height) for y in range(height): for x in range(width): pixel = image.get_pixel(x, y) flippedimg.set_pixel(x, height - (y + 1), pixel) flippedimg.show() else: print("Ain't an answer bud") def get_file(): # Read image file path from user, or use the default file filename = input('Enter image file (or press enter for default): ') if filename == '': filename = DEFAULT_FILE print("") print("") return filename if __name__ == '__main__': filename = get_file() go = True while (go): ans = input('What would you like to do? (or press enter to exit): ') if ans == "": go = False elif ans.lower() == 'show': show(filename) elif ans.lower() == 'flip': flip(filename) elif ans.lower() == 'hist': hist(filename) elif ans.lower() == 'grayscale': grayscale(filename) elif ans.lower() == 'help': print("Grayscale, Show, Flip, Hist, Help") else: print("That isn't a command, help for a list of commands.") print() print()
a25d20e7fb86adb75983fa04781aa33fbaacbd26
GabrielCernei/codewars
/kyu6/Mulitples_Of_3_Or_5.py
230
3.90625
4
# https://www.codewars.com/kata/multiples-of-3-or-5/train/python def solution(number): multiple_sum = 0 for n in range(3,number): if n % 3 == 0 or n % 5 == 0: multiple_sum += n return multiple_sum
385b679cfcc03ebc6ca424ac238d7eaecf26a4c5
iml-v/alpha
/Assignment.py
3,819
3.921875
4
########################################################## # CST8333 2018 Final Project # # # # Created by Arish Kakadiya # # Student number: 040894137 # # November 26 ,2018 # # # ########################################################## import csv import pandas as pd # import statements # I have choosed Pandas, because it's much faster, has an excellent and extremely rich API, a source code looks much cleaner and better, etc. import CommodityPerform df = pd.read_csv("32100054.csv", sep = ",") class DataReader(): # Created a class to read csv file and place into list def __init__(self, fname): # DatabaseReader constructor self.fname = fname; def rowList(self): with open(self.fname, newline='') as csvfile: reader = csv.reader(csvfile) dlist = list(reader) return dlist def showData(dlist): # function to show all the rows from dataset for row in dlist: print(row[2]) # prints all the rows in console def showNumRows(dlist): # function to count the total number of rows. return len(dlist) - 1 def showRow(dlist, row): # function to show specfic row that user wants. print(dlist[row]) def showCommodiytOnUOM(): print(df[df["UOM_ID"] == 205]) def showOnCommodityName():# To select rows whose column value equals a scalar, some_value, use ==: commodity_name = input("Enter Commodity Name for which you want to search same commodity values :\n")# Variable assignment print(df.loc[df['Commodity'] == commodity_name])# print all rows in which this specific commodity exist print("Total Count of data having ", commodity_name, "Commodity name is : ") print(df.loc[df.Commodity == commodity_name, 'Commodity'].count()) # find total count def show_on_UOM(): # To select rows whose column value equals a scalar, some_value, use ==: uom_name = input("Enter UOM Name which you want to search") # Variable assignment print((df.loc[df['UOM'] == uom_name]))# print all rows in which this specific UOM exist print("Total Count of data having ",uom_name,"UOM is : ") print(df.loc[df.UOM == uom_name, 'UOM'].count()) # find total count def total_ref_date(): ref_date = input("Enter Ref date for which you want to search") # Variable assignment print("Total Count of Ref Year ", ref_date, " is : ") # print([df.REF_DATE == ref_date, 'REF_DATE'].count()) # find total count def show_on_Food_categories(): food_categories = input("Enter Food categories Name which you want to search") print((df.loc[df['Food categories'] == food_categories])) # print all rows in which this specific Food categories exist def main(): data = DataReader('32100054.csv') # reads the .csv file dList = data.rowList() # Function for Showing the data # showData(dList) showCommodiytOnUOM() # Function for Showing all rows Commodity based on UOM showOnCommodityName() #Function for Showing all rows having specific commodity name total_ref_date() show_on_Food_categories() #function for showing all rows having specific food category show_on_UOM() # this block of code allows running this program from the command line, # taken from Python's official PyUnit documentation. # Python Software Foundation. (2015). 26.4.1. Basic example. [Webpage]. # Retrieved from https://docs.python.org/3/library/unittest.html#basic-example. if __name__ == "__main__": # executes if run as main program. main()
6455585e16b06d6eadb9ea6e3e81ca9009c43c1b
augustine-code/codey-jack
/My First Function.py
3,236
3.734375
4
### Basic EDA Function ### import numpy as np import pandas as pd def analyze(data): """A BASIC FUNCTION WITH ALL INITIAL PANDAS FUNCTION FOR BASIC EDA""" print('--------------------------------------------INITIAL ANALYSIS REPORT--------------------------------------------') data.columns = data.columns.str.strip().str.replace(' ', '_').str.replace('(', '').str.replace(')', '').str.replace('%', 'perc') display('DATA SHAPE') print('The number of rows (observations) is',data.shape[0],'\n''The number of columns (variables) is',data.shape[1]) print('-----------------------------------------------') display('DATA INFO') display(data.info()) print('---------------------------------------------------------------------------------------------------------------') display('DATA HEAD (First 15 records)', data.head(15)) print('---------------------------------------------------------------------------------------------------------------') display('DATA TAIL (Last 15 records)', data.tail(15)) for column in data.columns: if data[column].dtype == 'int': print('---------------------------------------------------------------------------------------------------------------') display('DATA DESCRIPTION (DISCRETE VARIABLES)', data.describe(include = 'int').T) break for column in data.columns: if data[column].dtype == 'float': print('---------------------------------------------------------------------------------------------------------------') display('DATA DESCRIPTION (CONTINUOUS VARIABLES)', data.describe(include = 'float').T) break data_types = ['int', 'float' 'object'] for column in data.columns: if data[column].dtype != 'int': if data[column].dtype != 'float': if data[column].dtype != 'object': print('---------------------------------------------------------------------------------------------------------------') display('DATA DESCRIPTION (OTHER VARIABLES)', data.describe(exclude = data_types).T) else: break print('---------------------------------------------------------------------------------------------------------------') display('DATA DESCRIPTION (CATEGORICAL VARIABLES)') print('---------------------------------------------------------------------------------------------------------------') for column in data.columns: if data[column].dtype == 'object': print(column.upper(),': ',data[column].nunique()) print(data[column].value_counts().sort_values(ascending=False)) print('\n') print('---------------------------------------------------------------------------------------------------------------') display('DATA NULLS COUNT', data.isnull().sum()) print('---------------------------------------------------------------------------------------------------------------') display('DATA DUPLICATES COUNT', data.duplicated().sum()) print('--------------------------------------------------END OF REPORT------------------------------------------------')
0a356fc76dd378ac38c2e893f03a2a560065331c
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/303/86915/submittedfiles/testes.py
246
3.703125
4
# -*- coding: utf-8 -* primeiro= int(input(DIGITE O PRIMEIRO NUMERO:)) segundo= int(input(DIGITE O SEGUNDO NUMERO:)) terceiro= int(input(DIGITE O TERCEIRO NUMERO:)) quarto= int(input(DIGITE O QUARTO NUMERO:))
4f48dc58d5e7d9fcb8bb02ea32789f21a785521b
daaimah123/LearningPython
/magic_method.py
735
4.0625
4
class Human: def __init__(self, first, last, age): self.first = first self.last = last self.age = age def __repr__(self): return f'Human name {self.first} {self.last}.' def __len__(self): return self.age def __add__(self,other): if isinstance(other, Human): return Human(first='newborn', last=self.last, age=0) return 'You cant add that' def __mul__(self, other): if isinstance(other, int): return [self for i in range(other)] return 'cant multiply' human1 = Human('Daaimah', 'Tibrey', 26) human2 = Human('Pete', 'The Cat', 28) print(human1) print(f'length is : {len(human1)}') print(human2 + human1) print(human1 * 2)
a74697b21d9a0ee069398be5c9ac50f377f4b301
SeongHyeonShin/ndb_algorithm
/4_Quick_Sort.py
1,025
3.515625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 14:50:29 2020 @author: SHIN """ import numpy as np # Quick sort # 특정 값을 기준으로 큰 숫자와 작은 숫자를 나눈다 : 분할 정복 # Max : O(N ^ 2), Min : O(N * log(N)) def quick_sort(_arr=[], start=0, end=0): if start >= end: return pivot = start left = start + 1 right = end - 1 while left <= right: while left <= end - 1 and _arr[left] <= _arr[pivot]: left += 1 while right > start and _arr[right] >= _arr[pivot]: right -= 1 if left <= right: _arr[left], _arr[right] = _arr[right], _arr[left] else: _arr[pivot], _arr[right] = _arr[right], _arr[pivot] quick_sort(_arr=_arr, start=start, end=right) quick_sort(_arr=_arr, start=right + 1, end=end) if __name__ == '__main__': # arr = [1, 10, 5, 8, 7, 6, 4, 3, 2, 9] arr = np.random.randint(0, 100, size=50) quick_sort(_arr=arr, start=0, end=len(arr)) print(arr)
7e63513e0023c8e57952bf13df974620a26b3ccc
FSD4Edu/ProgLang-2020
/src/lecture08/dollar_to_yen_multi.py
495
3.6875
4
def dollar_to_yen(dollar,rate): return dollar * rate my_d = 100 ur_d = 120 r_yesterday = 105 r_today = 102 print("昨日のレートで私が所持するドルは", dollar_to_yen(my_d,r_yesterday), "円") print("昨日のレートで君が所持するドルは", dollar_to_yen(ur_d,r_yesterday), "円") print("今日のレートで私が所持するドルは", dollar_to_yen(my_d,r_today), "円") print("今日のレートで君が所持するドルは", dollar_to_yen(ur_d,r_today), "円")
b1934ffc640be9df721207d211bfdd718b893ec5
gmarciani/pymple
/dstruct/base/baseheap.py
1,766
3.65625
4
class baseheap: """ Heap interface. is_empty() find_min() delete_min() find_max() delete_max() """ def is_empty(self): """ Returns True if heap is empty, otherwise False. is_empty() -> True/False @rtype: boolean @return: True if the heap is empty, otherwise False. """ raise NotImplementedError("is_empty: You should have implemented this method!") def find_min(self): """ Returns the minimum element into the heap. find_min() -> min_element @rtype: object @return: minimum element into the heap. """ raise NotImplementedError("find_min: You should have implemented this method!") def delete_min(self): """ Returns and deletes the minimum element into the heap. delete_min() -> min_element @rtype: object @return: minimum element into the heap. """ raise NotImplementedError("delete_min: You should have implemented this method!") def find_max(self): """ Returns the maximum element into the heap. find_max() -> max_element @rtype: object @return: maximum element into the heap. """ raise NotImplementedError("find_max: You should have implemented this method!") def delete_max(self): """ Returns and deletes the maximum element into the heap. delete_max() -> max_element @rtype: object @return: maximum element into the heap. """ raise NotImplementedError("delete_max: You should have implemented this method!")
9090553ef8bfb782b8241f40240da08f6c1b8b6a
Rexniu/CorePython
/5/5-11-d-2.py
286
4
4
def a_b(a,b): ta = False tb = False if(a%b)==0:ta = True if(b%a)==0:tb = True return (ta or tb) print 'Please input two numbers:' a = float(raw_input()) b = float(raw_input()) if a_b(a,b): print 'They are divisible!' else: print 'They are not divisible!'