blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
edec4a87a37e8b793a1b419c1be2261745b99fb6
akimi-yano/algorithm-practice
/lc/review_1291.SequentialDigits.py
1,300
3.78125
4
# 1291. Sequential Digits # Medium # 878 # 67 # Add to List # Share # An integer has sequential digits if and only if each digit in the number is one more than the previous digit. # Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. # Example 1: # Input: low = 100, high = 300 # Output: [123,234] # Example 2: # Input: low = 1000, high = 13000 # Output: [1234,2345,3456,4567,5678,6789,12345] # Constraints: # 10 <= low <= high <= 10^9 # This solution works: class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: all_nums = [] low_digit = len(str(low)) high_digit = len(str(high)) for digit in range(low_digit, high_digit+1): for start_num in range(1, 10): temp = 0 start_digit = 0 for num in range(start_num, 10): temp = temp*10+num start_digit += 1 if start_digit == digit: if len(str(temp)) == digit: all_nums.append(temp) break ans = [] for num in all_nums: if low <= num <= high: ans.append(num) return ans
f9a7ae48d416bf6506247ad7aa0681e64023216e
GL324/Facial_Keypoints
/models.py
1,558
3.53125
4
## TODO: define the convolutional neural network architecture import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(32, 64, 5) # self.conv3 = nn.Conv2d(64, 128, 5) # self.conv4 = nn.Conv2d(128, 256, 5) # self.conv5 = nn.Conv2d(256, 512, 5) self.fc1 = nn.Linear(53*53*64, 272) self.drop = nn.Dropout(p=0.4) self.fc2 = nn.Linear(272, 136) def forward(self, x): ## x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.tanh(self.conv1(x))) #110 x = self.drop(x) x = self.pool(F.tanh(self.conv2(x))) #53 # x = self.drop(x) # x = self.pool(F.relu(self.conv3(x))) #24 # x = self.drop(x) # x = self.pool(F.relu(self.conv4(x))) #10 # x = self.drop(x) # x = self.pool(F.relu(self.conv5(x))) #3 # x = self.drop(x) #Flatten x = x.view(x.size(0), -1) x = F.tanh(self.fc1(x)) x = self.drop(x) x = self.fc2(x) # a modified x, having gone through all the layers of your model, should be returned return x
685df561822b4feeb37e4685fbaf44b17f8e094c
SILIN-WANG/Sandbox
/Prac_02/files.py
498
3.8125
4
out_file = open("name.txt","w") name = input("What is your name?") print(name, file=out_file) out_file.close() out_file = open("name.txt","r") name = out_file.readline() print("Your name is {}".format(name)) out_file.close() out_file = open("number.txt","r") num1 = int(out_file.readline()) num2 = int(out_file.readline()) print(num1+num2) out_file.close() out_file = open("number.txt","r") total = 0 for i in out_file: numbers = int(i) total +=numbers print(total) out_file.close()
5683a39f5287fe231ff0f4806dbbdaab6dd4715b
vineethkuttan/College_Programs
/PYTHON/Semester 2/session7/t3.py
69
3.59375
4
import re x=input() y=re.findall('[A-Z][a-z]+',x) print(' '.join(y))
3a8e799e3816df332189107a9050b5d4d8357ac0
pkasper/info1-bm
/2016/tutor_sessions/unit_3/notebooks/3_Student_task_solved.py
652
3.78125
4
# coding: utf-8 # In[ ]: # Opening the file and reading the data import pickle with open('small_list.pickle', 'rb') as file: number_list = pickle.load(file) # In[ ]: # Calculate the mean from a list of numbers # In[ ]: def calc_median(elem_list): elem_list.sort() length = len(elem_list) half_length = int(length / 2) # Even number of elements in list if length % 2 == 0: first = elem_list[half_length - 1] second = elem_list[half_length] median = (first + second) / 2 else: median = elem_list[half_length - 1] return median # In[ ]: calc_median(number_list)
25ccb700e14d4bdc99dd0225ffc32cd37d0b7cab
jwright0991/KruskalsMSF
/KruskalsMSF.py
3,195
3.796875
4
import heapq import sys #Author - Josh Wright #Kruskals's Programming Assignment #Reads in a formatted file that contains an edge-weighted directed graph. #Uses Union-Find data structure with path compression to text for cycles. #Heapq data structure implemented by adding all the elements to a list and heapifying the list #unionFind data structure implemented with a list (array). The positions so of the #list heap = [] #Returns the parent of x in the UnionFind data structure #implemented with path compression def find(unionFind, x): if x != unionFind[x]: z = find(unionFind,unionFind[x]) unionFind[x] = z return z else: return x #returns the source vertex of an edge def source(edge): return edge[1] #returns the destination vertex of an edge def destination(edge): return edge[2] #returns the weight of an edge def weight(edge): return edge[0] #unions two "sets" in the union find data structure def union(unionFind,source,destination): s = find(unionFind, source) d = find(unionFind, destination) unionFind[s] = d #check for correct number of commandline arguments if(len(sys.argv)) == 2: #open the file passed in as a commandline argument dataFile = open(sys.argv[1], 'r') #read the number of vertices from the first line of the file size = dataFile.readline() size = int(size) #Union find data structure. #The index represents the vertex, ex v0 = pos 0, v1 = pos 1, etc #The value at that position is the parent of the vertex at that position #All vertices start out with a self reference, so pos 0 = 0, pos 1 = 1, etc unionFind = [] for i in range(0,size): unionFind.append(i) #read the lines of the data file in and insert a tuple (weight,vertex1,vertex2) into the heap for line in dataFile: i = 0 v1 = "" v2 = "" w = "" #extract the first vertex while line[i] != ',': v1 += line[i] i+=1 v1 = int(v1) i+=1 #extract the second vertex while line[i] != ":": v2 += line[i] i+=1 v2 = int(v2) i+=1 #extract the weight of the edge while line[i] != "\n": w += line[i] i+=1 w = int(w) #add the tuple (weight,v1,v2) to the heap heap.append((w,v1,v2)) #close the file dataFile.close() #call heapify to turn the heap list into a priority queue heap heapq.heapify(heap) #loop while the heap is not empty while heap: #remove the smallest edge from the heap edge = heapq.heappop(heap) #if the parent of the source is not the parent of the destination print the edge and call union on the edge if find(unionFind,source(edge)) != find(unionFind,destination(edge)): print(str(source(edge)) + ", " + str(destination(edge)) + ":" + str(weight(edge))) union(unionFind,source(edge),destination(edge)) else: #if there was an incorrect number of commandline arguments, print #an error message and terminate the program print("error: incorrect number of commandline arguments")
81d49875724b37520079b9b41c02d6cd63829445
MayankMaheshwar/fullpython
/Untitl.py
586
3.890625
4
class Mom: def __init__(self,name,color): self.name=name self.color=color def lov(self): print("hello " + self.name) def __add__(self,other): return Mom(self.name+ other.name,self.color+ other.color) class Mayank(Mom): def love(self): print("love u mom") super().lov() m=Mayank("yours","nm") print(m.name) m.love() first=Mom("Mayank"," Love") second=Mom("Maheshwari"," U mom") result=first+second print(result.name) print(result.color)
d53744b645336afc93dcddcd1a77d4bbd895b125
dabeiT3T/Data-Structures-Answer
/Chapter 4 Arrays and Linked Structures/Quiz 2/arrays.py
1,120
4.28125
4
#!/usr/bin/env python3 ''' Author: dabei My answer to Chapter 4 Quiz 2. ''' class Array: '''Represents an array''' def __init__(self, capacity, fillValue = None): self._items = [fillValue for i in range(capacity)] # logical size self._logicalSize = 0 def size(self): '''Get the logical size.''' return self._logicalSize def _inRange(self, index): '''Return if the list index is out of range''' if (index >= 0 and index < self.size()): return True else: raise IndexError('list index out of range') def __len__(self): '''Get the array length.''' return len(self._items) def __str__(self): return str(self._items) def __iter__(self): return iter(self._items) def __getitem__(self, index): if (self._inRange(index)): return self._items[index] def __setitem__(self, index, newItem): if (self._inRange(index)): self._items[index] = newItem if __name__ == '__main__': a = Array(10) print(a[100]) a[100] = 1024
f56742594244dcc5edf17389b2b7d9c8621dbb81
zhangpanzhan/leetcode-solution
/20120901 Recover Binary Search Tree.py
1,158
3.78125
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? ''' # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a tree node def recoverTree(self, root): self.pre = None self.n1 = self.n2 = None self.dfs(root) self.n1.val, self.n2.val = self.n2.val, self.n1.val return root def dfs(self, root): if not root: return self.dfs(root.left) if self.pre and root.val < self.pre.val: if not self.n1: self.n1, self.n2 = self.pre, root else: self.n2 = root self.pre = root self.dfs(root.right)
1db6d0a11e1e462a7fda8b1ea7923709e016fb5c
KhanWhale/Sudoku
/Board.py
7,122
3.640625
4
class Tile: num = None candidates = [] row = 1 column = 5 square = 3 def __init__(self, val, board=None): self.board = board if val not in range(1,10): self.num = None self.candidates = list(range(1,10)) else: self.num = val def __repr__(self): if self.board: return f"{self.board.name}: {str(self.num)}" else: return str(self.num) def update(self): if len(self.candidates) == 1: self.num = self.candidates[0] self.candidates = [] self.row.in_group.append(self.num) self.column.in_group.append(self.num) self.square.in_group.append(self.num) update_candidates(self.board) self.board.updated = True else: for cand in self.candidates: if cand in unique_in_group(self.row) or cand in unique_in_group(self.column) or cand in unique_in_group(self.square): self.num = cand self.candidates = [] self.row.in_group.append(self.num) self.column.in_group.append(self.num) self.square.in_group.append(self.num) update_candidates(self.board) self.board.updated = True return class Board: tiles = None rows =[] cols = [] name = 'Aniruddh\'s Sudoku Board' updated = True incomplete = True def __init__(self, tiles): self.squares = [Square() for _ in range(9)] for i in range(0,len(tiles)): for j in range(0,len(tiles[i])): tiles[i][j] = Tile(tiles[i][j], self) if i < 3: if j < 3: self.squares[0].add(tiles[i][j]) elif j < 6: self.squares[1].add(tiles[i][j]) else: self.squares[2].add(tiles[i][j]) elif i < 6: if j < 3: self.squares[3].add(tiles[i][j]) elif j < 6: self.squares[4].add(tiles[i][j]) else: self.squares[5].add(tiles[i][j]) else: if j < 3: self.squares[6].add(tiles[i][j]) elif j < 6: self.squares[7].add(tiles[i][j]) else: self.squares[8].add(tiles[i][j]) self.tiles = tiles for i in range(0, len(self.tiles)): r = Row(tiles[i]) self.rows.append(r) self.cols = [Column([tiles[i][j] for i in range(len(tiles))])for j in range(len(tiles))] def __repr__(self): out = 'Aniruddh\'s Sudoku Board \n' for i in range(0, len(self.tiles)): for j in range(0, len(self.tiles[i])): if self.tiles[i][j].num: out += str(self.tiles[i][j].num) out += ' ' else: out += '_ ' out += '\n' return out def check_complete(self): for r in self.tiles: for t in r: if t.num == None: self.incomplete = True return True self.incomplete = False return False class Row: tiles = [] def __init__(self, tiles): self.in_group = [] for tile in tiles: tile.row = self if tile.num: self.in_group.append(tile.num) self.tiles = tiles def __repr__(self): out = '' for tile in self.tiles: if tile.num: out += str(tile.num) out += ' ' else: out += '_ ' return out class Column: tiles = [] def __init__(self, tiles): self.in_group = [] for tile in tiles: tile.column = self if tile.num: self.in_group.append(tile.num) self.tiles = tiles def __repr__(self): out = '' for tile in self.tiles: if tile.num: out += str(tile.num) out += '\n' else: out += '_\n' return out class Square: def __init__(self): self.in_group = [] self.tiles = [] def add(self, tile): self.tiles.append(tile) tile.square = self if tile.num: self.in_group.append(tile.num) def __repr__(self): out = '' for i in range(len(self.tiles)): if self.tiles[i].num: out += str(self.tiles[i].num) else: out += '_' if (i+1) % 3 == 0: out += '\n' else: out += ' ' return out # 31 none def check_group(group): def check(el): return el not in group.in_group for tile in group.tiles: if tile.candidates: tile.candidates = list(filter(check, tile.candidates)) def update_candidates(board): for row in board.rows: check_group(row) for col in board.cols: check_group(col) for square in board.squares: check_group(square) def unique_in_group(group): nested = [tile.candidates for tile in group.tiles if not tile.num] all_candidates = [item for sublist in nested for item in sublist] all_candidates = convert_to_dict(all_candidates) unique_candidates = [] for cand, freq in all_candidates.items(): if freq == 1: unique_candidates.append(cand) return unique_candidates def convert_to_dict(my_list): freq = {} for items in my_list: freq[items] = my_list.count(items) return freq def common_candidates(group): return [tile for tile in group.tiles if tile.num == None] def update_tiles(board): for row in board.tiles: for tile in row: tile.update() def update_board(board): board.updated = False update_candidates(board) update_tiles(board) board.check_complete() return board def solve(board): iters = 0 while board.incomplete and board.updated and iters < 20: update_board(board) iters+= 1 if board.incomplete: print(f'Sorry, I couldn\'t solve the board in {iters} tries. Here is the partially solved version:') else: print(f'I solved the board in {iters} tries. Here it is:') return board def play(): my_tiles = [] row = [] while True: num = input("Row: ") for n in num: row.append(int(n)) my_tiles.append(row) row = [] if len(my_tiles) == 9: my_board = Board(my_tiles) return my_board my_tiles = [ [0,0,0,0,0,9,0,0,3], [3,0,0,0,0,0,0,2,0], [6,0,2,0,1,0,0,0,0], [0,0,6,0,0,7,3,8,9], [9,7,0,4,0,0,0,1,2], [0,0,0,2,0,0,0,0,7], [7,2,0,0,0,0,0,6,1], [0,0,0,0,0,0,0,0,8], [0,0,8,7,0,0,0,9,0]] my_board = Board(my_tiles)
dc9c4f5a9c22f8902bc8a272cf05861052e0b6f5
ArBond/ITStep
/Python/lessons/lesson10_function/main7.py
491
4.125
4
#7.Напишите функцию fib(n), которая по данному целому неотрицательному n возвращает n-e число Фибоначчи. # В этой задаче нельзя использовать циклы — используйте рекурсию. def fib(n): if n <= 2: return 1 else: return fib(n - 1) + fib(n - 2) n = int(input("Kakoje chislo chislo: ")) print(n, "-e chislo Fibonacchi =", fib(n))
ab0cd1ceae1c83b7df3389f2e465ae2da257be39
Nev-Iva/my-projects
/basic python (0 level)/7 exception handling/1.py
307
3.6875
4
fruit_list_1 = ['Яблоко', 'Банан', 'Киви', 'Апельсин', 'Манго', 'Персик'] fruit_list_2 = ['Яблоко', 'Мандарин', 'Апельсин', 'Фрукт_1', 'Фрукт_2'] result = [] result = [fruit for fruit in fruit_list_1 if fruit in fruit_list_2] print(result)
ce1c7cc68598892a6f6e5bb6ba6d93add0822d4c
Dimitrioglo/Find_Betrayal
/game.py
3,952
3.75
4
from random import randint class CreateBot(): def __init__(self, bot_name, bot_color, bot_pos, bot_tip): self.bot_name = bot_name self.bot_color = bot_color self.bot_pos = bot_pos self.bot_tip = bot_tip def new_bot(self, arr): for i in range(n): for j in range(n): match_struct = ([i+1],[j+1]) if match_struct == self.bot_pos: if self.bot_tip == 'Bot': arr[i][j] = 'XXX' else: arr[i][j] = 'YYY' return arr def print_board(self, arr): for i in range(n): for j in range(n): pass print("".join(arr[i])) print(' ') def move_bot(self, arr, arr_bots_pos, where_move): for i in range(n): for j in range(n): if arr[i][j] == 'YYY': match_struct = ([i+1], [j+1]) for a in range(n): if arr_bots_pos[a] == match_struct: if where_move == 'Up': arr_bots_pos[a] = ([i-1], [j]) elif where_move == 'Down': arr_bots_pos[a] = ([i+1], [j]) elif where_move == 'Left': arr_bots_pos[a] = ([i], [j-1]) elif where_move == 'Right': arr_bots_pos[a] = ([i], [j+1]) x = i y = j arr[i][j] = '---' if where_move == 'Up': arr[x-1][y] = 'YYY' elif where_move == 'Down': arr[x+1][y] = 'YYY' elif where_move == 'Left': arr[x][y-1] = 'YYY' elif where_move == 'Right': arr[x][y+1] = 'YYY' return arr_bots_pos def generate_bot(x, unique_arr): fist_value = randint(1, x) second_value = randint(1, x) bot_value = ([fist_value],[second_value]) while True: elem_unique = False for ind in range(x): if bot_value != unique_arr[ind]: elem_unique = True else: fist_value = randint(1, x) second_value = randint(1, x) elem_unique = False break if elem_unique == True: break return bot_value n = 10 arr = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): arr[i][j] = '---' bot_unique_arr = [0] * n bot_unique_arr[0] = generate_bot(n, bot_unique_arr) Hrummy = CreateBot('Hrummy', 'Green', bot_unique_arr[0],'Bot') Hrummy.new_bot(arr) bot_unique_arr[1] = generate_bot(n, bot_unique_arr) Truffie = CreateBot('Truffie', 'Green', bot_unique_arr[1],'Bot') Truffie.new_bot(arr) bot_unique_arr[2] = generate_bot(n, bot_unique_arr) Flutter = CreateBot('Flutter', 'Green', bot_unique_arr[2],'Bot') new_arr = Flutter.new_bot(arr) bot_unique_arr[3] = generate_bot(n, bot_unique_arr) Slip = CreateBot('Slip', 'Green', bot_unique_arr[3],'Player') new_arr = Slip.new_bot(arr) Slip.print_board(new_arr) while True: input_value = input() try: if input_value == 'w': new_bot_unique = Slip.move_bot(new_arr, bot_unique_arr, 'Up') Slip.print_board(new_arr) elif input_value == 's': new_bot_unique = Slip.move_bot(new_arr, bot_unique_arr, 'Down') Slip.print_board(new_arr) elif input_value == 'd': new_bot_unique = Slip.move_bot(new_arr, bot_unique_arr, 'Right') Slip.print_board(new_arr) elif input_value == 'a': new_bot_unique = Slip.move_bot(new_arr, bot_unique_arr, 'Left') Slip.print_board(new_arr) else: break except ValueError: print("Oops! That was no valid number. Try again...") break
0c3bf4478f0e06bba10a475971db4aaeefca111e
ThomasCarstens/SelfStudyIRM
/Data_structures/dictionary.py
2,295
4.03125
4
import numpy as np import math import test import matplotlib.pyplot as plt # orders = { # 'cappuccino': 54, # 'latte': 56, # 'cortado': 41 # } # # sort_orders = sorted (orders.items(), key=lambda x: x[1], reverse=True) # # for i in sort_orders: # print (i[0], i[1]) # # #also: # [print(key, value) for (key, value) in sorted(orders.items(), key=lambda x: x[1])] my_dict={'Dave' : '001' , 'Ava': '002' , 'Joe': '003'} print(my_dict.keys()) print(my_dict.values()) print(my_dict.get('Dave')) #access the key-value pairs of a dictionary easily by iterating over them. my_dict={'Dave' : '001' , 'Ava': '002' , 'Joe': '003'} print("All keys") for x in my_dict: print(x) #prints the keys print("All values") for x in my_dict.values(): print(x) #prints values print("All keys and values") for x,y in my_dict.items(): print(x, ":" , y) #prints keys and values #UPDATING VALUES. #my_dict={'Dave' : '001' , 'Ava': '002' , 'Joe': '003'} my_dict['Dave'] = '004' #Updating the value of Dave my_dict['Chris'] = '005' #adding a key-value pair print(my_dict) #DELETING ITEMS FROM DICTIONARY #my_dict={'Dave': '004', 'Ava': '002', 'Joe': '003', 'Chris': '005'} del my_dict['Dave'] #removes key-value pair of 'Dave' my_dict.pop('Ava') #removes the value of 'Ava' my_dict.popitem() #removes the last inserted item print(my_dict) #CONVERTING DICT INTO DATAFRAME import pandas as pd emp_details = {'Employee': {'Dave': {'ID': '001', 'Salary': 2000, 'Designation':'Python Developer'}, 'Ava': {'ID':'002', 'Salary': 2300, 'Designation': 'Java Developer'}, 'Joe': {'ID': '003', 'Salary': 1843, 'Designation': 'Hadoop Developer'}}} df=pd.DataFrame(emp_details['Employee']) print(df) #MERGING TWO DICTIONARIES def Merge(dict1, dict2): res = {**dict1, **dict2} print("res: ", res) return (dict2.update(dict1)) # Driver code dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} # This return None print(Merge(dict1, dict2)) # changes made in dict2 print("dict2: ", dict2)
8802d8396d5858c7cd221e1d04cbedfd2685e61e
chrislucas/hackerrank-lp-python
/builtin/Lambda/src/xplore/XploreReduce.py
356
3.59375
4
from functools import reduce def summation(): return reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]) def sumTerms(_list, i): _list[i&1] = _list[i & 1] + _list[(i-1) & 1] def fib(n): _list = [0, 1] reduce(lambda a, i: sumTerms(_list, i), [i for i in range(1, n + 1)]) return _list print(fib(30)) if __name__ == "__main__": pass
de999cf213bef860ac5bcce9c3e99ab824a48cdb
athdsantos/Basic-Python
/CourseC&V/mundo-1/ex017.py
463
3.875
4
'''catOposto = float(input('Cateto Oposto: ')) catAdj = float(input('Cateto Adjacente: ')) hi = (catOposto ** 2 + catAdj ** 2) ** (1/2) print('Cat OP {} Cat Adj {} e hip {:.2f}'.format(catOposto, catAdj, hi)) ''' from math import hypot catOposto = float(input('Cateto Oposto: ')) catAdj = float(input('Cateto Adjacente: ')) hi = hypot(catOposto, catAdj) print('Cateto Oposto: {}\nCateto Adjacente: {}\nHipotenusa: {:.2f}'.format(catOposto, catAdj, hi))
f431ce7067a9060c9c5c55490d430c1d64f43afe
karolinanikolova/SoftUni-Software-Engineering
/2-Python-Fundamentals (Jan 2021)/Course-Exercises-and-Exams/03-Lists-Basics/02_Exercises/04_Number-Beggars.py
1,205
3.78125
4
# 4. Number Beggars # Your task here is pretty simple: given a list of numbers and a number of beggars, you are supposed to return a # list with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last. # For example: [1,2,3,4,5] for 2 beggars will return a result of 9 and 6, as the first one takes [1,3,5], the second collects [2,4]. # The same list with 3 beggars would produce a better outcome for the second beggar: 5, 7 and 3, # as they will respectively take [1, 4], [2, 5] and [3]. # Also note that not all beggars have to take the same amount of "offers", # meaning that the length of the list is not necessarily a multiple of n; length can be even shorter, # in which case the last beggars will of course take nothing (0). earnings_list = input().split(", ") beggars_count = int(input()) earnings_per_beggar = [] start_index = 0 for beggar in range(beggars_count): current_beggar_earnings = 0 for earning in range(start_index, len(earnings_list), beggars_count): current_beggar_earnings += int(earnings_list[earning]) earnings_per_beggar.append(current_beggar_earnings) start_index += 1 print(earnings_per_beggar)
13be1d398842417f58eef082f7741f62225057ff
610yilingliu/leetcode
/Python3/490.the-maze.py
1,101
3.59375
4
# # @lc app=leetcode id=490 lang=python3 # # [490] The Maze # # @lc code=start class Solution(object): def hasPath(self, maze, start, destination): """ :type maze: List[List[int]] :type start: List[int] :type destination: List[int] :rtype: bool """ def dfs(x, y): # return if the ball can stop at destination if starting at (x, y) if [x,y] == destination: return True if (x, y) in visited: return False visited.add((x, y)) for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]: new_x, new_y = x, y # the ball rolls until hitting a wall while 0 <= new_x+dx < row and 0 <= new_y+dy < col and maze[new_x+dx][new_y+dy] == 0: new_x += dx new_y += dy if dfs(new_x, new_y): return True return False row, col = len(maze), len(maze[0]) visited = set() return dfs(start[0], start[1]) # @lc code=end
47851b2b9f0b337f1395c2332e4980cd9fe87c3c
calgaryfx/2021_programs
/Edabit/profitable_gamble.py
436
3.6875
4
# Create a function that takes three arguments prob, prize, pay and returns # True if prob * prize > pay; otherwise return False. def profitable_gamble(prob, prize, pay): if prob * prize > pay: return True else: return False a = profitable_gamble(0.2, 50, 9) print(a) a = profitable_gamble(0.9, 1, 2) print(a) a = profitable_gamble(0.9, 3, 2) print(a) # Shorter version line 4: # return (prob * prize) > pay
e59470052824a345087dd03ca528709d55b4f09b
zuoyuanh/365-lab1
/lab1-1/schoolsearch.py
4,669
3.6875
4
import sys class Student: def __init__(self, data): self.stLastName = data[0] self.stFirstName = data[1] self.grade = data[2] self.classroom = data[3] self.bus = data[4] self.gpa = data[5] self.tLastName = data[6] self.tFirstName = data[7] def matchedByStLastName(self, lastname): return self.stLastName == lastname def matchedBytLastName(self, lastname): return self.tLastName == lastname def matchedByBus(self, bus): return self.bus == bus def matchedByGrade(self, grade): return self.grade == grade def __str__(self): return self.stLastName + "," + self.stFirstName + "," + self.grade + "," + self.classroom + "," + self.bus + "," + self.gpa + "," + self.tLastName + "," + self.tFirstName def print_info(students): info = dict() for student in students: grade = int(student.grade) if grade in info: info[grade] += 1 else: info[grade] = 1 keys = sorted(info.keys()) for i in keys: print("{0}: {1}".format(i, info[i])) def student_list_of_grade(grade, students): results = [] for student in students: if student.matchedByGrade(grade): results.append(student) return results def main(): students = [] f = open("students.txt", "r") for line in f: line = line.strip() data = line.split(",") student = Student(data) students.append(student) f.close() for line in sys.stdin: line = line.strip() if line == "Q" or line == "Quit": break elif line == "I" or line == "Info": print_info(students) else: inputs = line.split(":") if len(inputs) <= 1: continue if inputs[0] == "S" or inputs[0] == "Student": tmp = inputs[1].strip() params = tmp.split(" ") lastname = params[0].strip() bus = False if len(params) > 1: if params[1].strip() == "B" or params[1].strip() == "Bus": bus = True found = 0 for student in students: if student.matchedByStLastName(lastname): found += 1 if bus == False: print(student.stLastName + "," + student.stFirstName + "," + student.grade + "," + student.classroom + "," + student.tLastName + "," + student.tFirstName) else: print(student.stLastName + "," + student.stFirstName + "," + student.bus) if found == 0: print() elif inputs[0] == "T" or inputs[0] == "Teacher": lastname = inputs[1].strip() found = 0 for student in students: if student.matchedBytLastName(lastname): found += 1 print(student.stLastName + "," + student.stFirstName) if found == 0: print() elif inputs[0] == "B" or inputs[0] == "Bus": bus = inputs[1].strip() for student in students: if student.matchedByBus(bus): print(student.stFirstName + "," + student.stLastName + "," + student.grade + "," + student.classroom) elif inputs[0] == "G" or inputs[0] == "Grade": tmp = inputs[1].strip() params = tmp.split(" ") grade = params[0].strip() results = student_list_of_grade(grade, students) if len(params) > 1 and len(results) > 0: def f(s): return float(s.gpa) student = None if params[1].strip() == "H" or params[1].strip() == "High": student = max(results, key=f) elif params[1].strip() == "L" or params[1].strip() == "Low": student = min(results, key=f) if student: print(student.stLastName + "," + student.stFirstName + "," + student.gpa + "," + student.tLastName + "," + student.tFirstName + "," + student.bus) else: if len(results) == 0: print() for student in results: print(student.stLastName + "," + student.stFirstName) elif inputs[0] == "A" or inputs[0] == "Average": grade = inputs[1].strip() results = student_list_of_grade(grade, students) if len(results) == 0: continue total = 0 for student in results: total += float(student.gpa) print("{0},{1:.2f}".format(grade, (total / len(results)))) if __name__ == "__main__": main()
3dfbb8ed9c5baf84ebf333d77f2045502d38fc94
xueanxi/learnAi
/test/18_array.py
449
4
4
array1 = ("a",) # 声明一个元组 ,如果里面只有一个对象,需要加一个逗号 print("len of array1 : ", len(array1)) array2 = ("a", "b", "c", "d") # 声明元组的方法1 print("len of array2 : ", len(array2)) array3 = "e", "f" # 声明元组的方法2 print("len of array3 : ", len(array3)) array4 = ("g", "h", array2) print("len of array4 : ", len(array4)) print("array4 ", array4) print("array4[2][1] :", array4[2][1])
111ef66915c38eeb41a2a3e177df994dfc7b4710
hayfiz/Base-Converter
/Base Converter.py
1,619
3.65625
4
# coding: utf-8 # In[2]: def convert(input, source, target): if (source == "0123456789") & (target == "01"): #converting decimal to binary return bin(int(input))[2:] if (source == "01") & (target == "0123456789"): #converting binary to decimal return int(input, 2) if (source == "0123456789") & (target == "0123456789ABCDEF"): #converting decimal to hexadecimal return hex(int(input))[2:] if (source == "0123456789ABCDEF") & (target == "0123456789"): #converting hexadecimal to decimal return int(input, 16) if (source == "0123456789ABCDEF") & (target == "abcdefghijklmnopqrstuvwxyz"): #converting hexadecimal to alphabet return input.decode("hex") if (source == "0123456789ABCDEF") & (target == "01"): #converting hexadecimal to binary return bin(input, 16)[2:] if (source == "01") & (target == "0123456789ABCDEF"): #converting binary to hexadecimal return hex(int(input, 2))[2:] if (source == "abcdefghijklmnopqrstuvwxyz") & (target == "0123456789ABCDEF"): #converting alphabet to hexadecimal hexValList = [] for i in input: hexVal = hex(ord(i))[2:] if len(hexVal) ==1: hexVal = '0'+hexVal hexValList.append(hexVal) return reduce(lambda x,y:x+y, hexValList) # In[5]: print convert("73766970", "0123456789ABCDEF","abcdefghijklmnopqrstuvwxyz") print convert("11", "01","0123456789") print convert("0000010010001101", "01","0123456789ABCDEF") # In[ ]:
67716d4e2a1beaad2b11c0eec63d41509b2fc63f
simi153/python_kurs
/dzien_4/dunkcje_zadanie_1.py
444
3.921875
4
def is_anagram(text1, text2): text1 = sorted(list(text1.lower())) # text1.sort() text2 = sorted(list(text2.lower())) # text2.sort() if text1 == text2: return True else: return False def test_is_anagram(): assert is_anagram("Tokyo", "Kyoto") == True assert is_anagram("Anna", "Boba") == False assert is_anagram("AnnaKowalska", "Bob") == False assert is_anagram("Bob", "Anna kowalska") == False
445815c6ca1b6df27dd14da5472bde64db35e4bd
pavlosZakkas/benchmarking-streaming-ddps
/generator/connector.py
626
3.53125
4
import socket class SocketConnectionException(Exception): pass def wait_for_connection_to(host, port): """ Opens a socket at the given host and port, waits for the client system to connect, and returns tha socket connection """ try: stream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) stream_socket.bind((host, port)) stream_socket.listen() connection, addr = stream_socket.accept() return connection, stream_socket except Exception as e: raise SocketConnectionException('Failed to set up connection with the streaming system', e)
662e588c12a1b86f9466a2ab5875c3ab420bc327
L0ganhowlett/Python_workbook-Ben_Stephenson
/35 Dog Years.py
180
3.703125
4
# 35 Dog Years x = int(input("Enter the number of human years = ")) if x < 2: age = 10.5 * x else: age = 21 + (x - 2) * 4 print("The number of dog years is = ",age)
84c942a850adda406ea8ed17162644052f4e9beb
CauchyPolymer/teaching_python
/python_class/a04_mi.py
613
3.765625
4
class Grandparent(): def __init__(self): self.car = 'Great Car' class Father(Grandparent): def __init__(self): Grandparent.__init__(self) self.house = 'Big house' class Mother(Grandparent): def __init__(self): Grandparent.__init__(self) self.land = 'Big Land' class ChildOne(Father, Mother): pass class ChildTwo(Mother, Father): pass if __name__ == '__main__': one = ChildOne() print(one.house, one.car) two = ChildTwo() print(two.land, two.car) print(one.car, one.house, one.land) print(two.car, two.house, two.land) ##
b51c161a6d4c6fc7509b1594d08b2030b3308d49
ramesh1990/Python
/Easy/sumOfKfrom2Lst.py
454
3.828125
4
''' Find Sum of two number as K. input : A = [0,0,-5,30212] B = [-10,40,-3,9] K = -8 output = True, (-5,-3) ''' def sumOfTwo(lst1,lst2,k): hash = {} for i in lst1: r = k - i if i not in hash: hash[r] = i for j in lst2: if j in hash: return (True,(j,hash[j])) return -1 A = [0,0,-5,30212] B = [-10,40,-3,9] K = -8 print ("\nFind Sum of two number as K : ",sumOfTwo(A,B,K))
a9eeb58801ae703ca3a7ee86bc82cb194bd20958
mbu4135/syntax
/help_createtable.py
596
3.6875
4
#!python import mysql.connector # MySQL Connection 연결 mydb = mysql.connector.connect( host="localhost", user="mbu4135", passwd="1288zpmqal", charset="utf8", database="menshut" ) mycursor = mydb.cursor() mycursor.execute('DROP TABLE IF EXISTS help') mycursor.execute("CREATE TABLE help (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,uid int(11) DEFAULT NULL,selec varchar(20) NOT NULL,name varchar(11) NOT NULL,phone varchar(20) NOT NULL,email varchar(20) NOT NULL,title varchar(20) NOT NULL,contents text NOT NULL)") mydb.commit() print(mycursor.rowcount, "record inserted.")
3dcc4ac57b0ce744901cf619bb131b7410435c04
RAMKUMAR7799/Python-program
/Beginner/Gnumbers.py
286
4.25
4
num1=int(input("Enter your number")) num2=int(input("Enter your number")) num3=int(input("Enter your number")) if(num1>=num2 and num1>=num3): print(num1,"is greatest number") elif(num2>=num1 and num2>=num3): print(num2,"is greatest number") else: print(num3,"is greatest number")
47a8edd0833009d7d9cf2c0279ffe122f9c81171
flippersmcgee/Refactoring-Practice
/Tennis/python/tennis.py
2,804
3.796875
4
# -*- coding: utf-8 -*- class TennisGameRefactored: score_names = {0: "Love", 1: "Fifteen", 2: "Thirty", 3: "Forty"} def __init__(self, player1Name, player2Name): self.player1Name = player1Name self.player2Name = player2Name self.p1points = 0 self.p2points = 0 def won_point(self, playerName): if playerName == self.player1Name: self.p1points += 1 else: self.p2points += 1 def print_score(self): score_is_tied = self.check_for_tie() someone_won = self.check_for_winner() someone_has_advantage = self.check_for_advantage() if score_is_tied: result = self.is_equal() else: if someone_won: result = self.winner() elif someone_has_advantage: result = self.advantage() else: result = self.different_scores() return result def convert_score_to_english(self): return self.score_names[self.p1points], self.score_names[self.p2points] def is_equal(self): if 0 <= self.p1points and self.p2points < 4: return self.score_names[self.p1points] + '-All' else: return "Deuce" def different_scores(self): p1_score, p2_score = self.convert_score_to_english() return "%s-%s" % (p1_score, p2_score) def check_for_advantage(self): min_score = min(self.p1points, self.p2points) abs_diff_score = abs(self.p1points - self.p2points) if min_score >= 3 and abs_diff_score == 1: return True else: return False def advantage(self): if self.p1points > self.p2points: return "Advantage %s" % self.player1Name else: return "Advantage %s" % self.player2Name def check_for_winner(self): max_score = max(self.p1points, self.p2points) abs_diff_score = abs(self.p1points - self.p2points) if max_score > 3 and abs_diff_score != 1: return True else: return False def winner(self): if self.p1points > self.p2points: champ = self.player1Name else: champ = self.player2Name return 'Win for %s' % champ def check_for_tie(self): if self.p1points == self.p2points: return True else: return False # NOTE: You must change this to point at the one of the three examples that you're working on! TennisGame = TennisGameRefactored
72b33aee52b5c2f8daeb8f2678d32fb9b0588391
jtm172018/assignment-6
/ps1.py
522
3.890625
4
###### Assignment 1 parity check and framing .py file ########### ####### write your code here ########## def parity(x): # function for parity bit z=x.count('1') if z%2==1: return 0 else: return 1 x= input() x=str(x) z=parity(x) z=str(z) frame=(x+z) print(frame) #frame after parity bit addition m=frame.replace('010','0100') #bit stuffing u=m[-2:] #for accessing last 2 character d='01' d=str(d) if u == d: m=m+'0' final= m+'0101' #modified string received at other end print(final)
74f1bce02dc47a95a2f2e4a5dec4032249346ae8
shaktisingh7409/faulty_calculator
/rough_work.py
170
4
4
list1 = ["shakti", "deepak", "abhishek", "himanshu", "23",5,11,23,4,45,2,7,657] for item in list1: if type(item) == int: if item > 6: print(item)
21f0e3f8d661bdf915b459fae23f416cb87410f5
Twicer/Homeworks
/Homework9-15.03/Task2(bd).py
3,787
3.71875
4
""" Задача 2 Реализовать программу с базой учащихся группы (данные хранятся в файле). Записи по учащемуся: имя, фамилия, пол, возраст. Программа должна предусматривать поиск по одному или нескольким полям базы. Результат выводить в удобочитаемом виде с порядковым номером записи. Скрипт программы должен принимать параметр, который определяет формат хранения и реализации БД: в текстовом файле с определенной структурой; в файле json. """ import json # import pdb # pdb.set_trace() class TXT(object): def __init__(self, filename=None): if not filename: # if filename is None filename = input('Enter filename: ') try: # необязательная проверка расширения файла if filename.split('.')[-1] != 'txt': print('Not a .txt file!') raise NotImplementedError except IndexError: print('Wrong filename') raise NotImplementedError self.filename = filename def search(self, param=None): """Поиск подмножества через issubset""" if not param: # if param is None try: inp = str(input("Search param here: ")).lower().split(',') # Andrew,18 self.inp = set(inp) except ValueError: raise NotImplementedError self.inp = set(param.lower().split(',')) print('Searching for:', self.inp) with open(self.filename) as f: for line in f.readlines(): student = set(line.lower().split()) if self.inp.issubset(student): return print("Student info: {}".format(line)) return print('No such student') class JSON(object): def __init__(self): filepath = '/home/aso/studystuff/python130218/Homework9-15.03/students.json' filename, filext = os.path.splitext(filepath) if filext != '.json': # необязательная проверка расширения файла print('Not a .json file!') raise NotImplementedError self.filename = str(filepath.split('/')[-1]) # последний эл-т в split'e self.filepath = filepath with open(self.filename) as f: data = json.load(f) self.data = data def search(self, someinput=None): """Поиск по сравнению множеств""" if not someinput: # if someinput is None someinput = input('Search for; ') # age=18,gender=m try: searchdata = {} # a dict of the form {'name':'...', 'lastname':'...'} for i in someinput.split(','): k, v = i.split('=') searchdata[k] = v except ValueError: print("Missing some args") raise NotImplementedError for student in self.data: # main func logic if set(searchdata.values()) <= set(self.data[student].values()): return print('Info: ', self.data[student]) return print('No such student') if __name__ == '__main__': try: a = TXT('studentsdata.txt') a.search('Andrew,18') a.search('56,Mark') print('***' * 5) b = JSON() b.search('age=18,gender=m') b.search('name=Mark,age=56') b.search('age=41') except NotImplementedError as e: print(e)
9178b61b24d57472299854f0ad1b127834220e0d
sankeerth/Algorithms
/Tree/python/leetcode/add_one_row_to_tree.py
2,754
3.765625
4
""" 623. Add One Row to Tree Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. The adding rule is: given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes with value v as N's left subtree root and right subtree root. And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root. If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree. Input: A binary tree as following: 4 / \ 2 6 / \ / 3 1 5 v = 1 d = 2 Output: 4 / \ 1 1 / \ 2 6 / \ / 3 1 5 Input: A binary tree as following: 4 / 2 / \ 3 1 v = 1 d = 3 Output: 4 / 2 / \ 1 1 / \ 3 1 """ from Tree.python.common.tree_operations import deserialize, TreeNode, print_levelorder_leetcode_style class Solution(object): def addOneRow(self, root, v, d): """ :type root: TreeNode :type v: int :type d: int :rtype: TreeNode """ def addOneRowRecursive(root, v, d, level): if root: if level == d - 1: node_left = TreeNode(v) node_left.left = root.left root.left = node_left node_right = TreeNode(v) node_right.right = root.right root.right = node_right else: addOneRowRecursive(root.left, v, d, level + 1) addOneRowRecursive(root.right, v, d, level + 1) if d == 1: node = TreeNode(v) node.left = root root = node else: addOneRowRecursive(root, v, d, 1) return root sol = Solution() print_levelorder_leetcode_style(sol.addOneRow(deserialize('[4,2,6,3,1,5]'), 1, 2)) print_levelorder_leetcode_style(sol.addOneRow(deserialize('[4,2,6,3,1,5]'), 1, 3)) print_levelorder_leetcode_style(sol.addOneRow(deserialize('[4,2,6,3,1,5]'), 1, 1)) """ leetcode discuss solution: def addOneRow(self, root, v, d): dummy, dummy.left = TreeNode(None), root row = [dummy] for _ in range(d - 1): row = [kid for node in row for kid in (node.left, node.right) if kid] for node in row: node.left, node.left.left = TreeNode(v), node.left node.right, node.right.right = TreeNode(v), node.right return dummy.left """
a19bfb60cdb49c381d7b789e352c41fdc305ac3d
haithamsha/grukking_book
/recursion.py
309
3.578125
4
def count_down(i): print(i) #base case if i <= 1: return else: #recursive case count_down(i-1) # count_down(10) #factorial def fac(i): #base case if(i == 1): return 1 else: #recursive case return i * fac(i -1) print(fac(3))
6c7783c62db2839518e43922895b2b6147128f2a
AbirameeKannan/Python-programming
/Beginner Level/swap,for,if.py
827
3.71875
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: user # # Created: 20/02/2018 # Copyright: (c) user 2018 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if __name__ == '__main__': main() #swap program x = 12 y = 18 x = y y = x print(x,y) #for loop ex1 x = 1 y = "2" z = 3 sum = 0 for i in (x,y,z): if isinstance(i, int): sum += i print sum #for loop ex2 x=0 for i in range(2, 10, 2): x = x + i print(x) #if else colors = ['Red', 'Black', 'White', 'Green'] if "green" in colors: print("Green Color") else: print("No Green Color") #ex x = 1 print(++++x)
0a6bad2984378728d4b7119d74d2b031e434f931
manurFR/sudoku-resolver
/src/main/python/HiddenSingleResolution.py
3,864
3.75
4
#!/usr/bin/env python # -*- coding: UTF8 -*- import logging import Stats from Grid import SIZE, startCoordinatesOfBlock class HiddenSingleResolution: """ A hidden single is a cell where one digit can only appear in its row, column or block. For a given cell, we will only consider the digits from the remaining candidates, so that we don't need to evaluate the digit already solved in its row, column or block. This implies that the Naked Single Resolutions MUST have been performed before trying this one, otherwise the results might be incorrect. """ def run(self, grid): solvedCells = 0 for x, y in iter(grid): if self.block_hidden_single(grid, x, y) or self.horizontal_hidden_single(grid, x, y) or self.vertical_hidden_single(grid, x, y): logging.info("Hidden Single resolution : found value for ({},{}) : {}".format(x, y, grid.get_solution(x, y))) Stats.increment(self.__class__.__name__) solvedCells += 1 return solvedCells def block_hidden_single(self, grid, x, y): """ For each of the remaining candidates in the (x, y) cell, determine if there is no other cell in the same block having the same digit among its remaining candidates. If not, since each digit must appear once in each block, it means that cell must hold that digit. Returns True if such a hidden single was found in this cell, False otherwise. """ if grid.get_solution(x, y): return False (xBlock, yBlock) = startCoordinatesOfBlock(x, y) for digit in grid.candidates[x][y]: notFound = True for i in range(3): for j in range(3): if xBlock + i == x and yBlock + j == y: continue if digit in grid.candidates[xBlock + i][yBlock + j]: notFound = False break if notFound: grid.set(x, y, digit) return True return False def horizontal_hidden_single(self, grid, x, y): """ For each of the remaining candidates in the (x, y) cell, determine if there is no other cell in the same row having the same digit among its remaining candidates. If not, since each digit must appear once in each row, it means that cell must hold that digit. Returns True if such a hidden single was found in this cell, False otherwise. """ if grid.get_solution(x, y): return False for digit in grid.candidates[x][y]: notFound = True for i in range(SIZE): if i == x: continue if digit in grid.candidates[i][y]: notFound = False break if notFound: grid.set(x, y, digit) return True return False def vertical_hidden_single(self, grid, x, y): """ For each of the remaining candidates in the (x, y) cell, determine if there is no other cell in the same column having the same digit among its remaining candidates. If not, since each digit must appear once in each column, it means that cell must hold that digit. Returns True if such a hidden single was found in this cell, False otherwise. """ if grid.get_solution(x, y): return False for digit in grid.candidates[x][y]: notFound = True for j in range(SIZE): if j == y: continue if digit in grid.candidates[x][j]: notFound = False break if notFound: grid.set(x, y, digit) return True return False
7d4026b1157ce7ca44b6f70dee784b14eff7e306
DamjanR/SN-2019-predavanje
/HM8.1.py
441
3.765625
4
# 8 predavanje (1 naloga) mood = input("Opiši svoje razpoloženje:") if mood == "vesel": print("Lepo te je videti veselega!") print("") elif mood == "žalosten": print("Ej stari 3× globoko vdihni!") print("") else: print("NO GO!") print("Danes si lahko le >>vesel<< ali >>žalosten<<!") print("") if mood == "živčen": print("Danes so itak vsi živčni!") print("") print("***** END *****")
19384c599d76e902e3abd7928830dbaed3b38463
Maneesha-Jayasundara/fyp
/pos.py
328
3.515625
4
import nltk text = "learn php from guru99" tokens = nltk.word_tokenize(text) print(tokens) tag = nltk.pos_tag(tokens) print(tag) grammar = "NP: {<DT>?<JJ>*<NN>}" cp=nltk.RegexpParser(grammar) result = cp.parse(tag) print(result) result.draw() # It will draw the pattern graphically which can be seen in Noun Phrase chunking
856e1ae0ea62c85f15e834b0ab88eddc113554f2
felipeaaguiar/toolsfordatascience
/teste.py
132
3.5625
4
a = 2 b = 3 dicionario = {'nome': 'Felipe', 'idade': 32} print('Olá Python!') print('É tudo meu') c = a d = b a = 7
b84bcbaaac5140273efff3ec8ab1daee280a5657
denispin/python_training1
/test.py
98
3.71875
4
a = 3 print(a) w = [2.3,3,5,5] for a in w: while a < 5: print(a*3) a = a+1
64c7eb0778621e512429ffd40c0e1d2597d6e876
Vractos/studying-python
/main.py
708
3.515625
4
#!python3 # print('Hello World') # import pacote.sub.arquivo # import tipos.variaveis # from tipos import variaveis, basicos # import tipos.lista # import tipos.tuplas # import tipos.conjuntos # import tipos.dicionario # import operadores.unarios # import operadores.aritimetricos # import operadores.relacionais # import operadores.atribuicao # import operadores.logicos # import operadores.ternario # import controle.if_1 # import controle.if_2 # import controle.for_1 from funcoes import basico # basico.saudacao_pela_manha() # basico.saudacao_pela_manha('Maria', 35) # basico.saudacao_pela_manha('João', 35) # basico.saudacao_pela_manha(idade=89) a = basico.soma_e_multi(x=10, a=2, b=3) print(a)
2f0a8bc7a01b163f59ac2fd8ab1288d8bc539f33
NevssZeppeli/my_ege_solutions
/Вариант 14/14.py
283
3.578125
4
y = (((9**22) + (3 ** 66) - 18)) c=0 def ternary (n): if n == 0: return '0' nums = [] while n: n, r = divmod(n, 3) nums.append(str(r)) return ''.join(reversed(nums)) for x in ternary(y): if x == '2': c+=1 print(c)
f4d9d1c65ff3f85c1125246688fce1d5c04fef90
anzumpraveen/Dictionary
/comprehension_dict.py
111
4.15625
4
d={"one":"1","two":"2","three":"3"} a={} for key in d: newlist = {x for x in d} a[key]=newlist print(a)
55ed2b583f856e0752f53e698bd9e7395d3f6076
EliasAltrabsheh/Managing-Big-Data-with-MySQL-Coursera-
/Managing Big Data with MySQL/Exercise_jupytar/python code/MySQL_Exercise_09_Subqueries_and_Derived_Tables.py
23,556
3.5
4
# coding: utf-8 # Copyright Jana Schaich Borg/Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) # # MySQL Exercise 9: Subqueries and Derived Tables # # Now that you understand how joins work, in this lesson we are going to learn how to incorporate subqueries and derived tables into our queries. # # Subqueries, which are also sometimes called inner queries or nested queries, are queries that are embedded within the context of another query. The output of a subquery is incorporated into the queries that surround it. Subqueries can be used in SELECT, WHERE, and FROM clauses. When they are used in FROM clauses they create what are called derived tables. # # ### The main reasons to use subqueries are: # # + Sometimes they are the most logical way to retrieve the information you want # + They can be used to isolate each logical part of a statement, which can be helpful for troubleshooting long and complicated queries # + Sometimes they run faster than joins # # Some people find subqueries easier to read than joins. However, that is often a result of not feeling comfortable with the concepts behind joins in the first place (I prefer join syntax, so admittedly, that is my preference). # # ### Subqueries must be enclosed in parentheses. Subqueries have a couple of rules that joins don't: # # + ORDER BY phrases cannot be used in subqueries (although ORDER BY phrases can still be used in outer queries that contain subqueries). # # + Subqueries in SELECT or WHERE clauses that return more than one row must be used in combination with operators that are explicitly designed to handle multiple values, such as the IN operator. Otherwise, subqueries in SELECT or WHERE statements can output no more than 1 row. # # ### So why would you use subqueries? # # Let's look at some examples. # # **Start by loading the sql library and database, and making the Dognition database your default database**: # In[1]: get_ipython().magic('load_ext sql') get_ipython().magic('sql mysql://studentuser:studentpw@mysqlserver/dognitiondb') get_ipython().magic('sql USE dognitiondb') # #### 1) "On the fly calculations" (or, doing calculations as you need them) # # One of the main uses of subqueries is to calculate values as you need them. This allows you to use a summary calculation in your query without having to enter the value outputted by the calculation explicitly. A situation when this capability would be useful is if you wanted to see all the records that were greater than the average value of a subset of your data. # # Recall one of the queries we wrote in "MySQL Exercise 4: Summarizing your Data" to calculate the average amount of time it took customers to complete all of the tests in the exam_answers table (we had to exclude negative durations from the calculation due to some abnormalities in the data): # # ```sql # SELECT AVG(TIMESTAMPDIFF(minute,start_time,end_time)) AS AvgDuration # FROM exam_answers # WHERE TIMESTAMPDIFF(minute,start_time,end_time)>0; # ``` # # What if we wanted to look at just the data from rows whose durations were greater than the average, so that we could determine whether there are any features that seem to correlate with dogs taking a longer time to finish their tests? We could use a subquery to calculate the average duration, and then indicate in our SELECT and WHERE clauses that we only wanted to retrieve the rows whose durations were greater than the average. Here's what the query would look like: # # ```sql # SELECT * # FROM exam_answers # WHERE TIMESTAMPDIFF(minute,start_time,end_time) > # (SELECT AVG(TIMESTAMPDIFF(minute,start_time,end_time)) AS AvgDuration # FROM exam_answers # WHERE TIMESTAMPDIFF(minute,start_time,end_time)>0); # ``` # # You can see that TIMESTAMPDIFF gets compared to the singular average value outputted by the subquery surrounded by parentheses. You can also see that it's easier to read the query as a whole if you indent and align all the clauses associated with the subquery, relative to the main query. # # **Question 1: How could you use a subquery to extract all the data from exam_answers that had test durations that were greater than the average duration for the "Yawn Warm-Up" game? Start by writing the query that gives you the average duration for the "Yawn Warm-Up" game by itself (and don't forget to exclude negative values; your average duration should be about 9934):** # In[5]: get_ipython().run_cell_magic('sql', '', 'SELECT AVG(TIMESTAMPDIFF(minute,start_time,end_time)) AS AvgDuration\nFROM exam_answers\nWHERE TIMESTAMPDIFF(minute,start_time,end_time)>0 AND test_name="Yawn Warm-Up";') # **Question 2: Once you've verified that your subquery is written correctly on its own, incorporate it into a main query to extract all the data from exam_answers that had test durations that were greater than the average duration for the "Yawn Warm-Up" game (you will get 11059 rows):** # In[6]: get_ipython().run_cell_magic('sql', '', 'SELECT *\nFROM exam_answers \nWHERE TIMESTAMPDIFF(minute,start_time,end_time) >\n (SELECT AVG(TIMESTAMPDIFF(minute,start_time,end_time)) AS AvgDuration\n FROM exam_answers\n WHERE TIMESTAMPDIFF(minute,start_time,end_time)>0 AND test_name="Yawn Warm-Up");') # Now double check the results you just retrieved by replacing the subquery with "9934"; you should get the same results. It is helpful to get into the habit of including these kinds of quality checks into your query-writing process. # # This example shows you how subqueries allow you retrieve information dynamically, rather than having to hard code in specific numbers or names. This capability is particularly useful when you need to build the output of your queries into reports or dashboards that are supposed to display real-time information. # # # #### 2) Testing membership # # Subqueries can also be useful for assessing whether groups of rows are members of other groups of rows. To use them in this capacity, we need to know about and practice the IN, NOT IN, EXISTS, and NOT EXISTS operators. # # Recall from MySQL Exercise 2: Selecting Data Subsets Using WHERE that the IN operator allows you to use a WHERE clause to say how you want your results to relate to a list of multiple values. It's basically a condensed way of writing a sequence of OR statements. The following query would select all the users who live in the state of North Carolina (abbreviated "NC") or New York (abbreviated "NY"): # # ```mysql # SELECT * # FROM users # WHERE state IN ('NC','NY'); # ``` # Notice the quotation marks around the members of the list referred to by the IN statement. These quotation marks are required since the state names are strings of text. # # A query that would give an equivalent result would be: # # ```mysql # SELECT * # FROM users # WHERE state ='NC' OR state ='NY'; # ``` # A query that would select all the users who do NOT live in the state of North Carolina or New York would be: # # ```mysql # SELECT * # FROM users # WHERE state NOT IN ('NC','NY'); # ``` # # **Question 3: Use an IN operator to determine how many entries in the exam_answers tables are from the "Puzzles", "Numerosity", or "Bark Game" tests. You should get a count of 163022.** # # In[7]: get_ipython().run_cell_magic('sql', '', "SELECT COUNT(*)\nFROM exam_answers\nWHERE subcategory_name IN ('Puzzles','Numerosity','Bark Game');") # **Question 4: Use a NOT IN operator to determine how many unique dogs in the dog table are NOT in the "Working", "Sporting", or "Herding" breeding groups. You should get an answer of 7961.** # In[8]: get_ipython().run_cell_magic('sql', '', "SELECT COUNT(DISTINCT dog_guid)\nFROM dogs\nWHERE breed_group NOT IN ('Working','Sporting','Herding');") # EXISTS and NOT EXISTS perform similar functions to IN and NOT IN, but EXISTS and NOT EXISTS can only be used in subqueries. The syntax for EXISTS and NOT EXISTS statements is a little different than that of IN statements because EXISTS is not preceded by a column name or any other expression. The most important difference between EXISTS/NOT EXISTS and IN/NOT IN statements, though, is that unlike IN/NOT IN statements, EXISTS/NOT EXISTS are logical statements. Rather than returning raw data, per se, EXISTS/NOT EXISTS statements return a value of TRUE or FALSE. As a practical consequence, EXISTS statements are often written using an asterisk after the SELECT clause rather than explicit column names. The asterisk is faster to write, and since the output is just going to be a logical true/false either way, it does not matter whether you use an asterisk or explicit column names. # # We can use EXISTS and a subquery to compare the users who are in the users table and dogs table, similar to what we practiced previously using joins. If we wanted to retrieve a list of all the users in the users table who were also in the dogs table, we could write: # # ```sql # SELECT DISTINCT u.user_guid AS uUserID # FROM users u # WHERE EXISTS (SELECT d.user_guid # FROM dogs d # WHERE u.user_guid =d.user_guid); # ``` # # You would get the same result if you wrote: # ```sql # SELECT DISTINCT u.user_guid AS uUserID # FROM users u # WHERE EXISTS (SELECT * # FROM dogs d # WHERE u.user_guid =d.user_guid); # ``` # # # Essentially, both of these queries say give me all the distinct user_guids from the users table that have a value of "TRUE" in my EXISTS clause. The results would be equivalent to an inner join with GROUP BY query. Now... # # **Question 5: How could you determine the number of unique users in the users table who were NOT in the dogs table using a NOT EXISTS clause? You should get the 2226, the same result as you got in Question 10 of MySQL Exercise 8: Joining Tables with Outer Joins.** # In[9]: get_ipython().run_cell_magic('sql', '', 'SELECT DISTINCT u.user_guid AS uUserID\nFROM users u\nWHERE NOT EXISTS (SELECT d.user_guid\nFROM dogs d\nWHERE u.user_guid =d.user_guid);') # #### 3) Accurate logical representations of desired output and Derived Tables # # A third situation in which subqueries can be useful is when they simply represent the logic of what you want better than joins. # # We saw an example of this in our last MySQL Exercise. We wanted a list of each dog a user in the users table owns, with its accompanying breed information whenever possible. To achieve this, we wrote this query in Question 6: # # ```sql # SELECT u.user_guid AS uUserID, d.user_guid AS dUserID, d.dog_guid AS dDogID, d.breed # FROM users u LEFT JOIN dogs d # ON u.user_guid=d.user_guid # ``` # # Once we saw the "exploding rows" phenomenon due to duplicate rows, we wrote a follow-up query in Question 7 to assess how many rows would be outputted per user_id when we left joined the users table on the dogs table: # # ```sql # SELECT u.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS numrows # FROM users u LEFT JOIN dogs d # ON u.user_guid=d.user_guid # GROUP BY u.user_guid # ORDER BY numrows DESC # ``` # # This same general query without the COUNT function could have been used to output a complete list of all the distinct users in the users table, their dogs, and their dogs' breed information. However, the method we used to arrive at this was not very pretty or logically satisfying. Rather than joining many duplicated rows and fixing the results later with the GROUP BY clause, it would be much more elegant if we could simply join the distinct UserIDs in the first place. There is no way to do that with join syntax, on its own. However, you can use subqueries in combination with joins to achieve this goal. # # To complete the join on ONLY distinct UserIDs from the users table, we could write: # # ```sql # SELECT DistinctUUsersID.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS numrows # FROM (SELECT DISTINCT u.user_guid # FROM users u) AS DistinctUUsersID # LEFT JOIN dogs d # ON DistinctUUsersID.user_guid=d.user_guid # GROUP BY DistinctUUsersID.user_guid # ORDER BY numrows DESC # ``` # # **Try it yourself:** # # In[10]: get_ipython().run_cell_magic('sql', '', 'SELECT DistinctUUsersID.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS numrows\nFROM (SELECT DISTINCT u.user_guid \n FROM users u) AS DistinctUUsersID \nLEFT JOIN dogs d\n ON DistinctUUsersID.user_guid=d.user_guid\nGROUP BY DistinctUUsersID.user_guid\nORDER BY numrows DESC;') # **<mark> Queries that include subqueries always run the innermost subquery first, and then run subsequent queries sequentially in order from the innermost query to the outermost query. </mark>** # # Therefore, the query we just wrote extracts the distinct user_guids from the users table *first*, and then left joins that reduced subset of user_guids on the dogs table. As mentioned at the beginning of the lesson, since the subquery is in the FROM statement, it actually creates a temporary table, called a derived table, that is then incorporated into the rest of the query. # # **There are several important points to notice about the syntax of this subquery.** First, an alias of "DistinctUUsersID" is used to name the results of the subquery. *We are required to give an alias to any derived table we create in subqueries within FROM statements.* Otherwise there would be no way for the database to refer to the multiple columns within the temporary results we create. # # Second, *we need to use this alias every time we want to execute a function that uses the derived table.* Remember that the results in which we are interested require a join between the dogs table and the temporary table, not the dogs table and the original users table with duplicates. That means we need to make sure we reference the temporary table alias in the ON, GROUP BY, and SELECT clauses. # # Third, relatedly, aliases used within subqueries can refer to tables outside of the subqueries. However, *outer queries cannot refer to aliases created within subqueries unless those aliases are explicitly part of the subquery output*. In other words, if you wrote the first line of the query above as: # # ```sql # SELECT u.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS numrows # ... # ``` # # the query would not execute because the alias "u" is contained inside the subquery, but is not included in the output. **Go ahead and try it to see what the error message looks like:** # In[ ]: # A similar thing would happen if you tried to use the alias u in the GROUP BY statement. # # Another thing to take note of is that when you use subqueries in FROM statements, the temporary table # you create can have multiple columns in the output (unlike when you use subqueries in outside SELECT statements). But for that same reason, subqueries in FROM statements can be very computationally intensive. Therefore, it's a good idea to use them sparingly, especially when you have very large data sets. # # Overall, subqueries and joins can often be used interchangeably. Some people strongly prefer one approach over another, but there is no consensus about which approach is best. When you are analyzing very large datasets, it's a good idea to test which approach will likely be faster or easier to troubleshoot for your particular application. # # # # Let's practice some more subqueries! # # **Question 6: Write a query using an IN clause and equijoin syntax that outputs the dog_guid, breed group, state of the owner, and zip of the owner for each distinct dog in the Working, Sporting, and Herding breed groups. (You should get 10,254 rows; the query will be a little slower than some of the others we have practiced)** # # In[11]: get_ipython().run_cell_magic('sql', '', "SELECT DISTINCT d.dog_guid, d.breed_group, u.state, u.zip\nFROM dogs d, users u\nWHERE breed_group IN ('Working','Sporting','Herding') AND d.user_guid=u.user_guid;") # **Question 7: Write the same query as in Question 6 using traditional join syntax.** # In[12]: get_ipython().run_cell_magic('sql', '', "SELECT DISTINCT d.dog_guid, d.breed_group, u.state, u.zip\nFROM dogs d JOIN users u\nON d.user_guid=u.user_guid\nWHERE breed_group IN ('Working','Sporting','Herding');") # **Question 8: Earlier we examined unique users in the users table who were NOT in the dogs table. Use a NOT EXISTS clause to examine all the users in the dogs table that are not in the users table (you should get 2 rows in your output).** # In[15]: get_ipython().run_cell_magic('sql', '', 'SELECT d.user_guid AS dUserID, d.dog_guid AS dDogID\nFROM dogs d\nWHERE NOT EXISTS (SELECT DISTINCT u.user_guid\nFROM users u\nWHERE d.user_guid =u.user_guid);') # **Question 9: We saw earlier that user_guid 'ce7b75bc-7144-11e5-ba71-058fbc01cf0b' still ends up with 1819 rows of output after a left outer join with the dogs table. If you investigate why, you'll find out that's because there are duplicate user_guids in the dogs table as well. How would you adapt the query we wrote earlier (copied below) to only join unique UserIDs from the users table with unique UserIDs from the dog table?** # # Join we wrote earlier: # # ```sql # SELECT DistinctUUsersID.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS numrows # FROM (SELECT DISTINCT u.user_guid # FROM users u) AS DistinctUUsersID # LEFT JOIN dogs d # ON DistinctUUsersID.user_guid=d.user_guid # GROUP BY DistinctUUsersID.user_guid # ORDER BY numrows DESC; # ``` # **Let's build our way up to the correct query. To troubleshoot, let's only examine the rows related to user_guid 'ce7b75bc-7144-11e5-ba71-058fbc01cf0b', since that's the userID that is causing most of the trouble. Rewrite the query above to only LEFT JOIN *distinct* user(s) from the user table whose user_guid='ce7b75bc-7144-11e5-ba71-058fbc01cf0b'. The first two output columns should have matching user_guids, and the numrows column should have one row with a value of 1819:** # In[14]: get_ipython().run_cell_magic('sql', '', "SELECT DistinctUUsersID.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS\nnumrows\nFROM (SELECT DISTINCT u.user_guid\nFROM users u\nWHERE u.user_guid='ce7b75bc-7144-11e5-ba71-058fbc01cf0b') AS\nDistinctUUsersID\nLEFT JOIN dogs d\nON DistinctUUsersID.user_guid=d.user_guid\nGROUP BY DistinctUUsersID.user_guid\nORDER BY numrows DESC;") # **Question 10: Now let's prepare and test the inner query for the right half of the join. Give the dogs table an alias, and write a query that would select the distinct user_guids from the dogs table (we will use this query as a inner subquery in subsequent questions, so you will need an alias to differentiate the user_guid column of the dogs table from the user_guid column of the users table).** # In[13]: get_ipython().run_cell_magic('sql', '', 'SELECT DISTINCT d.user_guid\nFROM dogs d;\n') # **Question 11: Now insert the query you wrote in Question 10 as a subquery on the right part of the join you wrote in question 9. The output should return columns that should have matching user_guids, and 1 row in the numrows column with a value of 1. If you are getting errors, make sure you have given an alias to the derived table you made to extract the distinct user_guids from the dogs table, and double-check that your aliases are referenced correctly in the SELECT and ON statements.** # In[16]: get_ipython().run_cell_magic('sql', '', "SELECT DistinctUUsersID.user_guid AS uUserID, DistictDUsersID.user_guid AS\ndUserID, count(*) AS numrows\nFROM (SELECT DISTINCT u.user_guid\nFROM users u\nWHERE u.user_guid='ce7b75bc-7144-11e5-ba71-058fbc01cf0b') AS\nDistinctUUsersID\nLEFT JOIN (SELECT DISTINCT d.user_guid\nFROM dogs d) AS DistictDUsersID\nON DistinctUUsersID.user_guid=DistictDUsersID.user_guid\nGROUP BY DistinctUUsersID.user_guid\nORDER BY numrows DESC;") # **Question 12: Adapt the query from Question 10 so that, in theory, you would retrieve a full list of all the DogIDs a user in the users table owns, with its accompagnying breed information whenever possible. HOWEVER, BEFORE YOU RUN THE QUERY MAKE SURE TO LIMIT YOUR OUTPUT TO 100 ROWS *WITHIN* THE SUBQUERY TO THE LEFT OF YOUR JOIN.** If you run the query without imposing limits it will take a *very* long time. If you try to limit the output by just putting a limit clause at the end of the outermost query, the database will still have to hold the entire derived tables in memory and join each row of the derived tables before limiting the output. If you put the limit clause in the subquery to the left of the join, the database will only have to join 100 rows of data. # # In[17]: get_ipython().run_cell_magic('sql', '', 'SELECT DistinctUUsersID.user_guid AS uUserID, DistictDUsersID.user_guid AS\ndUserID,\nDistictDUsersID.dog_guid AS DogID, DistictDUsersID.breed AS breed\nFROM (SELECT DISTINCT u.user_guid\nFROM users u\nLIMIT 100) AS DistinctUUsersID\nLEFT JOIN (SELECT DISTINCT d.user_guid, d.dog_guid, d.breed\nFROM dogs d) AS DistictDUsersID\nON DistinctUUsersID.user_guid=DistictDUsersID.user_guid\nGROUP BY DistinctUUsersID.user_guid;') # **Question 13: You might have a good guess by now about why there are duplicate rows in the dogs table and users table, even though most corporate databases are configured to prevent duplicate rows from ever being accepted. To be sure, though, let's adapt this query we wrote above:** # # ```sql # SELECT DistinctUUsersID.user_guid AS uUserID, d.user_guid AS dUserID, count(*) AS numrows # FROM (SELECT DISTINCT u.user_guid FROM users u) AS DistinctUUsersID # LEFT JOIN dogs d # ON DistinctUUsersID.user_guid=d.user_guid # GROUP BY DistinctUUsersID.user_guid # ORDER BY numrows DESC # ``` # # **Add dog breed and dog weight to the columns that will be included in the final output of your query. In addition, use a HAVING clause to include only UserIDs who would have more than 10 rows in the output of the left join (your output should contain 5 rows).** # In[18]: get_ipython().run_cell_magic('sql', '', 'SELECT DistictUUsersID.user_guid AS userid, d.breed, d.weight, count(*) AS numrows\nFROM (SELECT DISTINCT u.user_guid\nFROM users u) AS DistictUUsersID\nLEFT JOIN dogs d\nON DistictUUsersID.user_guid=d.user_guid\nGROUP BY DistictUUsersID.user_guid\nHAVING numrows>10\nORDER BY numrows DESC;') # You can see that almost all of the UserIDs that are causing problems are Shih Tzus that weigh 190 pounds. As we learned in earlier lessons, Dognition used this combination of breed and weight to code for testing accounts. These UserIDs do not represent real data. These types of testing entries would likely be cleaned out of databases used in large established companies, but could certainly still be present in either new databases that are still being prepared and configured, or in small companies which have not had time or resources to perfect their data storage. # # There are not very many incorrect entries in the Dognition database and most of the time these entries will not appreciably affect your queries or analyses. However, you have now seen the effects such entries can have in the rare cases when you need to implement outer joins on tables that have duplicate rows or linking columns with many to many relationships. Hopefully, understanding these rare cases has helped you understand more deeply the fundamental concepts behind joining tables in relational databases. # # **Feel free to practice more subqueries below!** # In[ ]:
bd9f19147302899732eabe5f2a52afc50d9d1942
qs8607a/Algorithm-39
/Euler/part2/p58.py
1,160
3.84375
4
##Starting with 1 and spiralling anticlockwise in the following way, a square ##spiral with side length 7 is formed. ##37 36 35 34 33 32 31 ##38 17 16 15 14 13 30 ##39 18 5 4 3 12 29 ##40 19 6 1 2 11 28 ##41 20 7 8 9 10 27 ##42 21 22 23 24 25 26 ##43 44 45 46 47 48 49 ##It is interesting to note that the odd squares lie along the bottom right ##diagonal, but what is more interesting is that 8 out of the 13 numbers lying ##along both diagonals are prime; that is, a ratio of 8/13 62%. ##If one complete new layer is wrapped around the spiral above, a square spiral ##with side length 9 will be formed. If this process is continued, what is the ##side length of the square spiral for which the ratio of primes along both ##diagonals first falls below 10%? from Crazy import isprime def fi(): a,b=0,1 first=1 mo=0 for i in range(100000): mo=mo+2 for j in range(3): first=first+mo if isprime(first): a=a+1 first=first+mo b=b+4 if i%1000==0: print(a,b) if b/a>10: return 2*i+3 print(fi())
60007702d7524ef5349426036f99f4557cc812a1
lisnb/lintcode
/ConvertExpressionToReversePolishNotation.py
2,684
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: LiSnB # @Date: 2015-05-07 09:00:52 # @Last Modified by: LiSnB # @Last Modified time: 2015-05-07 09:03:37 """ Definition of ExpressionTreeNode: """ class ExpressionTreeNode: def __init__(self, symbol): self.symbol = symbol self.left, self.right = None, None class Solution: # @param expression: A string list # @return: The Reverse Polish notation of this expression operset = set(['(',')','+','-','*','/']) operprio = { '+':1, '-':1, '*':2, '/':2 } def islegal(self, expression, b, e): t = [] for i in range(b, e+1): if expression[i]=='(': t.append(1) continue if expression[i]==')': if len(t)==0: return False if t[-1]==1: t.pop() return len(t)==0 def buildtree(self, expression, b, e): while b<e and expression[b]=='(' and expression[e]==')': if self.islegal(expression, b+1, e-1): b+=1 e-=1 else: break if b>e: return None if b==e: en = ExpressionTreeNode(expression[b]) return en #find the last operator that has the lowest priority out of parentheses lowestprio = 100 lowestoper = -1 parentheses = [] for i in range(b, e+1): if expression[i] == '(': parentheses.append(1) continue if expression[i] == ')': parentheses.pop() continue if len(parentheses)==0: tprio = Solution.operprio.get(expression[i], 100) if tprio<=lowestprio: lowestprio = tprio lowestoper = i root = ExpressionTreeNode(expression[lowestoper]) root.left = self.buildtree(expression, b, lowestoper-1) root.right = self.buildtree(expression, lowestoper+1, e) return root def postordertraversal(self, root, r): if not root: return self.postordertraversal(root.left, r) self.postordertraversal(root.right, r) r.append(root.symbol) def convertToRPN(self, expression): # write your code here root = self.buildtree(expression, 0, len(expression)-1) r = [] self.postordertraversal(root, r) return r if __name__ == '__main__': s = Solution() expression = ["3", "-", "4", "+", "5"] print s.convertToRPN(expression)
7b5f4b1b841bb3f49ee4977263ef253b4b5dc320
Durbek1/1-Lineyniy-algoritm
/27-пример.py
64
3.578125
4
A=int(input('A=')) y1=A**2 y2=A**4 y3=A**8 print(y1,y2,y3)
dcc0bf12f96221efe05d17095e24f3c87829863e
ryanjeric/python_playground
/PROJECT/SnakeAndLadderWithoutBoard.py
2,383
4
4
import time import random print("Snake and ladder w/o Board - v1.0") class Player: def __init__(self, player_id): self.score = 0 self.player_id = player_id def addScore(self, dice): """ If the player rolls a higher number than needed to land exactly on 100, their piece does not move and remains there until their next turn, when they can roll again.""" tempScore = self.score + dice if tempScore > 100: print('Score not added needs to be exactly 100, current score ' + str(self.score)) return 'void' else: self.score = self.score + dice return self.score def displayPlayer(self): return 'Player ' + str(self.player_id) def hasLadderOrSnake(self): # 8 ladders && 7 snakes dictionary ladders = {1: 38, 4: 14, 8: 30, 21: 42, 28: 76, 50: 67, 71: 92, 80: 99} snakes = {32: 10, 36: 6, 48: 26, 62: 18, 88: 24, 85: 56, 97: 78} if self.score in ladders: self.score = ladders[self.score] print(self.displayPlayer() + ' lands on a ladder, climbs to square ' + str(self.score)) elif self.score in snakes: self.score = snakes[self.score] print(self.displayPlayer() + ' was bitten by a snake, will go down to square ' + str(self.score)) else: print(self.displayPlayer() + ' proceed to square ' + str(self.score)) print("Max Players:") max_player = int(input()) players = [] def rollDice(): for i in range(0, 3): print(".", end=' ') time.sleep(1.5) return random.randint(1, 6) for player_count in range(0, max_player): players.append(Player(player_count + 1)) # GAME START player_win = False while not player_win: for player in range(len(players)): print("\n" + players[player].displayPlayer() + ' will now roll the dice') diceScore = rollDice() print(players[player].displayPlayer() + " rolled " + str(diceScore), end=' ') if players[player].addScore(diceScore) != 'void': players[player].hasLadderOrSnake() # CHECK HAS LADDER OR SNAKE if players[player].score == 100: player_win = True print('\n\n' + players[player].displayPlayer() + ' WIN!') break print('\n Next player ready!<Press Enter>') input()
6930b7edce92f35f089a38a0b158a3619865e924
Smerly/Lists-and-Loops-Tutorial
/main.py
354
3.515625
4
Songs = ["Rockstar", "Do it", "For the Night"] print(Songs[0]) print(Songs[2]) print(Songs[1:2]) Songs[2] = "Yoru Ni Kakeru" Songs.append("Tabun") Songs.append("Halzion") Songs.append("Lemon") del Songs[5] animals = ["Cat", "Dog", "Chicken"] animals.append("Potato") print(animals[2]) del animals[0] for i in range(len(animals)): print(animals[i])
04738719f4df13568db11977988f28249fd0d15d
roozbehsayadi/AI-Class-for-Freshmen-of-1398
/002 Minimax Algorithm/step3.py
2,854
3.90625
4
from random import choice from time import sleep from math import inf human = "x" computer = "o" def create_empty_board(): return [["_", "_", "_"], ["_", "_", "_"], ["_", "_", "_"]] def evaluate(b): # Checking for Rows for X or O victory. for row in range(0, 3): if b[row][0] == b[row][1] and b[row][1] == b[row][2]: if b[row][0] == computer: return +1 if b[row][0] == human: return -1 # Checking for Columns for X or O victory. for col in range(0, 3): if b[0][col] == b[1][col] and b[1][col] == b[2][col]: if b[0][col] == computer: return +1 if b[0][col] == human: return -1 # Checking for Diagonals for X or O victory. if b[0][0] == b[1][1] and b[1][1] == b[2][2]: if b[0][0] == computer: return +1 if b[0][0] == human: return -1 if b[0][2] == b[1][1] and b[1][1] == b[2][0]: if b[0][2] == computer: return +1 if b[0][2] == human: return -1 # Else if none of them have won then return 0 return 0 def game_over(board): # check if somebody wins or not if evaluate(board) == 0: return False else: return True def empty_cells(board): cells = [] for x, row in enumerate(board): for y, cell in enumerate(row): if cell == "_": cells.append((x, y)) return cells def is_valid_move(x, y, board): if board[x][y] == "_": return True else: return False def set_move(x, y, board, player): if not is_valid_move(x, y, board): return False board[x][y] = player return True def clear_screen(): print("\x1b[H\x1b[2J\x1b[3J", end="") def print_board(board): for row in board: print(row) def player(board): print("enter x ,y for your move") x, y = input().split() x, y = int(x), int(y) if not set_move(x, y, board, player=human): # get input again player(board) ############################################### def ai(board): print("ai is thinking") x, y = choice(empty_cells(board)) set_move(x, y, board, player=computer) if __name__ == "__main__": board = create_empty_board() player_turn = True while len(empty_cells(board)) > 0 and not game_over(board): # clear_screen() print_board(board) if player_turn: player(board) else: ai(board) player_turn = not player_turn print_board(board) result = evaluate(board) if result == +1: print("you lost") elif result == -1: print("you won") else: print("tie") # source: https://github.com/Cledersonbc/tic-tac-toe-minimax/blob/master/py_version/minimax.py
2234fd813cf426e6d42c3ad7f61a8ab1a9a0ef45
losskatsu/Programmers
/practice/sort/K번째수.py
382
3.5
4
# 100 점 def solution(array, commands): answer = [] n = len(commands) for i in commands: tmp_array = [] init = i[0]-1 end = i[1] n_ch = i[2]-1 for j in range(init, end): tmp_array.append(array[j]) tmp_array.sort() print(tmp_array) answer.append(tmp_array[n_ch]) return answer
33b01b2eebd61b7b48ea4abb4208bf585ca1f52c
Mahlatse0001/Pre-bootcamp-coding-challenges
/Task5.py
288
4.15625
4
a = int(input("Enter first side:")) b = int(input("Enter second side:")) c = int(input("Enter third side:")) def area_calc(a,b,c): p = (a + b + c)/2 area = ((p*(p - a)*(p - b)*(p - c))**0.5) return area print("The area of the triangle is: " + str(round(area_calc(a,b,c),2)))
a1a5bf51c5ce2e04e6b1a4b143d83537b6163751
sidsharma1990/Practicedose
/Matplotlib for grp 2.py
2,441
3.9375
4
# Matplotlib (Visualization) import matplotlib.pyplot as plt import numpy as np x = [1,2,3,4,5,6] y = [54,23,12,48,46,43] plt.plot(x, y) x = np.linspace(1,50,20) y = np.random.randint(1,50,20) y = np.sort(y) plt.plot(x, y, 'r') plt.plot(x, y, color = 'g') plt.plot(x, y, color = 'black') # Always run all codes together plt.plot(x, y, color = 'g') plt.xlabel('X-Axis') plt.ylabel('Y-Axis') plt.title('Random Graph') plt.show() # to remove text output ####### Subplot # (1,2,1) = rows, column and graph number plt.plot() plt.subplot(1,2,1) plt.subplot(1,2,2) plt.subplot(1,2,3) # it wont work plt.subplot(2,3,1) plt.plot(x,y,'r') plt.subplot(2,3,2) plt.plot(x,y,'g') plt.subplot(2,3,3) plt.plot(x,y,'b') plt.subplot(2,3,4) plt.plot(x,y,'m') plt.subplot(2,3,5) plt.plot(x,y,'c') plt.subplot(2,3,6) plt.plot(x,y,'b') plt.tight_layout() ##### Markers, line style plt.subplot(1,2,1) plt.plot(x,y,'r--') plt.plot(x,y,'r-') plt.plot(x,y,'r-.') plt.plot(x,y,'r-') plt.plot(x,y,'r+-') plt.plot(x,y,'rv-') plt.plot(x,y, linestyle = 'steps') plt.plot(x,y, linestyle = '--', marker = 'P', color = 'black') plt.plot(x,y, linestyle = '--', marker = 'P', color = 'black', markersize = 7) plt.plot(x,y, linestyle = '--', marker = 'P', color = 'black', markersize = 15, markerfacecolor = 'red') plt.plot(x,y, linestyle = '--', marker = 'P', color = 'black', markersize = 25, markerfacecolor = 'red', markeredgecolor = 'cyan') plt.plot(x,y, linestyle = '--', marker = 'P', color = 'black', markersize = 25, markerfacecolor = 'red', markeredgecolor = 'cyan', markeredgewidth = 5) ################################ plt.plot(x,y) plt.scatter(x,y) plt.hist(x,y) plt.hist2d(x, y, bins = 10) plt.bar(x,y) plt.boxplot(x,y) plt.polar(x,y) # Heatmap # num = np.random.random((4,4)) # plt.imshow(num, cmap = 'heat', interpolation = 'nearest') # plt.show() ##### OOP (object oreiented plot) x = np.linspace(1,50,20) y = np.random.randint(1,50,20) y = np.sort(y) fig = plt.figure() axes = fig.add_axes([0,0,1,1]) axes1 = fig.add_axes([0.4,0.2,0.4,0.7]) axes.set_xlabel('Master X-Axis') axes.set_ylabel('Master y-Axis') axes.set_title('Master Plot') axes1.set_xlabel('X-Axis') axes1.set_ylabel('y-Axis') axes1.set_title('Plot')
3fd9d7b358ae340765073af9a7da5511ea206491
violetyk/study-python
/statement.py
568
4.0625
4
# coding:utf-8 str = 'python' if str == 'PYTHON': print 'PYTHON!' elif str == 'python': print 'python!' else: print 'False!' # 同じ深さのインデントが同じブロックになる print '-----' i = 0 while i < 5: i += 1 print i print i # 無限ループ # while i: # print '.' # for 文 print '-----' k = 0 for k in xrange(5): print k # rangeは最初にリストをつくって返す関数。 # xrangeは呼ばれる度に数を返すジェネレータ。 # なので、範囲が大きいときにはxrangeの方がいいらしい。
cd4e73941d76d7665499f938b4f4686b2f6fa480
ivan-yosifov88/python_fundamentals
/list_advanced_lab/todo_list.py
309
3.59375
4
command = input() todo_list = [0] * 10 while not command == "End": tokens = command.split("-") index = int(tokens[0]) - 1 task = tokens[1] todo_list[index] = task command = input() task_list = [] for tasks in todo_list: if tasks != 0: task_list.append(tasks) print(task_list)
2ffe9fab1ab805217ab3d214648ab18fa0101bdd
KerronKing/python-projects
/Practice/loops.py
669
4.34375
4
# function that iterates over a list and print each element def print_list(myList): for item in myList: print(item) print_list([1, 2, 3, 4, 5]) # function that iterate over a list and prints all elements greater than 2 def print_over_two(myList): for item in myList: if item > 2: print(item) print_over_two([1, 2, 3, 4, 5]) # function that converts the temperatures in a list from celcius to fahrenheit def temp_converter(myList): for item in myList: if item < -273.15: print('This number cannot be converted') else: print((item * 9/5) + 32) temp_converter([10, -20, -289, 100])
488b27e4033ad64448b178c59f313b70b9ffa427
hernanre/rosebotics2
/src/capstone_2_runs_on_robot.py
2,517
3.921875
4
""" Mini-application: Buttons on a Tkinter GUI tell the robot to: - Go forward at the speed given in an entry box. Also: responds to Beacon button-presses by beeping, speaking. This module runs on the ROBOT. It uses MQTT to RECEIVE information from a program running on the LAPTOP. Authors: David Mutchler, his colleagues, and Ricardo Hernandez. """ import rosebotics_new as rb import time import mqtt_remote_method_calls as com import ev3dev.ev3 as ev3 def main(): robot = rb.Snatch3rRobot() rc = RemoteControlEtc(robot) george = com.MqttClient(rc) rc.mr = george george.connect_to_pc() while True: if robot.beacon_button_sensor.is_top_red_button_pressed(): ev3.Sound.beep().wait() time.sleep(0.01) # For the delegate to do its work if robot.beacon_button_sensor.is_top_blue_button_pressed(): ev3.Sound.speak('You pressed the blue button') class RemoteControlEtc(object): """ Stores the robot :type robot: rb.Snatch3rRobot """ def __init__(self, robot): self.robot = robot self.mr = None def go_forward(self, speed_string): speed = int(speed_string) self.robot.drive_system.start_moving(speed, speed) def go_backwards(self, speed_string): speed = -int(speed_string) self.robot.drive_system.start_moving(speed, speed) def turn_left_degrees(self, turn_left_string): degrees = int(turn_left_string) self.robot.drive_system.spin_in_place_degrees(-degrees) def turn_right_degrees(self, turn_right_string): degrees = int(turn_right_string) self.robot.drive_system.spin_in_place_degrees(degrees) def stop(self): self.robot.drive_system.stop_moving() def get_color(self): self.robot.camera.set_signature('SIG1') red = self.robot.camera.get_biggest_blob() self.robot.camera.set_signature('SIG2') orange = self.robot.camera.get_biggest_blob() self.robot.camera.set_signature('SIG3') yellow = self.robot.camera.get_biggest_blob() self.robot.camera.set_signature('SIG5') blue = self.robot.camera.get_biggest_blob() if red.get_area() > 1000: self.mr.send_message("robot_red") if orange.get_area() > 1000: self.mr.send_message("robot_orange") if yellow.get_area() > 1000: self.mr.send_message("robot_yellow") if blue.get_area() > 1000: self.mr.send_message("robot_blue") main()
5f87b9e2486e557e0008efa6df67a1042c8b8296
lofthouse/snippets
/adventofcode_2016/09.py
677
3.625
4
#!/usr/bin/env python import sys import os.path import re instruction=re.compile('\([0-9]+x[0-9]+\)') if len(sys.argv) != 2 or not os.path.isfile(sys.argv[1]) : print "Invalid argument" sys.exit(1) with open(sys.argv[1]) as input_file: content = input_file.read().splitlines() def decoded_length(line): next_ins=instruction.search(line) if next_ins: ins=next_ins.group(0) start,end = next_ins.span() n,c=map(int,ins.strip('()').split('x')) return len(line[0:start]) + c*decoded_length(line[end:end+n]) + decoded_length(line[end+n:]) else: return len(line) for line in content: print "The output is", decoded_length(line), "characters long" sys.exit(0)
705ebed6af0d89a0b38155e05d125b26d827cfed
RubenMarrero/Project-Euler-Solutions
/sum_fibonacci_even/evenFibSum.py
321
3.828125
4
#!/bin/python/ def evenFib(n) : if (n < 1) : return n if (n == 1) : return 2 # calculation of # Fn = 4*(Fn-1) + Fn-2 return ((4 * evenFib(n-1)) + evenFib(n-2)) evenFibSum = 0 i = 0 while evenFibSum <=4*(10**6): evenFibSum += evenFib(i) i+=1 print(evenFibSum)
25630fcfd78bba2d4f388a3df66293d6737a5a25
Tonyhao96/LeetCode_EveryDay
/415_Add Strings.py
913
3.5625
4
# 415_Add Strings #Using dict class Solution: def addStrings(self, num1: str, num2: str) -> str: dict = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "0": 0} def toint(s): res = 0 for i in range(len(s)): res *= 10 res += dict[s[i]] return res return str(toint(num1)+toint(num2)) #Using carry bit class Solution: def addStrings(self, num1: str, num2: str) -> str: i, j, carry, res = len(num1) - 1, len(num2) - 1, 0, '' while i >= 0 or j >= 0: a = num1[i] if i >= 0 else '0' b = num2[j] if j >= 0 else '0' r = ord(a) + ord(b) - 2 * ord('0') + carry carry = r // 10 r = r % 10 res = chr(r + 48) + res i -= 1 j -= 1 return '1' + res if carry else res
e685f94f8d6f8487e9941f875592b076e0120454
Preetham97/HousePricePrediction
/code.py
27,359
3.765625
4
#!/usr/bin/env python # coding: utf-8 # # Homework 3 - Ames Housing Dataset # For all parts below, answer all parts as shown in the Google document for Homework 3. Be sure to include both code that justifies your answer as well as text to answer the questions. We also ask that code be commented to make it easier to follow. # In[399]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction import FeatureHasher from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression, LinearRegression from sklearn.feature_extraction.text import CountVectorizer from sklearn import metrics from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import LabelEncoder from scipy.spatial.distance import squareform from scipy.spatial.distance import pdist from sklearn.linear_model import Ridge from sklearn.linear_model import RidgeCV plt.style.use('ggplot') # ## Part 1 - Pairwise Correlations # <font size="+1">Creating a "train" Dataframe which consists of data from train.csv.</font> # - <font size = "+1">filtering out 12 colomns from the train dataframe which I think are some of the most interesting variables.</font> # - <font size = "+1">Now, performing a pairwise pearson correlation on these variable </font> # In[400]: train = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\train.csv') train_1 = train.filter(['LotFrontage','LotArea','OverallQual','OverallCond','YearBuilt','BedroomAbvGr','TotRmsAbvGrd','Fireplaces ','GarageCars','GarageArea','OpenPorchSF','PoolArea','MiscVal','SalePrice']) plt.figure(figsize=(11,11)) sns.heatmap(train_1.corr(),vmin=-1,vmax=1,cmap='coolwarm',linewidths=0.2,annot=True); # ### Finding the most positive and negative correlations. # In[401]: c = train_1.corr() s = c.unstack() so = s.sort_values(kind="quicksort", ascending = False) print (so) # <font size="+1">From the above result and observing the HeatMap,</font> # - <font size="+1">3 Most Positively correlated pairs:-</font> # - <font size="+1">"Garage Cars, Garage Area": 0.882475</font> # - <font size="+1">"SalePrice, OverallQual" : 0.790982</font> # - <font size="+1">"SalePrice, GarageCars" : 0.676620</font> # - <font size="+1">3 Most Negitively correlated pairs:-</font> # - <font size="+1">"OverallCond, YearBuilt" : -0.375983</font> # - <font size="+1">"OverallCond, GarageCars" : -0.185758</font> # - <font size="+1">"GarageArea, OverallCond" : -0.151521</font> # ## Part 2 - Informative Plots # In[415]: # TODO: code to generate Plot 1 fig, axes = plt.subplots(1, 2,figsize=(14, 6)) train_1.groupby(['OverallQual']).mean()['SalePrice'].plot(kind="bar", ax=axes[0], title='OverallQual vs SalePrice') train.groupby(['OverallQual']).count()['Id'].plot(kind="bar", ax=axes[1], title='OverallQual vs No.of Houses') # <font size = "+1">What interesting properties does Plot 1 reveal?</font> # - <font size = "+1">From the above left bar graph we can observe that the sale price of the house increases as the OverallQuality of the material and finish of the house increases. But, if we observe the right side plot, the most sold houses have a overallquality around 5-7. From this we can infer that people are willing to compromise on the qualiity of materials used for Saleprice. </font> # # # In[414]: # TODO: code to generate Plot 2 plt.figure(figsize=(14, 6)) sns.lineplot(train['YrSold'],train['SalePrice']) # <font size = "+1">What interesting properties does Plot 2 reveal?</font> # - <font size = "+1"> From the above line plot we can observe that in 2008 there is a dip in the SalePrices of the houses in general. Also 2008 is the year in which recession hit the market. So, because of recession there is a dip in the sales prices of the houses. # In[413]: plt.figure(figsize=(14, 6)) sns.lineplot(train['GarageCars'],train['SalePrice']).set_title('Garage Cars vs SalePrice') # <font size = "+1">What interesting properties does Plot 3 reveal?</font> # - <font size = "+1"> From the above line plot we can see that there is a increase in price from GarageCars count 2 to GarageCars count 3 and suprisingly ther is a drop from GarageCars count 3 to GarageCars count 4. From this we can infer that people are more inclined in buying houses with Garage cars size 3 and hence the price for that 3. </font> # In[412]: # TODO: code to generate Plot 4 plt.figure(figsize=(14, 8)) sns.scatterplot(train['YearBuilt'],train['SalePrice']) # <font size = +1>What interesting properties does Plot 4 reveal?</font> # - <font size = +1> From the above scatter plot we can observe that the sale price of the houses is gradually increasing per year and also in the recent years count of the number of luxury houses built is also very high.</font> # In[420]: plt.figure(figsize=(14, 6)) train_1.groupby(['TotRmsAbvGrd']).mean()['SalePrice'].plot(kind="bar", title='TotRmsAbvGrd vs SalePrice') #train.groupby(['TotRmsAbvGrd']).count()['Id'].plot(kind="bar", ax=axes[1], title='OverallQual vs No.of Houses') # <font size = +1>What interesting properties does Plot 5 reveal?</font> # - <font size = +1>From the above graph we can observe that the Saleprice of houses increases as the total number of rooms increases. From this we can infer that total rooms count from 9 to 11 is in more demand and subsequently 12-14 are not in demand.</font> # In[421]: plt.figure(figsize=(14, 6)) sns.countplot(train['MoSold']).set_title('No. of Houses Sold Per Month') # <font size = +1>What interesting properties does Plot 6 reveal?</font> # - <font size = +1>From the above graph we can infer that during the months of may, june, july the number of houses sold if high when compared to the rest. From this we can say that during summers people are more interested in buying new houses this can be because in winters it gets extremely cold in Iowa.</font> # ## Part 3 - Handcrafted Scoring Function # - <font size = "+1">Creating a data frame "q3" and filtering only few features which I think are most interesting.</font> # - <font size = "+1">For the scoring Function to give meaningful results I am normalizing the values in all the colomns. Now values in all the colomns have scores from 0-10. The weightage of the each colomns is set to 1. So, the score of a particular house is going to be the summation of its feature's scores.And the house with the highest score is the most desirable house." </font> # In[422]: # TODO: code for scoring function q3 = train.filter(['LotFrontage','LotArea','LotShape','OverallQual','OverallCond','ExterQual','ExterCond','BsmtQual','BsmtCond','HeatingQC','BedroomAbvGr','Fireplaces','GarageCars','GarageArea','GarageQual','FireplaceQu','KitchenQual']) q3=q3.fillna(q3.median()) # In[423]: q3['Fireplaces']=q3['Fireplaces'].replace({0:0, 1:3.33,2:6.66,3:9.99}) q3['LotShape']=q3['LotShape'].replace({'Reg':10, 'IR1':7.5, 'IR2':5,'IR3':2.5}) q3['ExterQual']=q3['ExterQual'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2}) q3['ExterCond']=q3['ExterCond'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2}) q3['BsmtQual']=q3['BsmtQual'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2,'NA':0}) q3['BsmtCond']=q3['BsmtCond'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2,'NA':0}) q3['HeatingQC']=q3['HeatingQC'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2}) q3['GarageCars']=q3['GarageCars'].replace({0:2, 1:4,2:6,3:8,4:10}) q3['GarageQual']=q3['GarageQual'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2, 'NA':0}) q3['KitchenQual']=q3['KitchenQual'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2}) q3['FireplaceQu']=q3['FireplaceQu'].replace({'Ex':10, 'Gd':8, 'TA':6,'Fa':4,'Po':2}) # In[424]: q3=q3.fillna(0) # In[425]: mask = (q3['LotFrontage'] > 60.0) & (q3['LotFrontage'] <= 69.0) q3['LotFrontage'][mask] = 5 mask = (q3['LotFrontage'] <= 60.0) q3['LotFrontage'][mask] = 2.5 mask = (q3['LotFrontage'] > 69.0) & (q3['LotFrontage'] <= 79.0) q3['LotFrontage'][mask] = 7.5 mask = (q3['LotFrontage'] > 79.0) q3['LotFrontage'][mask] = 10 mask = (q3['LotArea'] <= 7553.500000) q3['LotArea'][mask] = 2.5 mask = (q3['LotArea'] > 7553.500000) & (q3['LotArea'] <= 9478.500000) q3['LotArea'][mask] = 5 mask = (q3['LotArea'] > 9478.500000) & (q3['LotArea'] <= 11601.500000) q3['LotArea'][mask] = 7.5 mask = (q3['LotArea'] > 11601.500000) q3['LotArea'][mask] = 10 mask = (q3['GarageArea'] <= 334.500000) q3['GarageArea'][mask] = 2.5 mask = (q3['GarageArea'] > 334.500000) & (q3['GarageArea'] <= 480.000000) q3['GarageArea'][mask] = 5 mask = (q3['GarageArea'] > 480.000000) & (q3['GarageArea'] <= 576.000000) q3['GarageArea'][mask] = 7.5 mask = (q3['GarageArea'] > 576.000000) q3['GarageArea'][mask] = 10 # In[426]: scores = q3.sum(axis = 1, skipna = True) # In[427]: answer = pd.DataFrame(scores) # In[428]: answer['score'] = pd.DataFrame(scores) # ### Distplot of the scores obtained for the houses. # In[453]: plt.figure(figsize=(9, 6)) sns.distplot(answer['score']) # In[431]: HouseID = train.filter(['Id']) HouseID = HouseID.join(answer['score']) # In[432]: HouseID['score'].corr(train['SalePrice']) #finding correlation between scoring function and SalePrice # In[433]: HouseID = HouseID.sort_values('score',ascending = False) # ### 10 Most Desirable Houses # In[434]: HouseID.head(10) # In[435]: HouseID = HouseID.sort_values('score') # ### 10 Least Desirable Houses # In[436]: HouseID.head(10) # <font size = "+1">What is the ten most desirable houses?</font> # - <font size = "+1">The following are the Id's of houses with highest scores from the scoring function</font> # - <font size = "+1">692, 799, 310, 441, 390, 225, 186, 1244, 279, 12</font> # <font size = "+1">What is the ten least desirable houses?</font> # - <font size = "+1">The following are the Id's of houses with lowest scores from the scoring function</font> # - <font size = "+1">534, 376, 40, 706, 1219, 637, 251, 1322, 1326, 89</font> # <font size = "+1">Describe your scoring function and how well you think it worked.</font> # - <font size = "+1"> In order to know if the scoring function is giving good results or not we can find the correlation between scores of all the houses and the salesprice of the houses. If there is a high positive correlation between those two colomns we can conclude that the scoring function is giving good results.</font> # - <font size = "+1"> Correlation obtained: 0.8049</font> # - <font size = "+1">Also, the distplot of scores is similar to Guassian Distribution. So, we can assume that the scores obtained by the handcrafted scoring function are good. </font> # ## Part 4 - Pairwise Distance Function # In[151]: # TODO: code for distance function q4 = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\train.csv') # In[152]: q4 = q4.fillna(q4.median()) q4 = q4.fillna('not avilable') # In[159]: res = pdist(q4, 'euclidean') result = squareform(res) # In[165]: print(result) # <font size = "+1">How well does the distance function work? When does it do well/badly?</font> # <font size = "+1"> computed a result (1460 x 1460) matrix in which result[i][j] of a matrix will give pair wise distance between the houses i and j. If the result[i][j] is less then it implies that both the houses are very similar to each other and will yield a similar sale price given that most of their attributes match closely.</font> # # <font size = "+1">It performs well(less pair wise distance) for the houses in same cluster and has a higher pairwise distance for the houses in different clusters. </font> # ## Part 5 - Clustering # In[509]: le = LabelEncoder() q5 = train q5 = q5.drop(['Id'], 1) q5 = q5.drop(['Alley'], 1) q5 = q5.drop(['PoolQC'], 1) q5 = q5.drop(['Fence'], 1) q5 = q5.drop(['MiscFeature'], 1) q5 = q5.drop(['Neighborhood'], 1) q5 = q5.fillna(q5.median()) q5 = q5.fillna('not avilable') q5 = q5.apply(le.fit_transform) # In[510]: from sklearn.decomposition import PCA pca = PCA(n_components=50) pca_result = pca.fit_transform(q5) # In[511]: import time from sklearn.manifold import TSNE tsne = TSNE(n_components=2, verbose=1, perplexity=100, n_iter=1000) tsne_results = tsne.fit_transform(pca_result) # In[512]: res = pdist(tsne_results, 'cosine') result = squareform(res) # In[437]: #plt.scatter(tsne_results[:,0], tsne_results[:,1]) # In[513]: # TODO: code for clustering and visualization #use dist matrix from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=8) kmeans.fit(result) plt.figure(figsize=(12, 6)) plt.scatter(tsne_results[:,0], tsne_results[:,1], c=kmeans.labels_, cmap='rainbow') # In[516]: coord_data = pd.DataFrame(tsne_results,columns=["pca-one","pca-two"]) coord_data["clusters"] = pd.Series(kmeans.labels_) coord_data["Neighborhood"] = train["Neighborhood"] # In[551]: # fig = plt.figure(figsize=(30,15)) # ax = fig.add_subplot(111) # ax = sns.countplot(x="Neighborhood", hue="clusters", data=coord_data) # In[552]: fig = plt.figure(figsize=(30,15)) ax = sns.countplot(x="Neighborhood", hue="clusters", data=coord_data,order=coord_data.Neighborhood.value_counts().iloc[:9].index) # <font size = +1>How well do the clusters reflect neighborhood boundaries? Write a discussion on what your clusters capture and how well they work.</font> # # <font size = +1>I am reducing the dimensions of the original dataframe from 80(Neighborhood is dropped at the beginning) to 50 columns using PCA and then reducing the dimensions even further using t-distributed Stochastic Neighbor Embedding (TSNE). I'm calculating the eucledian distance of each columns for each houses and plotted the clusters using kmeans cluster. The boundaries between the different clusters are visible and only very few of the houses in borders are colliding. So, we can say that the clusters have good boundaries and the clustering function was good.</font> # ## Part 6 - Linear Regression # <font size = +1>Creating a dataframe "q6" from train.csv and filtering only 17 colomns which I think are interesting. And then cleaned the data by filling Nan Values with median and 'not available' for numerical features and categorical features respectively.Then, label encoded on caterogical values and convreted them into numerical. Finally, performed linear regression on the data.</font> # In[365]: # TODO: code for linear regression Y = train.filter(['SalePrice']) # In[366]: q6 = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\train.csv') # In[367]: q6 = q6.filter(['LotFrontage','LotArea','LotShape','OverallQual','OverallCond','ExterQual','ExterCond','BsmtQual','BsmtCond','HeatingQC','BedroomAbvGr','Fireplaces','GarageCars','GarageArea','GarageQual','FireplaceQu','KitchenQual']) # In[368]: le = LabelEncoder() q6 = q6.fillna(q6.median()) q6 = q6.fillna('not avilable') q6 = q6.apply(le.fit_transform) # In[369]: feature,result = q6.loc[:,q6.columns != 'SalePrice'], Y.loc[:,'SalePrice'] X_train, X_test, y_train, y_test = train_test_split(feature,result, test_size=0.2) lm = LinearRegression().fit(X_train,y_train) y_pred = lm.predict(X_test) # ###### rmse obtained for log(saleprice): 0.2069 # In[370]: rmse = np.sqrt(metrics.mean_squared_error(np.log(y_test), np.log(y_pred))) print('Root Mean Squared Error:'+str(rmse)) # In[371]: def plot_top_coefficients(model, top_n = 10): cols = X_train.columns coef = model.coef_ zipped = list(zip(cols, coef)) zipped.sort(key=lambda x: x[1], reverse = True) top_coefficients = pd.DataFrame(zipped).head(top_n).sort_values(1) bottom_coefficients = pd.DataFrame(zipped).tail(top_n).sort_values(1,ascending=True) combined = pd.concat([bottom_coefficients,top_coefficients], axis=0) combined.columns = ['Feature', 'Coefficient'] return combined # In[372]: plt.figure(figsize=(9, 6)) combined= plot_top_coefficients(lm, 5) ax = sns.barplot(x='Coefficient', y='Feature', data=combined) plt.show() # <font size = "+1">How well/badly does it work? Which are the most important variables?</font> # - <font size = "+1">Inorder to check wether the model performed well/bad I calculated the RMSE value of log(saleprice) and got a value of 0.2069. I consider this a good score because I have taken only 17 columns and still got a score of 0.2069.</font> # - <font size = "+1">To find the most important varibles I drew a plot which contains top 5 variables with highest coefficients for prediction.</font> # - <font size = "+1">OverallQual</font> # - <font size = "+1">Fireplaces</font> # - <font size = "+1">GarageCars</font> # - <font size = "+1">BedroomAbvGr</font> # - <font size = "+1">OverallCond</font> # # ## Part 7 - External Dataset # In[628]: # TODO: code to import external dataset and test x = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\inflation.csv') q7 =pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\train.csv') def getYear(a): for i in range(len(a)): a[i] = int(a[i][0:4]) return a a=x['date'].to_list() x['YrSold'] = getYear(a) x.drop(['date'], axis=1, inplace=True) final= pd.merge(q7, x, on='YrSold') #final.sample(5) # In[629]: Y7 = train.filter(['SalePrice']) Y7 = np.log(Y7) # final = final.drop(['Id'], 1) # final = final.drop(['Alley'], 1) # final = final.drop(['PoolQC'], 1) # final = final.drop(['Fence'], 1) # final = final.drop(['MiscFeature'], 1) le = LabelEncoder() final = final.fillna(final.median()) final = final.fillna('not avilable') final = final.apply(le.fit_transform) # In[632]: feature,result = final.loc[:,final.columns != 'SalePrice'], Y7.loc[:,'SalePrice'] X_train, X_test, y_train, y_test = train_test_split(feature,result, test_size=0.3) # alphas = np.logspace(-6,9,12) # ridgecv = RidgeCV(alphas=alphas) # ridgecv.fit(X_train,y_train) # ridgecv_pred = ridgecv.predict(X_test) lm = LinearRegression().fit(X_train,y_train) y_pred = lm.predict(X_test) rmse = np.sqrt(metrics.mean_squared_error(y_test, y_pred)) print('Root Mean Squared Error:'+str(rmse)) # ridgereg = Ridge(alpha=0.6, normalize=True) # ridgereg.fit(X_train,y_train) # ridge_pred = ridgereg.predict(X_test) # <font size = +1>Describe the dataset and whether this data helps with prediction.</font> # - <font size = +1> External DataSet: # Although the given data is enough to accurately determine the saleprice with a RMSE of 0.134 some other external data sets such as crime rate at a location or a particular climate or vicinity to big cities and increasing land prices per year have an impact on determining the House sale price.</font> # # - <font size = +1>In the imported data I have date into year sold by passing it into the get year method. and then I am merging the newly converted data with my original data.</font> # # - <font size = +1>I have used the inflation values of a particular land price to determine a house price because the land cost has a huge influence on determining the house price from this link https://www.macrotrends.net/2497/historical-inflation-rate-by-year. By merging the two data sets, I calculated the RMSE value using the ridgeprediction and got a RMSE value of 0.129 # Although not by much this data set improves the accuracy by a small margin. So, there can be other external data sets which can be integrated with the current data to further improve the accuracy. </font> # ## Part 8 - Permutation Test # <font size = +1>Creating a q8 dataframe and cleaning all the NaN values and then label encoding on the data frame.</font> # - <font size = +1> Taking a list 'columns' with 5 good variables and 5 meaningless variables</font> # In[545]: q8 = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\train.csv') # In[546]: # TODO: code for all permutation tests le = LabelEncoder() result = q8.filter(['SalePrice']) #variable = q8.filter(['OverallCond']) q8 = q8.fillna(q8.median()) q8 = q8.fillna('not available') q8 = q8.apply(le.fit_transform) #fig = plt.figure(figsize=(8,8)) # In[547]: columns = ['YearRemodAdd','TotRmsAbvGrd','YearBuilt','GarageCars','GarageArea','YrSold','MSSubClass','OverallCond','MiscVal','Condition2'] # <font size = +1>Calculating the pvalue and rmse scores for each of the 10 variables.</font> # - <font size = +1>Plotting the rmse val of the original variable and rsme values of its permuted list(doing 100 permutations)</font> # - <font size = +1>For good variables we are expecting to see a p val very less(i.e line of p-val in the plot will be on the left most side). For meaningless variables we are expecting to see a pval higher(i.e line of p-val in the plot will be somewhere in between the scores).</font> # In[548]: from sklearn.model_selection import permutation_test_score from sklearn.metrics import make_scorer def rmsle(true, pred): #true, pred = np.exp(true), np.exp(pred) return -np.sqrt(metrics.mean_squared_error(np.log(true), np.log(pred))) for param in list(columns): variable = q8.filter([param]) X_train, X_test, y_train, y_test = train_test_split(variable,result, test_size=0.2) lm = LinearRegression()#.fit(X_train,y_train) rmsle_score = make_scorer(rmsle, greater_is_better=False) score, permutation_scores, pvalue = permutation_test_score(lm, X_train, y_train,scoring = rmsle_score,cv=3, n_permutations=100, n_jobs=1) #print(pvalue) #print(score) plt.hist(permutation_scores, 20, label='Permutation scores', edgecolor='black') ylim = plt.ylim() plt.plot(2 * [score], ylim, '--g', linewidth=3, label='Classification Score' ' (pvalue %s)' % pvalue) # plt.plot(2 * [1. / n_classes], ylim, '--k', linewidth=3, label='Luck') #fig = plt.figure(figsize=(12,8)) plt.ylim(ylim) plt.legend() plt.xlabel('Score') plt.show() # - <font size = +1>For Columns which had high co-relation value we can see that the RMSE value for shuffled cases is much higher than the original RMSE value implying that this value when altered/shuffled will impact the error in predicting the sale price.</font> # # - <font size = +1>For columns which had low co-relation we can see that the RMSE value for shuffled cases doesn't vary that much compared to the original RMSE values implying that in this case even altering the values wouldn't much impact in predicting the sale price.</font> # ## Part 9 - Prediction Model # - <font size = "+1">Reading the train.csv into a data frame and naming it "q9". Now, dropping 4 colomns which have more than 95% NaN values, they are 'Alley', 'PoolQC', 'Fence', 'MiscFeature'. Also dropping the 'Id' field as it doesnt have any affect on the predictions.</font> # - <font size = "+1">Creating a dataframe Y9 with only one colomn 'SalePrice'.</font> # - <font size = "+1">In the "q9" dataframe, for numerical features, if there is a Nan value replacing it with median.</font> # - <font size = "+1">In the "q9" dataframe, for cateforical features, if there is a Nan value replacing it with 'not available' </font> # - <font size = "+1">In my dataframe all the Nan Values are removed. Now, I am performing LabelEnconding on categorical features and converting them into numerical types.</font> # # In[601]: Y9 = train.filter(['SalePrice']) Y9 = np.log(Y9) # In[602]: q9 = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\train.csv') q9 = q9.drop(['Id'], 1) q9 = q9.drop(['Alley'], 1) q9 = q9.drop(['PoolQC'], 1) q9 = q9.drop(['Fence'], 1) q9 = q9.drop(['MiscFeature'], 1) le = LabelEncoder() q9 = q9.fillna(q9.median()) q9 = q9.fillna('not avilable') q9 = q9.apply(le.fit_transform) feature,result = q9.loc[:,q9.columns != 'SalePrice'], Y9.loc[:,'SalePrice'] # - <font size = "+1">Splitting the train and test data into 80:20 ratio.</font> # - <font size = "+1">Using RidgeCV regression with np.logspace(-6,9,12) and predicting the sales price into reidgecv_pred using X_test</font> # - <font size = "+1"> Finally calculating RMSE value.</font> # In[603]: #Y9 = train.filter(['SalePrice']) X_train, X_test, y_train, y_test = train_test_split(feature,result, test_size=0.2) #lm = LinearRegression().fit(X_train,y_train) #y_pred = lm.predict(X_test) alphas = np.logspace(-6,9,12) ridgecv = RidgeCV(alphas=alphas) # ridgereg = Ridge(alpha=0.6, normalize=True) # ridgereg.fit(X_train,y_train) # ridge_pred = ridgereg.predict(X_test) ridgecv.fit(X_train,y_train) ridgecv_pred = ridgecv.predict(X_test) # #### RMSE of log(salePrice): 0.134 # In[604]: rmse = np.sqrt(metrics.mean_squared_error(y_test, ridgecv_pred)) print('Root Mean Squared Error:'+str(rmse)) # - <font size = "+1"> Reading the test.csv into a new dataframe "test9". Now, dropping 4 colomns which have more than 95% NaN values, they are 'Alley', 'PoolQC', 'Fence', 'MiscFeature'. Also dropping the 'Id' field as it doesnt have any affect on the predictions.</font> # - <font size = "+1">In the "test9" dataframe, for numerical features, if there is a Nan value replacing it with median.</font> # - <font size = "+1">In the "test9" dataframe, for cateforical features, if there is a Nan value replacing it with 'not available' </font> # - <font size = "+1">In my dataframe all the Nan Values are removed. Now, I am performing LabelEnconding on categorical features and converting them into numerical types.</font> # - <font size = "+1"> Storing the results into res_pred using ridgecv.predict on "test9"</font> # In[314]: test9 = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\test.csv') test9 = test9.drop(['Id'], 1) test9 = test9.drop(['Alley'], 1) test9 = test9.drop(['PoolQC'], 1) test9 = test9.drop(['Fence'], 1) test9 = test9.drop(['MiscFeature'], 1) le = LabelEncoder() test9 = test9.fillna(test9.median()) test9 = test9.fillna('not avilable') test9 = test9.apply(le.fit_transform) #res_pred = lm.predict(test9) #res_pred = ridgereg.predict(test9) res_pred = ridgecv.predict(test9) # - <font size = "+1"> Creating a dataframe with 2 colomns. First colomn is Id ad second is the predicted SalePrice.</font> # - <font size = "+1"> Converting the data into CSV and uploading it on KAGGLE!</font> # # In[315]: test_9 = pd.read_csv(r'C:\Users\preet\Desktop\house-prices-advanced-regression-techniques\test.csv') res9 = pd.DataFrame() res9['Id'] = test_9['Id'] res9['SalePrice'] = np.exp(res_pred) res9.to_csv('ridgeCV_3.csv', index=False) # ## Part 10 - Final Result # Report the rank, score, number of entries, for your highest rank. Include a snapshot of your best score on the leaderboard as confirmation. Be sure to provide a link to your Kaggle profile. Make sure to include a screenshot of your ranking. Make sure your profile includes your face and affiliation with SBU. # Kaggle Link: https://www.kaggle.com/preetham17 # Highest Rank: 1635 # Kaggle Score: 0.12751 # Number of entries: 8 # INCLUDE IMAGE OF YOUR KAGGLE RANKING ![Screenshot%20%2811%29.png](attachment:Screenshot%20%2811%29.png)
d52f908fadff7db9ca77c75875cb47922296d3dd
anantkaushik/Competitive_Programming
/Python/GeeksforGeeks/facing-the-sun.py
1,238
4.09375
4
""" Problem Link: https://practice.geeksforgeeks.org/problems/facing-the-sun/0 Monu lives in a society which is having high rise buildings. This is the time of sunrise and monu wants see the buildings receiving the sunlight. Help him in counting the number of buildings recieving the sunlight. Given an array H representing heights of buildings. You have to count the buildings which will see the sunrise (Assume : Sun rise on the side of array starting point). Input: The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N, N is the number of buildings. The second line of each test case contains N input H[i], height of ith building. Output: Print the total number of buildings which will see the sunset. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 106 1 ≤ Hi ≤ 108 Example: Input: 2 5 7 4 8 2 9 4 2 3 4 5 Output: 3 4 Explanation: Testcase 1: Building with height 7, 8 and 9 will recieve the sunlight during sunrise. """ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) maxx = arr[0] count = 1 for i in range(1,n): if arr[i] > maxx: maxx = arr[i] count += 1 print(count)
4b476354bde1d2228f005af90889f7bb75d92fa2
wartrax13/exerciciospython
/Lista de Exercícios PYTHON BR/EstruturadeRepetição/26 - EtruturadeRepetição.py
1,082
4.03125
4
''' Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato. ''' A = [] B = [] C = [] eleitores = int(input('Quantos eleitores há? ')) print('-------------------------') for x in range(eleitores): voto = int(input('Qual seu voto?\n' '[1] A\n' '[2] B\n' '[3] C\n')) if voto == 1: A.append(voto) print('Você votou no candidato A') print('-------------------------') elif voto == 2: B.append(voto) print('Você votou no candidato B') print('-------------------------') elif voto == 3: C.append(voto) print('Você votou no candidato C') print('-------------------------') else: print('Você votou errado. Perdeu.') print('-------------------------') print(f'O candidato A teve {len(A)} votos\n' f'O candidato B teve {len(B)} votos\n' f'O candidato C teve {len(C)} votos')
fe8a93634f25e83f01951ebc52f22d9c3674e8fb
TaniaHernandezB/Week2
/medium.py
560
4.1875
4
number = int(input("Number: ")) if number == (1): print("January") elif number == (2): print("February") elif number == (3): print("March") elif number == (4): print('April') elif number == (5): print("May") elif number == (6): print("June") elif number == (7): print('July') elif number == (8): print('August') elif number == (9): print('September') elif number == (10): print('October') elif number == (11): print('November') elif number == (12): print('December') else: print('Invalid number: Number must be between 1 and 12')
56e2e6577474b3e58d3b3932cff056204efbd7f8
Srinath619/Shady
/proofdiag.py
173
3.765625
4
def uniq(string): a=[] for i in range(len(string)): if string[i] in a: continue a.append(string[i]) print(''.join(a)) def main(): str=input() uniq(str) main()
91c961c181bd35d9f32e2b0d500d21b0d1a35c6e
Luo-Kaiyi/Python-Learning
/7-9 熟食店牛肉卖完了.py
453
3.765625
4
food_order = ['鸡爪','鸭爪','鸡翅','鸭翅','鸡腿','牛肉'] print("牛肉卖完了!") finished_order = [] while food_order: food = food_order.pop() if food != '牛肉': print("给你一个" + food) finished_order.append(food) else: print("不好意思,牛肉已经卖完了!") print("现在,你有这些熟食了:") while finished_order: food = finished_order.pop() print(food)
56ffc71dbbf6101991c7ed2f6de97c7154ac1d56
unclebay143/UserApp
/login.py
1,192
3.5625
4
import dashboard import recover_password # login function def login_area(name, username, phone, email, password, security_pin, security_question): print("\n LOGIN AREA ") user_name_attempt = input("Enter Username: ") password_attempt = input("Enter Password: ") if user_name_attempt == username and password_attempt == password: print("Logged in as " + username.upper()) dashboard.profile(name, username, phone, email, password, security_pin, security_question) # return password elif user_name_attempt == username and password_attempt != password: print("\nUsername " + username.upper() + " Found but " + password_attempt + " did not match") print("\nDid you forgot your password? Press F") confirm_forgot = input("") if confirm_forgot.lower() == "f": recover_password.confirm_user(name, username, phone, email, password, security_pin, security_question) login_area(name, username, phone, email, password, security_pin, security_question) else: print("\nThose entries doesn't make sense") login_area(name, username, phone, email, password, security_pin, security_question)
3cf6aa6dc8f8e7938c7c29ecba86cef75190d081
GregoryMNeal/Digital-Crafts-Class-Exercises
/Python/Snippets/Formatted_Print_using_keywords.py
262
4.21875
4
print("____(name)____'s favorite person in the whole world is ____(person)____") name = input("What is name? ") person = input("Who is their favorite person? ") print("{name}'s favorite person in the whole world is {person}.".format(name=name, person=person))
2b4e2965b0b3ceaadabc21920bf8cadcb451f7d9
theadamsacademy/python_tutorial_for_beginners
/08_operators/rule_1_precedence.py
272
3.96875
4
# () # *, / # +, - # <, <=, >, >=, !=, == # not # and # or # Highest precedence at top, lowest at bottom. # Operators in the same line evaluate left to right. # a + b * c # 1 + 2 * 3 a = 1 b = 2 c = 3 print("a + b * c =", a + b * c) print("(a + b) * c =", (a + b) * c)
e6058b96ed0df45ca4d43dc656f946efebc72ecf
IsaacNewLee/IndividualIcomeTax
/tax_calculation.py
1,819
3.84375
4
# coding=utf-8 def calculator(salary): """ 税后工资计算器:2019年新税率个人所得税计算器,各地区五险一金比例有差异 """ point = 5000 yanglao_rate = 0.08 hospital_rate = 0.02 unemployment_rate = 0.005 housing_money_rate = 0.12 five_one_money = salary * (yanglao_rate + hospital_rate + unemployment_rate + housing_money_rate) housing_money = salary * housing_money_rate rest_money = salary - five_one_money - point res_money = salary - five_one_money if rest_money <= 0: tax_money = 0 rest_money -= tax_money elif rest_money <= 1500: tax_money = rest_money * 0.03 res_money -= tax_money elif 1500 < rest_money <= 4500: tax_money = rest_money * 0.1 res_money -= (tax_money - 105) elif 4500 < rest_money <= 9000: tax_money = rest_money * 0.2 res_money -= (tax_money - 555) elif 9000 < rest_money <= 35000: tax_money = rest_money * 0.25 res_money -= (tax_money - 1005) elif 35000 < rest_money <= 55000: tax_money = rest_money * 0.3 res_money -= (tax_money - 2755) elif 55000 < rest_money <= 80000: tax_money = rest_money * 0.35 res_money -= (tax_money - 5505) else: tax_money = rest_money * 0.45 res_money -= (tax_money - 13505) print('税前工资为:{0},税后工资为:{1},五险一金:{2},缴税:{3},住房公积金:{4}'.format(salary, res_money, five_one_money, tax_money, housing_money)) if __name__ == '__main__': # calculator(one_salary) salary_list = [7000, 8000, 10000, 14000, 15000, 16000, 18000, 25000, 80000, 100000] for one_salary in salary_list: calculator(one_salary)
08259d76c944e02bbc78e072e8949968225cc295
sophialuo/CrackingTheCodingInterview_6thEdition
/17.21.py
1,355
4
4
''' 17.21 Volume of Histogram: Imagine a histogram (bar graph). Design an algorithm to compute the volume of water it could hold if someone poured water across the top. You can assume that each historgram bar has width 1. EXAMPLE Input: 0, 0, 4, 0, 0, 6, 0, 0, 3, 0, 5, 0, 1, 0, 0, 0} Output: 26 ''' def volume_of_histograms(lst): prevBiggest, nextBiggest = [], [] cur_biggest = 0 for i in range(len(lst)): if lst[i] != 0: prevBiggest.append(cur_biggest) cur_biggest = max(cur_biggest, lst[i]) else: prevBiggest.append(0) nextBiggest.append(0) cur_biggest = 0 for i in range(len(lst)-1, -1, -1): if lst[i] != 0: nextBiggest[i] = cur_biggest cur_biggest = max(cur_biggest, lst[i]) for i in range(len(lst)): if lst[i] != 0 and lst[i] < prevBiggest[i] and lst[i] < nextBiggest[i]: lst[i] = -lst[i] total = 0 cur_num = 0 counter = 0 index = 0 while index < len(lst): if lst[index] < 0: total += lst[index] if lst[index] != 0 and cur_num == 0: cur_num = lst[index] elif lst[index] > 0: total += min(lst[index], cur_num)*counter counter = 0 cur_num = lst[index] elif lst[index] <= 0 and cur_num > 0: counter += 1 index += 1 return total lst = [0, 0, 4, 0, 0, 6, 0, 0, 3, 1, 0, 5, 0, 1, 0, 0, 0] print(volume_of_histograms(lst))
a786bea79a82e245cb0d198b7154032f93420898
Ryuodan/PPT-to-PDF-Converter
/PPT-to-PDF.py
594
3.890625
4
'''Author : Ryuodan''' import win32com.client def PPT_to_PDF(infile_path, outfile_path): '''convert from PPT to PDF file format''' powerpoint = win32com.client.Dispatch("Powerpoint.Application") pdf = powerpoint.Presentations.Open(infile_path, WithWindow=False) pdf.SaveAs(outfile_path, 32) pdf.Close() powerpoint.Quit() if __name__ == "__main__": path_of_inputfile = 'test.ppt' path_of_outputfile = 'test.pdf' print(f'Converting {path_of_inputfile} to {path_of_outputfile}') PPT_to_PDF(infile_path=path_of_inputfile, outfile_path=path_of_outputfile)
711061412adc6cc5927968337a42828d12bbd8e8
AnandD007/Amazing-Python-Scripts
/Songs-By-Artist/songs_of_artist.py
2,866
3.5625
4
import pandas as pd import spotipy import config # To access authorised Spotify data from spotipy.oauth2 import SpotifyClientCredentials client_id = config.client_id client_secret = config.secret_key client_credentials_manager = SpotifyClientCredentials( client_id=client_id, client_secret=client_secret) # spotify object to access API sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager) name = input("Enter Artist Name: ") # chosen artist result = sp.search(name) # search query artist_uri = '' for row in result['tracks']['items'][0]['artists']: if name.lower() in row['name'].lower(): artist_uri = row['uri'] break # Pull all of the artist's albums sp_albums = sp.artist_albums(artist_uri, album_type='album') # Store artist's albums' names' and uris in separate lists album_names = [] album_uris = [] for i in range(len(sp_albums['items'])): album_names.append(sp_albums['items'][i]['name']) album_uris.append(sp_albums['items'][i]['uri']) def albumSongs(uri): album = uri # assign album uri to a_name spotify_albums[album] = {} # Creates dictionary for that specific album # Create keys-values of empty lists inside nested dictionary for album spotify_albums[album]['album'] = [] # create empty list spotify_albums[album]['track_number'] = [] spotify_albums[album]['id'] = [] spotify_albums[album]['name'] = [] spotify_albums[album]['uri'] = [] tracks = sp.album_tracks(album) # pull data on album tracks for n in range(len(tracks['items'])): # for each song track # append album name tracked via album_count spotify_albums[album]['album'].append(album_names[album_count]) spotify_albums[album]['track_number'].append( tracks['items'][n]['track_number']) spotify_albums[album]['id'].append(tracks['items'][n]['id']) spotify_albums[album]['name'].append(tracks['items'][n]['name']) spotify_albums[album]['uri'].append(tracks['items'][n]['uri']) spotify_albums = {} album_count = 0 for i in album_uris: # each album albumSongs(i) album_count += 1 # Updates album count once all tracks have been added def popularity(album): spotify_albums[album]['popularity'] = [] track_count = 0 for track in spotify_albums[album]['uri']: pop = sp.track(track) spotify_albums[album]['popularity'].append(pop['popularity']) track_count += 1 for i in spotify_albums: popularity(i) dic_df = {} dic_df['name'] = [] dic_df['popularity'] = [] for album in spotify_albums: for feature in ['name', 'popularity']: dic_df[feature].extend(spotify_albums[album][feature]) df = pd.DataFrame.from_dict(dic_df) final_df = df.sort_values('popularity', ascending=False) pd.set_option("display.max_rows", None, "display.max_columns", None) print(final_df)
4252c9c5da34e3b81630a6aeb266d281c3762ce3
suhasv13/addition
/add.py
137
4.03125
4
#sum of two numbers a=int(input("enter the first number ")) b=int(input("enter the second number ")) sum=a+b print("THe sum is ",sum)
6580c2d450a8ec5070e3de9baba8ac91e0f4eea3
leebaek/TIL
/python/write_txt.py
557
3.5
4
# Write File # 1. open() f = open('mulcam.txt', 'w') # 'w' : write, 'r' : read, 'a' : append # for i in range(10): # f.write(f'Hello, Mulcam! {i}\n') # f.close() # 2. with open() # with open('mulcam.txt', 'w') as f: # f.write('Hello, Mulcam!\n') # 2-1. writelines with open('mulcam.txt', 'w') as f: f.writelines(['1\n', '2\n', '3\n']) # with : Context Manager # \로 시작하는 문자 -> 이스케이프 시퀀스(문자) # \n : 개행 문자 # \t : tab 문자 # \\ : 역슬래쉬 문자 # \' : 따옴표 문자 # \" : 쌍따옴표 문자
f680f5deb0653aa00c080a84d992f8bacb58d6d0
StRobertCHSCS/ics2o1-201819-igothackked
/unit_2/2_6_4_while_loops.py
276
4.34375
4
numerator = int(input("Enter a numerator: ")) denominator = int(input("Enter denominator: ")) if numerator // denominator : print("Divides evenly!") else: print("Doesn't divide evenly.") while denominator == 0: denominator = int(input("Enter denominator: "))
ec03b3cfe78b72958fcf89f0cdf9e97e0babc53e
moontree/leetcode
/version1/920_Number_of_Music_Playlists.py
2,763
3.875
4
""" Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip. You create a playlist so that: Every song is played at least once A song can only be played again only if K other songs have been played Return the number of possible playlists. As the answer can be very large, return it modulo 10^9 + 7. Example 1: Input: N = 3, L = 3, K = 1 Output: 6 Explanation: There are 6 possible playlists. [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]. Example 2: Input: N = 2, L = 3, K = 0 Output: 6 Explanation: There are 6 possible playlists. [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], [1, 2, 2] Example 3: Input: N = 2, L = 3, K = 1 Output: 2 Explanation: There are 2 possible playlists. [1, 2, 1], [2, 1, 2] Note: 0 <= K < N <= L <= 100 """ class Solution(object): def numMusicPlaylists(self, N, L, K): """ :type N: int :type L: int :type K: int :rtype: int """ base = 10 ** 9 + 7 def helper(n): res = 1 for i in range(2, n + 1): res = (res * i) % base return res cache = {} def count(N, L): if N == L: return helper(N) elif N == K: return 0 elif N < K: return 0 else: if (N, L) not in cache: if (N, L - 1) not in cache: cache[(N, L - 1)] = count(N, L - 1) if (N - 1, L - 1) not in cache: cache[(N - 1, L - 1)] = count(N - 1, L - 1) cache[(N, L)] = (cache[(N, L - 1)] * (N - K) + cache[(N - 1, L - 1)] * N) % base return cache[(N, L)] return count(N, L) examples = [ { "input": { "N": 3, "L": 3, "K": 1 }, "output": 6 }, { "input": { "N": 2, "L": 3, "K": 0 }, "output": 6 }, { "input": { "N": 2, "L": 3, "K": 1 }, "output": 2 }, { "input": { "N": 37, "L": 50, "K": 8 }, "output": 32125759 } ] import time if __name__ == '__main__': solution = Solution() for n in dir(solution): if not n.startswith('__'): func = getattr(solution, n) print(func) for example in examples: print '----------' start = time.time() v = func(**example['input']) end = time.time() print v, v == example['output'], end - start
ae00b5a28d57f57c71ccae7cdc9ccc822ca24e35
jakehoare/leetcode
/python_1_to_1000/347_Top_K_Frequent_Elements.py
952
3.75
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/top-k-frequent-elements/ # Given a non-empty array of integers, return the k most frequent elements. # Count the frequency of each element. Bucket sort the elements by frequency since the highest frequency cannot be # more than the length of nums. Take the most frequent buckets, ties are split randomly. # Time - O(n) # Space - O(n) from collections import Counter class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ n = len(nums) frequencies = [[] for _ in range(n + 1)] for num, freq in Counter(nums).items(): frequencies[freq].append(num) top_k = [] while k: while not frequencies[n]: n -= 1 top_k.append(frequencies[n].pop()) k -= 1 return top_k
289723e4f22489ff9c92d042643d2cfd42957cc4
GTxx/leetcode
/algorithms/1408. String Matching in an Array/python/solution.py
506
3.765625
4
from typing import List class Solution: def stringMatching(self, words: List[str]) -> List[str]: words.sort(key=lambda word: len(word)) res = [] for idx, word in enumerate(words): for word1 in words[idx+1:]: if word in word1: print(word, word1) res.append(word) break return res if __name__ == "__main__": s = Solution() s.stringMatching(["mass","as","hero","superhero"])
8f0d308f53670d2d5d0f8837de9fdd155a700362
nhanthien1504/bai_tap_buoi_7
/07.py
12,650
4.21875
4
''' Thực hiện code lại hàm sau và cho biết ý nghĩa của nó def enter_data(): while True: n = input("Nhập 1 số nguyên: ") if n.isnumeric(): n = int(n) if n > 0: print("Đã nhập số dương") return n print("Đã nhập số không dương. Chương trình sẽ tiếp tục!") else: print("Dữ liệu đã nhập không phải số nguyên") ''' # def enter_data(): # khai báo tên hàm # while True: # tạo vòng lặp while True # n = input("Nhập 1 số nguyên: ") # nhập số từ bàn phím # if n.isnumeric(): # điều kiện True or False nếu là số # n = int(n) # thực hiện ép kiểu từ str thành int # if n > 0: # điều kiện là số dương # print("Đã nhập số dương") # return n # lệnh thực thi khi hàm đúng điều kiện là số dương # else: # print("Đã nhập số không dương. Chương trình sẽ tiếp tục!") # else: # print("Dữ liệu đã nhập không phải số nguyên") # enter_data() ''' Viết hàm def find_x(a_list, x) trả lại tất cả các vị trí mà x xuất hiện trong a_list, nếu không có thì trả lại -1 ''' # def find_x (a_list,x): # result = [] # for i in range(len(a_list)): # if a_list[i] == x: # result.append(i) # if result: # return result # else: # return -1 # # a_list = [1,2,3,4,5] # x = 2 # find_x(a_list,x) # print(find_x(a_list,x)) ''' Cho dãy số Tribonacci với công thức truy hồi sau: F(n) = F(n-1) + F(n-2) + F(n-3), F(1) = 1, F(2) = 1, F(3) = 2 Xây dựng 2 hàm để tìm ra số thứ n trong dãy số theo: + Hàm Đệ quy + Hàm Không đệ quy ''' # # cách 1 # def nhap_so (n): # chú ý n chỉ được gọi trong hàm # if n <= 2: # return 1 # else: # return nhap_so(n-1) + nhap_so(n-2) # M = int(input('mời nhập số: ')) # # print(nhap_so(M)) # M được khởi tạo và chứa các phép toán của hàm nhập số #cách 2 '''Thuật toán được đưa ra là chúng ta sẽ dùng một mảng lưu lại các giá trị của hàm F(n), nếu như phần tử n có tồn tại giá trị trong mảng thì ta sử dụng luôn mà không cần tính toán lại giá trị. Ngược lại thì tính F(n – 1) + F(n – 2) và lưu nó vào mảng, sau đó trả về giá trị vừa tính. Chúng ta sẽ không gọi trực tiếp hàm tính số Fibonacci với chiến lược quy hoạch động mà thông qua một hàm khác, hàm này có chức năng tạo mảng gồm n + 1 phần tử, sau đó gọi hàm tính số Fibonacci thực sự với tham số là n và mảng vừa tạo.''' # def nhap_so (n,a_lis): # if n < 3: # return 1 # else: # a_lis = [] # for i in range (3, len(a_lis)): # a_lis.append(i) # a_lis[i] = a_lis[len(a_lis)-1] + a_lis[len(a_lis)-2] # return a_lis[n] # print(nhap_so(4,1)) # a_lis = [1,2.3,4,5,6] # for i in range(3, len(a_lis)) : # a_lis[i] = a_lis[len(a_lis)- 1] + a_lis[len(a_lis) - 2] # print(a_lis) '''' Viết hàm đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n cho trước. Ví dụ: Hàm trả về 4 nếu n là 19922610 (do n có 4 số lẻ là 1, 9, 9, 1) ''' # def ham_so_le (n): # count = 0 # for i in n: # a = int(i) # if a %2 != 0 and a != 0: # count +=1 # return count # # str = input('mời nhập chuỗi số: ') # print(ham_so_le(str)) # DONE ''' Viết hàm def change_upper_lower(str) chuyển toàn bộ các ký tự in hoa sang in thường và in thường thành in hoa trong str mẫu def change_upper_lower(str): res = [] for c in str: if 'a' <= c <= 'z': res.append(chr(ord(c) - 32)) elif 'A' <= c <= 'Z': res.append(chr(ord(c) + 32)) else: res.append(c) return ''.join(res) ''' # nhắc lại chr(): từ mã ascii về chữ # còn ord(): từ chữ về mã ascii # str = 'abcABCasdCVFadfe' # def change_upper_lower(str): # res = [] # for i in str : # if 'a' <= i <= 'z' : # res.append(chr(ord(i) - 32)) # elif 'A' <= i <= 'Z' : # res.append(chr(ord(i) + 32)) # else : # res.append(i) # return re_str.join(res) # str = input('mời nhập: ') # re_str = '' # print(change_upper_lower(str)) ''' 1. Viết hàm def body_mass_index(m, h) để tính toán chỉ số BMI của một người với cân nặng m (kg), chiều cao h (m) 2. Viết hàm def bmi_information(m, h) để đưa ra thông tin về chỉ số BMI cũng như phân loại mức độ gầy - béo của người cân nặng m, chiều cao h công thức cân nặng / chiều cao* chiều cao ''' def body_mass_index(m, h): bmi = round(float((m/(h**2))),2) return bmi def bmi_information(m, h): bmi = float((m/(h**2))) if bmi < 18.5: print('Cân nặng thấp (gầy)') elif 18.5<bmi<24.9: print('bình thường') elif 25 < bmi < 29.9: print('thừa cân') elif 30 < bmi < 34.9: print('béo phì 1') elif 35 < bmi < 39.9: print('béo phì 2') elif bmi>40: print('béo phì 3') m = int(input('nhập số cân: ')) h = float(input('nhập chiều cao: ')) print(f'chỉ số {body_mass_index(m,h)}') print(bmi_information(m,h)) """ BÀI TẬP VỀ NHÀ BUỔI 07 - Function: """ ''' # Bài 01: Viết hàm # def max_min(*numbers) # trả lại cả giá trị max, min của nhiều số được truyền vào def max_min(*numbers): maxx = minn = numbers[0] for it in numbers: if it > maxx: maxx = it if it < minn: minn = it return maxx, minn print(f'Max, min: {max_min(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 3, -3, -2)}') # Bài 02: Viết hàm # def reverse_string(str) # trả lại chuỗi đảo ngược của chuỗi str def reverse_string(str): return str[::-1] print(f'KQ: {reverse_string("chuoi can dao nguoc")}') # Bài 03: Viết hàm # def is_perfect(n) # để kiểm tra xem số tự nhiên n có phải là số hoàn hảo hay ko, trả lại True nếu có, False nếu không. # Ghi chú: Xem định nghĩa về số hoàn hảo: http://hanoimoi.com.vn/Tin-tuc/Thieu-nhi/592454/so-hoan-hao-la-gi def is_perfect(n): tong_uoc = 0 for i in range(1, n): if n % i == 0: tong_uoc += i return True if tong_uoc == n else False n = 8128 print(f'{n} là số hoàn hảo? {is_perfect(n)}') # Bài 04: Viết hàm # def is_prime(n) # để kiểm tra xem số tự nhiên n có phải số nguyên tố hay không, nếu có thì trả lại True, nếu không thì trả lại False def is_prime(n): if n < 2: return False for i in range(2, n): if n % i == 0: return False return True n = 5 print(f'{n} là số nguyên tố? {is_prime(n)}') # Bài 05: Viết hàm # def count_upper_lower(str) # trả lại số lượng chữ cái viết hoa, số lượng chữ cái viết thường trong chuỗi str def count_upper_lower(str): hoa = thuong = 0 for i in str: if 'A' <= i <= 'Z': hoa += 1 elif 'a' <= i <= 'z': thuong += 1 return hoa, thuong print(f'chữ cái viết hoa, chữ cái viết thường: {count_upper_lower("string Demo count Hoa THUONG")}') # Bài 06: Viết hàm # def is_pangram(str, alphabet) # đề kiểm tra xem chuỗi str có phải là Pangram không, trả lại True nếu có, False nếu không # Ghi chú: Pangram là chuỗi chứa mỗi chữ cái trong bảng alphabet ít nhất 1 lần def is_pangram(str, alphabet): for c in alphabet: if c not in str: return False return True str = '3010120130121' alphabet = '0123' print(f'{str} là Pangram? {is_pangram(str, alphabet)}') # Bài 07: Viết hàm # def create_matrix(n, m) # xử lý việc tạo ra ma trận n hàng, m cột với giá trị phần tử tại (i, j) = i*j import random def create_matrix(n, m): return [[random.randrange(10) for j in range(m)] for i in range(n)] n, m = 5, 4 res = create_matrix(n, m) print(f'Matrix {n}x{m}:') for i in range(n): print(res[i]) # Bài 08: Viết hàm # def body_mass_index(m, h) # để tính toán chỉ số BMI của một người với cân nặng m (kg), chiều cao h (m) # Viết hàm # def bmi_information(m, h) # để đưa ra thông tin về chỉ số BMI cũng như phân loại mức độ gầy - béo của người cân nặng m, chiều cao h def body_mass_index(m, h): return m/h**2 def bmi_information(m, h): bmi = body_mass_index(m, h) print(f'Your BMI: {round(bmi, 1)}') if bmi < 15: print('=>> Very severely underweight') elif 15 <= bmi < 16: print('=>> Severely underweight') elif 16 <= bmi < 18.5: print('=>> Underweight') elif 18.5 <= bmi < 25: print('=>> Normal (healthy weight)') elif 25 <= bmi < 30: print('=>> Overweight') elif 30 <= bmi < 35: print('=>> Obese Class I (Moderately obese)') elif 35 <= bmi < 40: print('=>> Obese Class II (Severely obese)') else: print('=>> Obese Class III (Very severely obese)') bmi_information(69, 1.73) # Bài 09: Viết hàm # def change_upper_lower(str) # chuyển toàn bộ các ký tự in hoa sang in thường và in thường thành in hoa trong str def change_upper_lower(str): res = [] for c in str: if 'a' <= c <= 'z': res.append(chr(ord(c) - 32)) elif 'A' <= c <= 'Z': res.append(chr(ord(c) + 32)) else: res.append(c) return ''.join(res) str = 'Demo thU xem SAO' print(f'KQ: {change_upper_lower(str)}') # Bài 10: Viết hàm đệ quy đếm và trả về số lượng chữ số lẻ của số nguyên dương n cho trước. # Ví dụ: Hàm trả về 4 nếu n là 19922610 (do n có 4 số lẻ là 1, 9, 9, 1) def count_odd(n): if n < 10: return n % 2 else: return (n % 10) % 2 + count_odd(n//10) n = 19922610 print(f'Số lượng số lẻ trong {n} là: {count_odd(n)}') # Bài 11: Cho dãy số Tribonacci với công thức truy hồi sau: # F(n) = F(n-1) + F(n-2) + F(n-3), F(1) = 1, F(2) = 1, F(3) = 2 # Xây dựng 2 hàm để tìm ra số thứ n trong dãy số theo: # + Hàm Đệ quy # + Hàm Không đệ quy # Hàm đệ quy: def tri_dequy(n): if n <= 2: return 1 elif n == 3: return 2 else: return tri_dequy(n-1) + tri_dequy(n-2) + tri_dequy(n-3) n = 10 print(f'Tribonacci {n}: {tri_dequy(n)}') # Hàm Không đệ quy def tri_ko_dequy(n): f1, f2, f3 = 1, 1, 2 f = 0 if n <= 2: f = f2 elif n == 3: f = f3 else: for i in range(4, n+1): f = f3 + f2 + f1 f3, f2, f1 = f, f3, f2 return f n = 3 print(f'Tribonacci {n}: {tri_ko_dequy(n)}') # Bài 12: Viết hàm # def find_x(a_list, x) # trả lại tất cả các vị trí mà x xuất hiện trong a_list, nếu không có thì trả lại -1 def find_x(a_list, x): res = [] for i in range(len(a_list)): if a_list[i] == x: res.append(i) return res alist = [1, 2, 3, -4, 5, 6, 8, 9, 0, 3, 2, 1, 4, 5] x = 3 print(f'Vị trí {x} trong list: {find_x(alist, x)}') # Bài 13. Thực hiện code lại hàm sau và cho biết ý nghĩa của nó # # def enter_data(): # while True: # n = input("Nhập 1 số nguyên: ") # if n.isnumeric(): # n = int(n) # if n > 0: # print("Đã nhập số dương") # return n # print("Đã nhập số không dương. Chương trình sẽ tiếp tục!") # else: # print("Dữ liệu đã nhập không phải số nguyên") print("Ý nghĩa: Giúp kiểm tra dữ liệu nhập vào phải là 1 số nguyên dương, nếu không thì sẽ yêu cầu nhập lại") '''
9520b72cc8fcf7c3bef137cf69c4b3ad7de0095c
kerja-remote/fundamental-python
/fundamental1-konstruksi-dasar.py
359
3.828125
4
#konstruksi dasar python #sequential print('Hello World!') print('by Bagus') print('-'*10) # percabangan: Eksekusi terpilih ingin_cepat = False if ingin_cepat: print('jalan lurus') else: print('jalan lain') # perulangan jumlah_anak = 4 for index_anak in range (1, jumlah_anak+1): #jumlah perulangan = 5 - 1 =4 print(f'halo anak #{index_anak}')
58a5345d62ee5b75496fca460f309a4092257177
DT211C-2019/programming
/Year 2/Paul Geoghegan/S1/Labs/Lab11/l11q7b.py
235
4.15625
4
#Creates list color_list = ['Red', 'Blue', 'Green', 'Black', 'White'] #Changes list to upper case for i in range(len(color_list)): #Changes element to upper case color_list[i] = color_list[i].upper() #prints list print(color_list)
64117cb9a58355ef3d6da4d5758c2c9cd58f0fb3
suhanacharya/Credit-Calculator
/Credit Calculator/task/creditcalc/creditcalc.py
4,144
3.578125
4
import math import argparse import sys # Creating arguments that are to be passed in command line. parser = argparse.ArgumentParser() parser.add_argument("--type") parser.add_argument("--principal") parser.add_argument("--periods") parser.add_argument("--interest") parser.add_argument("--payment") args = vars(parser.parse_args()) type_of_operation = args["type"] if type_of_operation == "diff": """ If the operation is based on differentiate payment, this branch takes care of that """ # Allow operation only if the input arguments are present, # and are valid i.e not -ve value if args["principal"] and args["periods"] and args["interest"]: # Just creating some variable to work with principal = int(args["principal"]) periods = int(args["periods"]) interest = float(args["interest"]) if principal < 0 or periods < 0 or interest < 0: # Values cannot be negative print("Incorrect parameters!") sys.exit() else: i = interest / (12 * 100) total_payment = 0 for m in range(1, periods + 1): D = round(principal / periods + i * (principal - principal * (m - 1) / periods), 2) total_payment += math.ceil(D) print(f"Month {m}: paid out {math.ceil(D)}") overpay = total_payment - principal print() print(f"Overpayment = {overpay}") else: print("Incorrect parameters") sys.exit() elif type_of_operation == "annuity": """ If the operation is based on annuity payment, this branch takes care of that """ # Allow operation only if the input arguments are present, # and are valid i.e not -ve value if args["principal"] and args["payment"] and args["interest"] and not args["periods"]: """ If the certain arguments are present, they indicate a certain action. So these conditions differentiate the cases """ # Just creating some variable to work with principal = int(args["principal"]) interest = float(args["interest"]) payment = int(args["payment"]) if principal < 0 or payment < 0 or interest < 0: print("Incorrect parameters!") sys.exit() else: i = (interest / (12 * 100)) n = math.ceil(math.log(payment / (payment - i * principal), 1 + i)) total_payment = n * payment months = n years = math.floor(months / 12) months = months % 12 month_singular = "month" month_plural = "months" year_singular = "year" year_plural = "years" if years > 0: if months > 0: print(f"You need {years} {year_plural if years > 1 else year_singular} " + f"and {months} {month_plural if months > 1 else month_singular} to repay this credit!") else: print(f"You need {years} {year_plural if years > 1 else year_singular} to repay this credit!") else: if months > 0: print( f"You need {months} {month_plural if months > 1 else month_singular} to repay this credit!") print(f"Overpayment = {total_payment - principal}") elif args["periods"] and args["interest"] and args["payment"] and not args["principal"]: periods = int(args["periods"]) interest = float(args["interest"]) payment = int(args["payment"]) if periods <= 0 or payment <= 0 or interest <= 0: print("Incorrect parameters!") sys.exit() else: i = (interest / (12 * 100)) annuity = payment n = periods total_payment = payment * n principal = math.floor((annuity / ((i * math.pow((1 + i), n)) / (math.pow(1 + i, n) - 1)))) print(f"Your credit principal = {principal}!") print(f"Overpayment = {total_payment - principal}") elif args["periods"] and args["interest"] and args["principal"] and not args["payment"]: periods = int(args["periods"]) interest = float(args["interest"]) principal = int(args["principal"]) if periods <= 0 or principal <= 0 or interest <= 0: print("Incorrect parameters!") sys.exit() else: i = (interest / (12 * 100)) n = periods annuity = math.ceil(principal * (i * math.pow(1 + i, n)) / (math.pow(1 + i, n) - 1)) total_payment = n * annuity print(f"The payment = {annuity}!") print(f"Overpayment = {total_payment - principal}") else: print("Incorrect parameters") sys.exit() else: print("Incorrect parameters") sys.exit()
490780df10237c40bcd0222bec796dae5f1feec5
eodenyire/holbertonschool-higher_level_programming-27
/0x0F-python-object_relational_mapping/100-relationship_states_cities.py
1,126
3.515625
4
#!/usr/bin/python3 """ State class: In addition to previous requirements, the class attribute cities must represent a relationship with the class City. If the State object is deleted, all linked City objects must be automatically deleted. Also, the reference from a City object to his State should be named state You must use the module SQLAlchemy Script that creates the State “California” with the City “San Francisco” from the database hbtn_0e_100_usa: (100-relationship_states_cities.py) """ if (__name__ == "__main__"): from sys import argv from relationship_state import Base, State from relationship_city import City from sqlalchemy import (create_engine) from sqlalchemy.orm import sessionmaker engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}' .format(argv[1], argv[2], argv[3]), pool_pre_ping=True) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() session.add(City(name="San Francisco", state=State(name="California"))) session.commit() session.close()
9b883c9d6e1c64fa3ebbc548b894bc3f3d748751
jh-lau/leetcode_in_python
/02-算法思想/二分查找/744.寻找比目标字母大的最小字母.py
1,801
3.625
4
""" @Author : liujianhan @Date : 2020/12/26 9:57 @Project : leetcode_in_python @FileName : 744.寻找比目标字母大的最小字母.py @Description : 给你一个排序后的字符列表 letters ,列表中只包含小写英文字母。另给出一个目标字母 target,请你寻找在这一有序列表里比目标字母大的最小字母。 在比较时,字母是依序循环出现的。举个例子: 如果目标字母 target = 'z' 并且字符列表为 letters = ['a', 'b'],则答案返回 'a' 示例: 输入: letters = ["c", "f", "j"] target = "a" 输出: "c" 输入: letters = ["c", "f", "j"] target = "c" 输出: "f" 输入: letters = ["c", "f", "j"] target = "d" 输出: "f" 输入: letters = ["c", "f", "j"] target = "g" 输出: "j" 输入: letters = ["c", "f", "j"] target = "j" 输出: "c" 输入: letters = ["c", "f", "j"] target = "k" 输出: "c" 提示: letters长度范围在[2, 10000]区间内。 letters 仅由小写字母组成,最少包含两个不同的字母。 目标字母target 是一个小写字母。 """ from typing import List from bisect import bisect class Solution: # 112ms, 15.3MB @staticmethod def next_greatest_letter(letters: List[str], target: str) -> str: index = bisect(letters, target) return letters[index % len(letters)] if __name__ == '__main__': test_cases = [ (["c", "f", "j"], 'a'), (["c", "f", "j"], 'c'), (["c", "f", "j"], 'd'), (["c", "f", "j"], 'g'), (["c", "f", "j"], 'j'), (["c", "f", "j"], 'k'), ] for tc in test_cases: print(Solution.next_greatest_letter(*tc))
c4ebaba8961307243c6c9f2c8a654a411befad7d
A-hungry-wolf/python
/study/fibs.py
152
3.609375
4
def fibs(num): results = [0, 1] for i in range(num - 2): results.append(results[-2] + results[-1]) print(results) print(fibs(10))
1b8fa28577b1e66ebcf07f1d09b372cd21bdd7e7
Gangamagadum98/Python-Programs
/prgms/OperatorOverloading.py
1,300
4.125
4
# WE have diff methods for diff operators # __add__(), __sub__(), __mul__() call as 'magic methods' # a=5 # b=6 # print(a+b) Its possible with help of int/string bt no with class/obj # print(int.__add__(a,b)) class Student: def __init__(self,m1,m2): self.m1 = m1 self.m2= m2 def __add__(self,other): m1=self.m1 +other.m1 m2=self.m2 + other.m2 s3 = Student(m1,m2) return s3 def __gt__(self,other): r1=self.m1+self.m2 r2=other.m1+other.m2 if r1>r2: return True else: return False def __str__(self): return '{} {}'.format(self.m1,self.m2) s1=Student(34,23) s2=Student(13,14) s3=s1+s2 #addition using '+' operator with class is not possible # this code connverted into (Student.__add__(s1,s2)) here s1 is self and s2 is other in __add__ method print(s3.m1) # compare if s1>s2: print('s1 wins') else: print('s2 wins') a=12 print(a) # indirectly its calling (a.__str__()) method print(s1) print(s2) # --- Operator overloading -- # operator like +,-,* operator vl remain same operands vl change and type of parameter vl change # __add__() takes diff type of parameter/arguments # Same method name bt no of arguments/ type of args are diff.
db1f5a6b87b54ad316dd5bc93c42b5fe6f0f99b9
wancong/leetcode
/listnode/get_intersection_node.py
1,957
3.671875
4
""" Intersection of two linked lists Write a program to find the node at which the intersection of two singly linked lists begins. A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 begin to intersect at node c1. """ class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def get_len(self, head): cnt = 0 cur = head while cur: cnt += 1 cur = cur.next return cnt def get_intersection_node(self, headA, headB): """ :type headA: ListNode :type headB: ListNode :rtype: ListNode """ lenA = self.get_len(headA) lenB = self.get_len(headB) diff_len = 0 if lenA > lenB: diff_len = lenA - lenB for _ in range(diff_len): headA = headA.next else: diff_len = lenB - lenA for _ in range(diff_len): headB = headB.next currA, currB = headA, headB while currA and currB: if currA == currB: return currA else: currA = currA.next currB = currB.next if __name__ == "__main__": node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(4) node5 = ListNode(5) node6 = ListNode(6) node7 = ListNode(7) node8 = ListNode(8) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node6.next = node7 node7.next = node3 ans_node = Solution().get_intersection_node(node1, node6) print(ans_node.val)
2663aa80bc79556a62276664461455f0ba54870a
doct0rX/PythonMIT1x
/week2/assignments/guessMyNumber.py
957
4.5625
5
""" This was exercise 3 at week 2 In this problem, you'll create a program that guesses a secret number! The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number! """ print("Please think of a number between 0 and 100!") low = 0 high = 100 answer = False while not answer: guess = (high + low) // 2 print("Is your secret number " + str(guess) + "?") indicator = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ") if indicator == 'c': answer = True elif indicator == 'h': high = guess elif indicator == 'l': low = guess else: print("Sorry, I did not understand your input.") print("Game over. Your secret number was: " + str(answer))
07137115d299454cde0578af41bb5d5acbe2877a
Gryphon90/Python
/TripCalculator.py
652
3.96875
4
##TRIP COST CALCULATOR def hotel_cost (nights): return 140 * nights def plane_ride_cost (city): if city == "Charlotte": return 183 elif city == "Tampa": return 220 elif city == "Pittsburgh": return 222 elif city == "Los Angeles": return 475 def rental_car_cost (days): cost = 40 * days if days >=7: cost = cost-50 elif days >=3: cost = cost -20 return cost def trip_cost (city, days, spending_money): return hotel_cost(days) + plane_ride_cost(city) + rental_car_cost(days) + spending_money print trip_cost ("Charlotte", 14, 1500)
f971b58b835579bb16a8c9923c2ed31ef502dc0d
BeniyamL/alx-higher_level_programming
/0x0B-python-input_output/9-student.py
776
4.03125
4
#!/usr/bin/python3 """ class defintion Student """ class Student: """ implementation of class student """ def __init__(self, first_name, last_name, age): """ initialization fuction of student Arguments: first_name: the first name of the student last_name: the last name of the student age: the age of the student Returns: nothing """ self.first_name = first_name self.last_name = last_name self.age = age def to_json(self): """ function to find dictionary representation of an object Arguments: obj: the given object Returns: dictionary representation of an object """ return self.__dict__
5047e5545ab8b9464e36d651866bdf92278ae1b9
danhiel98/pensamento-computacional-python
/07_aproximacion.py
513
3.875
4
objetivo = int(input('Escriba un número: ')) epsilon = 0.01 # Margen de error o precisión paso = epsilon**2 # Cantidad a aumentar por cada iteración respuesta = 0.0 while abs(respuesta**2 - objetivo) >= epsilon and respuesta <= objetivo: print(respuesta) respuesta += paso if abs(respuesta**2 - objetivo) >= epsilon: #Si el margen de error no entró en el margen aceptable print(f'No se encontró la raiz cuadrada de {objetivo}') else: print(f'La raiz cuadrada de {objetivo} es {respuesta}')
09b4443569bff7d35a119d8c1f7f148513e78872
JohanHansen-Hub/PythonProjects
/Arkiv/SøkeAlgoritmer/iterative_binary_search.py
415
3.625
4
eksamplelist = [5,3,8,1,9,2] def iterativeBinarySearch(the_list, item): start = 0 end = 0 found = 0 while start <= end and not found: mid = (start + end) // 2 if the_list[mid] > item: end = mid - 1 elif the_list[mid] < item: end = mid - 1 else: found = True return found print(iterativeBinarySearch(eksamplelist.sort(), 9))
3b4f6a278d3dd453ae3c3189bb2aeffb0774e4a2
ATLJoeReed/CodecademyTraining
/intro_data_analysis/capstone/biodiversity/jreed_biodiversity_capstone.py
12,320
4.1875
4
# coding: utf-8 # # Capstone 2: Biodiversity Project # # Introduction # You are a biodiversity analyst working for the National Parks Service. You're going to help them analyze some data about species at various national parks. # # Note: The data that you'll be working with for this project is *inspired* by real data, but is mostly fictional. # # Step 1 # Import the modules that you'll be using in this assignment: # - `from matplotlib import pyplot as plt` # - `import pandas as pd` # In[1]: from matplotlib import pyplot as plt import pandas as pd # # Step 2 # You have been given two CSV files. `species_info.csv` with data about different species in our National Parks, including: # - The scientific name of each species # - The common names of each species # - The species conservation status # # Load the dataset and inspect it: # - Load `species_info.csv` into a DataFrame called `species` # In[2]: species = pd.read_csv('species_info.csv') # In[3]: species.shape # In[4]: species.info() # Inspect each DataFrame using `.head()`. # In[5]: species.head() # # Step 3 # Let's start by learning a bit more about our data. Answer each of the following questions. # How many different species are in the `species` DataFrame? # In[6]: species.scientific_name.nunique() # What are the different values of `category` in `species`? # In[7]: species.category.unique() # What are the different values of `conservation_status`? # In[8]: species.conservation_status.unique() # # Step 4 # Let's start doing some analysis! # # The column `conservation_status` has several possible values: # - `Species of Concern`: declining or appear to be in need of conservation # - `Threatened`: vulnerable to endangerment in the near future # - `Endangered`: seriously at risk of extinction # - `In Recovery`: formerly `Endangered`, but currnetly neither in danger of extinction throughout all or a significant portion of its range # # We'd like to count up how many species meet each of these criteria. Use `groupby` to count how many `scientific_name` meet each of these criteria. # In[9]: species.groupby('conservation_status').scientific_name.nunique().reset_index() # As we saw before, there are far more than 200 species in the `species` table. Clearly, only a small number of them are categorized as needing some sort of protection. The rest have `conservation_status` equal to `None`. Because `groupby` does not include `None`, we will need to fill in the null values. We can do this using `.fillna`. We pass in however we want to fill in our `None` values as an argument. # # Paste the following code and run it to see replace `None` with `No Intervention`: # ```python # species.fillna('No Intervention', inplace=True) # ``` # In[10]: species.fillna('No Intervention', inplace=True) # Great! Now run the same `groupby` as before to see how many species require `No Protection`. # In[11]: species.groupby('conservation_status').scientific_name.nunique().reset_index() # Let's use `plt.bar` to create a bar chart. First, let's sort the columns by how many species are in each categories. We can do this using `.sort_values`. We use the the keyword `by` to indicate which column we want to sort by. # # Paste the following code and run it to create a new DataFrame called `protection_counts`, which is sorted by `scientific_name`: # ```python # protection_counts = species.groupby('conservation_status')\ # .scientific_name.count().reset_index()\ # .sort_values(by='scientific_name') # ``` # In[12]: protection_counts = species.groupby('conservation_status') .scientific_name.nunique().reset_index() .sort_values(by='scientific_name') # Now let's create a bar chart! # 1. Start by creating a wide figure with `figsize=(10, 4)` # 1. Start by creating an axes object called `ax` using `plt.subplot`. # 2. Create a bar chart whose heights are equal to `scientific_name` column of `protection_counts`. # 3. Create an x-tick for each of the bars. # 4. Label each x-tick with the label from `conservation_status` in `protection_counts` # 5. Label the y-axis `Number of Species` # 6. Title the graph `Conservation Status by Species` # 7. Plot the grap using `plt.show()` # In[13]: plt.figure(figsize=(10, 4)) ax = plt.subplot() plt.bar(range(len(protection_counts)), protection_counts.scientific_name.values) ax.set_xticks(range(len(protection_counts))) ax.set_xticklabels(protection_counts.conservation_status.values) plt.ylabel('Number of Species') plt.title('Conservation Status by Species') plt.show() # # Step 4 # Are certain types of species more likely to be endangered? # Let's create a new column in `species` called `is_protected`, which is `True` if `conservation_status` is not equal to `No Intervention`, and `False` otherwise. # In[14]: species['is_protected'] = species.conservation_status != 'No Intervention' # Let's group by *both* `category` and `is_protected`. Save your results to `category_counts`. # In[15]: category_counts = species.groupby(['category', 'is_protected']) .scientific_name.nunique().reset_index() # Examine `category_count` using `head()`. # In[16]: category_counts.head() # It's going to be easier to view this data if we pivot it. Using `pivot`, rearange `category_counts` so that: # - `columns` is `conservation_status` # - `index` is `category` # - `values` is `scientific_name` # # Save your pivoted data to `category_pivot`. Remember to `reset_index()` at the end. # In[18]: category_pivot = category_counts.pivot( columns='is_protected', index='category', values='scientific_name' ).reset_index() # Examine `category_pivot`. # In[19]: category_pivot.head() # Use the `.columns` property to rename the categories `True` and `False` to something more description: # - Leave `category` as `category` # - Rename `False` to `not_protected` # - Rename `True` to `protected` # In[20]: category_pivot.columns = ['category', 'not_protected', 'protected'] # In[21]: category_pivot.head() # Let's create a new column of `category_pivot` called `percent_protected`, which is equal to `protected` (the number of species that are protected) divided by `protected` plus `not_protected` (the total number of species). # In[22]: category_pivot['percent_protected'] = category_pivot.protected / (category_pivot.protected + category_pivot.not_protected) # Examine `category_pivot`. # In[28]: category_pivot # It looks like species in category `Mammal` are more likely to be endangered than species in `Bird`. We're going to do a significance test to see if this statement is true. Before you do the significance test, consider the following questions: # - Is the data numerical or categorical? # - How many pieces of data are you comparing? # Based on those answers, you should choose to do a *chi squared test*. In order to run a chi squared test, we'll need to create a contingency table. Our contingency table should look like this: # # ||protected|not protected| # |-|-|-| # |Mammal|?|?| # |Bird|?|?| # # Create a table called `contingency` and fill it in with the correct numbers # In[24]: contingency = [[30, 146], [75, 413]] # In order to perform our chi square test, we'll need to import the correct function from scipy. Past the following code and run it: # ```py # from scipy.stats import chi2_contingency # ``` # In[25]: from scipy.stats import chi2_contingency # Now run `chi2_contingency` with `contingency`. # In[26]: chi2_contingency(contingency) # It looks like this difference isn't significant! # # Let's test another. Is the difference between `Reptile` and `Mammal` significant? # In[27]: contingency = [[30, 146], [5, 73]] chi2_contingency(contingency) # Yes! It looks like there is a significant difference between `Reptile` and `Mammal`! # # Step 5 # Conservationists have been recording sightings of different species at several national parks for the past 7 days. They've saved sent you their observations in a file called `observations.csv`. Load `observations.csv` into a variable called `observations`, then use `head` to view the data. # In[29]: observations = pd.read_csv('observations.csv') observations.head() # Some scientists are studying the number of sheep sightings at different national parks. There are several different scientific names for different types of sheep. We'd like to know which rows of `species` are referring to sheep. Notice that the following code will tell us whether or not a word occurs in a string: # In[30]: # Does "Sheep" occur in this string? str1 = 'This string contains Sheep' 'Sheep' in str1 # In[31]: # Does "Sheep" occur in this string? str2 = 'This string contains Cows' 'Sheep' in str2 # Use `apply` and a `lambda` function to create a new column in `species` called `is_sheep` which is `True` if the `common_names` contains `'Sheep'`, and `False` otherwise. # In[32]: species['is_sheep'] = species.common_names.apply(lambda x: 'Sheep' in x) species.head() # Select the rows of `species` where `is_sheep` is `True` and examine the results. # In[33]: species[species.is_sheep] # Many of the results are actually plants. Select the rows of `species` where `is_sheep` is `True` and `category` is `Mammal`. Save the results to the variable `sheep_species`. # In[34]: sheep_species = species[(species.is_sheep) & (species.category == 'Mammal')] sheep_species # Now merge `sheep_species` with `observations` to get a DataFrame with observations of sheep. Save this DataFrame as `sheep_observations`. # In[35]: sheep_observations = observations.merge(sheep_species) sheep_observations # How many total sheep observations (across all three species) were made at each national park? Use `groupby` to get the `sum` of `observations` for each `park_name`. Save your answer to `obs_by_park`. # # This is the total number of sheep observed in each park over the past 7 days. # In[36]: obs_by_park = sheep_observations.groupby('park_name').observations.sum().reset_index() obs_by_park # Create a bar chart showing the different number of observations per week at each park. # # 1. Start by creating a wide figure with `figsize=(16, 4)` # 1. Start by creating an axes object called `ax` using `plt.subplot`. # 2. Create a bar chart whose heights are equal to `observations` column of `obs_by_park`. # 3. Create an x-tick for each of the bars. # 4. Label each x-tick with the label from `park_name` in `obs_by_park` # 5. Label the y-axis `Number of Observations` # 6. Title the graph `Observations of Sheep per Week` # 7. Plot the grap using `plt.show()` # In[37]: plt.figure(figsize=(16, 4)) ax = plt.subplot() plt.bar(range(len(obs_by_park)), obs_by_park.observations.values) ax.set_xticks(range(len(obs_by_park))) ax.set_xticklabels(obs_by_park.park_name.values) plt.ylabel('Number of Observations') plt.title('Observations of Sheep per Week') plt.show() # Our scientists know that 15% of sheep at Bryce National Park have foot and mouth disease. Park rangers at Yellowstone National Park have been running a program to reduce the rate of foot and mouth disease at that park. The scientists want to test whether or not this program is working. They want to be able to detect reductions of at least 5 percentage point. For instance, if 10% of sheep in Yellowstone have foot and mouth disease, they'd like to be able to know this, with confidence. # # Use the sample size calculator at <a href="https://www.optimizely.com/sample-size-calculator/">Optimizely</a> to calculate the number of sheep that they would need to observe from each park. Use the default level of significance (90%). # # Remember that "Minimum Detectable Effect" is a percent of the baseline. # In[38]: minimum_detectable_effect = 100 * 0.05 / 0.15 minimum_detectable_effect # How many weeks would you need to observe sheep at Bryce National Park in order to observe enough sheep? How many weeks would you need to observe at Yellowstone National Park to observe enough sheep? # In[41]: bryce = 510 / 250 print("Number of weeks to reach sample size: {}".format(bryce)) # In[42]: yellowstone = 510 / 507 print("Number of weeks to reach sample size: {}".format(yellowstone))
8ec484b45e201479b5dfbb3625be3fde5312a2c1
emmanavarro/holbertonschool-higher_level_programming
/0x0B-python-input_output/0-read_file.py
301
4.1875
4
#!/usr/bin/python3 """Read text file module """ def read_file(filename=""): """ Write a function that reads a text file (UTF8) and prints it to stdout. """ with open(filename, mode='r', encoding='utf-8') as my_file: print(my_file.read(), end='') my_file.close()
dda8db23078ae3635f504fd3c4418ef902cc0d51
Adrite04/BRACUCSE422
/Assignment/P2.5.7.py
377
3.515625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import time start = time.time() n = 27 def hailstone(a): print(a) if a != 1: if a %2 == 0: hailstone(a/2) else: hailstone(3*a + 1) hailstone(n) print("Time Required: " ,(time.time() - start))
a92d4076985b8279ddd0eebb44705b1c186dcec8
Dearyyyyy/TCG
/data/3920/AC_py/518495.py
135
3.65625
4
# coding=utf-8 a=int(input()) b=int(a/100%10) c=int(a/10%10) d=int(a/1%10) if b**3+c**3+d**3==a: print("YES") else: print("NO")
f11c35af93c8093b10a95b4a87b72aa83c10cad3
alejandro-parra/Programming-Fundamentals---Python
/Act2.3.py
303
3.984375
4
print("Escribe una medida en pies que desea convertir:") x=input() x=float(x) yarda=x/3 pulgada=x*12 centimetro=pulgada*2.54 m=centimetro/100 print("Valor en pies: "+str(x)) print("Valor en yardas: "+str(yarda)) print("Valor en metros: "+str(m)) print("Valor en pulgadas: "+str(pulgada))
cbf35bc9bbbd02a387e7b8d620ce554689a154ab
Ran-oops/python
/2/01Python中的字符串数学列表 内键函数 数学模型/07.py
975
3.765625
4
#数学函数 #abs 获取绝对值 num = -123.5 result = abs(num) print(result) #sum 计算一个序列的和(列表和元组集合) lists = {1,2,234,6,21,57,156,7} result = sum(lists) print(result) #max & min 获取最大值/最小值(列表和元组集合) lists = [12,56,1,67,23,87,2,8,0,457,99] maxresult = max(lists) print(maxresult) minresult = min(lists) print(minresult) #pow 计算一个数值的N次方 用 ** 更快 很少 result = pow(3,4) print(result) #round() 四舍五入 num = 5.5 result = round(num) #result = round(num,2) print(result) #range 产生一个连续的整型序列(生成器) result = range(0,9) print(result) for i in result: print(i) #只写结束值 result = range(20) for i in result: print(i) #带有间隔值的写法 result = range(0,101,5) for i in result: print(i) #max和min也接收多个数据的参数 result = max(12,56,1,67,23,87,2,8,0,457,99) print(result)