blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
c2cdaaf5f6e92f390b2d1ab35b052f1ad48c334a
susieir/advent_of_code_2020
/day3part2.py
1,377
3.765625
4
import math def main(file, step_right, step_down): # Open file and read into forest with open(file, 'r') as fp: forest = fp.read() # Return width width = forest.find("\n") # Create a forest with no line breaks forest = forest.replace("\n", "") # Find height of forest height = int(len(forest) / width) pos = 0 # Starting position # step_right = 3 # Number of horizontal steps tree_count = 0 # Initialise empty tree count moves = math.floor(height / step_down) # for n in range(moves): while pos < len(forest): if forest[pos] == "#": tree_count += 1 # Check whether move will cross columns if 0 < width - (pos % width) <= step_right: # If so, add step_right only pos = pos + step_right + ((step_down - 1) * width) else: # Otherwise normal move pos = pos + step_right + (step_down * width) return tree_count if __name__ == '__main__': a = main('day3.txt', 1, 1) b = main('day3.txt', 3, 1) c = main('day3.txt', 5, 1) d = main('day3.txt', 7, 1) e = main('day3.txt', 1, 2) print(a) print(b) print(c) print(d) print(e) print(a * b * c * d * e) # read_input('day3.txt') # travel_through_forest('day3.txt')
9caf8e76a3a63bbea630962c41437d62a48bd572
Runn1ngW1ld/Domaca-naloga-10
/Guess game.py
398
3.65625
4
from random import randint intro = "Ugani skrit stevilo med 1 in 10" print intro def main(): while True: secret = randint(1, 10) guess = int(raw_input("Vpisi skrito stevilo: ")) if guess == secret: print "Bravo stevilka je pravilna :)" else: print "Stevilo ni pravo. Vec srece prihodnjic :(" if __name__ == '__main__': main()
bd1cffe7412ec3c2be6e923c5480b859ac0ed989
karlabelazcos/Ejercicios-Python-Guia-de-examen-
/Ejercicio9. Acumulado.py
558
3.75
4
acumulado=int(0) numero=str("") #Un bucle while permite repetir la ejecución de un grupo de instrucciones mientras se cumpla una condición #(es decir, mientras la condición tenga el valor True). while True: numero=input("Dame un numero entero: ") if numero=="": #(Break) ,nos permite salir de adentro de un ciclo (tanto sea for como while ) en medio de su ejecución. print("Vacio. Salida del programa.") break else: acumulado+=int(numero) salida="Monto acumulado: {}" print(salida.format(acumulado))
91d5feec5179301980e29615403ee969adf32330
Zheng-Li01/Python_Excersise
/Day1/5.py
2,044
3.734375
4
## 41.0 举例说明 Try except else finally 的相关意义 TrY\Except\Else 没有捕获到异常,执行else 语句. Try/Except/Finally 不管是否捕获到异常, 都执行Finally 与举报 ## 42.0 Python 中交换两个数值 ## 啊,b = 3,4 A,B = B,A ## 43.0 Zip() 的用法 ## zip() 函数在运算时,会以一个或者多个序列(可迭代对象) 作为参数,返回一个元组的列表, 同时将这些序列中并排的元素配对;zip() 参数可以接受任何类型的序列, 同时也可以有两个以上的参数; 当传入的参数长度不同时 ## zip 能够自动以最短序列长度作为基准进型截取, 获得元组 # a = [1,2] # b = [3,4,2] # print([i for i in zip(a,b)]) # a = (1,2) # b = (3,4,2) # print([i for i in zip(a,b)]) # a = "qw" # b = "asd" # print( [i for i in zip(a,b)]) ## 44.0 a = "张明98分" 用 re.sub 将98 替换为 100 # import re # a = "张明98分" # res = re.sub(r"\d+", "100",a) # print(res) ## 45.0 写5条常用的sql 语句 ## show databases show tables desc 表名 select * from 表明 update studetns et gender =0, hometown = "beijng" where id =5 ## 46.0 a = "hello" 和 b = "你好" 编码成bytes类型 # a = "hello" # b = "你好" # print(a.encode(), b.encode()) ## 47.0 [1,2,3] + [4,5,6] # A = [1,2,3] # B = [4,5,6] # C1 =A.extend(B) # C2 = A.append(B) # print(A+B) # print(C1) # print(C2) ## 48.0 提高Python 运行效率的方法 ## 1. 使用生成器节约内存 2. 循环代码优化,避免重复代码 3. 核心模块使用Cython,Pypy等 4. 多进程多次线程协程的使用 5. 多个if/else 的判断把最有可能先发生的条件放在最前面减少程序判断的次数 ##49.0 简述mysql和redis的区别 ## redis 内存型非关系数据库 数据保存在内存中 速度快 ## mysql 关系型数据库 数据保存在磁盘中 检索的时候 会有一定的 IO 操作 访问速度比较慢 ## 50.0 遇到debug 应该怎样处理 ## 1. 细节上的错误 可以通过print() 打印 2. 涉及到第三方框架查看文档 3.
11d26c20d3c2d4c38b2c306f1f05c7f700111e55
vt0311/python
/ch4/7dict.py
503
3.78125
4
''' Created on 2017. 10. 19. @author: acorn ''' ''' 순서 없고 ''' dict1 = {'john':25, 'jane':26} print(dict1) print(type(dict1)) print(dict1['john']) dict1['john'] = 27 print(dict1) print("length : ", len(dict1)) print(()) #v8, v9 = dict1 ''' print(v8) print(dict1(v8)) print(v9) print(dict1(v9)) ''' dict2 = {'john':31, 'jack': 32} dict1.update(dict2) print(dict1) dict1.pop('jack') print(dict1) print(dict1.keys()) print(type(dict1.keys())) print(dict1.values()) print(type) print()
c6e9008ccd5a68db4da8811083607005ea5210bf
ErickRDev/ufrj-ai-othello_player
/noobnoob_player.py
17,190
3.59375
4
class NoobNoob: """ Simulates an inteligent player """ import time import copy from models.move import Move def __init__(self, color): """ Constructor. """ self.DEBUG_FLAG = False self.color = color self.opponent_color = "o" if self.color == "@" else "@" self.turn = 1 if self.color == "@" else 2 self.first_turn = True self.CORNERS = [ (1, 1), # north-western corner (1, 8), # north-eastern corner (8, 8), # south-eastern corner (8, 1) # south-western corner ] self.CORNER_NEIGHBOURS = [ (2, 1), (2, 2), (1, 2), (1, 7), (2, 7), (2, 8), (7, 1), (7, 2), (8, 2), (8, 7), (7, 7), (7, 8) ] self.DIRECTIONS = [ (-1, -1), # north-west (-1, 0), # north (-1, 1), # north-east (0, 1), # east (1, 1), # south-east (1, 0), # south (1, -1), # south-west (0, -1) # west ] def evaluate_board_configuration(self, board): """ Evaluates the current board configuration based on the linear combination of the heuristics described below. The intuition for the heuristics was taken from the articles below: # https://courses.cs.washington.edu/courses/cse573/04au/Project/mini1/RUSSIA/Final_Paper.pdf # https://pdfs.semanticscholar.org/235f/b5f2ebae93e33e2bf7038bb37a690fa9390e.pdf The heuristics under employment are: * Disc Parity * Corners * Stability * Mobility @params: board: the board configuration to be evaluated; @returns: A score. """ # counters for disc parity heuristic max_discs, min_discs = 0, 0 # counters for potential mobility heuristic max_frontier_discs = set() min_frontier_discs = set() max_potential_moves = set() min_potential_moves = set() # counters for edge heuristic max_edge_discs, min_edge_discs = 0, 0 # iterating over the board and evaluating current configuration of discs: for i in range(1, 9): min_discs_in_row = 0 max_discs_in_row = 0 for j in range(1, 9): disc = board[i][j] if disc == self.color: # disc parity max_discs_in_row += 1 max_discs += 1 if i == 1 or i == 8 or j == 1 or j == 8: # this is an edge, so this disc is semi-stable max_edge_discs += 1 # potential mobility for direction in self.DIRECTIONS: _i, _j = i + direction[0], j + direction[1] if board[_i][_j] == ".": # adding to potential moves set if (_i, _j) not in min_potential_moves: min_potential_moves.add((_i, _j)) # adding to frontier discs set if (i, j) not in min_frontier_discs: min_frontier_discs.add((i, j)) elif disc == self.opponent_color: # disc parity min_discs_in_row += 1 min_discs += 1 if i == 1 or i == 8 or j == 1 or j == 8: # this is an edge, so this disc is semi-stable min_edge_discs += 1 # potential mobility for direction in self.DIRECTIONS: _i, _j = i + direction[0], j + direction[1] if board[_i][_j] == "." and (_i, _j): # adding to potential moves set if (_j, _j) not in max_potential_moves: max_potential_moves.add((_i, _j)) # adding to frontier discs set if (i, j) not in max_frontier_discs: max_frontier_discs.add((i, j)) # calculating disc parity score disc_parity_score = (100 * (float(max_discs - min_discs) / float(max_discs + min_discs))) mobility_score = 0 max_potential_mobility = len(max_potential_moves) + len(max_frontier_discs) min_potential_mobility = len(min_potential_moves) + len(min_frontier_discs) # calculating potential mobility score if max_potential_mobility + min_potential_mobility != 0: mobility_score = (100 * (float(max_potential_mobility - min_potential_mobility) / float(max_potential_mobility + min_potential_mobility))) edge_score = 0 # calculating edge score if max_edge_discs + min_edge_discs != 0: edge_score = (100 * (float(max_edge_discs - min_edge_discs) / float(max_edge_discs + min_edge_discs))) # counters for corners heuristics max_corners_captured = 0 min_corners_captured = 0 max_potential_corners = 0 min_potential_corners = 0 max_potential_corners_considered = set() min_potential_corners_considered = set() # evaluating corners: for corner_coords in self.CORNERS: corner_color = board[corner_coords[0]][corner_coords[1]] if corner_color == self.color: # corner captured by max player max_corners_captured += 1 continue if corner_color == self.opponent_color: # corner captured by min player min_corners_captured += 1 continue # corner uncaptured # evaluating potential corners: for direction in self.DIRECTIONS: _i, _j = corner_coords[0], corner_coords[1] di, dj = direction[0], direction[1] _i += di _j += dj current_pos = board[_i][_j] if current_pos == "?" or current_pos == ".": continue if current_pos == self.opponent_color: if corner_coords not in max_potential_corners_considered: max_potential_corners_considered.add(corner_coords) max_potential_corners += 1 if current_pos == self.color: if corner_coords not in min_potential_corners_considered: min_potential_corners_considered.add(corner_coords) min_potential_corners += 1 captured_corners_score = 0 # calculating captured corner scores if max_corners_captured + min_corners_captured != 0: captured_corners_score = (100 * (float(max_corners_captured - min_corners_captured) / float(max_corners_captured + min_corners_captured))) potential_corners_score = 0 # calculating potential corner scores if max_potential_corners + min_potential_corners != 0: potential_corners_score = (100 * (float(max_potential_corners - min_potential_corners) / float(max_potential_corners + min_potential_corners))) return disc_parity_score + mobility_score + 10 * (captured_corners_score + potential_corners_score) + edge_score def minimax(self, board, should_maximize, depth_level, max_depth, alpha, beta): """ Implementation of the minimax algorithm with alpha-beta pruning. @intuition: In general, the minimax algorithm has a search strategy and heuristics that are used to evaluate a given configuration of the board. The idea here is to use a depth-first search strategy until we reach the desired depthness level, at which point we evaluate the board configuration as if we were on a leaf node, calculating a "score". This score is then propagated up the tree following the strategy of each node - to minimize or to maximize - while also applying alpha-beta pruning to optimize max depth reach. @params: board : the current board configuration; should_maximize : whether this node should maximize or minimize the score; depth_level : current depth-level in the search; max_depth : the max depth that we're allowed to go in the search; alpha : the highest-score we've found so far along current branch; beta : the lowest-score we've found so far along current branch; @returns: The best action (movement) found by the algorithm; """ if depth_level == max_depth: # recursion max depth reached; treating this node as if it was a leaf-node score = self.evaluate_board_configuration(board) return (None, score) if should_maximize: # if we're maximizing, this is our turn, # as we always want to maximize our score; color = self.color target_color = self.opponent_color else: # if we're minimizing, this is our opponent's turn, # as we always want to minimize his/her score; color = self.opponent_color target_color = self.color found_move = False possible_moves = [] for i in range(1, 9): for j in range(1, 9): if board[i][j] == ".": flanked_discs = [] found_flank = False for direction in self.DIRECTIONS: _i = i _j = j di = direction[0] dj = direction[1] buf = [] while True: _i = _i + di _j = _j + dj current_pos = board[_i][_j] if current_pos == "?": # invalid position: no flank to be found along this path break elif current_pos == ".": # blank position: no flank to be found along this path break elif current_pos == color and len(buf) == 0: # neighbouring already controlled disc: no flank to be found here break elif current_pos == target_color: # storing coordinates of current disc # as it will be flipped if we find a valid # flank along this path buf.append((_i, _j)) continue else: # flank detected: this is a valid move; found_flank, found_move = True, True flanked_discs.extend(buf) break if not found_flank: # moving to next position on the board continue # cloning board # updated_board = self.deepcopy(board) updated_board = self.copy.deepcopy(board) # effectively making the move updated_board[i][j] = color # flipping flanked discs for disc in flanked_discs: updated_board[disc[0]][disc[1]] = color _, score = self.minimax( updated_board, not should_maximize, depth_level + 1, max_depth, alpha, beta ) # applying alpha-beta pruning if should_maximize: if score >= beta: return ((i, j), score) alpha = max(alpha, score) else: if score <= alpha: return ((i, j), score) beta = min(beta, score) possible_moves.append(((i, j), score)) if not found_move: # this is a leaf node (terminal state), # so we must stop the recursion and evaluate score = self.evaluate_board_configuration(board) return (None, score) # finding best move based on current node's strategy (to maximize or to minimize) coord, best_score = None, float("-inf") if should_maximize else float("inf") for c, score in possible_moves: if ((should_maximize and score > best_score) or (not should_maximize and score < best_score)): coord = c best_score = score return (coord, best_score) def play(self, board_wrapper): """ Method implementing the expected interface for a player @params: board_wrapper: an object wrapping the current board configuration; @returns: The chosen move. """ # measuring time we're taking to make the play # by the tournament rules, # we have at most 3 seconds to make a move. start = self.time.time() if not self.first_turn: # incrementing turn-count by two, # to keep up-to-date with the # turn our opponent just played self.turn += 2 else: self.first_turn = False if self.turn == 1: # returning default first move # if we're the first player to play return self.Move(4, 3) # unwrapping board configuration object board = board_wrapper.board corner_checks = self.time.time() # we always capture a corner if we can if self.turn > 20: for corner_coords in self.CORNERS: corner_color = board[corner_coords[0]][corner_coords[1]] if corner_color == ".": for direction in self.DIRECTIONS: _i, _j = corner_coords[0], corner_coords[1] di, dj = direction[0], direction[1] _i += di _j += dj current_pos = board[_i][_j] if current_pos != self.opponent_color: continue found_flank = False while True: _i += di _j += dj current_pos = board[_i][_j] if current_pos == "?" or current_pos == ".": # no flank found along this path break if current_pos == self.color: # found flank, we can capture this corner! return self.Move(corner_coords[0], corner_coords[1]) corner_checks = self.time.time() - corner_checks depthness = 4 while True: # executing minimax with alpha-beta pruning using an iterative DFS elapsed_in_iteration = self.time.time() move, score = self.minimax(board, True, 0, depthness, float("-inf"), float("inf")) elapsed_in_iteration = self.time.time() - elapsed_in_iteration elapsed = self.time.time() - start if elapsed + (elapsed_in_iteration * 8) >= 2.5: break depthness += 1 if self.DEBUG_FLAG: print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" print "Turn {}".format(str(self.turn)) print "Reached depthness {}".format(str(depthness)) print "Took {} to play".format(str(self.time.time() - start)) print "Took {} to check corners".format(str(corner_checks)) print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" return self.Move(move[0], move[1])
9309ead951070f482f006fcd6d453a5f76ba9b24
Mauricio1xtra/python
/python_django/project/calculo_imc.py
826
4.03125
4
nome = input("Qual o seu nome?\n") idade = input("Qual a sua idade?\n") altura = input("Qual a sua altura?\n") peso = input("Qual o seu peso?\n") idade = int(idade) altura = float(altura) peso = float(peso) imc = peso / (altura **2) ano_atual = 2021 ano_nasc = ano_atual - idade print(f'{nome} tem {idade} anos, {altura} e pesa {peso}kg') print(f'O IMC de {nome} é {imc:.2f}') print(f'{nome} nasceu em {ano_nasc}') #print(nome, 'tem', idade, 'anos', 'de idade e seu imc é:', imc) #print(f'{nome} tem {idade} anos de idade e seu imc é {imc:.2f}') #print('{} tem {} anos de idade e seu imc é {:.2f}'.format(nome, idade, imc)) #print('{n} tem {i} anos de idade e seu imc é {im:.2f}'.format(n=nome, i=idade, im=imc)) """ print('Nome:', nome) print('Idade:', idade) print('Altura:', altura) print('É maior:', e_maior) """
6af51a556a534b2bf74149f8263f5708d13b5c49
yazdanimehrdad1/CodingDojo-pythonStack
/assignments/python loops predict.py
63
3.59375
4
#1 for i in range(1, 10, 1): print(i) # prints 1 through 9
e2b16b0847efaca364ad5e2e45d031a874be8d45
tuckerbrooks/COS125HW1
/hw1c.py
303
3.71875
4
# File: hw1b.py # Author: Tucker Brooks # Date: September 14, 2019 # Section: 1001 # E-mail: [email protected] # Description: # Get the sum of 10 numbers # Collaboration: # N/A x = 0 total = 0 while (x < 10): value = input("Enter a value: ") total = total + int(value) x = x + 1 print ("The sum is:", total)
dc0ea6ece7d6d6f44a52485f9741248335a6f514
gchacaltana/python_snippets
/01_multiple_assignments.py
639
4.4375
4
# !/usr/bin/env python # -*- coding: utf-8 -*- # Declaración y asignación múltiple de variables. x ,y, z = 2, 3, 5 # x = 2 # y = 3 # z = 5 print(f"\n1ra Asignacion") print(f"x = {x} \ty = {y}\tz = {z}") # Devuelve: 2 3 5 print(f"\n2da Asignacion") print(f"y, x = x, z") y, x = x, z # y = x # x = z print(f"x = {x} \ty = {y}\tz = {z}") # Devuelve: # x = 5 # y = 2 # z = 5 print(f"\n3ra Asignacion") print(f"x, z = 2y, 3x") x, z = 2*y, 3*x # x = 2y # z = 3x print(f"x = {x} \ty = {y}\tz = {z}") # Ejemplo # r = 2x + 3y - 2z r = 2*x + 3*y - 2*z print(f"\nr = 2x + 3y - 2z") print(f"r = 2({x}) + 3({y}) - 2({z})") print(f"r = {r}")
681b457c04be0bbf4699535760ccd0c7a6e00dfe
rkalz/CS355
/hw3_pokerhands.py
2,843
3.65625
4
# Rofael Aleezada # January 29 2018 # Pokerhands Program, CS 355 # A program that simulates several instances in a poker game from random import shuffle from multiprocessing import Process # Creates a player with a hand that can draw cards from the top of a deck class Player: hand = None def __init__(self): self.hand = [] def __str__(self): return self.hand def draw_card(self, game_deck): card = game_deck.cards.pop(0) self.hand.append(card) return card # Creates a deck that generates all standard cards, and can give a specific # card to a specific player class Deck: cards = None def __init__(self): self.cards = [] for i in range(10): for j in range(i+1): self.cards.append(i+1) def __str__(self): return self.cards def give_card(self, player, id_req): for i in range(len(self.cards)): if self.cards[i] == id_req: player.hand.append(self.cards.pop(i)) break # Check if a player received a pair def has_pair(player): seen = set() for card in player.hand: if card in seen: return True seen.add(card) return False def setup(q3): deck = Deck() A = Player() deck.give_card(A, 6) deck.give_card(A, 5) deck.give_card(A, 3) if q3: deck.give_card(A, 10) B = Player() deck.give_card(B, 10) deck.give_card(B, 6) deck.give_card(B, 5) shuffle(deck.cards) return deck, A, B # Simulate total matches and find when A gets a pair def a_got_pair(total): pairs = 0 for i in range(total): deck, A, _ = setup(False) A.draw_card(deck) if has_pair(A): pairs = pairs + 1 print("A gets a pair " + str(int(pairs/total * 49)) + "/49 of the time") # Simulate total matches and find when B gets a pair def b_got_pair(total): pairs = 0 for i in range(total): deck, _, B = setup(False) B.draw_card(deck) if has_pair(B): pairs = pairs + 1 print("B gets a pair " + str(int(pairs/total * 49)) + "/49 of the time") # Simulate total matches and find when A draws, doesn't get a pair # then B draws, gets a pair def b_got_pair_after_a_got_ten(total): pairs = 0 for i in range(total): deck, A, B = setup(True) B.draw_card(deck) if has_pair(B): pairs = pairs + 1 print("B gets a pair after A draws a 10 " + str(int(pairs/total * 48)) + "/48 of the time") def run(times): p1 = Process(target=a_got_pair, args=[times,]) p2 = Process(target=b_got_pair, args=[times,]) p3 = Process(target=b_got_pair_after_a_got_ten, args=[times,]) p1.start() p2.start() p3.start() p1.join() p2.join() p3.join() run(10000)
536e518b933fbc3a81ab05162f4719d26c564a49
xavierohan/movie_recom
/RecommNet/RecommNet.py
3,541
3.734375
4
import pandas as pd import numpy as np pathname = '/Users/xavierthomas/Desktop/the-movies-dataset' df_movies = pd.read_csv(pathname + '/' + 'df_large.csv') df_ratings = pd.read_csv(pathname + '/' + 'd_large.csv') ratings = pd.read_csv(pathname + '/' + 'ratings_small.csv') del df_movies['overview'] # df_movies.head() df_ratings.rename(columns = {'id':'MovieId'}, inplace = True) df_ratings = df_ratings[['userId', 'MovieId', 'title', 'genres', 'keywords', 'rating']] d = df_ratings # print("Size of ratings dataframe: ",len(ratings), " Size of movies dataframe: ",len(df_movies)) from ast import literal_eval # To return the first 3 genres df_movies['genres'] = df_movies['genres'].apply(literal_eval).apply(lambda x : x[0:3]) del df_movies['Unnamed: 0'] # Split the genres to separate columns df_movies[['genre1','genre2', 'genre3']] = pd.DataFrame(df_movies.genres.tolist(), index= df_movies.index) # df_movies.head(2) # Drop movies that do not have two genre values n = len(df_movies) df_movies.dropna(subset = ["genre1", "genre2"], inplace=True) # print("Size of DataFrame after dropping movies that do not have 2 genre valus : ",len(df_movies)) print("Number of movies dropped from original dataset (because of null values) : ", n - len(df_movies)) # Map genre1 to integer values genre1_list = np.unique(df_movies.genre1) g1_dict = {k: int(v) for v, k in enumerate(genre1_list)} # Map genre2 to integer values genre2_list = np.unique(df_movies.genre2) g2_dict = {k: int(v) for v, k in enumerate(genre2_list)} # Replace categorical values of genre with integer values df_movies = df_movies.replace({"genre1": g1_dict, "genre2": g2_dict}) df_movies.head(2) ratings = ratings.rename(columns={'movieId': 'id'}) # merge ratings and df_movies based on movieid d = pd.merge(ratings, df_movies, on ='id' ) del ratings del d['timestamp'] del d['popularity'] del d['release_date'] del d['actors'] del d['director'] # mapping the movieid to continous targets, as there are breaks between ids t = dict([(y,x) for x,y in enumerate(np.unique(d['id']))]) d['id'] = d['id'].map(t) # starting userId from 0 d['userId'] = d['userId'] - 1 # Getting the most common movie keywords import ast temp =[] for i in d['keywords']: res = ast.literal_eval(i) temp.extend(res) # print(len(temp)) from collections import Counter Counter = Counter(temp) most_occur = Counter.most_common(1500) #1500 # Convert most common keywords to integer values k = dict([(y[0], x) for x, y in enumerate(most_occur)]) f = [] for i in d['keywords']: temp = [] for j in ast.literal_eval(i): if j in k.keys() and len(temp) < 3: temp.append(k[j]) f.append(temp) d['key'] = f d['key_count'] = d['key'].apply(lambda x: len(x)) # print("Size before dropping: ",len(d)) d = d[d['key_count'] >1] # Drop movies that have less than one most common keywords # print("Size of DataFrame after dropping : ",len(d)) # Create columns based on keyword integer value d[['key1','key2', 'key3']] = pd.DataFrame(d.key.tolist(), index= d.index) # Map the Keyword values to continous values starting from 0 key_list = np.unique(list(np.unique(d['key1'])) + list(np.unique(d['key2']))) t = dict([(y,x) for x,y in enumerate(key_list)]) d = d.replace({"key1": t, "key2":t}) del d['genre3'] del d['key'] del d['key_count'] del d['key3'] print("Number of unique movies : ",len(np.unique(d['id'])),"\nNumber of unique users: ", len(np.unique(d['userId'])), "\nTotal Number of enteries in the DataFrame: ", len(d))
c5ec9fe5a423e13519cf51b3f4bca441e923363b
jweiwu/ucom-python
/lab36.py
562
3.53125
4
import itertools a1 = list('pqr') a2 = list('ABCDE') a3 = list('5678') c1 = itertools.chain(a1, a2, a3) print type(c1) for c in c1: print c, print print "again..." for c in c1: print c, print c2 = itertools.chain(a1, a2, a3) l1 = [c for c in c2] for l in l1: print l, print "\nagain...\n" for l in l1: print l, print "" l2 = 'ABCDEF' c3 = itertools.permutations(l2, 2) l2 = [c for c in c3] print len(l2), [l for l in l2] print "now print c4" l3 = 'ABCDEF' c4 = itertools.combinations(l3, 3) l4 = [c for c in c4] print len(l4), [l for l in l4]
c49459825e7ba927ac0e1907aac3bb34a3300db9
nisamk/Hello-world
/hackerrank/common child.py~
428
3.6875
4
str1,str2 =input(),input() matrix = [[0]*(len(str2)+1) for i in range(len(str1)+1)] for i in range(len(str1)+1): for j in range(len(str2)+1): if i == 0 or j == 0: matrix[i][j] = 0 elif str1[i-1] == str2[j-1]: matrix[i][j] = matrix[i-1][j-1]+1 else: matrix[i][j] = max(matrix[i-1][j],matrix[i][j-1]) print (matrix[len(str1)][len(str2)])
bf4c424b501e6736f47cff2382896a2c5190c2fe
tonper19/PythonDemos
/beyond_the_basics/03.closures_an_decorators/demo05_function_factories_raise_to_any_number.py
634
4.59375
5
""" """ def raise_to(exponent): def raise_to_exponent(x): return pow(x, exponent) return raise_to_exponent if __name__ == "__main__": # the parameter exponent will be a closure with the value of 2 square = raise_to(2) # and here is the proof: print(square.__closure__) # and now, when square is invoked, it will raise a number to the power of 2 print(f"The square of 5 is: {square(5)}") print(f"The square of 19 is: {square(19)}") # and we can create functions the same way: cube = raise_to(3) print(f"The cube of 5 is: {cube(5)}") print(f"The cube of 19 is: {cube(19)}")
79cce00c5afcbd2c1a77b4d3164d51a452cb796e
pengyuhou/git_test1
/leetcode/49. 字母异位词分组.py
438
3.703125
4
class Solution(object): def groupAnagrams(self, strs): a = {} for s in strs: ret = sorted(s) res = ''.join(ret) if res not in a.keys(): a[res] = [s] else: a[res].append(s) ret = [i for i in a.values()] return ret if __name__ == "__main__": print(Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
a97f76817a4a1b5b0779f854a74df83bf5d1ca81
therohitsingh/Top300DSACode
/Dynamic Programming/fibonacci-dp.py
144
3.6875
4
def fib(n): f = [0,1] for i in range(2,n+1): f.append(f[i-1]+f[i-2]) return f[n] n = int(input()) print(fib(n))
85cc8af0e80530cf7ea03907d23a5aca234e1221
inki-hong/python-fast
/func.py
143
3.859375
4
def cube(n): c = n * n * n return c result = cube(5) print(result) for x in range(100, 110): result = cube(x) print(result)
44ce4c0b69e186bff6b5cf3d3bb5cab35aa3813b
jduerbig/random-files
/hangman2.py
344
4.21875
4
#how tp change a string into a list myString = "Arizona" mysteryWord = list(myString) print(mysteryWord) guessList = [] #how to make a list using underscores for characters for letter in mysteryWord: guessList.append("_") print(guessList) # how to replace a specific index in a list guessList[3] = "z" print(guessList)
bafaeeca05cca931623d3b1f93c01fd728c57b2f
wjymath/leetcode_python
/415.add_strings/add_strings.py
945
3.5
4
class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ if len(num1) == 0: return num2 if len(num2) == 0: return num1 if len(num2) > len(num1): num1, num2 = num2, num1 num1 = num1[::-1] num2 = num2[::-1] value = 0 result = '' for i in range(len(num2)): tmp = int(num1[i]) + int(num2[i]) + value result += str(tmp % 10) value = tmp / 10 if value == 0: return (result + num1[len(num2):])[::-1] for i in range(len(num2), len(num1)): tmp = int(num1[i]) + value result += str(tmp % 10) value = tmp / 10 if value == 1: result += '1' return result[::-1] if __name__ == '__main__': print Solution().addStrings('999', '1')
fca0385fa12f88d026ffec5fa70fea1043be5bb6
perfectyuan/neural-network
/02-neural-network.py
757
3.671875
4
#创建一个神经网络类 class neuralNetwork : #initialise the neural network def __init__(self,inputnodes,hiddiennotes,outputnodes,learningrate): #set number of nodes in each input,hidden,output layer self.inodes = inputnodes self.hnodes = hiddiennotes self.onodes = outputnodes #learning rate self.lr = learningrate pass #train the neural network def train(): pass #query the neural network def query(): pass #创建一个小型神经网络,每层三个节点,学习率为0.3 input_nodes = 3 hidden_nodes = 3 output_nodes = 3 learning_rate = 0.3 #创建一个对象 n = neuralNetwork(input_nodes,hidden_nodes,output_nodes,learning_rate)
81dc55eb9417199fbf3e3e7d87a0906c7820c717
zhangxiatlq/pythonDemo
/classDemo/classSimple.py
800
3.78125
4
class Employee: '所有哦员工的基类' empCount = 0 def __init__(self,name,age): self.name = name self.age = age Employee.empCount +=1 def displayCount(self): print("Total Employee %d" % Employee.empCount) def displayEmplyee(self): print("Name:",self.name," age:",self.age) def prt(self): #self不是关键字,可以随意命名 print(self) print(self.__class__) if __name__ == "__main__": #构造方法创建对象 emp1 = Employee("xiaoming",25) emp2 = Employee("xiaoqiang",30) print(emp1.displayEmplyee()) print(emp2.displayEmplyee()) emp1.prt() #直接定义对象,然后调用初始化方法 t = Employee; t.__init__(t,"xiaozhang",20) print(t.displayEmplyee(t))
46abb35ce255285b9a3dd65aaca5fb51f567ccd1
ambosing/PlayGround
/Python/Problem Solving/BOJ/boj11729.py
242
3.796875
4
def hanoi(h, a, b, c, res): if h < 1: return hanoi(h - 1, a, c, b, res) res.append((a, c)) hanoi(h - 1, b, a, c, res) n = int(input()) lst = [] hanoi(n, 1, 2, 3, lst) print(len(lst)) for i, j in lst: print(i, j)
29e0cf91cbb6387e96042ea623508453655665fb
abbykahler/Python
/algo/functions_basic_II.py
794
3.921875
4
# 1 Countdown # num = 5 # def countdown(num): # new_list = [] # for x in range(num,-1,-1): # new_list.append(x) # return new_list # print(countdown(5)) # 2 Print and Return # list=[1,2] # def print_return(list): # print (list[0]) # return list[1] # print (print_return(1,2)) # 3 First Plus Length # def first_plus_length(list): # sum = list[0] + len(list) # return sum # 4 Values Greater than Seconds def value_greater(list): new_list = [] for i in list: if i > list[1]: new_list.append(i) print(len(new_list)) if len(new_list) < 2: return False else: return new_list # 5 This Length, That Value def length_value(size,value): list = [value] * size return list
1af92bbf191f005bc17d0b9f113c5fa87486ab4b
KonstantinKlepikov/scikit-fda
/examples/plot_clustering.py
7,201
4.1875
4
""" Clustering ========== In this example, the use of the clustering plot methods is shown applied to the Canadian Weather dataset. K-Means and Fuzzy K-Means algorithms are employed to calculate the results plotted. """ # Author: Amanda Hernando Bernabé # License: MIT # sphinx_gallery_thumbnail_number = 6 import matplotlib.pyplot as plt import numpy as np from skfda import datasets from skfda.exploratory.visualization.clustering import ( plot_clusters, plot_cluster_lines, plot_cluster_bars) from skfda.ml.clustering.base_kmeans import KMeans, FuzzyKMeans ############################################################################## # First, the Canadian Weather dataset is downloaded from the package 'fda' in # CRAN. It contains a FDataGrid with daily temperatures and precipitations, # that is, it has a 2-dimensional image. We are interested only in the daily # average temperatures, so we select the first coordinate function. dataset = datasets.fetch_weather() fd = dataset["data"] fd_temperatures = fd.coordinates[0] # The desired FDataGrid only contains 10 random samples, so that the example # provides clearer plots. indices_samples = np.array([1, 3, 5, 10, 14, 17, 21, 25, 27, 30]) fd = fd_temperatures[indices_samples] ############################################################################## # The data is plotted to show the curves we are working with. They are divided # according to the target. In this case, it includes the different climates to # which the weather stations belong to. climate_by_sample = [dataset["target"][i] for i in indices_samples] # Note that the samples chosen belong to three of the four possible target # groups. By coincidence, these three groups correspond to indices 1, 2, 3, # that is why the indices (´climate_by_sample´) are decremented in 1. In case # of reproducing the example with other ´indices_samples´ and the four groups # are not present in the sample, changes should be made in order ´indexer´ # contains numbers in the interval [0, n_target_groups) and at least, an # occurrence of each one. indexer = np.asarray(climate_by_sample) - 1 indices_target_groups = np.unique(climate_by_sample) climates = dataset["target_names"][indices_target_groups] # Assigning the color to each of the groups. colormap = plt.cm.get_cmap('tab20b') n_climates = len(climates) climate_colors = colormap(np.arange(n_climates) / (n_climates - 1)) fd.plot(sample_labels=indexer, label_colors=climate_colors, label_names=climates) ############################################################################## # The number of clusters is set with the number of climates, in order to see # the performance of the clustering methods, and the seed is set to one in # order to obatain always the same result for the example. n_clusters = n_climates seed = 2 ############################################################################## # First, the class :class:`~skfda.ml.clustering.KMeans` is instantiated with # the desired. parameters. Its :func:`~skfda.ml.clustering.KMeans.fit` method # is called, resulting in the calculation of several attributes which include # among others, the the number of cluster each sample belongs to (labels), and # the centroids of each cluster. The labels are obtaiined calling the method # :func:`~skfda.ml.clustering.KMeans.predict`. kmeans = KMeans(n_clusters=n_clusters, random_state=seed) kmeans.fit(fd) print(kmeans.predict(fd)) ############################################################################## # To see the information in a graphic way, the method # :func:`~skfda.exploratory.visualization.clustering_plots.plot_clusters` can # be used. # Customization of cluster colors and labels in order to match the first image # of raw data. cluster_colors = climate_colors[np.array([0, 2, 1])] cluster_labels = climates[np.array([0, 2, 1])] plot_clusters(kmeans, fd, cluster_colors=cluster_colors, cluster_labels=cluster_labels) ############################################################################## # Other clustering algorithm implemented is the Fuzzy K-Means found in the # class :class:`~skfda.ml.clustering.FuzzyKMeans`. Following the # above procedure, an object of this type is instantiated with the desired # data and then, the # :func:`~skfda.ml.clustering.FuzzyKMeans.fit` method is called. # Internally, the attribute ``labels_`` is calculated, which contains # ´n_clusters´ elements for each sample and dimension, denoting the degree of # membership of each sample to each cluster. They are obtained calling the # method :func:`~skfda.ml.clustering.FuzzyKMeans.predict`. Also, the centroids # of each cluster are obtained. fuzzy_kmeans = FuzzyKMeans(n_clusters=n_clusters, random_state=seed) fuzzy_kmeans.fit(fd) print(fuzzy_kmeans.predict(fd)) ############################################################################## # To see the information in a graphic way, the method # :func:`~skfda.exploratory.visualization.clustering_plots.plot_clusters` can # be used. It assigns each sample to the cluster whose membership value is the # greatest. plot_clusters(fuzzy_kmeans, fd, cluster_colors=cluster_colors, cluster_labels=cluster_labels) ############################################################################## # Another plot implemented to show the results in the class # :class:`~skfda.ml.clustering.FuzzyKMeans` is # :func:`~skfda.exploratory.visualization.clustering_plots.plot_cluster_lines` # which is similar to parallel coordinates. It is recommended to assign colors # to each of the samples in order to identify them. In this example, the # colors are the ones of the first plot, dividing the samples by climate. colors_by_climate = colormap(indexer / (n_climates - 1)) plot_cluster_lines(fuzzy_kmeans, fd, cluster_labels=cluster_labels, sample_colors=colors_by_climate) ############################################################################## # Finally, the function # :func:`~skfda.exploratory.visualization.clustering_plots.plot_cluster_bars` # returns a barplot. Each sample is designated with a bar which is filled # proportionally to the membership values with the color of each cluster. plot_cluster_bars(fuzzy_kmeans, fd, cluster_colors=cluster_colors, cluster_labels=cluster_labels) ############################################################################## # The possibility of sorting the bars according to a cluster is given # specifying the number of cluster, which belongs to the interval # [0, n_clusters). # # We can order the data using the first cluster: plot_cluster_bars(fuzzy_kmeans, fd, sort=0, cluster_colors=cluster_colors, cluster_labels=cluster_labels) ############################################################################## # Using the second cluster: plot_cluster_bars(fuzzy_kmeans, fd, sort=1, cluster_colors=cluster_colors, cluster_labels=cluster_labels) ############################################################################## # And using the third cluster: plot_cluster_bars(fuzzy_kmeans, fd, sort=2, cluster_colors=cluster_colors, cluster_labels=cluster_labels)
9e91d29f86091554855d989ca871a66b09c7e123
LuizFelipeBG/CV-Python
/Mundo 2/ex61.py
269
3.75
4
n1 = int(input('primeiro termo da PA: ')) r = int(input('Razão da PA: ')) ter = n1 c = 1 to = 0 r1 = 10 while r1 != 0: to = to + r1 while c <= to: print('{} >'.format(ter),end=' ') ter += r c += 1 r1 =int(input('Mais números? '))
dd81d79c64a90c6e5eb6a3c888df73f99d72348e
Joelma-Avelino/curso-em-video-python
/desafio/desafio13.py
214
3.78125
4
valor = float(input('Qual valor do seu salario atual? ')) vaumento = valor * 0.15 nvalor = valor + vaumento print ('O seu atual salario de {} com aumento de 15% R${} fica por R${}'.format(valor, vaumento, nvalor))
6776e26844e55e831a01e0c5d5a63c0a352c99a9
Dheeraj1998/code2flow
/code2flow/__main__.py
766
3.5
4
import code2flow from code2flow import flowchart_generator import sys def main(): arguments = [argument for argument in sys.argv[1:] if not argument.startswith("-")] #options = [option for option in sys.argv[1:] if option.startswith("-")] if(len(arguments) == 0): print("A python module / CLI command to create flow charts from python code.") print("") print("Usage: code2flow <file name>") print("") else: file_name = arguments[0] function_dot_codes = flowchart_generator.read_source_code(file_name) for function_name in function_dot_codes: print(function_name) print(function_dot_codes[function_name]) print("") if __name__ == "__main__": main()
f90d1fa61cabc649258cec1ccb80fdec91702ce0
baocogn/self-learning
/big_o_coding/Blue_13/Schoolwork/exam4.py
906
3.953125
4
# Phone List class TrieNode: def __init__(self): self.count_leaf = 0 self.child = dict() self.pre_check = False class Trie: def __init__(self): self.root = TrieNode() def add_word(self, s): cur = self.root flag = True for c in s: if c not in cur.child: cur.child[c] = TrieNode() cur.pre_check = True cur = cur.child[c] if cur.count_leaf != 0: flag = False cur.count_leaf += 1 if cur.pre_check: flag = False return flag TC = int(input()) for t in range(TC): n = int(input()) trie = Trie() check = True for i in range(n): s = input().strip() check = check and trie.add_word(s) if check: print('Case {}: YES'.format(t+1)) else: print('Case {}: NO'.format(t+1))
c763ccca1b984a69753ca163410587b96af2909a
zenginbusraa/flatten-reverse
/main.py
421
3.859375
4
def flatten(list1): if len(list1)== 0: return list1 if isinstance(list1[0],list): return flatten(list1[0]) + flatten(list1[1:]) return list1[:1] + flatten(list1[1:]) def reverse2(liste): rlist = [] for x in liste: x.reverse() rlist.append(x) rlist.reverse() return rlist print(flatten([[1,'a',['cat'],2],[[[3]],'dog'],4,5])) print(reverse2([[1, 2], [3, 4], [5, 6, 7]]))
5758478dfd2c70bde878b61898595aa16d458033
karolramos/aprendendo_pitonha
/console_blackjack.py
3,156
4.09375
4
############### Our Blackjack House Rules ##################### ## The deck is unlimited in size. ## There are no jokers. ## The Jack/Queen/King all count as 10. ## The the Ace can count as 11 or 1. ## Use the following list as the deck of cards: ## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] ## The cards in the list have equal probability of being drawn. ## Cards are not removed from the deck as they are drawn. ## The computer is the dealer. import random import os from mini_projects_python.art import logo_blackjack def deal_card(): """ retorna uma carta aleatória do baralho """ cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] card = random.choice(cards) return card def calculate_score(cards): """ pega a lista de cartas e retorna o valor somado nelas """ if sum(cards) == 21 and len(cards) == 2: # checando blackjack return 0 # checando se tem 11 e se a pontuação está acima de 21, se tiver substitua 11 por 1 if 11 in cards and sum(cards) > 21: cards.remove(11) cards.append(1) return sum(cards) def compare(user_score, computer_score): if user_score == computer_score: return "Draw!" elif computer_score == 0: return "Lose, opponent has Blackjack!" elif user_score == 0: return "Win with a Blackjack!" elif user_score > 21: return "You went over. You lose" elif computer_score > 21: return "Opponent went over. You win!" elif user_score > computer_score: return "You win!" else: return "You lose!" def play_game(): print(logo_blackjack) user_cards = [] computer_cards = [] is_game_over = False # adicionando duas cartas para os dois(usuário e computador) for _ in range(2): new_card = deal_card() user_cards.append(new_card) # ou user_cards.append(deal_card()) da a mesma coisa computer_cards.append(deal_card()) # adc duas cartas para cada um. while not is_game_over: user_score = calculate_score(user_cards) computer_score = calculate_score(computer_cards) print(f"You cards: {user_cards}, current score: {user_score} ") print(f"Computer cards: {computer_cards[0]} ") if user_score == 0 or computer_score == 0 or user_score > 21: is_game_over = True else: answer = input("Type 'y' to get another card, type 'n' to pass: ").islower() if answer == "y": user_cards.append(deal_card()) # se o user decidir continuar jogando vai chamar outras cartas else: is_game_over = True while computer_score != 0 and computer_score < 17: computer_cards.append(deal_card()) computer_score = calculate_score(computer_cards) # atualizando o score print(f" Your final hand: {user_cards}, final score: {user_score} ") print(f" Computer's final hand: {computer_cards}, final score: {computer_score} ") print(compare(user_score, computer_score)) while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y": os.system('clear') play_game()
c86e94c4a0bde15280bfb8cbc8c94e265d1e917c
marcusorefice/-studying-python3
/Exe045.py
905
3.84375
4
'''Crie um programa que faça o computador jogar Jokenpê com você.''' from random import randint j = int(input('Você quer: \n[1] PEDRA \U0000270A \n[2] PAPEL \U0000270B \n[3] TESOURA \U0000270C \n')) print('-'*30) r = int(randint(1, 3)) if j == 1 and r == 3: print(f'VOCÊ GANHOU! O computador colocou TESOURA\U0000270C') elif j == 2 and r == 1: print(f'VOCÊ GANHOU! O computador colocou PEDRA\U0000270A') elif j == 3 and r == 2: print(f'VOCÊ GANHOU! O computador colocou PAPEL\U0000270B') elif j == 1 and r == 1 or j == 2 and r == 2 or j == 3 and r == 3: print(f'EMPATOU') elif j == 1 and r == 2: print(f'O COMPUTADOR GANHOU! Colocou PAPEL\U0000270B') elif j == 2 and r == 3: print(f'O COMPUTADOR GANHOU! Colocou TESOURA \U0000270C') elif j == 3 and r == 1: print('O COMPUTADOR GANHOU! Colocou PEDRA \U0000270A') else: print('OPÇÃO INVÁLIDA')
558334e31b01cf66421685c2d2b5a31eac8d29ca
jenniferyhwu/CS50-psets
/pset6/sentimental/mario/more/mario.py
379
3.984375
4
while True: height = int(input("Height: ")) if (height > 0 and height < 24): break for y in range(0, height): for space in range(0, height - (y + 1)): print(" ", end="") for x in range(0, y + 1): print("#", end="") print(" ", end="") print(" ", end="") for x in range(0, y + 1): print("#", end="") print()
4f8e05b85325605d48f47f8ef25dcc17c6189d30
rioadinugraha/1st-year
/pascal.py
577
3.6875
4
def pascal_triangle(n): print([1]) print([1,1]) pascal = [0,0,0] prevLine = [1,1] for k in range (3,n+1): for i in range(0,k): if i == 0: value = prevLine[i] pascal[i] = value elif i == k-1: value = 1 pascal[i]= value else: value = prevLine[i] + prevLine[i-1] pascal[i] = value print(pascal) prevLine = list(pascal) pascal=[0]*(len(pascal)+1) prevLine.append(0) pascal_triangle(6)
4936f793e739edfcca551a44524e2e452fb94bf7
Anshul1196/leetcode
/solutions/121.py
766
4
4
""" Solution for Algorithms #121: Best Time to Buy and Sell Stock. - N: Number of prices - Space Complexity: O(1) - Time Complexity: O(N) Runtime: 32 ms, faster than 99.07% of Python3 online submissions for Best Time to Buy and Sell Stock. Memory Usage: 13.9 MB, less than 60.94% of Python3 online submissions for Best Time to Buy and Sell Stock. """ class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 max_profit = 0 lowest_point = prices[0] for price in prices[1:]: if price - lowest_point > max_profit: max_profit = price - lowest_point if price < lowest_point: lowest_point = price return max_profit
f892388a9ae5298df6c185703b59c3cce04b1290
GdubyaSDSU/Networks-Coursework
/TCPserver.py
1,386
3.53125
4
#!/usr/bin/python # Gary Williams # CS 576 # Prog 1 Due 2/26/17 # This is a basic server TCP socket connection. # It connects to the localhost and specified port # and listens for packets with a max 256 characters. # The string is encoded by changing each character # to the next character in the ASCII table by default. # If the string is prefaced by a 'D', then the string # is decoded by doing the opposite. # Directions: Change host to local machine or other. # Run and wait for output for successful connection # or error. import socket import sys HOST = 'nibbler' #localhost used for dev PORT = 5760 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Enclosed bind in try block to catch busy port try: s.bind((HOST, PORT)) except Exception as inst: print inst print 'Host: ' + HOST + ' Port: ' + str(PORT) sys.exit(0) s.listen(1) conn, addr = s.accept() print 'Connected by ', addr tmpRay = [] fixed = [] while 1: data = conn.recv(256) if not data: break print 'Received: ', data ray = list(data) for i in ray: tmpRay.append(ord(i)) if tmpRay[0] == 68: # Test for 'D' new_list = [x-1 for x in tmpRay] new_list = new_list[1:] else: new_list = [x+1 for x in tmpRay] for i in new_list: fixed.append(chr(i)) conn.sendall(''.join(fixed)) conn.close()
3a1acb7dd6b015ef336e13bd087ebd594ba5091f
forvaishali/PythonProjects
/quizGame/quiz_game.py
955
4.125
4
print("Welcome to my computer game") playing = input("Do you want to play? ") if playing.lower() != "yes": quit() print("Okay, Lets Play :)") score = 0 answer = input("What does CPU stand for? ") # space after question important if answer.lower() == "central processing unit": print("Correct") score += 1 else: print("Incorrect") answer = input("What does US stand for? ") if answer.lower() == "united states": print("Correct") score += 1 else: print("Incorrect") answer = input("What does PSU stand for? ") # space after question i if answer.lower() == "power supply": print("Correct") score += 1 else: print("Incorrect") answer = input("What does RAM stand for? ") # space after question i if answer.lower() == "random access memory": print("Correct") score += 1 else: print("Incorrect") print("You got " + str(score) + " questions correct") print("You got " + str( (score / 4) * 100 ) + "%.")
d71e59d09dafffea5821431675b599a9c9bf5400
Parzival-Wade/Unit-conversion
/unitconverter.py
1,219
4.15625
4
import pandas user_input=input("What do you want to convert?[Distance or Time] ") user_input_for_col=user_input+":unit" user_input_list=user_input+":value" data= pandas.read_csv('conversion_table.csv', index_col=user_input_for_col) data_dict=data.to_dict() conversions_list=data_dict[user_input_list] def value_valid_checker(value): try: value = int(value) except ValueError: try: value = (input("Pls enter the value again")) value_valid_checker(value) finally: pass def conversion_checker(): if user_input == "Distance": if input_unit in conversions_list.keys(): pass elif output_unit in conversions_list.keys(): pass else: print("Conversion is not possible. Sorry!!") exit() def converting(val,unit_in,unit_out): return val * conversions_list[unit_in] / conversions_list[unit_out] input_unit=input("Which unit you want to convert??") output_unit = input("Which unit you want to be converted into??") value=input("Pls enter the value") value_valid_checker(value) value = int(value) conversion_checker() print(converting(value,input_unit,output_unit))
386ad990148de8693700e5046db9c8da11938ee8
divae/keepcodingLearnPython
/functions/map_filter_reduce.py
677
3.78125
4
from functools import reduce list_values = [1,2,-1,15,9] def double(x): return x*2 list_double_values = map(double,list_values) list_double_values1 = map(lambda x: x * 2 ,list_values) def is_pair(x): return x % 2 == 0 list_pairs_values = filter(is_pair, list_values) list_pairs_values = filter(lambda x: x % 2 == 0, list_values) unique_value = reduce(lambda collector, next_value : collector + next_value, list_values) sum100 = reduce(lambda collector,next_value: collector + next_value,range(101)) sum100 = reduce(lambda collector,next_value: collector + next_value,range(101)) print(list(list_double_values)) print(list(list_pairs_values)) print(unique_value)
2b253469bd6b88202743b9c894ee6d65ce3fd637
gabriellaec/desoft-analise-exercicios
/backup/user_061/ch26_2019_03_13_21_37_32_553158.py
232
3.65625
4
dias = int(input("DIAS")) horas = int(input("HORAS")) minutos = int(input("MINUTOS")) segundos = int(input("SEGUNDOS")) dias = dias*24*60*60 horas = horas*60*60 minutos = minutos*60 a = dias + horas + minutos + segundos print(a)
0efad27f73b67b3d3f30c5f084e3c5d618a663be
manthalkaramol/Demo
/PythonPrograms/assignment_operator2.py
166
3.78125
4
a=b=c=1 print (a,b,c) a=2 c=0 print (a,b,c) print (a and b) print (a and c) print (b or c) list = [1,2,4,5,7,8,10,16] print (a not in list) if a in list: print (a)
13a853bfd298ef7beaa826d4b41d6d0f7a3586f8
AhmedSadaqa/Qvirt
/my_django_app/customer/Myqueue.py
1,471
3.578125
4
try: from Queue import Queue, Full, Empty except: from queue import Queue, Full, Empty from datetime import datetime class MyQueue(Queue): "Wrapper around Queue that discards old items instead of blocking." def __init__(self, maxsize=10): assert type(maxsize) is int, "maxsize should be an integer" Queue.__init__(self, maxsize) def put(self, item): "Put an item into the queue, possibly discarding an old item." try: Queue.put(self, (datetime.now(), item), False) except Full: # If we're full, pop an item off and add on the end. Queue.get(self, False) Queue.put(self, (datetime.now(), item), False) def put_nowait(self, item): "Put an item into the queue, possibly discarding an old item." self.put(item) def get(self): "Get a tuple containing an item and the datetime it was entered." try: return Queue.get(self, False) except Empty: return None def get_nowait(self): "Get a tuple containing an item and the datetime it was entered." return self.get() def main(): "Simple test method, showing at least spec #4 working." queue = MyQueue(10) for i in range(1, 12): queue.put("Test item number %u" % i) while not queue.empty(): time_and_data = queue.get() print("%s => %s" % time_and_data) if __name__ == "__main__": main()
ee7c4082046ab8166f446c211a6d7ca00082dc12
tawfiqul27/python_code
/13_built_in_functions.py
2,052
4.0625
4
#### Numeric built-in functions x = '47' y = int(x) z = float(x) # y = abs(x) for absolute value # y = divmod(x, 3) for devision modulus value # y = complex(x, 32) this is for complex number. And will print 47 + 32j ### https://docs.python.org/3/library/functions.html # this list all the built-in numeric functions. print(x) print(f'The type of x is {type(x)}') print(y) print(f'The type of y is {type(y)}') print(z) print(f'The type of z is {type(z)}') ### String functions s = 'Hello world' print(repr(s)) # repr is the best string representation function class bunny: def __init__(self, n): self._n = n def __repr__(self): return f'repr: the number of bunnies is {self._n} 🖖' def __str__(self): return f'str: the number of bunnies is {self._n}' p = bunny(47) print(p) print(repr(p)) # repr will pick repr method from the class bunny print(ascii(p)) # this will print ascii value and unicode of any emoji print(chr(128406)) # chr prints the character representation of that number print(ord('🖖')) # this will give you number of that character ############################################################### ############################################################## # Container functions k = (1, 2, 3, 4, 5) # l = len(k) # l = reversed(k) # this will print reversed object string. # l = list(reversed(k)) # l = sum(k) # there are max, min, any, all, l = (6, 7, 8, 9, 10) z = zip(k, l) print(k) print(l) for a, b in z: print(f'{a} - {b}') print('------------This is the use of enumerator which set the index and value for a tupple-------------------') c = ('cat', 'dog', 'raptile', 'eagle') for i, v in enumerate(c): print(f'{i} - {v}') # x = 42 # y = isinstance(x, int) this will return true or false if x is not integer # y = id(x) id will print the unique of variable x # y = type(x) here type is a function and x is an object. These two combinely return the class of that object
5ceb4afeb691dbfd31eb9b01d0fe46283b815509
abhishekguptapune/DataScience
/Label_Encoding_or_Ordinal_Encoding.py
630
3.5
4
#Label Encoding or Ordinal Encoding import category_encoders as ce import pandas as pd train_df=pd.DataFrame({'Degree': ['High school','Masters','Diploma','Bachelors','Bachelors','Masters','Phd','High school','High school'] }) #Original data train_df print(train_df) # create object of Ordinalencoding encoder= ce.OrdinalEncoder(cols=['Degree'],return_df=True, mapping=[{'col':'Degree', 'mapping':{'None':0,'High school':1,'Diploma':2,'Bachelors':3,'Masters':4,'Phd':5}}]) #fit and transform train data df_train_transformed = encoder.fit_transform(train_df) print(df_train_transformed)
f29bff36d0153c454488d7bdf40bc7cfa932d3a9
ak-ashwin/leet_code
/12_balancedStringSplit.py
2,054
3.671875
4
from typing import List from collections import Counter # Example 1: # # Input: s = "RLRRLLRLRL" # Output: 4 # Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. # Example 2: # # Input: s = "RLLLLRRRLR" # Output: 3 # Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'. def arr_count_keys(MyList, unique_keys): a_list = dict(Counter(MyList)) l = unique_keys[0] r = unique_keys[1] if l in a_list: l_count = a_list[l] else: l_count = 0 if r in a_list: r_count = a_list[r] else: r_count = 0 return l_count, r_count def keys_equal(MyList, unique_keys): l, r = arr_count_keys(MyList, unique_keys) if l == r: return True else: return False class Solution: def balancedStringSplit(self, s: str) -> int: s_list = list(s) unique_keys = list(set(s_list)) arr = s_list.copy() output = 0 for i, _ in enumerate(s_list): j = i + 1 if j > 1: if keys_equal(arr[:j], unique_keys): output += 1 return output # class Solution: # def balancedStringSplit(self, s: str) -> int: # # scale = 0 # max_balance = 0 # # for c in s: # # if (c == 'R'): # scale += 1 # else: # scale -= 1 # # if (scale == 0): # max_balance += 1 # # return max_balance # class Solution: # def balancedStringSplit(self, S: str) -> int: # m = c = 0 # for s in S: # if s == 'L': c += 1 # if s == 'R': c -= 1 # if c == 0: m += 1 # return m if __name__ == "__main__": Sol = Solution() print(Sol.balancedStringSplit("RLLLLRRRLR")) print(Sol.balancedStringSplit("RLRRLLRLRL")) print(Sol.balancedStringSplit("LLLLRRRR")) print(Sol.balancedStringSplit("RLRRRLLRLL"))
02b0d0931164c92791f443282d14e90a9c19e703
VanillaTiger/adventofcode2020
/exercise_9/exercise_9.py
1,192
3.578125
4
with open('exercise_9_all.txt', 'r') as file: input_data = file.readlines() input_data = [int(m[:-1]) for m in input_data] print("input_data=",input_data) preamble = 25 def verify_data(number, previous_data): length = len(previous_data) sumita = [previous_data[x] + previous_data[y] for x in range(0, length) for y in range(0, length) if x != y] if number in sumita: return True def part1(preamble): for i in range(preamble, len(input_data)): previous_data = input_data[i - preamble:i] valid = verify_data(input_data[i], previous_data) if not valid: return input_data[i] def part2(vulnerability): length = len(input_data) for x in range(0, length): sumita = 0 for y in range(x, length): sumita += input_data[y] if sumita > vulnerability: break elif sumita == vulnerability: return (x, y) vulnerability = part1(preamble) print("vulnerability=",vulnerability) contigoues_set = part2(vulnerability) contigoues_set = input_data[contigoues_set[0]:contigoues_set[1]] print("encryption weakness=",min(contigoues_set) + max(contigoues_set))
9bcb3e98ee3a0f9d3ea0dd3ffdf808faf918dda5
jbizzlefoshizzle/Financial_Analysis-and-Voter_Results
/Python Script for Bank Data/main.py
2,056
3.875
4
# Declarations import os import csv #NEED THIS TO CALCULATE DIFFERENCES BETWEEN MONTHS import numpy as np # Defining max and min functions # ------------------------------------- def max(array, n): max = array[0] for i in range (1, n): if array[i] > max: max = array[i] return max # ------------------------------------- def min(array, n): min = array[0] for i in range (1, n): if array[i] < min: min = array[i] return min # Show me the money cash_csv = os.path.join('..','Resources','budget_data.csv') # Open and Read with open(cash_csv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") # Skip headers when counting data csv_header = next(csvfile) # Empty lists all_months = [] all_profits = [] # Put stuff in lists for row in csvreader: months = row[0] profits = int(row[1]) all_months.append(months) all_profits.append(profits) # Months of largest profit/loss n = len(all_profits) biggest_profit = max(all_profits, n) biggest_loss = min(all_profits, n) if row[1] == str(biggest_profit): big_profit_month = row[0] if row[1] == str(biggest_loss): big_loss_month = row[0] # Create list of changes between months monthly_changes = np.diff(all_profits) # How to find average average = sum(monthly_changes)/len(monthly_changes) average_change = format(average,'.2f') m = len(monthly_changes) greatest_increase = max(monthly_changes, m) greatest_loss = min(monthly_changes, m) print("Financial Analysis") print("----------------------------") print("Total Months: " + str(len(all_months))) print("Total: $" + str(sum(all_profits))) print("Average Change: $" + str(average_change)) print("Greatest Increase in Profits: " + str(big_profit_month) + " ($" + str(greatest_increase) + ")") print("Greatest Decrease in Profits: " + str(big_loss_month) + " ($" + str(greatest_loss) + ")")
a29fbfbfba7a113e31e99405eeb4ecd3fd7ebc2b
liuleee/python_base
/day02/08-continue和break.py
1,357
3.796875
4
# -*- coding:utf-8 -*- #continue结束本次循环,然后可以继续下次循环,整个循环不一定结束 #break:跳出当前循环,当前循环执行结束 #continue和Break不能单独使用,只能在循环语句中使用 # num = 1 # while num < 6: # print(num) # if num == 2: # num += 1 # #执行continue结束本次循环,continue后面的代码不会执行 # continue # num += 1 # else: # print('循环数据结束') num = 1 while num < 6: print(num) if num == 2: num += 1 #执行break结束当前循环,break后面的代码不会执行 break num += 1 else: # 如果循环语句里面执行了break,那么else不会执行 print('循环数据结束') print('=========') # for value in range(1, 5): # # if value == 2: # #continue结束本次循环 # continue # print(value) # else: # print('循环结束') for value in range(1, 5): if value == 2: #continue结束本次循环 break print(value) else: print('循环结束') #循环语句里面只要不执行break那么就是执行else语句 result = input('请输入您的姓名:') for value in ['zhang','lee']: if value == result: print(value,'here') #找到了这个人 break else: print('no this one')
a28fdb5ad4eded15b0b26da363660e9c1aeaf54f
suhao16/CSEScompetitiveprogramming
/introductory_problems/missing_number.py
310
3.78125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #------------------------------* # Author: Arijit Dasgupta | # Email: [email protected] | #------------------------------* len_line = int(input()) sum_line = len_line*(len_line+1)//2 line = [int(x) for x in input().split()] missing_num = sum_line - sum(line) print(missing_num)
a41cb795150f5c76b92f1d8a3163f3d9374b3db6
Pinto18/travis_example
/checkPrime.py
281
3.890625
4
import math def check(num): isPrime = False if num <= 1: return isPrime for index in range(2, math.ceil(math.sqrt(num))): isPrime = True if num % index == 0: isPrime = False return isPrime return isPrime
f3a976f2af9e53a3f392b4a3c30c9be5f390bc68
raginikk/Leetcode_May_Challenge
/FloodFill.py
582
3.515625
4
def FillPixel(image,r,c,prevC,newC): if( r<0 or r>=len(image) or c<0 or c>=len(image[0]) or image[r][c]==newC or image[r][c]!=prevC): return image[r][c]=newC FillPixel(image,r+1,c,prevC,newC) FillPixel(image,r-1,c,prevC,newC) FillPixel(image,r,c+1,prevC,newC) FillPixel(image,r,c-1,prevC,newC) class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: prevC = image[sr][sc] FillPixel(image,sr,sc,prevC,newColor) return image
2b6e00de5bb7207a01264950c32d4f8af8f4653f
LeslieK/JOBPREP
/Exercises.py
4,339
4.03125
4
def fib(n): '''find fibonacci number of n''' def helper(a, b, count): if count == 0: return b else: return helper(a + b, a, count - 1) return helper(1, 0, n) def sum(list): '''add the integers in a list''' num_elements = len(list) def sum_iter(acc, count): '''sum the itegers in a list''' if list == []: return 0 if count > 0: return sum_iter(acc + list[count - 1], count - 1) else: return acc return sum_iter(0, num_elements) def lastIndexOf(n, list): '''return the last index of n in a list''' if list == []: return -1 def helper(index, i, count): if i < count: if list[i] == n: index = i return helper(index, i + 1, count) else: return index return helper(-1, 0, len(list)) #lastIndexOf(5, [1,2,3,4,5,6,7,5,8,9,5,4]) # write a recursive function to compute sum of numbers stored in a binary tree class Node(object): def __init__(self, value, l=None, r=None): self.value = value self.left = l self.right = r tree1 = Node(1, Node(2, Node(3), Node(4)), Node(5, Node(6), Node(7))) tree2 = Node(1, Node(2, Node(3)), Node(2)) tree3 = Node(1) def sumTree(tree): '''sum of integer elements in tree''' root = tree.value left = tree.left right = tree.right def helper(acc, tree, parents): #print 'len parents: {}, root: {}'.format(len(parents), parents[-1].value) if tree is None: return acc parents.append(tree) acc = helper(acc + tree.value, tree.left, parents) acc = helper(acc, tree.right, parents) parents.pop() return acc return helper(0, tree, [tree]) def printTreeDFS(tree): '''prints elements in DFS order''' root = tree.value left = tree.left right = tree.right stack = [] def dfs(tree, stack): if tree is None: return stack stack = dfs(tree.left, stack) stack = dfs(tree.right, stack) stack.append(tree.value) return stack print dfs(tree, stack) import collections def printTreeBFS(tree): q = collections.deque() q.append(tree) while len(q) > 0: tree = q.popleft() if tree is not None: print tree.value q.append(tree.left) q.append(tree.right) def numberOfWays(n, cache): '''number of ways to climb a staircase of n steps can climb 1, 2, or 3 steps at a time''' if n < 1: return 0 elif n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: key = 'numberOfWays(' + str(n) + ')' if key in cache: return cache[key] else: cache[key] = numberOfWays(n - 1, cache) + numberOfWays(n - 2, cache) + numberOfWays(n - 3, cache) return cache[key] def numberOfWaysTaxi(row, col, cache): '''number of ways to get from start to goal NxN grid; only move right or down''' if row == 0 and col == 0: return 0 elif row == 0 and col == 1: return 1 elif row == 1 and col == 0: return 1 else: key = (row, col) if key in cache: return cache[key] elif col == 0: # on left border cache[key] = numberOfWaysTaxi(row-1, col, cache) elif row == 0: # on top border cache[key] = numberOfWaysTaxi(row, col-1, cache) else: cache[key] = numberOfWaysTaxi(row-1, col, cache) + numberOfWaysTaxi(row, col-1, cache) print cache[key] return cache[key] #numberOfWaysTaxi(10, 10, {}) def nChooseKCount(n, k, cache): '''compute the number of ways of choosing k elements from a set of n elements''' if k == n: return 1 elif k == 1: return n elif k == 0: return 1 else: key = (n, k) if key in cache: return cache[key] else: cache[key] = nChooseKCount(n-1, k-1, cache) + nChooseKCount(n-1, k, cache) return cache[key] # a set is a list of unique elements (use 'list' not 'set') def subsets(s): '''compute list of subsets from a list of unique items''' if s == []: return [[]] else: rest = subsets(s[1:]) return rest + map(lambda x: ([s[0]] + x), rest) def subsets_k(s, k): def subsets(s): '''compute list of subsets from a list of unique items''' if s == []: return [[]] else: rest = subsets(s[1:]) return rest + map(lambda x: ([s[0]] + x), rest) r = subsets(s) return filter(lambda x: len(x) == k, r) def sublists(big_list, selected_so_far): if big_list == []: return [selected_so_far] else: curr_element = big_list[0] rest_of_big_list = big_list[1:] return (sublists(rest_of_big_list, selected_so_far) + sublists(rest_of_big_list, selected_so_far + [curr_element]))
8fbc6adfeb4f97dafb955053e337dede71ed8935
trolly0305/LeetCode
/Algorithms/0143 Reorder List.py
1,406
3.875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def split(self, node): prev = None slow = fast = node while fast and fast.next: prev = slow slow = slow.next fast = fast.next.next if prev: prev.next = None return slow def reverse(self, node): prev, curr = None, node while curr: p = curr.next curr.next = prev prev = curr curr = p return prev def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place instead. """ # This special handling is important. # Otherwise for single node, it will generate # circle linked list if head is None or head.next is None: return mid = self.split(head) h1 = head h2 = self.reverse(mid) dummy = curr = ListNode(0) while h1 and h2: t1, t2 = h1.next, h2.next curr.next = h1 h1.next = h2 curr = h2 h1, h2 = t1, t2 if h1: curr.next = h1
87a67ef786c2ce9b996a04152b4b42aedd4dc523
DanDaMan23/CardGames
/deck_of_cards.py
1,707
3.8125
4
import random class Card: def __init__(self, suit, value): suits = ("hearts", "diamonds", "clubs", "spades") values = [str(i) for i in range(1, 14)] values[0] = "A" values[12] = "K" values[11] = "Q" values[10] = "J" values = tuple(values) if suit not in suits: raise Exception("Invalid suit") elif value not in values: raise Exception("Invalid value") self.suit = suit self.value = value def __repr__(self): return f"{self.value} of {self.suit}" class Deck: def __init__(self): suits = ("hearts", "diamonds", "clubs", "spades") values = [str(i) for i in range(1, 14)] values[0] = "A" values[12] = "K" values[11] = "Q" values[10] = "J" values = tuple(values) self.cards = [Card(suit, value) for suit in suits for value in values] def count(self): return len(self.cards) def _deal(self, number): if self.count() == 0: raise ValueError("All cards have been dealt") self.cards = self.cards[:-number] def shuffle(self): if self.count() != 52: raise ValueError("Only full decks can be shuffled") random.shuffle(self.cards) return self.cards def deal_card(self): card = self.cards[self.count() - 1] self._deal(1) return card def deal_hand(self, num): hand = self.cards[-num:] self._deal(num) return hand def __repr__(self): return f"Deck of {self.count()} cards"
018824e3c25b018d9330e956ecc0cf682cab32d5
layroyc/python01
/lx.py
12,126
4.03125
4
#输入函数: ''' 输入函数: input() 没有参数输出的是一个空白行 input(“提示信息”) input接收到的都是字符串类型 eval(input("")) 接收到数据的实际数据类型 ''' #a = input("请输入一个整数:") #print(a) #输出函数 ''' 输出函数: print() 一次输出多个内容: 1.用逗号链接 不限制数据类型 多个数据之间逗号分隔 2.用加号连接 只能拼接字符串类型的数据 3.格式化输出 print(“格式化输出符号” % (变量名1,变量名2.......)) 字符串 %s 整数 %d 浮点数 %f 百分号 %% num = 9.9555 print("%.2f" % num) # 保留两位小数 stu_num = 100 print("%06d" % stu_num) # 六位 不够补零 a = 15 b ='roy' print('a的值是',a,'b的值是',b) print('a的值是'+ str(a) +'b的值是'+ b) print('a的值是%d,b的值是%s' % (a,b)) x = 1.23456 print('%.2f' % x) y = 123 print('%05d' % y) ''' #数据类型: ''' 数据类型: 数字型(整型(int)、浮点型(float)、复数(complex)) 数字型也包含其他进制 二进制 八进制 十六进制 转二进制bin(X) 转八进制 oct(X) 转十六进制 hex() 转十进制 int(X,base) num = 20 print('转二进制',bin(num)) print('转八进制',oct(num)) print('转十六进制',hex(num)) print('转十进制',int(0x14)) #检测数据类型:type(X) print(type(num)) ''' #字符串操作: # in 判断字符串包含关系 'a' in 'abcd' → True print('s' in 'transform') # 空格 以空格分隔的字符串自动合并 'a' 'b' 'c' → 'abc' print('123' 'pwd' 'cd') # 加号 将多个字符串合并 'a' + 'b' + 'c' → 'abc' print('123'+'pwd'+'cd') # 星号 字符串重复输出 'a' * 5 → 'aaaaa' print('pwd' * 5) #字符串索引 ''' 字符串索引: 可以通过索引去查,但是不能修改 z = 'abcdefg' 索引号从左到右 z[0] - z[6] 从右到左 z[-1] - z[-7] 字符串长度:len(X) 字符串切片: 获取某一个区间的多个字符 x[start:end] 从start(包括)开始到end(不包括)之前结束 x[start:] 从start开始,一直到最后、 x[:end] 从开头开始,到end(不包括)之前结束 x[:] 返回全部字符 x = 'qwertyuiop' print(len(x)) print(x[3:7]) print(x[3:]) print(x[:7]) print(x[:]) print(x[-5:]) ''' ''' 分支结构: 1.单分支 if 表达式: 语句块 后续代码 2.双分支 if 表达式: 语句块1 else: 语句块2 后续代码 3.多重分支 if 表达式1: 语句块1 elif 表达式2: 语句块2 ...... else: 语句块n 后续代码 4.分支嵌套(注意缩进) 5.三元运算符 变量 = 表达式为真的结果 if 表达式 else 表达式为假的结果 ''' #单分支 ''' num = int(input('请输入一个整数:')) if num%2==0: print('该数字是偶数') else: print('该数字是奇数') ''' #多分支 ''' english = float(input('请输入英语成绩:')) math = float(input('请输入数学成绩:')) if english>90 and math>90: print('成绩优秀') elif english>80 and math>80: print('成绩良好') elif english>60 and math>60: print('成绩不错') else: print('还要继续努力啊!') ''' #循环结构 ''' 循环结构 1.while循环 while 循环条件: 循环体 2.for循环 for 迭代变量 in 循环对象: 代码块 range() 产生一组整数 1.range(a) 从0开始 到a-1结束 range(10) 0-9 2.range(a,b) 从a开始 到b-1结束 range(5,15) 5-14 3.range(a,b,c) 从a开始,到b-1结束,每次跳跃c个数 range(1,10,2) 1 3 5 7 9 3.break(直接终止循环) continue(跳出此次循环,继续进行下一次循环) pass(直接跳过,不执行任何操作) 产生一随机数: 1.导入random模板 import random 2.random.randint(a,b) 随机返回一个[a,b]之间的数 ''' # 九九乘法表 w = 1 while w < 10: y = 1 while y<=w: print('%d*%d=%2d' % (w,y,w*y),end=' ') y+=1 print() w+=1 # 冒泡排序 list1 = [3,6,9,11,8,56,4] def sort_list(list): n = len(list) i = 0 j = i for i in range(n-1): for j in range(n-1-i): if list[j] < list[j+1]: list[j],list[j+1] = list[j+1],list[j] sort_list(list1) print(list1) #循环100内的偶数 #while ''' i=1 while i<100: if i%2==0: print("%d是偶数" %i) i+=1 ''' #for ''' for s in range(10): print(s) ''' ''' i = 1 for s in range(i,101): if s%2==0: print('%d是偶数'%s) ''' ''' for s in range(2,101,2): print('%d是偶数' % s) ''' ''' x = 10 y = 50 import random print(random.randint(x,y)) ''' #列表: ''' 1.定义一个列表 列表名 = [元素1,元素2,.......] 列表名 = list() ''' a = [12,15,'asd'] b = list() print(a) #空集合 print(b) ''' 2.增 列表名.append() 追加元素到列表的最后面 列表名.insert(index,value) 把元素插入到列表中指定的位置 列表名1.extend(列表名2) 把列表2追加到列表1后面 ''' a.append('qwer') print(a) a.insert(3,'886') print(a) b = [345] a.extend(b) print(a) ''' 3.删 列表名.remove(obj) 将列表中的某个元素移除 列表名.pop(index) 通过索引将元素移除 列表名.clear() 清空列表中的所有元素 列表还存在 del 列表名[index] 通过索引将元素移除 del 列表名 删除列表 列表不存在 a.remove(345) print(a) a.pop(2) print(a) del a[3] print(a) a.clear() print(a) del a print(a) ''' ''' 4.改 列表名[index] = value 5.查 print(列表名) print(列表名[index]) 从左边开始数,第一个索引是0 从右边开始数,第一个索引是-1 print(列表名[a:b]) 从a开始 到b-1结束 ''' a[3] = 996 print(a) print(a[3:]) print(a[2:5]) ''' 6.列表名.count() 计算某一个元素在列表中出现的次数 7.列表名.reverse() 将元素反转 8. 列表名.sort() 默认进行升序排列 对列表本身做改变 列表名.sort(reverse=True) 降序排列 列表名.sort(key=len) 根据字符串的长度进行排列 sorted() 对列表进行排序 不改变列表本身,只返回排序后的结果 9.列表也可以进行+ 和 * 操作 ''' b = ['qwe','123','456','rty'] ''' b.count() print(b) ''' b.reverse() print(b) b.sort() print(b) b.sort(reverse=True) print(b) c = sorted(b) print(c) ''' 元组: 1.定义元组 元组名 = tuple() 元组名 = (元素1,元素2,......) a = 'a','b','c' 元组类型 b = (1,) 2. 元组名.count(obj) 统计查找对象在元组中的出现次数 元组名.index() 找到第一个匹配项的索引值 3. len() 返回元组长度,也是元素个数 max() 字符串通过它的首字符的ASCLL码判断大小 min() 4. 元组转列表:list(元组名) 列表转元组:tuple(列表名) ''' x = tuple() print(x) x = ('zxc','yy','dw','yy') print(x) c = x.count('yy') print(c) c = x.index('yy') print(c) a = list(x) print(a) b = tuple(a) print(b) ''' 字典: 1.创建字典: 字典名 = {键:值,键:值,......} 键只能是字符串、数字、元组 值可以是任意数据类型 2.查 字典名[键] 获取该键对应的值 字典名.get(键) 获取该键对应的值 字典名.keys() 获取字典中的所有键 字典名.values() 获取字典中的所有值 字典名.items() 获取字典中的所有项 [(键,值),(键,值),......] print(字典名) 3.增和改 字典名[键] = 值 如果键存在,就修改原值 如果键不存在,就新增该键值对 字典名.setdefault(键, 值) 如果键存在,不作操作 如果不存在,就新增该键值对 字典名1.update(字典名2) 将字典2中的键值对合并进字典1中 如果键冲突,则保存字典2中的值 4.删 del 字典名[键] 删除该键对应的键值对 字典名.pop(键) 返回该键对应的值,然后删除该键所在的键值对 字典名.popitem() 删除并返回最后一项键值对 字典名.clear() 清空字典中的所有内容 5.遍历字典 for i in 字典名: print(i) //键 print(字典名[i]) // 该键对应的值 len(字典名) 计算字典中键的个数 ''' msg = { "name":"小王", "age":"20", "sex":"男", "hobby":["singsong","write","tan"] } print(msg["hobby"][2]) print(msg.get("name")) print(list(msg.keys())) print(msg.values()) print(list(msg.items())) #增和改 msg["height"] = 185 msg["age"] = 19 msg.setdefault("weight","110") msg.setdefault("height",180) # 遍历 for i in msg: print("%s : %s" % (i,msg[i])) #集合: #差集- 对称差集^ 交集& 并集| a = {1,2,3,4,5} b = {4,5,6,7,8} print(a.symmetric_difference(b)) print(a-b) print(a^b) print(a.intersection(b)) print(a&b) print(a.union(b)) print(a|b) print(a) #函数 ''' 内置函数: print() input() int() str() range() ...... 自定义函数: 先定义后执行 def 函数名([参数]): 函数体 return [指定返回值] w = "我是浩子" def money(apple1,weight2): price = apple * weight #在函数内部有效修改全局变量 global w w = "我变成了耗子" #print("本次消费了"+str(price)+"元") #函数内部访问全局变量 print(w) return price apple = float(input("价格")) weight = float(input("重量")) #将函数返回值保存到SUM_PRICE SUM_PRICE = money(apple,weight) print("总价为"+str(SUM_PRICE)+"元") print(w) ''' ''' 文件操作: 打开文件 ---- 操作文件 ---- 关闭文件 打开文件: file = open("文件路径"[,"文件打开方式",buffering="缓冲方式",encoding="字符集"]) with open("文件路径"[,"文件打开方式",buffering="缓冲方式",encoding="字符集"]) as file: # 进行文件操作 pass 文件打开方式: r 只读 file.read() 读取文件的全部内容 file.read(n) 读取文件的前n个字符 file.readline() 读取文件的一行内容 file.readlines() 读取文件所有行的内容 返回的是一个列表,每一行就是列表中的一个元素 w 覆盖写入 a 追加写入 file.write("...") 存在缓冲区 file.close() 存入文件 目录操作: import os # 导入模块 创建一个目录: os.mkdir("hello") 创建在当前工作目录下 os.mkdir("C:/Users/Administrator/Desktop/Python/aaa") 在指定目录下创建文件夹 当前工作目录: os.getcwd() 删除空目录: os.rmdir() 删除文件: os.remove() 重命名: os.rename("C:/Users/Administrator/Desktop/Python/aaa","C:/Users/Administrator/Desktop/Python/bbb") import os print(os.getcwd()) #os.mkdir('hh') os.rmdir('hh') ''' #面向对象: class Wy: name = "王" sex = "男" age = "20" #方法 def eat(self): self.food = "番茄炒蛋" #实例化对象 对象名 = 类名() wy1 = Wy() wy2 = Wy() #访问类属性 #1.通过类名访问类属性 print(Wy.name) #2.通过对象名访问类属性 print(wy1.age) #通过对象名访问实例属性 wy1.eat() print(wy1.food) #封装 class Students: def __init__(self,name): self.name = name self.__age = 20 def set(self,age): self.__age = age def get(self): a = self.__age return a s1 = Students('roy')#实例化对象 print(s1.get()) s1.set(19) print(s1.get()) #继承 class House: def live(self): print("能住") class Car: def run(self): print("能跑") class FangChe(House,Car): pass h1 = FangChe() h1.live() h1.run() #多态 class Animals: def __init__(self,kinds): self.kinds = kinds def skill(self,s): self.s = s print(self.kinds+"的特长是:"+self.s) cat = Animals("猫") cat.skill("抓老鼠") dog = Animals("狗") dog.skill("吃粑粑")
84addc37d4ea68d0ce44ad103db892947917fbb4
KarlYapBuller/Quiz-Quest-game-Assesment-Ncea-Level-1-Programming-Karl-Yap
/07_Statement_Decorator_v1.py
964
4.1875
4
#Statement Decorator component version 1 #Statement generator #The statement generator funcrion decorates the statements in the Quiz Quest Game def statement_generator(statement, decoration): #The sides of the statement on each side is three of the decorations sides = decoration * 3 #The sides of the statement will have three of the chosen decoration on each side statement = "{} {} {}".format(sides, statement, sides) #The top and bottom of the statement is decorated #The length of the statement is the length that the #Decoration goes for on the top and bottom of the statement top_bottom = decoration * len(statement) #The statement that is decorated is displayed to the User print(top_bottom) print(statement) print(top_bottom) return "" #Main routine goes here statement_generator("Welcome to the Quiz Quest Game","*") print() statement_generator("Thank You for playing the Quiz Quest Game", "-")
2ef6f24403f232b3876423645aa63dd5abbfc81f
sg45905/Artificial_Intelligence
/Tower-of-Hanoi/priority.py
1,285
3.796875
4
import heapq import itertools # Create a priority queue class PQ: def __init__(self): self.pq = [] self.entry_finder = {} self.REMOVED = -1 self.counter = itertools.count() self.size = 0 self.numAdded = 0 # update the queue and priorities def update(self,game,priority=0): hash = game.hash() self.numAdded += 1 if hash in self.entry_finder: self.remove_game(game) count = next(self.counter) entry = [priority,count,game] self.entry_finder[hash] = entry heapq.heappush(self.pq,entry) self.size += 1 # remove some particular move def remove_game(self,task): entry = self.entry_finder.pop(task.hash()) entry[-1] = self.REMOVED self.size -= 1 # pop an object out of the queue def pop(self): while len(self.pq) > 0: priority,count,task = heapq.heappop(self.pq) if task is not self.REMOVED: del self.entry_finder[task.hash()] self.size -= 1 return task return KeyError("Pop from an empty priority queue",str(self.size),str(self.pq)) # check if a queue is empty def isEmpty(self): return self.size == 0
ed8b03aa8d813b943c8a37be564711d023c07feb
kakru/puzzles
/leetcode/037_sudoku_solver.py
3,541
3.65625
4
#/usr/bin/env python3 import unittest class Solution: # 2364ms EMPTY = "." def isValidSudoku(self, board): seen = [] for i, row in enumerate(board): for j, digit in enumerate(row): if digit != '.': # seen.append((i, digit)) # numbers in rows are unique "by design" seen.append((digit, j)) seen.append((i // 3, j // 3, digit)) return len(seen) == len(set(seen)) def firstEmpty(self, board): for j in range(9): if self.EMPTY in board[j]: return j, board[j].index(self.EMPTY) def solve(self, board, counter=0): numbers = set(str(i) for i in range(1,10)) try: y, x = self.firstEmpty(board) except TypeError: return board for n in numbers - set(board[y]): board[y][x] = n if self.isValidSudoku(board): result = self.solve(board, counter+1) if self.firstEmpty(result) == None: return result board[y][x] = self.EMPTY return board def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ board = self.solve(board) class Solution: # 2996ms EMPTY = "." def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ def solve(board, fields): if not fields: return y, x = fields.pop() for k in "123456789": row = (board[y][i] for i in range(9)) col = (board[i][x] for i in range(9)) box = (board[i+y//3*3][j+x//3*3] for i in range(3) for j in range(3)) if not any([ k in row, k in col, k in box ]): board[y][x] = k solve(board, fields) if not fields: return board[y][x] = self.EMPTY fields.append((y, x)) fields = [(y,x) for y in range(9) for x in range(9) if board[y][x] == self.EMPTY] solve(board, fields) class BasicTest(unittest.TestCase): def test_1(self): input_ = [["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"]] output = [["5","3","4","6","7","8","9","1","2"], ["6","7","2","1","9","5","3","4","8"], ["1","9","8","3","4","2","5","6","7"], ["8","5","9","7","6","1","4","2","3"], ["4","2","6","8","5","3","7","9","1"], ["7","1","3","9","2","4","8","5","6"], ["9","6","1","5","3","7","2","8","4"], ["2","8","7","4","1","9","6","3","5"], ["3","4","5","2","8","6","1","7","9"]] Solution().solveSudoku(input_) # in-place self.assertEqual(input_, output) if __name__ == '__main__': unittest.main(verbosity=2)
293b090732ce5cdb3ac0d626228bdc8360bc6133
linchangyi/LeecodeInterview
/07partition.py
1,764
3.625
4
''' 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 示例: 输入: "aab" 输出: [ ["aa","b"], ["a","a","b"] ] ''' class Solution: def __init__(self): self.s = None self.PMatrix = None self.res = [] def _init_palindrome_matrix(self): s = self.s length = len(s) dp = [[0 for _ in range(length)] for _ in range(length)] for i in range(length): dp[i][i] = 1 for i in range(length - 1): if s[i] == s[i + 1]: dp[i][i + 1] = 1 for k in range(length - 2): for i in range(length - k - 2): if dp[i + 1][i + k + 1] == 1 and s[i] == s[i + k + 2]: dp[i][i + k + 2] = 1 self.PMatrix = dp # 深度优先搜索 def _find(self, start_index: int, splits: list): if start_index == len(self.s): self._add_result(splits) return for i in range(start_index, len(self.s)): if not self.PMatrix[start_index][i]: continue splits.append(i) self._find(i + 1, splits) splits.pop() def _add_result(self, splits): partitions = [] start_index = 0 for i in range(len(splits)): partitions.append(self.s[start_index: splits[i] + 1]) start_index = splits[i] + 1 self.res.append(partitions) def partition(self, s): self.s = s self._init_palindrome_matrix() self._find(0, []) return self.res if __name__ == '__main__': solution = Solution() res = solution.partition('a') for l in res: print(l)
9851595fc43e11cfcc62e6e63e357e38e6904049
AnacondaFeng/AnacondaFeng
/class_S/test_decorator3.py
790
3.703125
4
# 带参数的装饰器 def log(name=None): def decorator(func): def wrapper(): print('{0}.start..'.format(name)) func() print('{0}.end..'.format(name)) return wrapper return decorator # 执行方法带参数的装饰器 def log2(name=None): def decorator(func): def wrapper(*args, **kwargs): print('{0}.start..'.format(name)) rest = func(*args, **kwargs) print('{0}.end..'.format(name)) return rest return wrapper return decorator @log('you') def hello(): """ 简单功能模拟 :return: """ print("hello world") @log2('test') def add(a,b): return a+b if __name__ == '__main__': hello() rest = add(5,6) print(rest)
6050ad32082015b2e60d46fbd0a37114bcf4eb95
tguterres/projectpython
/aulas/aula04.py
204
3.796875
4
#Exercício Aluguel de Carros d = int(input('Quantos dias o carro foi alugado? ')) km = float(input('Quantos kilometros foram rodados? ')) v = (d*60) + (km * 0.15) print('O valor do aluguel é: R${:.2f}'.format(v))
268ebc13b3e9ea7ce7995bf64bd03a08c6552376
PabloYepes27/holbertonschool-higher_level_programming
/0x0A-python-inheritance/10-square.py
831
4.34375
4
#!/usr/bin/python3 """[Write a class Square that inherits from Rectangle (9-rectangle.py):]""" Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """[class square from class Rectangle] Arguments: Rectangle {[class]} -- [parent class] """ def __init__(self, size): """[Instantiation with size] Arguments: size {[int]} -- [size of the square] """ self.integer_validator("size", size) self.__size = size def area(self): """area Returns: [int] -- [area of rectangle] """ return self.__size * self.__size def __str__(self): """[str] Returns: [str] -- [description] """ return ("[Rectangle] {}/{}".format(self.__size, self.__size))
0973ce6f2fc911c16ff244509b19351539da0a1b
sharingplay/Introduccion-a-la-programacion
/Python/Recursion de Pila/Listas/listaInverso.py
447
3.984375
4
"""Desarrolle un programa que recibe como parametro una lista y la regresa en orden invertido""" def listaInverso (lista): if isinstance (lista,list): return inverso(lista) else: return "Error" def inverso (lista): #suma el primer numero de la derecha y manda los demas if lista == []: #como parametro de derecha a izquierda return [] else: return [lista [-1]] + inverso (lista[:-1])
d927685e2a7421e4c98334c64b76d7b512366558
CoderFemi/AlgorithmsDataStructures
/practice_challenges/python/decent_number.py
1,078
4
4
def decentNumber(num_digits) -> int: """Form a decent number from input digits""" def check_decent(num_threes): remainder = num_digits - num_threes if remainder % 3 == 0 and remainder > -1: decent_num = int(("5" * remainder) + ("3" * num_threes)) return decent_num decent_num = -1 is_multiple_three = num_digits % 3 == 0 if is_multiple_three: decent_num = int("5" * num_digits) else: result = check_decent(5) if result: decent_num = result else: result = check_decent(10) if result: decent_num = result return decent_num print(decentNumber(1)) print(decentNumber(3)) print(decentNumber(5)) print(decentNumber(11)) print(decentNumber(15)) print(decentNumber(13)) print("=================") print(decentNumber(1)) print(decentNumber(2)) print(decentNumber(3)) print(decentNumber(4)) print(decentNumber(5)) print(decentNumber(6)) print(decentNumber(7)) print(decentNumber(8)) print(decentNumber(9)) print(decentNumber(10))
7f587fd5a9c455f70125e25766da38091a06310f
chloe-wong/pythonchallenges
/GC45.py
79
3.6875
4
char = input() if len(char) == 1: print("Char") else: print("Not char")
ee99669514af63fc9837021b60e9274b210d5449
acaciooneto/cursoemvideo
/ex_videos/ex-082.py
538
3.703125
4
principal = [] pares = [] impares = [] while True: continuar = ' ' principal.append(int(input('Digite um número: '))) while continuar not in 'SN': continuar = str(input('Você deseja continuar? [S/N]: ')).strip().upper()[0] if continuar == 'N': break for elemento in principal: if elemento % 2 == 0: pares.append(elemento) else: impares.append(elemento) print(f'A lista principal é: {principal}') print(f'A lista de pares é: {pares}') print(f'A lista de ímpares é: {impares}')
6ef893ea3efb34dd92cf606ece9b70f27bc98d8c
AmrutaBhujbal09/Basic_Programs_Aarray_In_C
/PYTHON/Global_Variables.py
696
3.96875
4
"""def f(): print(s) s="m in def f()" print(s) return "helo world" global s s="NAMASTE INDIA!!!" t=f() print(t) OUTPUT: UnboundLocalError: local variable 's' referenced before assignment MEANING OF THIS ERROR IS THAT IF ANY VARIABLE declared inside a function ,it becomes local variable inside that function so to solve this error we have to declared variable s exceeded by keyword global """ def f(): global s print(s) s="m in def f()" print(s) return "helo world" global s s="NAMASTE INDIA!!!" t=f() print(t) """ OUTPUT: NAMASTE INDIA!!! m in def f() helo world """
2f71e971076ade95b1b2377b5f870436c416ad1e
eVoRisk/Python
/prime.py
967
4.15625
4
__author__ = 'eVomeR' # import only sqrt from math package from math import sqrt # prime test function def isPrime(number): for index in range(2, int(sqrt(number)) + 1): if number % index == 0: return False return True # read the input from console isNumber = False while isNumber <> True: try: number = int(raw_input("Number: ")) isNumber = True except ValueError: print "Not a number" # write the result if isPrime(number) <> True: print "%d is not a prime number" % (number) else: print "%d is a prime number" % (number) # first N prime numbers # read the input from console isNumber = False while isNumber <> True: try: n = int(raw_input("N = ")) isNumber = True except ValueError: print "Not a number" print "First %d prime numbers are: " % (n) prime = 2 while n <> 0: if(isPrime(prime) == True): n -= 1 print prime prime += 1
5fb265dbd3602eb8f8fa214e1b4cc16f342078cb
DShmunk/h3_homework
/calc_grid.py
2,098
3.890625
4
from tkinter import * from tkinter import messagebox from tkinter import ttk # для добычи корня import math root = Tk() root.title("Calculator") # сотворение ввода calc_entry = Entry(root, width = 44) calc_entry.grid(row=0, column=0, columnspan=4, sticky=N+S+W+E) # сотворение кнопок bttn_list = [ "(", ")", "√2", "/", "7", "8", "9", "*", "4", "5", "6", "-", "1", "2", "3", "+", "C", "0", ".", "=", ] # присвоение кнопкам места и действий r = 1 c = 0 for i in bttn_list: cmd=lambda x=i: calc(x) ttk.Button(root, text=i, command=cmd, width=12).grid(row=r, column=c) c += 1 if c > 3: c = 0 r += 1 # функционал калькулятора def calc(key): if key == "=": # проверка на начало ввода текста (ибо не мышью единой) + немного обезопасить eval str1 = "0123456789.-+*/)(" if calc_entry.get()[0] not in str1: calc_entry.insert(END, "First symbol is not number!") messagebox.showerror("Error!", "You did not enter the number!") # расчет при помощи ф-ии eval try: result = eval(calc_entry.get()) calc_entry.insert(END, "=" + str(result)) # если навводили непонятного except: calc_entry.insert(END, "Error!") messagebox.showerror("Error!", "Check the correctness of data") #очищение поля ввода elif key == "C": calc_entry.delete(0, END) # скобки elif key == "(": calc_entry.insert(END, "(") elif key == ")": calc_entry.insert(END, ")") # корень elif key == "√2": calc_entry.insert(END, "=" + str(math.sqrt(int(calc_entry.get())))) # после ввода "=" очистить поле else: if "=" in calc_entry.get(): calc_entry.delete(0, END) calc_entry.insert(END, key) root.mainloop()
bff0cc5f0193a703a676ba8f8febdd330d403e12
Voron07137/PythonTutor
/ch4/l46.py
284
3.65625
4
import copy A = [[10, 20], [[30, 40], [50, 60]]] B = copy.deepcopy(A) print("Список A", A) print("Список B", B) print("Выполняются команды A[0][1] = 0 и A[1][1][1] = 0.") A[0][1] = 0 A[1][1][1] = 0 print("Список A", A) print("Список B", B)
d6f1d6b6da6d64924c850b5a2653b0ef70ea4390
vaibhavboliya/DSA-Programming-Problems
/Geeksforgeeks/02 Array/Alternate positive and negative numbers.py
1,697
4.125
4
# URL : https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/0/ # Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of alternate positive and negative numbers without changing the relative order of positive and negative numbers. # Note: Array should start with positive number. # Example 1: # Input: # N = 9 # Arr[] = {9, 4, -2, -1, 5, 0, -5, -3, 2} # Output: # 9 -2 4 -1 5 -5 0 -3 2 # Example 2: # Input: # N = 10 # Arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8} # Output: # 5 -5 2 -2 4 -8 7 1 8 0 # Your Task: # You don't need to read input or print anything. Your task is to complete the function rearrange() which takes the array of integers arr[] and n as parameters. You need to modify the array itself. # Expected Time Complexity: O(N) # Expected Auxiliary Space: O(N) # Constraints: # 1 ≤ N ≤ 107 # -106 ≤ Arr[i] ≤ 107 class Solution: def rearrange(self,arr, n): neg = [] pos = [] for i in arr: if i<0: neg.append(i) if(i>=0): pos.append(i) for i in range(n): if i%2==0 and len(pos)>0 or len(neg)==0: arr[i] = pos.pop(0) else: arr[i] = neg.pop(0) # code here #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': tc = int(input()) while tc > 0: n = int(input()) arr = list(map(int, input().strip().split())) ob = Solution() ob.rearrange(arr, n) for x in arr: print(x, end=" ") print() tc -= 1 # } Driver Code Ends
7f3a8e59b07b3034014727c02a683f274b1fc67b
meliatiya24/Python_Code
/p1.py
912
3.75
4
data1=[None]*2 for i in range(2): data1[i]=[None]*2 for x in range(2): for y in range(2): data1[x][y]=int(input()); print(data1) data2=[None]*2 for i in range(2): data2[i]=[None]*2 for x in range(2): for y in range(2): data2[x][y]=int(input()); print(data2) a=data2[0][0] b=(data2[0][1]) c=(data2[1][0]) d=data2[1][1] det=a*d-b*c b=-(b) c=-(c) e=[[d,b],[c,a]] if det==0: print ("Maaf determinan tidak boleh sama dengan 0" ) exit("coba lagi") print ("karena pembagian maka matriks 2 harus kita inverskan terlebih dahulu") print (e) hasil=[] for x in range(len(data1)): isi = [] for y in range(len(data1[0])): total = 0 for z in range(len(data1)): total = total + (data1[x][z] * e [z][y]) / det isi.append(total) hasil.append(isi) print ("Jadi hasil matriks 1 / matriks 2 adalah :") for jadi in hasil: print (jadi)
81d7e839bd92cf916b66467430c0e96628c42954
Kabir12401/FIT1008
/Interview Prac 2/army.py
10,241
4.09375
4
""" The below is created for the creation of an army elements. It has the Soldier, Archer and cavalry classes that inherit from a a fighter class with the abstract method defend. """ __author__ = "Ashwin Sarith" # implemented classes and their methods below here from abc import ABC, abstractmethod from queue_adt import CircularQueue from stack_adt import ArrayStack class Fighter(ABC): def __init__(self, life: int, experience: int): """ Initialise life and experience of the fighter in :pre: life and experience must be >= 0 :return: None """ self.life = life self.experience = experience assert self.life >= 0 , " life cant be negative" assert self.experience >= 0 , "experience cant be negative" def is_alive(self): """ Checks if the fighter is alive via a boolean :return: Boolean :complexity: Best and worst case is both O(1) """ if self.life>0: return True return False def lose_life(self, lost_life: int): """Here health deduction is implemented, lost life will be a result of damage :param lost_life: life to be deducted from the life of the specific fighter :return: None """ self.lost_life = lost_life if lost_life<=0: raise ValueError("Needs to be a positive value") else: self.life = self.life - self.lost_life def gain_experience(self, gained_experience: int): """Unit experience increased by the value gained_experience :pre: gained_experience >= 0 :post: experience added and greater :param gained_experience: The experience to be added to fighter's experience :return: the integer value for lifge of the fighter""" if gained_experience<=0: raise ValueError("Experience cannot be negative") else: self.experience += gained_experience def get_life(self): """returns the fighters life :return: the integer value for life of the fighter""" return self.life def get_experience(self): """returns fighters experience :return: the integer value for experience of the fighter""" return self.experience def get_cost(self): """returns fighters cost :return: the integer value for cost of the fighter""" return self.cost def get_attack_damage(self): """returns attack damage :return: the int value for damage with respect to the experience. """ self.damage = 1 + self.experience return self.damage def get_unit_type(self): """returns the string unit type :return: str unit_type """ return self.unit_type @abstractmethod def get_speed(self): """is an abstract method""" pass @abstractmethod def defend(self, damage: int): """is an abstract method""" pass def __str__(self): """just for the classes description""" val= self.unit_type +"'s life = "+str(self.life)+" and experience = "+str(self.experience) return val "====================== Task 2 =====================================" class Soldier(Fighter): unit_type = "Soldier" cost = 1 def __init__(self): """retrieves init method from Fighter and is initialised with the fighters value :return: None """ super().__init__(3,0) def get_speed(self): """returns the speed of a soldier with respect to its experience :returns: integer value for speed """ return 1 + self.experience def defend(self, damage: int): """ A method to invoke defense with damage as input :param damage: is the integer for damage thats inflicted on the unit :returns: None """ if damage>self.experience: self.life -= 1 class Archer(Fighter): unit_type = "Archer" cost = 2 def __init__(self): """retrieves init method from Fighter and is initialised with the fighters value :return: None """ super().__init__(3,0) def get_speed(self): """returns the speed of a soldier with respect to its experience :returns: integer value for speed """ return 3 def defend(self, damage: int): """ A method to invoke defense with damage as input :param damage: is the integer for damage thats inflicted on the unit :returns: None """ if damage>0: self.life -=1 class Cavalry(Fighter): unit_type = "Cavalry" cost = 3 def __init__(self): """retrieves init method from Fighter and is initialised with the fighters value :return: None """ super().__init__(4,0) def get_speed(self): """returns the speed of a soldier with respect to its experience :returns: integer value for speed """ self.speed = 2 return self.speed def get_attack_damage(self): """Used to retrieve the attack damage for a class :returns: damage scaled to unit experience """ self.attack = (2*self.experience) + 1 return self.attack def defend(self, damage: int): if damage>(self.experience)//2: self.life -=1 "====================== Task 3 =====================================" class Army(Soldier, Archer, Cavalry, ABC): def __init__(self): " first we initialise the names and the fighting force0" self.name = None self.force = None def __correct_army_given(self, soldiers:int, archers:int, cavaliers:int): s = Soldier() a = Archer() c = Cavalry() total_cost = (s.cost*soldiers) + (a.cost*archers) + (c.cost*cavaliers) if soldiers >= 0 and archers >= 0 and cavaliers >=0 and total_cost <=30: return True else: return False def __assign_army(self, name:str, sold: int, arch: int, cav:int, formation: int): # NOTE: this is based on the assesment assumption that the formation would always be 0 for a stack and not 1 which is meant for a queue # print("work god dammit") if formation == 0: stack_size = sold + arch + cav force = ArrayStack(stack_size) #Soldier s = Soldier() #Archer a = Archer() #Cavalry c = Cavalry() index = 0 while index != sold: force.push(s) index+=1 index = 0 while index != arch: force.push(a) index+=1 index = 0 while index != cav: force.push(c) index+=1 self.force = force self.name = name else: queue_size = sold +arch +cav force = CircularQueue(queue_size) s = Soldier() a = Archer() c = Cavalry() index = 0 while index != sold: force.append(s) index+=1 index = 0 while index != arch: force.append(a) index+=1 index = 0 while index != cav: force.append(c) index+=1 self.force = force self.name = name def choose_army(self, name:str, formation:int): """ docstring """ self.name = name # or it could just be name, it just depends on how its going to be used, will debate this later x = 1 SAC = [] while x<4: if x == 1: SAC.append(int(input("Player "+self.name+" Number of Soldiers? "))) x+=1 elif x == 2: SAC.append(int(input("Player "+self.name+" Number of Archers? "))) x+=1 elif x == 3: SAC.append(int(input("Player "+self.name+" Number of Cavalry men? "))) x+=1 else: x+=1 Soldiers = SAC[0] Archers = SAC[1] Cavalries = SAC[2] if self.__correct_army_given(Soldiers, Archers, Cavalries) is True: # print("work god dammit") self.__assign_army( self.name, Soldiers, Archers, Cavalries, formation) # print(self.force) def __str__(self) -> str: return str(self.force) # def main(): # # pass # # Army.choose_army(Army, "Player 1", 0) # #testing speed # s1 = Soldier() # print(s1.get_attack_damage()) # s2 = Archer() # print(s2.get_attack_damage()) # s3 = Cavalry() # print(s3.get_attack_damage()) # print(type(s3.cost)) # s1 = Soldier() # print(s1.get_life()) # s2 = Archer() # print(s2.get_life()) # s3 = Cavalry() # print(s3.get_life()) # s1 = Soldier() # print(s1.get_experience()) # s2 = Archer() # print(s2.get_experience()) # s3 = Cavalry() # s1 = Soldier() # s1.defend(1) # print(s1.get_life()) # print(str(s1)) # s2 = Archer() # print(str(s2)) # s3 = Cavalry() # print(str(s3)) import sys class Test(ABC): def test_function(self): sys.stdin = open("tester.txt") t1 = Army() t1.choose_army("t1",1) t2 = Army() t2.choose_army("t2",0) # print(len(t2.force)) u1 = t1.force.serve() u2 = t2.force.pop() print(u1) # print(u1.get_attack_damage()) # print(u2.get_speed()) def setup_method(self): self.orig_stdin = sys.stdin def teardown_method(self): sys.stdin = self.orig_stdin if __name__ == "__main__": Test.test_function(Army)
3880ab2d6db8654b6ce78de9611f65325caa54be
eldss-classwork/Python-for-Everybody-Specialization
/Accessing Web Data/Extracting-Data-JSON.py
753
4.21875
4
# Evan Douglass # Extracting Data from JSON # This program reads JSON from a webpage and finds information about # comment counts. The webpage used for this assignment (Coursera) is: # http://py4e-data.dr-chuck.net/comments_40264.json import json from urllib.request import urlopen import ssl # ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # get info from address address = input('Enter an address - ') if address == '': quit() data = urlopen(address).read() # unpack JSON data = json.loads(data) # get total comment count from data total = 0 for user in data['comments']: total = total + user['count'] print('Total comments:', total)
74115da0fccba79782d46f2db625afd53a8893bb
srdecny/diasys
/hw1/minDistUtil/tests.py
1,110
3.578125
4
from levenshtein import Levenshtein from io import StringIO import unittest class TestBasicFunctionality(unittest.TestCase): def test_example(self): examples = { ("", "") : 0, ("a a a", "a a a") : 0, ("a b", "a a a") : 1, ("a b c a", "a a a") : 1, ("foo", "bar") : 6, ("foo", "fooo") : 1 } for words, distance in examples.items(): out = StringIO() Levenshtein(words[0], words[1], " ", True, False, False, out=out) self.assertEqual("Minimum edit distance: " + str(distance) + '\n', out.getvalue()) def test_wer(self): examples = { ("foo", "bar") : 1.0, ("foo bar", "foo baz") : 1/2, ("foo foo", "bar baz") : 1.0, ("", "") : 0.0 } for words, wer in examples.items(): out = StringIO() Levenshtein(words[0], words[1], " ", False, False, True, out=out) self.assertEqual("WER: " + str(wer) + '\n', out.getvalue()) if __name__ == "__main__": unittest.main()
d28652293f4e6fb7ca5b6bc0e4d865576ebe82e8
SarthakVerma26/291197dailycommit
/binarysearch.py
579
4.03125
4
def binarySearch(numbers, low, high, x): if (high >= low): mid = low + (high - low)//2 if (numbers[mid] == x): return mid elif (numbers[mid] > x): return binarySearch(numbers, low, mid-1, x) else: return binarySearch(numbers, mid+1, high, x) else: return -1 numbers = [ 9,4,6,7,2,1,5 ] x = 7 result = binarySearch(numbers, 0, len(numbers)-1, x) if (result != -1): print("Search successful, element found at position ", result) else: print("The given element is not present in the array")
9aeb1b699083a0d041e3f919dcf6cc11d6967fd9
chandthash/nppy
/Minor Projects/removing vowels.py
547
4.34375
4
def remove_vowels(strings): '''Remove vowels from the word given by the user''' try: if not str(strings).isalpha(): # If the given value is integer strings = str(strings) new_word = '' for letter in strings: if letter not in 'aeiou': new_word += letter # Joining only consonant letters print(new_word) except (ValueError, NameError): print('String value was expected') if __name__ == '__main__': remove_vowels('santosh')
9b92b8cd82319f62364bbdd52e913078f3495603
wesley74alexander/PY4E
/json_parser_1.py
1,075
4.125
4
#In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will #prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON #data, compute the sum of the numbers in the file and enter the sum below: #We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment. #Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553) #Actual data: http://py4e-data.dr-chuck.net/comments_119216.json (Sum ends with 89) import json import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET url = input('Enter URL: ') print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read() print('Retrieved', len(data), 'characters') info = json.loads(data) values = list() print('User count:', len(info['comments'])) for i in info['comments']: values.append(float(i['count'])) print(sum(values))
92f5c20828b7488e0d1a5de7b93e070c18efb0fe
miguel-aguilar/trabajo09.aguilar.arroyo
/arroyo/libreria.py
15,283
3.71875
4
#EJERCICIO NUMERO 1 #EN ESTE EJERCICIO PEDIREMOS EL DNI DE LA PERONAS #NO DEBE SER DIFERENTE DE UN NUMERO Y NO SOBREPASAR LOS 8 DIGITOS, def pedir_dni(dni): if (len(str(dni)) != 8): mensa="el DNI es falso" return mensa else: return dni ################################################################################ #EJERCICIOS NUMERO 2 #EN ESTE EJERCICIO PEDIREMOS UN CODIGO PARA PODER ACCEDER A LA CUENTA GOOGLW #EL CODIGO NO DEBE PASAR LOS 6 DIGTTOS, DE LO CONTRARIO VOLVERA A PEDIR EL CODIGO ################################################################################ def pedir_codigo_google(codigo): if(len(str(codigo)) == 6): print("el codigo es correcto") else: print("el codigo es incorrecto") return codigo ################################################################################ #EJERCICIO NUMERO 3 #EN ESTE EJERCCIO NOS AYUDARA A CALCULAR LA EDAD DE CUALQUIER PERSONA #PARA CALCULAR LA EDAD HALLAREMOS LA DIFERENCIA ENTRE LA FECHA ACTUAL Y LA DE SU NACIMIENTO def hallar_edad(nombre,nacimiento): #DEFINIREMOS EL NOMBRE CON MAYUSCULA AL MOMENTO DEL PRINT nombre=nombre.upper() #CALCULAMOS LA EDAD MEDIANTE OPERACION DE DIFERENCIA edad=2019-nacimiento edad_calculada="La edad de "+ nombre+" es: "+str(edad) return edad_calculada ################################################################################ #EJERCICIO NUMERO 4 #EN ESTE EJRCICO HALLAREMOS LA TABAL DE MULTIPLICA DE CUALQUIER NUMERO #LA TABLA SERA DESDE EL UNO HASTA EL 12 def tabla_multiplicar(n): #DEFINIMOS EL RANGO DE MULTIPLICIDAD for i in range(1,13): #DEFINIMOS LA FORMA EN QUE IRA IMPRESO print("ªª ",n,"*",i,"=",i*n, "ªª") return n ################################################################################ #EJERCICIO NUMERP 5 #EN ESTE EJERCICIO RESOLVERMOS EL FACTORIAL DE CUALQUIER NUMERO #EL FACTORIAL CONSISTE EN LA MULTIPLICACION DE UN NUMEROS POR SU MISMO NUMEROS DISMINUIDO EN UNO, # ASI SUCESIVAMENTE HASTA LLEGAR A UNO def factorial_numero(m): factorial=1 #VERIFICAMOS QUE EL NUMERO SEA DIFERENTE DE CERO , CASO CONTRARIO NO TENDRIA SENTIDO EL FACTORIAL while m>0: factorial=factorial*m m -=1 return factorial ################################################################################ #EJERCICIO NUMERO 6 #ESTE EJERCICIO COSNISTE EN SEPARAR LAS PALABRAS QUE COMIENZEN CON minuscula CON LAS PALABRAS QUE COMIENZEN CON MAYUSCULAS #INTRODUCIMOS CUALQUIER PALABA Y EL PROGRAMA LAS SEPARARA def separandor_de_mayusculas_minusculas(lista): #ESTABLECEMOS LISTAS, DONDE SE GUARDARAN LAS PALABRAS YA SEPARADAS mayuscula=[] minuscula=[] for i in lista: #VERIFICAMOS QUE LAS PALABRAS QUE COMIENZEN CON CUALQUIER LETRA MINUSCULA SE TRASLADEN A LAS LISTA minuscula if (i[0:1]=="a" or i[0:1]=="b" or i[0:1]=="c" or i[0:1]=="d" or i[0:1]=="e" or i[0:1]=="f" or i[0:1]=="g" or i[0:1]=="h" or i[0:1]=="i" or i[0:1]=="j" or i[0:1]=="k" or i[0:1]=="l" or i[0:1]=="m" or i[0:1]=="n" or i[0:1]=="o" or i[0:1]=="p" or i[0:1]=="q" or i[0:1]=="r" or i[0:1]=="s" or i[0:1]=="t" or i[0:1]=="y" or i[0:1]=="w" or i[0:1]=="z"): minuscula.append(i) else: #CASO CONTRARIO SE BASEARAN A LA LISTA mayuscula mayuscula.append(i) return minuscula,mayuscula ################################################################################ #EJERCICIO NUMERO 7 #EN ESTE EJERCICIO NOS PEDIRA EL NOMBRE DE UNA PERSONAS #SI SI INTRODUCE UN NUMERO, APARECERA FALSE def letra(valor): #ESTABLECEMSO QUE VALOR ES UNA CADENA if (valor!=valor.isalpha()): respu=("Los signos introducidos son correctos, puede acceder señor", valor) else: respu=("La palabra es incorrecta, verifique bien sus signos :", valor) return respu ################################################################################ #EJERCICIO NUMERO 8 #EN ESTE EJERCICO CALCULAREMOS EL AREA DE UN TRAPECIO #EL AREA DE UN TRAPECIO SE HALLA CON LOS DATOS DE ALTURA, BASE MAYOR Y BASE MENOR def area_trapecio(base_mayor, altura,base_menor): #ESTABLECEMOS LA FORMULA PARA HALLA EL AREA resultado=(int(base_mayor)+int(base_menor)*altura)/2 return resultado area_trapecio(base_mayor=10,base_menor=23,altura=32) ################################################################################ #EJERCICIO NUMERO 9 #EN ESTE EJERCICIO HALLAREMOS LA MEDIDA DE UN TERRENO #EL AREA DE ESTABLECE EN METROS CUADRADOS, LOS DATOS PARA HALLA EL AREA ES; LARGO Y ANCHO def medicion_terreno(largo,ancho): #ESTABLECEMOS LA FORMAULA PARA HALLAR EL AREA AUTOMATICAMENTE area=largo*ancho #ESTABLECEMOS CONCION PARA CLASIFICAR EL TERRENO; TERRENO COMERCIAL Y TERRENO DE USO DOMESTICO if (area<100): mensa="El terreno es para uso domestico(construccion para casa familiar) y La medida del terreno en metros cuadrados es: ", area else: mensa="El terreno esta acto para contruccion de centros comerciales y La medida del terreno en metros cuadrados es: ", area return mensa ################################################################################ #EJERCICIO NUMERO 10 #EN ESTE EJERCICO HALLAREMOS EL VOLUMEN DE CUALQUIER HEXAEDRO TENIENDO LOS DATOS #DATOS PARA OBTENER EL HEXAEDRO; LARGO, ANCHO Y ALTURA def volumen_hexaedro(largo,ancho,altura): volumen=largo*ancho*altura #SI EL HEXAEDRO ES MAYOR 500 ENTONCES SIRVIRA PARA CONTENER MAS DE MIL LITROS DE AGUA if (volumen>500): print("Puede contener mil litros de agua y el volumen del hexaedro es: ", volumen) else: #SI EL VOLUMEN DEL EHEXAEDRO ES MENOR A 500 NO ESTA ACTO PARA CONTENER UN LIQUIDO print("No esta acto, para contener liquidos ya que su volumen es: ", volumen) return volumen ################################################################################ #EJERCICIO NUMERO 11 #ESTE EJERCICIO CONSISTE EN HALLAR EL TRABAJO Y MOSTRALE UN MENSAJE SEGUN LA CANTIDA DE TRABAJO RESULTANTE #ESTA CALCULADORA HALLA EL TRABAJOREALIZADO def calcular_tranjohecho(fuerza,aceleracion): #DEFINIMOS LA FORMULA DE TRABAJO trabajo=fuerza*aceleracion if (trabajo>100): msg="Ustes es un trabajador muy eficiente " else: msg="Debe esforzarse mas" trabajo_calculado="el trabajo es; ", trabajo return msg ################################################################################ #EJERCICIO NUMERO 12 #EN ESTE EJERCICO CALCULAREMOS LA DISCTANCIA DE CUALQUIER VEHICULO QUE HALLA RECORRIDO #PARA HALLAR LA DISTANCIA NECESITAREMOS LA VELOCIDAD Y EL TIEMPO def calcular_distacia_recorrida(velocidad,tiempo): distancia=velocidad*tiempo #SI LA DISTANCIA ES MAYOR A 800 LE SALDRA UN MENSAJE DE ALIENTO; Ha recorrido un muy buen trayecto if (distancia>800): mensaje="Ha recorrido un muy buen trayecto y su distancia es: ", distancia #CASO COTRARIO LE MOSTRARA QUE DEBE RECORRER MAS LUGARES else: mensaje="Maneje, y conosca mas lugares y su distancia es: ", distancia return mensaje ################################################################################ #EJERCICIO NUMERO 13 #EN ESTE EJERCICO CALCULAREMOS LA DISCTANCIA DE CUALQUIER VEHICULO QUE HALLA RECORRIDO #PARA HALLAR LA DISTANCIA NECESITAREMOS LA VELOCIDAD Y EL TIEMPO def calcular_aceleracion_auto(velocidad,tiempo): aceleracion=(velocidad)/tiempo #SI LA DISTANCIA ES MAYOR A 800 LE SALDRA UN MENSAJE DE ALIENTO; Ha recorrido un muy buen trayecto if (aceleracion>100): mensaje="Usted esta infrinfiendo la ley ya que su aceleracion es: ", aceleracion #CASO COTRARIO LE MOSTRARA QUE DEBE RECORRER MAS LUGARES else: mensaje="Usted es un muy buen ciudadano, sigua asi y su aceleracion aproximadamente es", aceleracion return mensaje ################################################################################ #EJERCICIO NUMERO 14 #EN ESTE EJERCICO CALCULAREMOS LA POTENCIA DE UN MOTOR #PARA HALLAR LA POTENCIA SE NECECISTA DOS VARIABLES; TRABAJO Y TIEMPO def calcular_potencia(trabajo,tiempo): potencia=trabajo/tiempo #DEFINIMOS UNA FORMULA if (potencia>50): mensaje="La potencia de su motor es optimo, numericamente es igual a: ", potencia #CASO COTRARIO LE MOSTRARA QUE DEBE RECORRER MAS LUGARES else: mensaje="Usted deberia cambiar su motor, La potencia de su motor es", potencia return mensaje ################################################################################ #EJERCICIO NUMERO 15 #EN ESTE INTERESANTE EJERCICIO NOS HALLARAN LOS NOMBRES QUE COMIENCEN CON LAS LETRAS A,B,C;D;F,G Y LAS PONDRA EN UNA LISTA #LOS DEMAS NOMBRES SOBRANTES SE BASEARAN EN OTRA LISTA def separandor_de_normabres_porinicial(lista): #ESTABLECEMOS LAS LISTA aletra=[] gletra=[] for i in lista: #VERIFICAMOS QUE LOS NOMBRES COMIENCEN CON LAS LETRAS A,B,C;D;F,G PARA UBICARLAS EN UNA LISTA APARTE DE LOS DEMAS NOMBRES if (i[0:1]=="A" or i[0:1]=="B" or i[0:1]=="C" or i[0:1]=="D" or i[0:1]=="F" or i[0:1]=="G"): aletra.append(i) #SI LOS NOMBRES NO COMIENZAN CON LAS LETRAS ESTABLECIDAS SE BASEARAN EN OTRA LSTA else: gletra.append(i) return gletra,aletra ################################################################################ #EJERCICIO NUMERO 16 #EN ESTE EJERCICIO HALLAREMOS LAS POSIBLES SOLUCIONES, CON LA FORMULA GENERAL #LA FORMULA GENERA SE ESTABLECE CON b(cuadraro) -4ac, lo cual me dara unas posibles soluciones def hallando_posibles_soluciones(a,b,c): #Establecemos la formula general valor=(float(b)**2)-4*float(a)*float(c) if valor < 0: return "No hay solucion" #SI EL RESULTADO ES MENOR A CERO NO HAY POSIBLES SOLUCIONES elif valor==0: x1=-1*float(b)/(2*float(a)) return x1 #SI EL RESULTADO ES MAYOR A CERO Y HAY RESULTADO else: x1=(-1*float(b)+valor**(0.5))/(2*float(a)) x2=(-1*float(b)-valor**(0.5))/(2*float(a)) return x1,x2 #TAMBIEN HABRA RESULTADOS return valor ################################################################################ #EJERCICIO NUMERO 17 #EN ESTE EJERCICIO DETECTAREMOS EL EXCESO DE VELOCIDAD #PARA HALLAR LA VELOCIDAD SE NECESITA DISTNACI Y TIEMPO def detectar_excso_velocidad(distancia,tiempo): velocidad=distancia/tiempo #USAMOS LA CONDICION SOBRE LA VELOCIDAD, SI SOBREPASA LOS 300 KM/H ES EXCESO DE VELOCIDAD if (velocidad>800): mensaje="La velocidad es muy acta, sobrepasa los limites, segun figuera su velocidad es :", velocidad #CASO COTRARIO LE MOSTRARA QUE DEBE RECORRER MAS LUGARES else: mensaje="Excelente conductor, su velocidad figura es :", velocidad return mensaje ################################################################################ #EJERCICIO NUMERO 18 #ESTE EJERCICIO CONSISTE EN MULTIPLICAR LAS ORACIONES, CUNATAS VECES QUERRAMOS #LO HARA EN ORACIONES SEPARADAS def palabra_rep(palabra,numero): var="" var=("\nLa palabra "+palabra+" se repitio "+str(numero)+" veces") for i in range (numero): i=palabra print(i) return var ################################################################################ #EJERCICIO NUMERO 19 #EN ESTE EJERCICO CALCULAREMOS LA VELOCIDAD FINAL #PARA HALLAR LA VELOCIDAD FINAL=DOS VARIABLES: VELOCIDAD INICIAL,ACELERACION Y TIEMPO def calcular_velocidad_final(velinical,aceleracion,tiempo): velocidaad_final=velinical+aceleracion*tiempo #ESTABLECEMOS UNA CONDICION if (velocidaad_final>50): mensaje="El auto es demasiado rapido , Su velocidad final fue de : ", velocidaad_final #ESTABLECEMOS UNA CONDICION else: mensaje="UEl auto es demasiado lento, deberia equiparlo, Su velocidad final fue", velocidaad_final return mensaje ################################################################################ #EJERCICIO NUMERO 20 #EN ESTE EJERCICO HALLAREMOS EL VOLUMEN DE CUALQUIER CELIENDRO #DATOS PARA OBTENER EL CILINDRO; GENERATRIZ, LARGO,ANCHO def volumen_cilindro(largo,ancho,generatriz): volumen=largo*ancho*generatriz #ESTABLECEMOS UNA CONDICION if (volumen>200): print("El cilindro es grande puede ser utilizado y el volumen del cilindro es: ", volumen) else: #ESTABLECEMOS UNA CONDICION print("El volumen del cilindro es pequeñod ya que su volumen es: ", volumen) return volumen ################################################################################ #EJERCICIO NUMERO 21 #ESTE EJERCICIO CONSISTE EN CALCULAR LA DENSIDAD DE CAULQUIER PISCINA def calcular_densidad(masa,volumen): densidad=(masa)/volumen #ESTABECEMOS UNA CONDICION if (densidad>100): msg="El objeto es demasiado denso " else: msg="El pbjeto es liviano" trabajo_calculado="LA densidad medida fue ; ", densidad return msg ################################################################################ #EJERCICIO NUMERO 22 #EN ESTE EJERCICO CALCULAREMOS LA DISCTANCIA DE CUALQUIER VEHICULO QUE HALLA RECORRIDO #PARA HALLAR LA DISTANCIA NECESITAREMOS LA VELOCIDAD Y EL TIEMPO def calcular_ACELERACION_ANGULAR(radio,velocidad_angular): ACELERACION_ANGULAR=radio*velocidad_angular #SI LA DISTANCIA ES MAYOR A 800 LE SALDRA UN MENSAJE DE ALIENTO; Ha recorrido un muy buen trayecto if (ACELERACION_ANGULAR>400): mensaje="El disco esta girando bastante rapido y la revolucion por minuto es: ", ACELERACION_ANGULAR #CASO COTRARIO LE MOSTRARA QUE DEBE RECORRER MAS LUGARES else: mensaje="El disto estagirando demasiado lentro, quiza se deba a algun problema y la revolucion por minuto es: ", ACELERACION_ANGULAR return mensaje ################################################################################ #EJERCICIO NUMERP 23 #EN ESTE EJERCICIO RESOLVERMOS EL FACTORIAL DE CUALQUIER NUMERO #EL FACTORIAL CONSISTE EN LA MULTIPLICACION DE UN NUMEROS POR SU MISMO NUMEROS DISMINUIDO EN UNO, Y SUMANDO # ASI SUCESIVAMENTE HASTA LLEGAR A UNO Y AL VEZ SUMAND LA DIFERENCIA def factorial_numero(m): factorial=1 #VERIFICAMOS QUE EL NUMERO SEA DIFERENTE DE CERO , CASO CONTRARIO NO TENDRIA SENTIDO EL FACTORIAL while m>0: factorial=factorial*m+m m -=1 return factorial ################################################################################ #EJERCICIO NUMERO 24 #EN ESTE EJERCICO CALCULAREMOS EL AREA DE UN ROMBO #EL AREA DE UN TRAPECIO SE HALLA CON LOS DATOS DE DIAGONAL MAYO, DIAGONAL MENOR def area_rombo(diagonal_mayor, diagonal_menor): #ESTABLECEMOS LA FORMULA PARA HALLA EL AREA resultado=(diagonal_mayor*diagonal_menor)/2 return resultado ################################################################################ #EJERCICIO NUMERO 25 #EN ESTE EJERCICO CALCULAREMOS EL VOLUMEN DE UNA PIRAMIDE #EL AREA DE UN TRAPECIO SE HALLA CON LOS DATOS DE ALTURA, AREA DELA BASE def hallar_volumn_piramide(area_base, altura): #ESTABLECEMOS LA FORMULA PARA HALLA EL AREA resultado=(area_base*altura) return resultado ################################################################################
988bcf77a3294e7a26291219539f10177266e3a1
midi0/python
/CodingDojang/Unit 26/26.6.py
290
3.734375
4
''' 세트 표현식 사용하기 a = {i for i in 'apple'} #중복되는 p는 하나만 요소로 들어간다 표현식과 if 조건문 사용 a = {i for i in 'pineapple' if i not in 'apl'} # e i n이 요소로 들어감 ''' a = {i for i in 'pineapple' if i not in 'apl'} print(a)
c9065d4530057f993572c6cd3dd335a747f245d7
tydhoang/CSE-143
/N-Gram Language Models/Training_Token_Initialization.py
3,769
3.609375
4
# @author Tyler Hoang # CSE-143 # Training_Token_Initialization.py program that finds the frequency of all tokens in the training data. Words that occur less than 3 times are replaced # with <UNK> tokens. Dev and test data set are then analyzed for OOV vocab and subsequently replaced with <UNK> tokens. This data is outputted to the # file Training_Token_Data.txt. # Afterwards, the bigrams and trigram frequencies are analyzed in the training set are stored in dictionaries and outputted to text files. # #! /usr/bin/env python3 import fileinput import sys def main(): N = 0 trainingTokens = {} bigramTokens = {} trigramTokens = {} # Create dictionary with token frequencies trainingData = open("1b_benchmark.train.tokens") for line in trainingData: words = line.split() words.append("<STOP>") N += len(words) words.insert(0, "<START>") for token in words: if token in trainingTokens: trainingTokens[token] = trainingTokens[token] + 1 else: trainingTokens[token] = 1 trainingData.close() #Replace words with frequency < 3 with <UNK> for line in fileinput.FileInput("1b_benchmark.train.tokens", inplace=True): words = line.split() for n, i in enumerate(words): if trainingTokens[i] < 3: words[n] = "<UNK>" newSentence = ' '.join(words) print(newSentence) trainingTokens["<UNK>"] = 0 UNKS = list() for token in trainingTokens: if(trainingTokens[token] < 3 and token != "<UNK>" and token != "<STOP>"): trainingTokens["<UNK>"] = trainingTokens["<UNK>"] + trainingTokens[token] UNKS.append(token) for UNK in UNKS: if UNK in trainingTokens: del trainingTokens[UNK] #Apply <UNK> tokens to test and dev for line in fileinput.FileInput("1b_benchmark.test.tokens", inplace=True): words = line.split() for n, i in enumerate(words): possKey = trainingTokens.get(i) if possKey == None: words[n] = "<UNK>" newSentence = ' '.join(words) print(newSentence) for line in fileinput.FileInput("1b_benchmark.dev.tokens", inplace=True): words = line.split() for n, i in enumerate(words): possKey = trainingTokens.get(i) if possKey == None: words[n] = "<UNK>" newSentence = ' '.join(words) print(newSentence) ################################################################################################ # <UNK>'ing is now complete ################################################################################################ #Bigrams are now to be analyzed updatedTrainingData = open("1b_benchmark.train.tokens") for line in updatedTrainingData: words = line.split() words.insert(0, "<START>") words.append("<STOP>") for i in range(len(words)): if i + 1 == len(words): break; bigram = (words[i], words[i + 1]) if bigram in bigramTokens: bigramTokens[bigram] = bigramTokens[bigram] + 1 else: bigramTokens[bigram] = 1 updatedTrainingData.close() #Trigrams are now to be analyzed updatedTrainingData = open("1b_benchmark.train.tokens") for line in updatedTrainingData: words = line.split() words.insert(0, "<START>") words.append("<STOP>") for i in range(len(words)): if i + 2 == len(words): break; trigram = (words[i], words[i + 1], words[i + 2]) if trigram in trigramTokens: trigramTokens[trigram] = trigramTokens[trigram] + 1 else: trigramTokens[trigram] = 1 updatedTrainingData.close() # Output the data to the respective text files outFile = open("Training_Token_Data.txt", "w") outFile.write(str(N) + "\n") outFile.write(str(trainingTokens)) biOutFile = open("Training_Bigram_Data.txt", "w") biOutFile.write(str(N) + "\n") biOutFile.write(str(bigramTokens)) triOutFile = open("Training_Trigram_Data.txt", "w") triOutFile.write(str(N) + "\n") triOutFile.write(str(trigramTokens)) main()
1c793073240fb3059830981ebaccd22555902641
Joeffison/coding_challenges
/challenges/spoj/nsteps/nsteps_v001.py
475
3.5625
4
#!/usr/bin/env python3 import fileinput import sys if sys.version_info[0] >= 3: map = lambda func, l: [func(i) for i in l] else: range = xrange if __name__ == '__main__': f_in = fileinput.input() n_test_cases = int(f_in.readline()) for i in range(n_test_cases): x, y = map(int, f_in.readline().split()) if x == y or (x > 1 and y == x - 2): if x % 2 == 0: print(x + y) else: print(x + y - 1) else: print('No Number')
75b7ba38d4cba1f2233a5b263623ff31c08771c0
aneeshdurg/dotfiles
/.quotes.py
2,081
3.546875
4
#! /usr/bin/python3 from random import randint import os _, columns = os.popen('stty size', 'r').read().split() columns = int(columns) def fitColumn(final, s): if len(s) < columns: final.append(s) else: c = columns while c>=0 and s[c] != ' ': c-=1 if c < 0: final.append(s) else: #print('SPLIT', s[:c],'|', s[c:]) final.append(s[:c]) fitColumn(final, s[c:]) quotes = [ "Just as there's no such thing as a bug-free program, there's no program that can't be debugged.\n\t-Ghost in the Shell (1995)", # "Everyone, deep in their hearts, is waiting for the end of the world to come.\n\t-Haruki Murakami, 1Q84 ", "It is not that the meaning cannot be explained. But there are certain meanings that are lost forever the moment they are explained in words.\n\t-Haruki Murakami, 1Q84", "Only the inanimate may be so alive.\n\t-David Mitchell, Cloud Atlas", 'The mind is not like raindrops. It does not fall from the skies, it does not lose itself among other things.\n\t-Haruki Murakami, Hard Boiled Wonderland And The End Of The World', # "Distilled for the eradication of seemingly incurable sadness.\n\t-Cillian Murphy, Peaky Blinders", # "Come here you worthless pup. Come here and take your medicine!\n\t-Stephen King, The Shining", "Arguing with anonymous strangers on the Internet is a sucker's game because they almost always turn out to be—or to be indistinguishable from—self-righteous sixteen-year-olds possessing infinite amounts of free time.\n\t-Neal Stephenson, Cryptonomicon", "But everyone also lives in the world inside their own head. An \x1B[3minscape\x1B[0m, a world of thought.\n\t-Joe Hill, NOS4A2", "Dance. As long as the music plays.\n\t-Haruki Murakami, Dance Dance Dance", "Shriek into the vacuum if in spite of your accomplishments you wake up feeling empty like Houdini’s grave probably is.\n\t-Aesop Rock, Klutz" ] r = randint(0, len(quotes)-1) selected = quotes[r].split('\n') final = [] for s in selected: fitColumn(final, s) for f in final: print(f)
61947b62db459cbe3644338e33eff61f0aff8e6c
zhangdavids/workspace
/Daily/180507.py
631
3.734375
4
# 哈夫曼算法 from heapq import heapify, heappush, heappop from itertools import count def huffman(seq, frq): num = count() print(num) trees = list(zip(frq, num, seq)) print(trees) heapify(trees) while len(trees) > 1: fa, _, a = heappop(trees) fb, _, b = heappop(trees) n = next(num) heappush(trees, (fa+fb, n, [a, b])) print() print(trees) return trees[0][-1] def main(): seq = "abcdefghi" frq = [4, 5, 6, 9, 11, 12, 15, 16, 20] print(huffman(seq, frq)) if __name__ == "__main__": pass main()
6c8d2634de6b7c13f4c7dbf94f0ffdad7362ff8c
jntushar/leetcode
/30-Day LeetCoding Challenge/Maximum Subarray.py
370
3.859375
4
""" Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. """ """---SOLUTION---""" class Solution: def maxSubArray(self, nums): T=[0]*len(nums) T[0]=nums[0] for i in range(1,len(nums)): T[i]=max(T[i-1]+nums[i],nums[i]) return max(T)
954eec135fd979cec4bb3aa59c98cfcc307258d3
TREMOUILLEThomas/ex-68
/ex 68 (3).py
401
3.96875
4
from turtle import * def triangle(a): begin_fill() for i in range (3): forward(a) left(120) end_fill() def tritri(a): for i in range(3): triangle(a) left(90) up() forward(a/2) right(90) forward(a/6) down() a=a*(2/3) if i == 7: a=100 a=int(input("cote")) tritri(a) hideturtle() input()
d875656e721146c25dae984c847498ea7a59bb9d
jatinrajani/Principles-of-Computing
/rockpaperlizard.py
2,645
4.25
4
# Rock-paper-scissors-lizard-Spock template import random # The key idea of this program is to equate the strings # "rock", "paper", "scissors", "lizard", "Spock" to numbers # as follows: # # 0 - rock # 1 - Spock # 2 - paper # 3 - lizard # 4 - scissors # helper functions def name_to_number(name): # delete the following pass statement and fill in your code below # convert name to number using if/elif/else # don't forget to return the result! if name=="rock": return 0 elif name=="Spock": return 1 elif name=="paper": return 2 elif name=="lizard": return 3 elif name=="scissors": return 4 def number_to_name(number): # delete the following pass statement and fill in your code below if number=="0": return "rock" elif number=="1": return "Spock" elif number=="2": return "paper" elif number=="3": return "lizard" elif number=="4": return "scissors" # convert number to a name using if/elif/else # don't forget to return the result! player_choice=raw_input("Please Enter your choice") def rpsls(player_choice): # delete the following pass statement and fill in your code below # print a blank line to separate consecutive games print (" ") # print out the message for the player's choice" print "player choice is "+player_choice # convert the player's choice to player_number using the function name_to_number() player_number=name_to_number(player_choice) # compute random guess for comp_number using random.randrange() comp_number=random.randrange(4) # convert comp_number to comp_choice using the function number_to_name() comp_choice=number_to_name(str(comp_number)) # print out the message for computer's choice print "Computer choice is "+str(comp_choice) # compute difference of comp_number and player_number modulo five dif=(comp_number-player_number)%5 # use if/elif/else to determine winner, print winner message if dif==0: print "It is a tie" elif dif>2: print "Player Wins" elif dif<=2: print "Computer Wins" # test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE rpsls(player_choice) player_choice=raw_input("Please Enter your choice") rpsls(player_choice) # always remember to check your completed program against the grading rubric
fddc71038001b4de9eb1013bdb7f4a3aadfe6def
Tofitk/TextMinesweeper
/main.py
1,046
3.9375
4
from classes import board_class, tile_class from functions import functions height = int(input("give the height of the playing board (max 10): ")) lenght = int(input("give the lenght of the playing board (max 10): ")) max_mines = str((height * lenght) - 1) mines = int(input("give the amount of mines you want (max " + max_mines + "): ")) board = functions.create_board(height,lenght,mines) turn = 0 while not board.loss and not board.victory: print(board) move = functions.user_move(board) if turn == 0: board.place_the_mines(int(move[0]),int(move[1])) turn += 1 if move[2] == "f" or move[2] == "F": board.flag_tile(int(move[0]),int(move[1])) if move[2] == "r" or move[2] == "R": board.reveal_tile(int(move[0]),int(move[1])) board.check_victory() if move[2] == "d" or move[2] == "D": board.deflag_tile(int(move[0]),int(move[1])) print(board) if board.loss: print("You revealed a mine, you die.") if board.victory: print("You win, graz")
9f38ccbe3335dc8ac4dba611f0b81d72e2a6c8e9
lawrenceh123/data-challenges
/data-science-400/04-NumericData.py
7,580
3.53125
4
""" L04 Assignment: Numeric Data Dataset: Credit Approval Data from UCI Machine Learning Repository Operations: assign column names, impute and assign median values for missing numeric values, replace outliers (with median values), create a histogram and a scatterplot, determine the standard deviation of all numeric variables Please see summary comment block for discussion """ #1. Import statements for necessary package(s). import numpy as np import pandas as pd import matplotlib.pyplot as plt ######################################## # 2. Read in the dataset from a freely and easily available source on the internet. # using Credit Approval Data Set from UCI Machine Learning Repository # this dataset contains: # --numeric attributes with missing data for this assignment # --categorical attributes (also with missing data) for potential later use # --specified attribute headings url = "https://archive.ics.uci.edu/ml/machine-learning-databases/credit-screening/crx.data" Credit = pd.read_csv(url, header=None) ######################################## # 3. Assign reasonable column names. # create column names as specified on dataset website (UCI Machine Learning Repository): A1, A2, ..., A16 # note that per dataset website: "all attribute names and values have been changed to meaningless symbols to protect confidentiality of the data." Credit.columns = ['A{}'.format(i) for i in range(1,Credit.shape[1]+1)] ######################################## # 4. Impute and assign median values for missing numeric values. # check data types Credit.dtypes # from dataset website, A2, A3, A8, A11, A14, A15 should be numeric, # but A2 and A14 are have dtype "object", and have missing values ('?' as placeholders) # Flag missing values in A2 and A14 and assign the median value # A2 # convert to numeric data including nans Credit.loc[:,'A2'] = pd.to_numeric(Credit.loc[:,'A2'], errors='coerce') HasNan2 = np.isnan(Credit.loc[:,'A2']) #sum(HasNan2) # num of missing values Credit.loc[HasNan2, 'A2'] = np.nanmedian(Credit.loc[:,'A2']) # A14 # convert to numeric data including nans Credit.loc[:,'A14'] = pd.to_numeric(Credit.loc[:,'A14'], errors='coerce') HasNan14 = np.isnan(Credit.loc[:,'A14']) #sum(HasNan14) # num of missing values Credit.loc[HasNan14, 'A14'] = np.nanmedian(Credit.loc[:,'A14']) # Create histograms + scatterplots for all numeric variables before replacing outliers # histograms can be used to visualize outliers for the next step pd.plotting.scatter_matrix(Credit, alpha=0.2, figsize=[10,10]) plt.suptitle('Histogram and scatterplots of numeric variables before replacing outliers') plt.show() ######################################## #5. Replace outliers. # referencing the histograms created above, and without additional domain knowledge, # use a standard definition for outliers: x > mean(x)+2*std(x) or x < mean(x)-2*std(x) # define function that replaces outliers with the median def replace_outlier(y): x = np.copy(y) LimitHi = np.mean(x) + 2*np.std(x) LimitLo = np.mean(x) - 2*np.std(x) # Create Flags for outliers FlagBad = (x < LimitLo) | (x > LimitHi) # Replace outliers with the median x = x.astype(float) # since np.median returns float x[FlagBad] = np.median(x) return x # perform replacement on numeric columns Credit[['A2', 'A3', 'A8', 'A11', 'A14', 'A15']] = Credit[['A2', 'A3', 'A8', 'A11', 'A14', 'A15']].apply(replace_outlier) ######################################## # 6. Create a histogram of a numeric variable. Use plt.show() after each histogram. # create a histogram of numeric variable A2 plt.hist(Credit.loc[:, 'A2']) plt.xlabel('A2') plt.ylabel('Count') plt.title('Histogram of A2 after replacing outliers') plt.show() # 7. Create a scatterplot. Use plt.show() after the scatterplot. # create a scatterplot of A3 vs. A2 plt.scatter(Credit.loc[:,'A2'], Credit.loc[:,'A3']) plt.xlabel('A2') plt.ylabel('A3') plt.title('Scatterplot of A3 vs. A2 after replacing outliers') plt.show() # from assginment instructions, the number of histograms and scatterplots requested was unclear. (one numeric variable? all numeric variables?) # Create histograms + scatterplots for all numeric variables pd.plotting.scatter_matrix(Credit, alpha=0.2, figsize=[10,10]) plt.suptitle('Histogram and scatterplots of numeric variables after replacing outliers') plt.show() ######################################## # 8. Determine the standard deviation of all numeric variables. Use print() for each standard deviation. # std for all numeric variables stds = np.std(Credit) # per instruction, use print() for each std for i, x in enumerate(stds): print('Numeric variable:', stds.index[i], ', Standard deviation:', x) ######################################## # 9. Add comments to explain the code blocks. # Please see comments in code blocks above. ######################################## # 10. Add a summary comment block on how the numeric variables have been treated: # 1. Which attributes had outliers and how were the outliers defined? # ANS: Referencing the histograms (after median imputation of missing values but before replacing outliers), # the standard definition of outliers was used in the absence of additional domain knowledge: # x < mean(x)-2*std(x) or x > mean(x)+2*std(x). # By this definition, numeric attributes A2, A3, A8, A11, A14, A15 had outliers. # 2. Which attributes required imputation of missing values and why? # ANS: Numeric attributes A2 and A14 had missing values with '?' as placeholders and required imputation. # Missing values in numeric attributes make the column elements as datatype object and represented as strings, # which prevents math operations such as calcuating the standard deviation, or plotting a (correct) histogram. # In addition, subsequent analyses may not tolerate the placeholders. # 3. Which attributes were histogrammed and why? # ANS: histograms were plotted for all numerical attributes to examine their distributions and visualize outliers. # 4. Which attributes were removed and why? # ANS: No numeric attribtues were removed. Per assignment instructions, median imputation of missing values was performed instead. # The advantage of this replacement option is that data are not lost. # The disadvantage is that the replacement value is based on a guess (median in this case). # If numeric attribtues with missing data was to be removed instead, then all attributes/columns that have one or more NaN should be removed. # (Missing categorical values were not replaced or removed in this assignment.) # 5. How did you determine which rows should be removed? # ANS: If missing data was to be removed using the row removal method, then all rows that have one or more NaN should be removed. # However, per assignment instructions, median imputation of missing values was performed for numeric attributes, # and no rows were removed. (Per assignment instructions, outliers were also replaced and not removed.) # The following could be used to remove attributes or rows with missing values: ## After reading in the dataset, Replace '?' with NaNs # Credit = Credit.replace(to_replace="?", value=float("NaN")) ## Remove columns that contain one or more NaN # Credit_FewerCols = Credit.dropna(axis=1) ## Remove rows that contain one or more NaN # Credit_FewerRows = Credit.dropna(axis=0) ########################################
f19b2d5f2efcef610edc572f99603ea1f3e54347
Iven022/TD3_Iven_Henna
/main.py
1,075
4.25
4
from addTwoInt import add from mulTwolnt import mul x="a" while((x=="a") or (x=="q") or (x=="b")): print("For Addition of two numbers press < a > ") print("For multiplacation press < m > ") print("For both calculations press < b > ") print("To quit press < q > ") x=input("Enter desired process ") if ((x=="a") or (x=="m") or (x=="b")): try: a=int(input("Enter first number ")) b=int(input("Enter Second number ")) if (x=="a"): print("Your Addition result is: " + str(add(a,b))) elif (x=="m"): print("Your Multiplication result is " + str(mul(a,b))) x=="m" else: print("Your Addition result is: " + str(add(a,b))) print("Your Multiplication result is " + str(mul(a,b))) x=="a" print(" ") print(" ") z=input("More Calculations ? Press < y > for more or < n > to stop ") if (z=="y"): x=="a" elif(z=="n"): break else: print("Invalid input") break except Exception as e: print("Invalid Input, try again") elif (x=="q"): break else: print("Invalid input, try again") x="a"
509dc153042e70bc17b917a7495f86f6409c5234
mucahidyazar/python
/worksheets/09-advance/exercises/harf-kac-kez.py
423
3.578125
4
print(""" QUESTION: Elinizde uzunca bir string olsun. "ProgramlamaÖdeviİleriSeviyeVeriYapılarıveObjeleripynb" Bu string içindeki harflerin frekansını (bir harfin kaç defa geçtiği) bulmaya çalışın. """) newString = "ProgramlamaÖdeviİleriSeviyeVeriYapılarıveObjeleripynb" newList = dict() for x in newString: if x in newList: newList[x] += 1 else: newList[x] = 1 print(newList)
d52bd6d4dd90e10832ce8aa446fd8c9c7cb30c0a
srajeevan/Python-apps
/Misc/function.py
162
3.625
4
def hello(name): print('Hey '+ name) hello('Roy') hello('Alice') def plusOne(num): print(num + 1) plusOne(5) for i in range(0, 10, 2): print(i)
6ef5f64f0b6061be957d71c7b41ae2289ecb8693
kamalkorede/MIT-6.001
/6.00a/ps2a.py
4,564
3.953125
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 31 20:45:00 2017 @author: KAMALDEEN """ import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. """ # inFile: file inFile = open(WORDLIST_FILENAME, 'r') line = inFile.readline() wordlist = line.split() return wordlist wordlist = load_words() def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) #wrd=print(choose_word(wordlist)) def is_word_guessed(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing; assumes all letters are lowercase letters_guessed: list (of letters), which letters have been guessed so far; assumes that all letters are lowercase returns: boolean, True if all the letters of secret_word are in letters_guessed; False otherwise ''' lists=[] sub_secret=secret_word[:] for letters in sub_secret: if letters not in lists: lists.append(letters) guess_left=6 lst=[] while True: letters_guessed=input('Enter your guess: ',) if letters_guessed in lst: guess_left-=1 elif letters_guessed in secret_word: lst.append(letters_guessed) else: guess_left-=1 if guess_left==0:break if (secret_word==lst or set(secret_word).issubset(lst)):break letters_guessed=lst print('secret word is: ',secret_word) return secret_word==letters_guessed or set(secret_word).issubset(letters_guessed) def alphabets(): '''all letters in english alphabet''' return(string.ascii_lowercase) def get_guessed_word(secret_word, letters_guessed): ''' secret_word: string, the word the user is guessing letters_guessed: list (of letters), which letters have been guessed so far returns: string, comprised of letters, underscores (_), and spaces that represents which letters in secret_word have been guessed so far. ''' rep=('_ ')*len(secret_word) print('Guess the secret word: ',rep) lists=[] secret_wrd=secret_word[:] for letters in secret_wrd: if letters not in lists: lists.append(letters) # sub_secret=lists guess_left=6 warning=0 lst=[] all_guessed=[] atoz=string.ascii_lowercase while True: secret_wrd=secret_word[:] letters_guessed=input('Enter your guess(only 1 guess at a time): ',) str.lower(letters_guessed) if str.isalpha(letters_guessed)==False: warning+=1 print('invalid input!') print('you have',(3-warning),'warnings left') all_guessed.append(letters_guessed) for leter in atoz: if leter in all_guessed: atoz=atoz.replace(leter,'_') print('remaining letters yet to be guessed: ',atoz) if letters_guessed in lst: guess_left-=1 elif letters_guessed==secret_word: print('your guess was perfect!,YOU WON!') break elif letters_guessed in secret_word: lst.append(letters_guessed) print('That was a pretty good guess') else: print('your guess was wrong') guess_left-=1 print('you have',guess_left,'guesses left') for alpha in secret_wrd: if alpha not in lst: secret_wrd=secret_wrd.replace(alpha,' _ ') print(secret_wrd) print('-------------') if (secret_word==lst or set(secret_word).issubset(lst)): print('YOU WON!') break if guess_left==0: print('Sorry,you lost!') print('The correct word is:',secret_word) break if warning==3: print('you have no warning left,Game Over!') break letters_guessed=lst # print('secret word is: ',secret_word) print('would you like to play again?') return (secret_wrd) def hangman(secret_word): print('Welcome to the game Hangman!') print('I am thinking of a word',len(secret_word),'letters long.') print('You have 6 guess(es) left.') letters_guessed=None get_guessed_word(secret_word, letters_guessed) print('*********************') return('endgame') secret_word=choose_word(wordlist) play=hangman(secret_word) #####
14e8eff740778825d49784a77dfc77960763d812
Jelly-yeah/Study
/小写大写 判断.py
114
3.5625
4
pan = input() def pan(a): if ord(a)>=97: return "大写" else: return "小写"
9f57906df9e4615f1d8f5297c9fb1cd0e225b544
ishantk/Enc2019B
/venv/Session20E.py
775
3.84375
4
class BaningException(Exception): pass print(">> Banking Started") accBalance = 10000 minBalance = 2000 attempts = 0 def withdraw(amount): global accBalance global minBalance global attempts accBalance = accBalance - amount if accBalance > minBalance: print("Withdrawl Finished!! New Balance is \u20b9{}".format(accBalance)) else: accBalance = accBalance + amount print("Withdrawl Failed!! Balance is Low \u20b9{}".format(accBalance)) attempts += 1 # We are crashing the App ourselves !! if attempts == 3: # error = ZeroDivisionError("Illegal Attempts") error = BaningException("Illegal Attempts") raise error for i in range(7): withdraw(3000) print(">> Banking Finished")
ba79b4f345ab83931d8fb1e64c844715b4259c22
toastdriven/euler
/jason/problem-005.py
164
3.765625
4
#!/usr/bin/env python def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b) : return a * b / gcd(a, b) print reduce(lcm, range(1,21))
a327e96d8090b1017478764680dcdd3cf9de89a6
spearfish/python-crash-course
/example/16.1.2_print_header/highs_lows.py
365
3.75
4
#!/usr/bin/env python3 import csv fname = 'sitka_weather_07-2014.csv' with open(fname) as f : # create a reader object reader = csv.reader(f) # next function calls reader.__next__, which returns a line and move the pointer to the next line header_row = next(reader) for index, header in enumerate(header_row) : print(index, header)
1ea7b71be476e782b004ca82bd5c2ec050aec769
sana25052001/FSD
/data structure.py
301
4
4
from enum import Enum class Country(Enum): Africa = 93 Asia = 355 America = 213 Antarctica = 376 Europe = 244 Paris = 672 print('\nMember name: {}'.format(Country.Paris.name)) print('Member value: {}'.format(Country.Paris.value)) Output: Member name: Paris Member value: 672
a65c26564f84ee38ec382cc2b7a34cb56c30d2c3
harmansehmbi/Project10
/practice10j.py
261
3.890625
4
class CA: num = 101 def __init__(self): self.a = 102 def show(self): print("num is: ", self.num) # we can also use print("num is: ", CA.num) # class name print("num is: ", ca.num) ca = CA() ca.show()
034989642e0474b3e8fb52b4cdf0015288455d93
HaydenInEdinburgh/LintCode
/547_intersection_of_two_arrays.py
1,027
3.84375
4
class Solution: """ @param nums1: an integer array @param nums2: an integer array @return: an integer array """ def intersection(self, nums1, nums2): # write your code here if not nums1 or not nums2: return [] p1, p2 = 0, 0 intersection = [] nums1.sort() nums2.sort() while p1< len(nums1) and p2< len(nums2): n1, n2 = nums1[p1], nums2[p2] if n1 < n2: p1 += 1 while p1< len(nums1) and nums1[p1] == nums1[p1-1]: p1 += 1 elif n1 > n2: p2 += 1 while p2< len(nums2) and nums2[p2] == nums2[p2-1]: p2 += 1 else: if n1 not in intersection: intersection.append(n1) p1 += 1 p2 += 1 return intersection if __name__ == '__main__': s = Solution() a = [1, 2, 2, 1] b = [2, 2] print(s.intersection(a,b))