blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d5b59ff5725bc969689af8de9d5fcea0e6d0d547
theopolis/osquery
/tools/codegen/substitute.py
1,314
3.609375
4
#!/usr/bin/env python3 # Copyright (c) 2014-present, Facebook, Inc. # All rights reserved. # # This source code is licensed in accordance with the terms specified in # the LICENSE file found in the root directory of this source tree. """ Replace every occurrences of pattern in every string of input file and write...
63ab515f478a0259680633c62e19c5b15093b460
Kurtis-Leach/RandomPython
/RandomLittleThings/dictionaries.py
411
3.984375
4
#Dictionaries are objects banana = { 'color': 'yellow', 'taste': 'good' } print (banana.get('color')) banana['age'] = '1 week' for x in banana: print(x) for x, y in banana.items(): print(x, y) if 'color' in banana: print (True) print(len(banana)) banana.pop('color') # also {del banana['color']} prin...
0d556419e74ba3eb027f5ad81be5f2ea2eb676ae
myanir/Campus.il_python
/self.py/7.2.7.py
594
3.859375
4
def arrow(my_char, max_length): shape = '' holder = 1 while holder <= max_length: shape += my_char * holder + '\n' holder += 1 holder = max_length - 1 while holder > 0: shape += my_char * holder + '\n' holder -= 1 return shape def arrow2(my_char, max_length): ...
7f1ff6a44cd8e103bad356a01a7508c8ab3b60e3
myanir/Campus.il_python
/next.py/2.3.4.py
1,509
3.640625
4
class Pixel: """ _x - x coordinate _y - y coordinate _red - a value between 0 and 255 _green - a value between 0 and 255 _blue - a value between 0 and 255 """ def __init__(self, x=0, y=0, red=0, green=0, blue=0): self._x = x self._y = y self._red = red self._green = green ...
203fce15b7c96945e99e29dfc92e336b05020677
myanir/Campus.il_python
/next.py/2.2.2.py
353
3.71875
4
class Animal(): def __init__(self, name, age = 0): self.name = name self.age = age def birthday(self): self.age += 1 def get_age(self): return self.age def main(): deer = Animal('deer', 2) dolphin = Animal('dolphine', 3) deer.birthday() print('{}, {}'.forma...
9d768667090b10dbf6592d45e86f6482278c07d6
myanir/Campus.il_python
/self.py/distance.py
256
4.03125
4
def distance(num1, num2, num3): if (abs(num2 - num1) == 1 or abs(num3 - num1) ==1) and (abs(num3 - num2) > 2 and (abs(num3 - num1) > 2 or abs(num2 - num1) > 2)): return True return False print(distance(1, 2, 10)) print(distance(4, 5, 3))
c47d32391b8c18705ab43c0129135a3ac36f1a3b
myanir/Campus.il_python
/self.py/dateconvert.py
213
4.15625
4
import calendar user_input = input("Enter a date: ") # 01/01/2000 year = int(user_input[-4:]) month = int(user_input[3:5]) day = int(user_input[:2]) print(calendar.day_name[calendar.weekday(year, month, day)])
588d73eb31c3c12fd79308a032cd8d1f34a073cb
jeffreybrowning/algorithm_projects
/problems/mathing_brackets.py
923
3.859375
4
# def is_matched(expression): # if len(expression) % 2 != 0: return False # # mid = len(expression) // 2 # char_map = {'}': '{', ')': '(', ']': '['} # first_half = expression[:mid] # second_half = expression[mid:] # # for i in range(len(first_half)): # if char_map.get(first_half[-i - 1],...
221a8faf61fc8d5e507718cd06c76d905ffa22d2
jeffreybrowning/algorithm_projects
/dynamic/minimum_steps.py
1,583
4.34375
4
def get_min_steps (num): """ For any positive integer num, returns the amount of steps necessary to reduce the number to 1 given the following possible steps: 1) Subtract 1 2) Divide by 2 3) Divide by 3 >>>get_min_steps(15) 4 """ if num <= 0 or type(num) != int: return None min_steps_list = [...
8324e5b761144cc48ca9f94f4fbba526e57d3948
jeffreybrowning/algorithm_projects
/sort/insertionsort.py
1,710
4.03125
4
def insertionsort(l): """insertionsort is a sorting algrorithm similar to selection sort, although with a much better best case time complexity: quadratic vs. linear. Insertion sort is very simple: 1. i increments to the length of our list 2. j decrements from i to beginning of th...
9459fddd3d3380c3d7a3f3f2e1e981ab4faf208e
lagzuxsb/GuessingGame
/Guessing Game.py
547
3.96875
4
import random randomNumber = random.randint(1, 100) GU = int(input("Take a guess: ")) tries = 1 while GU != randomNumber: if GU > randomNumber: print("Lower..") else: print("Higher...") GU = int(input("Take a guess: ")) tries += 1 if tries == 5: print("You failed to g...
1896dbbbe96e75dfa68a1aa5f432d3ad45a04246
Yaminis688/SDLC_2_Electron
/3_Implementation/TicTacToe/p1_tictactoe/computermove.py
1,009
3.671875
4
from . import selectrandom from . import winner def computer_move(board): """Function to take computer move""" possible_moves = [x for x, letter in enumerate(board) if letter == ' ' and x != 0] move = 0 for let in ['O', 'X']: for i in possible_moves: ...
3821ed1cd74a6bf3860206c59796671acb6a8fdd
Yaminis688/SDLC_2_Electron
/3_Implementation/TicTacToe/p1_tictactoe/spacefree.py
138
3.53125
4
def space_is_free(board, pos): """Function to check whether particular position is occupied or not""" return board[pos] == ' '
5955ec960621c829c3a7598e652ccd93d62c254a
AlgotAxelzon/aoc-2020
/12/solution.py
1,707
3.546875
4
from math import cos, sin, pi def input(): with open("12/input.txt", "r") as f: return [line.strip() for line in f.readlines()] def instruction1(line, pos): a = line[0] if a == "N": pos[2] += int(line[1:]) if a == "S": pos[2] -= int(line[1:]) if a == "E": pos[1] += ...
c9e91af1546f019a0e80755cf728a7ac312ade79
rafaelfcardoso/financial-returns-in-government-bonds
/parte1.py
3,319
3.828125
4
# Projeto 2 - Prevendo o Retorno Financeiro de Investimentos em Títulos Públicos # Parte 1 - Desenvolvimento do Modelo Usando Framework # Imports import math import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import Lin...
dd8de0fffe620d308352924bf851fa9c6f6ffd7d
SeannLin/search_engine
/index_search.py
2,575
3.765625
4
from collections import defaultdict # https://docs.python.org/2/library/collections.html from words import get_text, words def create_index(files): """ Given a list of fully-qualified filenames, build an index from word to set of document IDs. A document ID is just the index into the files parameter...
48e64691647a17950b2e7f14da3899c16a754d60
Rodrigovf/analise_lexica
/Analisando.py
3,824
3.75
4
class Analise(object): def analisaFrase(self, letra, palavra, letraProx): # rece a paavra formada ate o momento e o caracter #Ler lista de tokens arquivo = open('keywords.txt', 'r') arquivo2 = open('keywords.txt', 'r') '''print("inicio") print(letra) print(...
5ab8c843e2316edfbd99707e80099d2922d192a8
hub2/patchwork
/state.py
1,742
3.65625
4
from map import Map from board import Board import copy class State: def __init__(self, map: Map, p1board: Board, p2board: Board): self.map: Map = map self.current_board = p1board self.p1board = p1board self.p2board = p2board def get_further_player(self): player = self....
40a7ca47ff416c547169ce8f9847af794e03cb5d
loanchip/fast_ner
/fast_ner/utils/entity_handling.py
8,175
4.03125
4
import pandas as pd import pickle from os import walk from . string_handling import string_cleaning def insert_entity(dict_, entity): """Inserts a new entity value into a dictionary. Finds the appropriate dictionary in the nested dictionary structure and inserts the new entity value. Args: ...
8a11fdec858d9cfeec061e75640adc8e6468a6e5
JaD33Z/Encrypted-Personal-Password-Manager-GUI
/main.py
6,482
3.84375
4
from tkinter import * from tkinter import messagebox from random import choice, randint, shuffle import sqlite3 from entry import Login conn = sqlite3.connect('pw.db') c = conn.cursor() # ---------------------------- PASSWORD GENERATOR -------------------------------------------- # # Generate Password button fu...
516e2b93f0a07f1d829d20819aad005f84e8a8b5
LucasLeone/tp1-algoritmos
/estructura_secuencial/es21.py
1,445
3.984375
4
''' Ingresar por teclado los precios correspondientes a cinco artículos y las cantidades vendidas de cada uno de ellos. Calcular e imprimir el importe total de ventas de cada uno y un importe total de lo vendido. ''' precio_art1 = float(input('Cual es el precio del articulo 1? ')) cant_art1 = int(input...
1a0f1fc2a0070c21e7ad2fc1460663cd18522da7
LucasLeone/tp1-algoritmos
/estructuras_selectivas_multiples/esm32.py
920
4
4
''' Se leen el sueldo básico y la categoría de un empleado. Para calcular el sueldo neto se efectúan los siguientes descuentos: Categoría 1: 30% Categoría 2: 25% Categoría 3: 25% Categoría 4: 10% Para otras Categorías no hay descuentos. Imprimir el sueldo neto básico y Cate...
014551641de0edc81ce1fbab56bbc8ba59504850
LucasLeone/tp1-algoritmos
/estructura_secuencial/es12.py
631
4.0625
4
''' Teniendo como dato la hipotenusa y el ángulo que forma ésta con la base de un triángulo rectángulo. calcular e imprimir los datos y ángulos restantes. ''' import math hipotenusa = float(input('El valor de la hipotenusa: ')) angulo = float(input('El valor del angulo: ')) if angulo > 90: print...
7f5449e1b52066532818aa611c59f5fe4aee00ea
LucasLeone/tp1-algoritmos
/estructuras_selectivas_multiples/esm33.py
504
3.765625
4
''' Leer un número comprendido entre uno y siete, ambos inclusive e imprimir el nombre del día de la semana correspondiente. ''' num = int(input('Número entre 1 y 7: ')) if num == 1: print('Es lunes') elif num == 2: print('Es martes') elif num == 3: print('Es miercoles') elif num == 4: pri...
2692e538d72e8ac46ba2d2cb6db4256b2445e7b4
henryHTH/Algo-Challenge
/Largest_prime_factor.py
840
4.28125
4
''' Given a number N, the task is to find the largest prime factor of that number. Input: The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains an integer N. Output: For each test case, in a new line, print the largest prime factor o...
fb88182b582c4e6f07031bb887c71a94ef2b9279
sriarunaravi/sri
/primeintervals.py
311
3.75
4
def isprime(n): if(n>1): for i in range(2,n): if(n%i==0): return False else: return True a,b=map(int,input().split()) c=0 for i in range(a+1,b): if(isprime(i)): if(c!=0): print(" ",end="") print(i,end="") c=c+1
2525ae9181aacfe7f0a5689043f04c25c61a130b
sriarunaravi/sri
/checkinbetween.py
108
3.578125
4
s=int(input())#input a,b=map(int,input().split()) if(s>=a and s<b): print("yes") else: print("no")
2b47041e6797c477343fac96f147057df858fef4
sriarunaravi/sri
/roman.py
140
3.640625
4
roman={"I":1,"V":5,"X":10,"M":1000,"D":500,"L":50,"C":100}#input n = input("") if n in roman:3condition print(roman[n])#print the ouput
ae10b0553328ae98e5f703d37c875fea671abf7a
AK-007/mock-machine-coding-1
/index.py
2,092
3.84375
4
import sys from lib import * from player import Player from board import Board # Initialize the Board and Player objects def init(final_pos, root_pos, players, number_of_players, board_size): board = Board(board_size, 1, final_pos, root_pos, number_of_players, players, []) player_info = {} # Initializing ...
8fe335582eab0cb9b8ca4ccf62193d04744df241
FirzenYogesh/DynamicProgramming
/Python/CuttingRod.py
908
4.15625
4
""" http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/ """ # find the maximum price that can be obtained with the given price set with Space : O(n*x) def cutting_rod(price, n): t = [[0 for i in range(n + 1)] for i in range(n + 1)] for i in range(1, n + 1): for j in range(1, n + 1):...
eb30ff67f5f1ec9aadbf959d030da48723c85044
FirzenYogesh/DynamicProgramming
/Python/LongestCommonSubsequence.py
1,897
4.15625
4
""" http://www.geeksforgeeks.org/longest-common-subsequence/ """ # get the count of longest commom subsequence def get_longest_common_subsequence(a, b): r = len(a) + 1 c = len(b) + 1 # create table to store the longest common sub-sequence value t = [[0 for i in range(c)] for i in range(r)] # trave...
0b5348cb514686eae1e95606a94c64043db7e51b
suhaylx/for-loops
/main.py
535
4.34375
4
for item in {1,2,3,4,6}: for values in {'a', 'b','c'}: print(item, values) user = { 'name' : 'Suhaylx', 'age' : 18, 'can_swim' : False } for dictionary_items in user.values(): print(dictionary_items) for dict_items in user.items(): print(dict_items) for keys, item_s in user.items(): print(keys,item_s) #...
a575629e7d8ff19e6cdf44ae92c0e94a9f9e52cd
Melissendra/ocPurBeurre
/database/substitute.py
1,897
3.625
4
import records db = records.Database() class Substitute: """ Class to get healthier product based on the category of the original product. All products will be with a nutriscore of a or b Attributes: database: link to the database cat_name(str): it's the category b...
c2de97cd5a2c1aea2c0bf373f3140a0b560ae92f
ivyfangqian/python36-learning
/day2/loop5.py
10,451
3.875
4
# 当我们需要重复执行某一代码块的时候,会用到循环操作 # 循环语句包含 while ,for # while 条件表达式: # 条件表达式为真时执行代码 # 例如:输出1-10 i = 0 while i <= 10: print(i) i += 1 # range(start,end,step),step为空默认为1 # 从0到10(不包含10) print(range(10)) # 从1到10(不包含10) print(range(1, 10)) # 从1到10,间隔2(不包含10) print(range(1, 10, 2)) # 举例:求1-10的所有数字的和 num = 0 sum = 0 whi...
11329f53098fe008f6d2571e994d73d5ce90491c
ivyfangqian/python36-learning
/day4/practice.py
5,623
3.828125
4
# 1、编写一组数据,记录组内每个人的语文成绩、数学成绩、英语成绩 # data = { # 'WeiYingLuo': [60, 68, 45], # 'FuCha': [10, 28, 5], # 'FuHeng': [44, 86, 73], # 'XianFei': [99, 95, 95], # 'ErQing': [98, 65, 100], # 'HongZhou': [77, 97, 65] # } # a.找到平均分不足60分的人 # b.找出各科的最高分 # c.算出各科的平均分,再找出各科的学霸 # ...
140d610ffa7212e9c40a6193bc66b93052b422c1
ivyfangqian/python36-learning
/commonly_used_modules/xmldom_demo.py
1,838
3.984375
4
# 文件对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理可扩展置标语言的标准编程接口。 # 一个 DOM 的解析器在解析一个 XML 文档时,一次性读取整个文档,把文档中所有元素保存在内存中的一个树结构里,之后你可以利用DOM 提供的不同的函数来读取或修改文档的内容和结构,也可以把修改过的内容写入xml文件。 # python中用xml.dom.minidom来解析xml文件 from xml.dom.minidom import parse import xml.dom.minidom # 解析xml文件生成Dom树对象 DomTree = parse(r"movies.xml") ...
6c5dcf3f5ad4d00dca274e5fde09e3a378aac73f
ivyfangqian/python36-learning
/day1/input_output1.py
2,218
4.34375
4
# 我们的第一个程序 print('Hello World!') # python2.x默认字符集为ASCII,打印中文需要设置coding为utf-8 # python3.x默认字符集为UTF-8 import sys print(sys.getdefaultencoding()) print('你好!') # 'print 可以同时打印多个字符串,两个字符串之间以逗号隔开 print('小明,', '你好!') # python单行注释为#, # 多行注释也推荐使用# # print 'Hello World!' # print 'Hello World!' # print 'Hello World!' # 多行注释...
86df0cf04d16bf63eb0a6f93d2435dcb83c3fec9
milinddalakoti/Python-Projects
/Password Manager Project/main.py
4,466
3.5
4
from tkinter import * from tkinter import messagebox from password_gen import Passgen import pyperclip import json # import os # vas = os.getcwd() # print(vas) BLUE= "#00A19D" SKIN= "#FFF8E5" DSKIN= "#FFB344" # ---------------------------- SEARCH FOR ENTRY ------------------------------- # def search_entry(): we...
18ec7e6c828008cf950e27c4176833f4ec0648b6
nadvornix/python-fizzle
/fizzle.py
6,418
3.515625
4
#-*- encoding: utf-8 -*- '''TODO: ''' def dl_distance(s1, s2, substitutions=[], symetric=True, returnMatrix=False, printMatrix=False, nonMatchingEnds=False, transposition=True, secondHalfDis...
c857733d40b965837e804c4deb5be5a87bb565c8
LuanPetruitis/minis_programas_python
/calculos_com_números.py
972
3.90625
4
e = 0 n1 = float(input('Digite um numero; ')) n2 = float(input('Digite outro numero; ')) while not e == 6: e = int(input('''Escolha O que deseja fazer; [1] soma [2] multiplicar [3] maior [4] Calcular o fatorial de um número [5] Digitar novos números [6] sair ''')) if e == 1: ...
f2e61a0b1b808817a28743df139cd0695ac0b7c2
LuanPetruitis/minis_programas_python
/cursoemvideo/ex0057.py
215
3.578125
4
s = d = str(input("""Qual é o seu sexo [M] -> Masculino [F] -> Feminino """)) while s not in 'MmFf': s = d = str(input("""Qual é o seu sexo [M] -> Masculino [F] -> Feminino """)) print('FIM')
f6d538970d51a9eb13f8a37dd60cc4fec373c767
LuanPetruitis/minis_programas_python
/cursoemvideo/aula8.py
107
3.6875
4
import math n = float(input('digite um numero real')) print('a parte inteira é {}' .format(math.trunc(n)))
810525d44e8b65487d21feae1cc00c9ec048f84f
LuanPetruitis/minis_programas_python
/cursoemvideo/ex0105.py
738
3.921875
4
def notas(*n, sit=False): """ -> Função para analisar notas e situação dos alunos. :param n: uma ou mais notas dos aulunos (aceita varias) :param sit: valor opicional indicando se deve ou não adcionar a situação :return: dicionário com varias informações sobre a situação da turma """ r = dic...
893f21d2564805533f392a218515ada94ea5b84a
LuanPetruitis/minis_programas_python
/alistamento.py
357
4
4
ano = int(input('Digite o ano que você nasceu: ')) idade = 2021 - ano if idade == 18: print('Esta no ano de você se alistar') elif idade > 18: p = idade - 18 print('Já passou {} dois anos que você tinha que ter se alistado'.format(p)) else: f = 18 - idade print('Não esta no ano de você se alistar ...
2e4c519e43df261f5bee39942f6d8bced9e4353e
LuanPetruitis/minis_programas_python
/cursoemvideo/ex0060.py
110
4.03125
4
n = int(input('Digite um numero inteiro; ')) f = n while not n == 1: f = f * (n - 1) n -= 1 print(f)
5760ed97a6f5e2ef6aec1ccb66f012f52d1f8637
tgogakos/python
/rosalind1.py
882
3.890625
4
#!/usr/bin/python import re ##count characters #print("{} {} {} {}".format(dna.count('A'), dna.count('C'), dna.count('G'), dna.count('T'))) ##T_to_U def main(): dna = raw_input("enter sequence: ") a = t_to_u(dna) b = rev_comp(dna) print b string = 'AAATTGAGAGAGAGAATTGAGAGAGAGAGAGAATT' ...
9104e0223023f42c87d7030eb7443c2c62f3c49e
StalinMazaEpn/Python_Calculos_Exam
/Volumen de las formas de la piscina.py
1,506
3.953125
4
print ("VOLUMEN DE UNA PISCINA") import math def menu_vol(): opcion=0 while (opcion!=4): print ("\n") print("Calcular el volumen de una piscina") print("1.Volumen de forma rectangular") print("2.Volumen de forma eliptica") print("3.volumen de forma cilindrica") p...
a2d206cb1f478d405cb8535c925f4d543ee0f74b
AP-MI-2021/lab-4-AverageLinuxEnjoyer
/are_positives_sorted.py
663
3.9375
4
def are_positives_sorted(lst: list[int]) -> bool: """Verifica daca elementele pozitive ale unei liste sunt in ordine crescatoare Args: lst (list[int]): Lista verificata Returns: bool: True daca elementele sunt in ordine crescatoare, False in caz contrar """ positive_lst = [x for x ...
e575bc14a903d16aaa7555699cf90a7af65ec3b5
dzynin/FlexNeuART
/scripts/data_convert/msmarco/similarity_funcs.py
443
3.703125
4
import re def is_equal(text_str_1, text_str_2): return text_str_1 == text_str_2 def tokenized_equal(text_str_1, text_str_2): """Tokenizes input strings and matches the token sets """ token_list1 = list(map(lambda x: x.lower(), re.sub('[^a-zA-Z0-9 ]', ' ', text_str_1).split())) token_list2 = list(...
35bf351112ee5abeb120a3989d17e70c095ea189
tsunny92/LinuxAcademyScripts
/ex1.py
301
4.21875
4
#!/usr/bin/env python3.6 msg = input("Enter the message to echo : ") count = int(input("Enter the number of times to display message ").strip()) def displaymsg(msg , count): if count > 0: for i in range(count): print(msg) else: print(msg) displaymsg(msg , count)
eacca59369d76776c6b4b0871a9ee091e8d7be03
Prakash594/StudentManagementSystem
/project.py
16,302
3.65625
4
from tkinter import * from tkinter import messagebox from tkinter.ttk import Combobox import sqlite3 as sql con = sql.connect(database="studentdb.sqlite") cursor = con.cursor() try: cursor.execute("create table students(stu_id int,stu_name text, stu_mob text,stu_course text,reg_fee int,bal int)") cursor.execut...
49832f122ea5e009cf3573158b47059bb7a2284b
YanRevuz/gce
/dev/lecCSV2.py
1,511
3.609375
4
#-*- coding: utf-8 -*- import csv """Cette fonction permet d'insérer une virgule a un indice donné""" def insert_comma(string, index): return string[:index] + ',' + string[index:] """Cette fonction permet de traiter les notes d'un élève""" def traitement_eleve(ligne,notes,code_eleve,diplome): nb_elements_tab = l...
3d34ea796269ec52e3fe1bf2070d25dfc7d091ad
aashu-tosh/New
/routine.py
692
3.984375
4
day=int(input("""Select the day: 1. Sunday 2. Monday 3. Tuesday 4. Wednesday 5. Thursday 6. Friday Day : """)) days = ['Invalid','Sunday','Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday'...
35194eee73dcdcd1d21a8a77cac4f3bfe98da1d8
cindyclarestabasrie/Alien-Invasion
/Pythonpygame/game_functions.py
6,729
3.625
4
import sys import pygame from Pythonpygame.Bullet import Bullet from Pythonpygame.Alien import Alien from time import sleep def get_number_aliens_x(settings, alien_width): # Available space for aliens in one row available_space_x = settings.screen_width - 2 * alien_width # Number of aliens able to occupy t...
da643f117987410670878690fdfea9807efca07a
yiorgosk/python
/polynomials.py
1,498
4.34375
4
import numpy.polynomial.polynomial as poly import numpy as np '''The user can enter 2 polynomial functions and perform the basic math praxis of addition, subtraction, multiplication and division. Also the user is able to discover the roots of the two function and perform for instance an addiction praxis with a polynomi...
8a6cb32d0717fb87c59851812f63c0063119dbce
jhuang292/Decision-Tree
/RootNode.py
964
3.984375
4
#RootNode Class used to illustrate the root of decision tree class RootNode(): # Constructor children list with the attributes index and name def __init__(self): self.children = [] # Add children add method def addChild(self, childNode): self.children.append(childNode) ...
1fbe3b0ebb525f925c637d7d36360f24445e374e
oJacker/_python
/numpy_code/03/bittwiddling.py
1,559
3.65625
4
import numpy as np x = np.arange(-9, 9) y = -x ''' (1) 第一个小技巧需要用XOR或者^操作符。 XOR操作符又被称为不等运算符,因此当两个操 作数的符号不一致时, XOR操作的结果为负数。在NumPy中, ^操作符对应于bitwise_xor函数, <操作符对应于less函数。 ''' print ("Sign different?", (x ^ y) < 0) print ("Sign different?", np.less(np.bitwise_xor(x, y), 0)) ''' (2) 在二进制数中, 2的幂数表示为一个1后面跟一串0的形式,例如10、 100、 100...
ee742e94e08e5898e5369699c4d0d64e74556283
oJacker/_python
/numpy_code/04/urn.py
1,474
4.125
4
''' 超几何分布(hypergeometric distribution)是一种离散概率分布,它描述的是一个罐子里有 两种物件,无放回地从中抽取指定数量的物件后,抽出指定种类物件的数量。 NumPy random模 块中的hypergeometric函数可以模拟这种分布 设想有这样一个游戏秀节目,每当参赛者回答对一个问题,他们可以从一个罐子里摸出3个 球并放回。罐子里有一个“倒霉球”,一旦这个球被摸出,参赛者会被扣去6分。而如果他们摸出 的3个球全部来自其余的25个普通球,那么可以得到1分。因此,如果一共有100道问题被正确回 答,得分情况会是怎样的呢?为了解决这个问题,请完成如下步骤 ''' import numpy as np...
e6949996a59828f9017d0f3ee57b00f82782a5cf
oJacker/_python
/numpy_code/03/bmatcreation.py
313
3.90625
4
import numpy as np #(1) 首先,创建一个2×2的单位矩阵: A = np.eye(2) print("A", A) B = 2* A print("B", B) #2) 使用字符串创建复合矩阵,该字符串的格式与mat函数中一致,只是在这里你可以用矩阵变量名代替数字: print("Compound matrix\n", np.bmat("A B; A B"))
d2c999bc28621dbecef9316b12719c3d71280d74
oJacker/_python
/python_03/reverse_by_word.py
587
3.90625
4
# -*- coding: utf-8 -*- def reverse(str_list, start, end): while start < end: str_list[start] , str_list[end] = str_list[end], str_list[start] start += 1 end -= 1 setence = ' Hello, how are you? Fine. ' str_list = list(setence) i = 0 while i < len(str_list): if str_list[i...
53493b0c11b03e70e4eb302ff82504f652d80a3f
oJacker/_python
/FullStack/02/login-to-while.py
577
3.78125
4
#!/usr/bin/env python #-*- coding:utf-8 -*- user = 'ojacker' passwd = '123456' counter = 0 while counter < 3: username = input("Please input Username: ") password = input("Please input Password: ") if username == user and password == passwd : print("Welcome %s login ..." % user) break ...
3503da87ce777c831ce13892c906a2f33d46c862
oJacker/_python
/numpy_code/04/headortail.py
1,359
3.71875
4
''' 随机数在蒙特卡罗方法(Monto Carlo method)、随机积分等很多方面都有应用。真随机数的 产生很困难,因此在实际应用中我们通常使用伪随机数。 设想你来到了一个17世纪的赌场,正在对一个硬币赌博游戏下8份赌注。每一轮抛9枚硬币, 如果少于5枚硬币正面朝上,你将损失8份赌注中的1份;否则,你将赢得1份赌注。我们来模拟 一下赌博的过程,初始资本为1000份赌注。为此,我们需要使用random模块中的binomial 函数。 ''' import numpy as np from matplotlib.pyplot import plot, show # (1) 初始化一个全0的数组来存放剩余资本。以参数10000调用b...
c84df693bdd6ce45210e8b58263027dc59f0c662
TanwirZaki/GITSampleTest
/SampleTest/GITTest.py
394
3.65625
4
import json payload = {"id":1,"firstName":"Vernon","lastName":"Harper","email":"egestas.rhoncus.Proin@massaQuisqueporttitor.org","programme":"Financial Analysis","courses":["Accounting","Statistics"]} # Loads method parse json string and it returns dict object dict_payload = json.loads(json.dumps(payload)) course...
b496fb679a87ad1087198a2a09b5073397ee531e
Seongkyun-Yu/TIL
/algorithm-study/baekjoon/Fibonacci.py
222
4.125
4
wantCount = int(input()) def fibonacci(count, num1, num2): if wantCount == count: return num1 sum = num1 + num2 num1 = num2 num2 = sum return fibonacci(count+1, num1, num2) print(fibonacci(0, 0, 1))
8354760f01716d78034a172e7de84f70772a7f01
Seongkyun-Yu/TIL
/algorithm-study/study/kingsNight.py
555
3.5
4
# 행: 알파벳 # 열: 숫자 # 체스에서 나이트가 움직일 수 있는 개수 구하기 # 나이트 위치 받기 input_data = input() row = int(input_data[1]) column = int(ord(input_data[0])-int(ord('a'))) + 1 # 이동 가능 패턴 steps = [(-2, 1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)] # 움직임 가능한지 체크 result = 0 for step in steps: next_row = row + step[0] ...
9ba2688ebe600fb03d4e31f3c61ccbbfafe396f8
Seongkyun-Yu/TIL
/algorithm-study/programers/level3/network.py
410
3.515625
4
def solution(n, computers): global network global nets network = computers nets = n count = 0 for i in range(n): for j in range(n): if checkLink(i, j): count += 1 return count def checkLink(i, j): if network[i][j] == 0: return False network[i][j] = 0 for k in range(nets): ...
ebdccfed7188f2a4a35a8763dda1296f3e6d9918
Seongkyun-Yu/TIL
/algorithm-study/data-structure/tree2.py
4,504
3.5625
4
import random # 이진탐색트리 삭제 코드 구현 # 이진탐색트리 class Node: def __init__(self, value): self.value = value self.left = None self.right = None class NodeMgmt: def __init__(self, head): self.head = head def insert(self, value): self.current_node = self.head while True: if value < self.cu...
a5259bd497e16b7601029e31077643f8d196be9a
Seongkyun-Yu/TIL
/algorithm-study/data-structure/tree1.py
1,103
4.03125
4
# 이진탐색트리 class Node: def __init__(self, value): self.value = value self.left = None self.right = None class NodeMgmt: def __init__(self, head): self.head = head def insert(self, value): self.current_node = self.head while True: if value < self.current_node.value: if self...
a6387a367478c19490e2e16367799209afb2d771
lucasmsantini/lucasmsantini
/p1_aula5/13.py
170
3.71875
4
sal = int(input('Qual seu salário? ')) aum = sal + (sal * 0.15) aMais = aum - sal print ('Seu salario de {} foi para {}, um aumento de {} Reais'.format(sal, aum, aMais))
562bc2fdb76a1d9d4295a29885e3e852832015a3
lucasmsantini/lucasmsantini
/p1_aula5/87.py
581
3.875
4
matriz = [[0,0,0], [0,0,0], [0,0,0]] #matriz = [[0]*3]*3 spar = mai = scol = 0 for l in range(0,3): for c in range(0,3): matriz[l][c] = int(input(f'Digite o valor para [{l} e {c}]')) print('!!!'*20) print(matriz) print('!!!'*20) for l in range(0,3): for c in range(0,3): print (f'[{matriz [l][c]...
03db4d621614f6e93926562d3cd06f953c2d2a87
lucasmsantini/lucasmsantini
/p1_aula5/54.py
370
3.78125
4
from datetime import date tmaior = 0 tmenor = 0 atual = date.today().year for c in range(1,8): ano = int(input('Digite o ano de nascimento da pessoa {}: '.format(c))) idade = atual - ano if idade >= 18: tmaior += 1 else: tmenor += 1 print('Total de pessoas maiores: {}'.format(tmaior)) pr...
a14f06c86a4f4401b915a440acef6fcb66ae6c8b
lucasmsantini/lucasmsantini
/p1_aula5/101.py
344
3.765625
4
def voto(ano): from datetime import date atual = date.today().year idade = atual - ano if idade > 65: return f'Voto opcional com {idade}' elif idade < 65 > 18: return f'Voto Obrigatório com {idade}' else: return 'Voto opcional' nasc = int(input('Digite ano de nascimento:...
7c332313e2c9726051f1c2ceebea75931003da08
lucasmsantini/lucasmsantini
/p1_aula5/Exercicios/ex011.py
190
3.78125
4
valor = float(input('Qual o valor do produto?: ')) desc = valor - (valor * 0.05) print('O produto com valor R$ {:.2f}, agora sairá com 5% de desconto, R$ {:.2f} reais'.format(valor, desc))
61498c8ca54731670ea375f86c33d69831f1ed3b
lucasmsantini/lucasmsantini
/p1_aula5/77.py
298
3.765625
4
palavras = ('aprender', 'linguagem', 'pythom', 'pycharm', 'nddigital', 'star wars', 'computador', 'teclado', 'mouse') for p in palavras: print(f'\nNa palavra {p.upper()} temos: ', end='') for letra in p: if letra.lower() in 'aeiou': print(letra, end='')
8d607f91f279c4e6ca13cd7c29079157058a4f88
lucasmsantini/lucasmsantini
/p1_aula5/tuplas.py
1,646
3.9375
4
lanche = 'Hamburguer', 'pizza', 'pudim', 'suco', 'batata' lanche = 'Hamburguer', 'pizza', 'pudim', 'suco', 'batata' print(lanche) # ('Hamburguer', 'pizza', 'pudim') print(lanche[1]) # pizza print(lanche[0]) # hamburguer print(lanche[2:]) # ('pudim', 'suco', 'batata') print(lanche[1:3]) # ('pizza', 'pudim') print(l...
1729687822b920ff4d1f88f842e4fae9ab4714af
lucasmsantini/lucasmsantini
/p1_aula5/16.py
100
4.09375
4
numero = float(input('Digite um numero: ')) print('numero inteiro: {}' .format(numero, int(numero)))
0a51d42a52539a033efb66485df04128d20cf674
lucasmsantini/lucasmsantini
/p1_aula5/Exercicios/ex038.py
267
4.0625
4
a = int(input('Digite um número: ')) b = int(input('Digite outro: ')) if a > b: print('O número {} é maior que o {}'.format(a,b)) elif a == b: print('Os números {} e {} são iguais'.format(a,b)) else: print('O número {} é maior que {}'.format(b,a))
5ce946ff90ab6651a16cc0bc3dbbf33731ef7189
lucasmsantini/lucasmsantini
/p1_aula5/teste/Traversy Media.py
220
3.765625
4
x = 10 y = 50 if x > y: print(f'{x} é maior que {y}') elif x == y: print(f'São iguais, {x} e {y}') else: print(f'{y} é maior que {x}') numbers = [1,3,4,5,6] if x not in numbers: print(x in numbers)
34fb4b7d14064d94b197a39b6d7d2fc84130184f
lucasmsantini/lucasmsantini
/p1_aula5/114.py
263
3.5
4
import urllib.request try: site = 'https://www.allyourmusic.com' response = urllib.request.urlopen("http://pudim.com.br") except urllib.error.URLError: # ou só o except print("site inexistente") else: print("site ok!!") print(site.title())
f82c2ebd248d692c6ee88ddd3299056cb3773ddf
lucasmsantini/lucasmsantini
/p1_aula5/pessoas_teste.py
866
3.625
4
pessoas_teste = [['pedro', 25], ['maria', 18], ['joão', 30], ['moisés', 20], ['catarina', 23]] print(pessoas_teste, end=' '), print(pessoas_teste[0], end=' '), print(pessoas_teste[0][1], end=' '), print(pessoas_teste[1][1]) print('##' * 20) for unidade in pessoas_teste: print(f'{unidade[0]} tem {unidade[1]} anos d...
6931e0a9f874648a74198d0c65064f7d3165d63e
lucasmsantini/lucasmsantini
/p1_aula5/31.py
306
3.859375
4
distancia = float(input('Qual a distancia percorrida? ')) if distancia > 200: valor = (distancia * 0.45) print('O Valor para {} km é de R$ {:.2f} reais'. format(distancia, valor)) else: valor = (distancia * 0.50) print ('O valor para {} km é de R$ {:.2f} reais'.format(distancia, valor))
13df34fd29ba72cb0d310aaa891d3f1b56ade141
Wildcard357/OOP-II
/variales.py
382
3.953125
4
#python variables #let's start with int #int a=3 #a at this point is an intager #float a=2.3 #a at this point is a float because of the decimal point #complex a=2k3 #a at this point is a complex because of the combination of numbers and letters #strig a="John" #a at this point is string meaning its a word #boolean...
4d06f1d87056b50e3bff2077fc558b6f7ffe1269
kanido386/rush-hour-puzzle-solver
/model/board.py
596
3.84375
4
class Board(object): def __init__(self): self.height = 6 self.width = 6 self.grid = [] self.init_grid() def init_grid(self): ''' Initialize the board grid (-1 means nothing on the grid) ''' for y in range(self.height): self.grid.append([]) for x in range(self.width): se...
e03cb37c0ead32c1771c04272008a7e40f297399
tongsq/mytest
/python/test/queue.py
473
3.84375
4
from collections import deque queue = deque(['aa','bb','cc']) queue.append('dd') print(queue.popleft()) print(queue) vec = [2,4,6] vec3 = [[x,x*3] for x in vec if x>2] print(vec3) question = ['aa?','bb?'] answer = ['a', 'b'] for que,ans in zip(question, answer): print('question:{0} answer:{1}'.format(que,ans)) knigh...
a438a27aff5bc9e12f7133db8ac8d891cfad81e5
devathecoder/AutomatedLoginSystem
/Generate_password.py
876
4.0625
4
def generatepass(): import string import random print(''' I am your password generator ''') NameOFUser = input("Enter your name : ") s1 = string.ascii_lowercase s2 = string.ascii_uppercase s3 = string.digits plen = ...
8f7e3917a52810960ecf45544654226ab5111552
chanchs/euler
/problems/problem-12.py
1,744
3.53125
4
import lib.utilities as ut import time import math def number_of_divs(n, p): d = 0 i = 0 div = False if n in p: return 2 while p[i] <= n: if n % p[i] == 0: d += 1 n = int(n / p[i]) div = True else: i += 1 if div: ...
85174966cd2b3b7fae26954c85ed37b799d54361
chanchs/euler
/problems/problem-90.py
534
3.703125
4
# ? import lib.utilities as ut from itertools import combinations import time def valid(c1, c2): squares = [(0, 1), (0, 4), (0, 6), (1, 6), (2, 5), (3, 6), (4, 6), (8, 1)] return all(x in c1 and y in c2 or x in c2 and y in c1 for x, y in squares) if __name__ == "__main__": start = time.time() cube =...
2a74c686c0556ab94347eb715d49959a0a4e1012
chanchs/euler
/problems/problem-42.py
1,379
3.609375
4
import math import time import lib.utilities as ut def generate_triangle_numbers(n): tn = [0] * (n + 1) for i in range(n + 1): tn[i] = int(0.5 * i * (i + 1)) return tn def calculate_weight(word): alphabet = {'A': 1, 'B': 2, 'C': 3, 'D': 4, ...
1151d8c852fec081d502aac7273c808375e86b5a
chanchs/euler
/problems/problem-64.py
961
3.65625
4
import time import math if __name__ == "__main__": print("Starting....") start = time.time() odd_period_count = 0 for s in range(10001): m = 0 d = 1 print("s = {} : ".format(s), end=" ") a0 = a = math.floor(math.sqrt(s)) key = False print("a0 = {} : ".fo...
28a187eab6d954ca8e354297ac8a8bc438e4edad
chanchs/euler
/problems/problem-51.py
1,539
3.609375
4
import math import time from collections import Counter import lib.utilities as ut checked = [] primes = [] def replace_repeated_digits(n): numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] str_n = str(n) repeat = Counter(str_n) set_n = Counter(set(str_n)) sol = [] #print(repeat - ...
fce9898efd987ac04deadbaecda088f55a0cf8dd
chanchs/euler
/problems/problem-28.py
1,863
3.953125
4
import time class direction(): RIGHT = [0, 1] LEFT = [0, -1] DOWN = [1, 0] UP = [-1, 0] def turn_right(d): if d == direction.RIGHT: return direction.DOWN elif d == direction.DOWN: return direction.LEFT elif d == direction.LEFT: return direction.UP elif d == d...
dbea02f4f48303118abe9a8c83d3da8fe83a5847
chanchs/euler
/problems/problem-73.py
499
3.515625
4
from lib.utilities import gcd import time if __name__ == "__main__": print("Starting....") start = time.time() N = 12000 count = 0 for d in range(1, N + 1): for n in range(1, d): if 3 * n > d > 2 * n: if gcd(n, d) == 1: print("{} / {}".forma...
fbea4f6a060ba8b512fc28e1110cc117265bb541
djmnano/Stepik-Bioinformatics
/1.8-step4.py
640
3.546875
4
#1.8 Code Challenge: Solve the Approximate Pattern Matching Problem. #Made by Dennis Kenbeek (4686357) def HammingDistance(seq1, seq2): d = 0 for i in range(0,len(seq1)): if seq1[i] != seq2[i]: d += 1 return d def FindPatterns(seq, pattern, d): pos = [] for i in range(0,len(se...
bd002d33930db5289e34aee368bfa05a59023d05
jaggukaka/grokdeeplearning
/nlpRelatedSent.py
6,777
4.09375
4
import numpy as np import random def softmax(x): x = np.atleast_2d(x) temp = np.exp(x) return temp/np.sum(temp, axis=1, keepdims=True) wordembed = {} wordlist = ['yankees', 'bears', 'braves', 'red', 'socks', 'lose', 'defeat', 'beat', 'tie'] for word in wordlist: wordembed[word] = np.array([[0., 0., 0....
ad364c5ef418438c33677ad44d1ec5e3ed05c093
mbeissinger/image-wrangler
/wrangler/download_from_file.py
5,965
3.515625
4
""" Given a csv or txt file, download the image urls to form the dataset. """ import argparse import os from csv import writer as csv_writer from multiprocessing import Process, Queue import requests import pandas as pd import numpy as np from tqdm import tqdm from pathlib import Path def create_dataset(filepath, url...
731a544a4353cf934188d8e0ee21aca7b0e8e577
BhaswatiGope/Web_Development
/Predicted_Model/model.py
853
3.578125
4
# Simple Linear Regression model using sample data to run through the prediction model on API using Python Flask import numpy as np import matplotlib.pyplot as plt import pandas as pd import pickle sample_dataset = pd.DataFrame({"Experience":[9,6,5,2,7,3,10,11], "Score":[8,8,6,10,9,6,7,8], "Annual_Income":[50000, 4...
fbd94720a3026d169283ce15aec1496424da53e4
wenyaowu/leetcode
/algorithm/lengthOfLastWord/lengthOfLastWord.py
636
4.03125
4
# Length of last word """ Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. For example, Given s = "He...
04b818d3a8e91e3ec412d008dd23bae7ddafdedb
wenyaowu/leetcode
/algorithm/wildcardMatching/wildcardMatching.py
1,190
4.1875
4
# Wildcard Matching """ '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMat...
f8774f9112bc56c320dc081cddcb3bf5705c1006
wenyaowu/leetcode
/algorithm/minimumPathSum/minimumPathSum.py
782
3.796875
4
# Minimum Path Sum """ Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ class Solution: # @param {integer[][]} grid # @return {integer} ...
bf3194d31daa0fde740f70f19ef4b502c1d82708
wenyaowu/leetcode
/algorithm/spiralMatrix/spiralMatrix.py
948
4.1875
4
# Spiral Matrix """ Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] You should return [1,2,3,6,9,8,7,4,5]. """ class Solution: # @param {integer[][]} matrix # @return ...