blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d350d933d0815d1e1a0a6f3d579ab15634ef65f1
heyfavour/code_sniippet
/singleton.py
955
3.671875
4
#不推荐会重复执行init 会重新加载一次init的数据 import threading class Singleton: _instance_lock = threading.Lock() def __new__(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): with Singleton._instance_lock: if not hasattr(Singleton, "_instance"): Singleton._instance = super()....
27a47571f0d477f1e59ce12ae096f8f027f5432c
lizenghui1121/DS_algorithms
/数据结构/二分查找二分搜索/03.区间查找.py
1,267
4.03125
4
""" 给定排序数组nums, 如果target在数组中出现, 则返回区间左右端点[i, j], 否则返回[-1, -1] @Author: Li Zenghui @Date: 2020-03-29 14:08 """ def search_range(nums, target): left = left_bound(nums, target) right = right_bound(nums, target) return [left, right] def left_bound(nums, target): begin = 0 end = len(nums) - 1 whi...
bdba09e055ca846451805545858a64ed44ed2cb3
nikosias/python-example
/matrix.py
1,216
3.578125
4
import random def vectorMatrixMultiplication(vector, matrix): return [sum([vector[x]*matrix[n][x] for x in range(len(vector))]) for n in range(len(matrix))] def matrix_multiplication(matrix1,matrix2): if len(matrix1[0]) != len(matrix2): print( "ERROR! Matrix1 column not equal to Matrix2 row! :D !!" )...
663630ba629873b2f3ef40f7de4e66f87168b087
esz22/python-training
/seccion 08/persona.py
434
3.84375
4
class Persona: def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad Persona.nombre="juan" Persona.edad=28 print(Persona.nombre) print(Persona.edad) # creacion de un objeto persona1=Persona("enrique",22) print(persona1.nombre) print(persona1.edad) print(id(persona1)) #cre...
794b195fb99fcf44adfabad1a2d6def0a53ea7c1
PriyankaBuchkul/PythonPractice
/regular Expression/regularexp/regex_ex8.py
378
4.03125
4
##import re ##regex = r"([a-zA-Z]+) (\d+)" ##print(re.sub(regex, r"\2 of \1", "June 24, August 9, Dec 12")) import re regex = re.compile(r"(\w+) World") result = regex.search("Hello World is the easiest") if result: print(result.start(), result.end()) for result in regex.findall("Hello World, Python World"): pr...
3410c7620f731547b3ed684b4a2f5de3fe01d16c
chrisxue815/leetcode_python
/problems/test_0830.py
787
3.59375
4
import unittest from typing import List import utils # O(n) time. O(1) space. Array, iteration. class Solution: def largeGroupPositions(self, s: str) -> List[List[int]]: result = [] lo = 0 for hi in range(len(s)): if hi == len(s) - 1 or s[hi] != s[hi + 1]: if ...
0cd652711928c77176aecbed23e90777f76111b4
SimonFans/LeetCode
/Onsite_Interview_Questions/Generate_Subset.py
1,095
4.03125
4
Given [1,2,3] Result: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]] class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: ''' Backtracking is an algorithm for finding all solutions by exploring all potential candidates. If the solution candidate turns to be not a solution...
72bee5acbe5c5df9ce4a888c798143f279616141
suraj-deshmukh/myCodes
/crout.py
1,270
3.546875
4
#!/usr/bin/python2.7 import numpy as num import sys import csv def crout(A): n = A.shape if(n[0]!=n[1]): print("Give matrix is not square matrix. Code Terminated") sys.exit() n=n[0] A = num.mat(A,dtype=float) U = num.matrix(A*0) L = num.matrix(U) for i in range(0,n): L[i,0] = A[i,0] U[i,i] = 1 ...
03f103425fa81fa4c53653fbe569fc0d122629b7
wtracyliu/exercism
/python/word-count/word_count.py
670
3.875
4
def word_count(phrase): char_list = list(phrase) for i in range(len(phrase)): c = char_list[i] if c.isalpha() or c.isdigit(): continue if c != "'": char_list[i] = " " elif (i < (len(phrase) - 1) and char_list[i+1].isalpha()) and (i >1 and char_list[i-1].is...
30ef54c0228387a6d6c654768fc928c996ebaa82
mgorgei/codeeval
/Medium/c66 Pascal's Triangle.py
1,310
4.25
4
'''PASCALS TRIANGLE A Pascals triangle row is constructed by looking at the previous row and adding the numbers to its left and right to arrive at the new value. If either the number to its left/right is not present, substitute a zero in it's place. More details can be found here: Pascal's triangle. E.g. a Pascal's tr...
0ba5835bacf72f19eb87fdfc87d8bf9d16215b8d
6desislava6/Hack-Bulgaria
/Hack-first-week/Monday/to_number.py
212
3.84375
4
def to_number(digits): number = 0 counter = len(digits) - 1 for digit in digits: number += digit*(10**counter) counter -= 1 return number print (to_number([1,2,3,0,2,3])) print (to_number([9,9,9,9,9]))
72d4c2a6ad96cbd23ee747d4b49da74c090c51ec
aaronwlma/PythonSpecialization
/Course03_PythonWebData/assignment13.py
1,888
4.125
4
# Assignment 13 # For University of Michigan's Coursera Specialization "Python for Everybody" # Course 3 - Using Python to Access Web Data # Problem: # Exploring the HyperText Transport Protocol # You are to retrieve the following document using the HTTP protocol in a way # that you can examine the HTTP Res...
4e4990a5a88905656794a533cece0c55b996ed5e
asilverhawk/asilverhawk-todo-app
/todo.py
2,623
4.03125
4
#!/usr/bin/env python3 import sys from methods import list_tasks, add_task, remove_task, complete_task # Count the arguments command = sys.argv disc_msg = """ To run todo application please enter todo with an argument Command Line Todo application ============================= Command line arguments: -l Lists al...
777d50379625b524d9844f70eb435b84f4db35d5
danielptm/practice
/python/src/test/PalindromeNumberTest.py
547
3.9375
4
import unittest from src.problems.PalindromeNumber import PalinedromeNumber class PalindromeNumberTest(unittest.TestCase): def test_is_palindrome(self): pr = PalinedromeNumber() x = 121 expected = True result = pr.isPalindrome(x) self.assertEqual(expected, result) def...
78c6dc3ecddbadc7866ee12f7dfab76c0c4dc0f2
Gttz/Python-03-Curso-em-Video
/Curso de Python 3 - Guanabara/Mundo 02 - Estruturas de Controle/Aula 13 - Estrutura de repetição for/054 - Grupo_da_maioridade.py
606
4.03125
4
# Exercício Python 054: Crie um programa que leia o ano de nascimento de sete pessoas. # No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores. from datetime import date totmaior = 0 totmenor = 0 for i in range(1, 8): ano = int(input("Digite o ano de nascimento da {}ª pess...
653699d709402d441300a4efe15b8e88ef77e7f7
weaver/exercises
/think-bayes/cookies-without-replacement.py
2,958
3.796875
4
"""# 2.8 Exercises # http://www.greenteapress.com/thinkbayes/html/thinkbayes003.html#sec25 ## Exercise 1 ## In Section 2.3 I said that the solution to the cookie problem generalizes to the case where we draw multiple cookies with replacement. But in the more likely scenario where we eat the cookies we draw, the lik...
8782e153b4d4e79823d58869b32b88187750c7fe
SpeechieX/algorithms-and-data-structures
/algorithmic-toolbox/week4_divide_and_conquer/1_binary_search/binary_search.py
654
3.953125
4
# Uses python3 import sys def binary_search(list, left, right, target): midpoint = left + (right-left)//2 if (left+1 == right and list[midpoint] != target): return -1 elif (list[midpoint] == target): return midpoint elif (list[midpoint] < target): return binary_search(...
12911df610c449a02f52622633078e729afc8313
ashwani8958/Python
/Image Processing/Computer_Vision_A_Z/Face Recognition/3_FaceRecognitionInImages.py
1,317
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 24 15:14:22 2020 @author: ashwani """ # https://realpython.com/face-recognition-with-python/ import cv2 # Loading the cascades face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarca...
f395cdffcff7ca8290437e623b9979700a901d63
JoyLeeA/CodeUp
/32.py
72
3.515625
4
N = '0o' + input() print(int(N,8)) # a=input() # n=int(a, 8) # print(n)
ab74e09914845259d9e58f3afeff0e85997e1457
mt589/randomcode
/list.py
156
3.796875
4
numbers = [538,36,81,6,70,4,2,10,14,32] person = int(input("Pick a number")) for counter in numbers: if counter < person : print (counter)
1b4e886c969c633d538ac50c6b35871ba325e3f8
hvaandres/Learning-Python
/Python/Swap_Values.py
112
3.703125
4
#Swap Values first = 'Oliver' second = 'Andres' third = 'Adrian' print (first) second = third print(second)
19fcf106a16b157200bc64028c242c3aed5f794b
Ashwinbicholiya/Python
/Python/3(2Darray)/3darray.py
295
4.625
5
#create 3d array from 2d array #function use reshape() from numpy import * arr1=array([ [1,2,3,4,5,6], [5,6,7,8,9,1] ]) arr2=arr1.flatten() arr3=arr2.reshape(2,2,3) print(arr3) #we got 1 big 3d array which has 2 2d array and which has 2 single array #and then which has 3 values
a3a98455d2bbf2851ba2397038b0e0a04a454556
Pabitha-1/python
/pro2.py
150
3.53125
4
a=int(input()) b=int(input("value")) c=str(a) d=[] for i in range(len(c)): d.append(c[i]) for i in range(b,len(c)): print(int(d[i]),end=' ')
a3e5a4337e9adfbf1a95137d25b0d2439bb782f8
mindovermiles262/codecademy-python
/07 Battleship/04_check_it_twice.py
271
4.1875
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 6 10:03:12 2017 @author: mindovermiles262 Codecademy Python Use the print command to display the contents of the board list. """ board = [] #initalize board for i in range(0,5): board.append(["O"] * 5) print(board)
fdd194b344019a20a213fa54b9eaac3ab5cf02df
AnPoryadina/lab5
/ex2.2.py
96
3.59375
4
__author__ = 'student' a=['1', '2', '3', '4', '5'] a.insert(0, a[len(a)-1]) print(a[0:len(a)-1])
8d9179583231bd848c8ae8e0a23afa3c22044e5f
ejdeposit/nb_capstone
/deposit/src/driver.py
3,624
3.9375
4
#Evan DePosit #New Beginnings #capstone #this file contains main program for the reading group scheduler # --------------------------------------------------------------------------------------------------------------------------- # $main # -----------...
4d979ab91ff9068d24bf4808eae1fa593dc2a6a6
renjieliu/leetcode
/0001_0599/37.py
2,728
3.578125
4
class Solution: def solveSudoku(self, board: 'List[List[str]]') -> None: """ Do not return anything, modify board in-place instead. """ def isGoodRow(arr, r, c): # return if current row is good with current number cnt = 0 for x in arr[r]: if ...
48903ae6bf5366ff4ab5b85dee23bfbe96c77ab6
ExperienceNotes/Python_Practice
/First_Test/arrangement.py
146
3.5
4
for i in range(5): for j in range(5): for k in range(5): if (i!=j) and (i!=k) and (j!=k): print(i,j,k)
0bd22dfad86cd397f0ae51cf4c367c48608d177e
coach-wang/workwork
/阿里01_小猪母猪.py
1,595
3.875
4
''' 小明是一个数学家,他喜欢用数字给事物命名编号,他给自己编号为1,同时在2019年小明开办了一个农场,准备开始养母猪, 他专门给农场的母猪用以下数列2,3,4,5,7,9,12,16,21,28,37,49,65,86,114,151...进行命名。 假设农场的母猪永远不会死,小母猪出生后3年后成熟,成熟后从第三年开始每年只会生一只小母猪。 第一年农场,有一只刚刚出生的小母猪和一只成熟的母猪(本年不再生小猪,下一年开始生小猪),并给他们编号为2和3。 请问,第m只母猪编号为多少?其是哪一年出生的?小明还准备了1份礼物,专门颁给农场第1到m只的母猪颁奖, 颁奖规则如下:选出第1到m只的母猪翻转编号(114编号翻转为411)为第k...
65021c8819d8b2892c95088c0fccf52fcd1629d4
CodingDojoDallas/python_oct_2017
/Aadil_Moosa/Bike.py
665
4.0625
4
class Bike(object): def __init__ (self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print "Bike {}$ {}mph {}miles".format(self.price, self.max_speed, self.miles) def ride(self): print "Riding: {}".format...
f4985511c9b3b79afd9acded0d2b7fbce3fd8892
rodrigosilvanew/pythonexercicios-guanabara
/ex065_WHILE_maior&menor&media.py
1,159
4.03125
4
resposta = 'SIM' negativo = 'NÃONAO' cont = 0 soma = 0 maior = 0 menor = 0 while resposta not in negativo: num = int(input('Digite um número inteiro: ')) cont += 1 soma += num if cont == 1: maior = num menor = num if cont > 1: if num > maior: maior = num i...
e90ac3db8054a2879bd0617af55cbde4fadaa5ab
MarioViamonte/Curso_Python
/aula21/aula21.py
482
4.1875
4
''' for in em python interando strings com for função range(start=0, stop, step=1) laço for: utilizado para coisas finitas ''' texto = 'python' c = 0 # iteração com laço while infinito while c < len(texto): print(texto[c]) c += 1 # iteração com laço for finito for letra in texto: # para 'letra' em 'texto' ...
c290fcf4005f44ad2cad82c9c7b0629b49751360
dustinpfister/examples-python
/for-post/python-standard-library-inspect/s1-is-what/isclass.py
293
3.59375
4
import inspect class P(object): """Definition for P class.""" def __init__(self, b, e): self.b = b self.e = e def get_p(self): return pow(self.b, self.e) a=P(2, 4) print(a.get_p()) # 16 print(inspect.isclass(P)) # True print(inspect.isclass(a)) # False
8d3c7d944f1573e5554149bac85692cbb10f5b89
prashant97sikarwar/leetcode
/Bit manipulation/number_of_1_bits.py
313
3.734375
4
"""Write a function that takes an unsigned integer and return the number of '1' bits it has""" class Solution(object): def hammingWeight(self, n): n = bin(n)[2:] res = 0 for i in range(len(n)): if n[i] == '1': res += 1 return res
3a81ad357e073ac4118b1e0d3ea6e367d8991342
rishabhchoudhary2496/python_practice_files
/other types/named_tuples.py
230
3.625
4
from collections import namedtuple Colors = namedtuple('Colors',['red','blue','green']) colors = Colors(10,20,30) print(colors.red) print(colors.blue) print(colors.green) #printing using key print(colors[2]) #printing using index
048b4aadc4729cf9219f8d59e264c784c268b4b7
Netfreak21/HousePricePredictions
/feature_extraction.py
7,665
3.515625
4
#making list of all important features which can help us extracting features from strings keywords=["Built","Priced","garden","Dock","Capital","Royal","Guarding","River","dining","bedrooms","bathrooms","pay","Sorcerer","blessings","farm","Location","Holy","Knight's","ID","renovation","sorcerer","Visited"] #list of all ...
f0e0c6c30dff80035be6d9b009c4ecb7e587a62e
stephenh369/python_course
/day_1/beatles.py
835
3.640625
4
beatles = [ {"name": "John Lennon", "birth_year": 1940, "death_year": 1980, "instrument": "piano"}, {"name": "Paul McCartney", "birth_year": 1942, "death_year": None, "instrument": "bass"}, {"name": "George Harrison", "birth_year": 1943, "death_year": 2001, "instrument": "guitar"}, {"name": "Ringo Starr...
51be7d4c6fa367b1d7157a6f2b75774a12b7bf7d
RithickDharmaRaj-darkCoder/Linked_List
/singlyLL.py
4,090
4.21875
4
# Data Structure ... # User-Defined ... # Linked List ... # Singly Linked List (Adding data @ Ending) ... class creatingnode(): def __init__(self,data): self.data = data self.linkto = None class S_linkedlist(): def __init__(self,object_name): self.name = object_name self.head =...
d09bb3ab9831a60344e749753ba6b0b5d66e11ec
sodri126/hackerrank
/print_bilangan_triangle.py
273
3.6875
4
import sys if __name__ == "__main__": n = int(input()) + 1 for i in range(0, n): cal = n - i for j in range(0, cal): print(end=' ') for k in range(0, i): print(k+1, end=' ') print() # create triangle numer
57f655da39ad227a7ad05da211b35669d91c7733
karoitay/projecteuler
/python/077_prime_summations.py
769
3.53125
4
#!/usr/bin/python from utils.primes import get_primes MAX = 100 primes_dict = get_primes(MAX) primes = [i for i in xrange(2, MAX) if primes_dict[i]] cache = {} def update_answer(n, max_element=None): assert n >= 0, "n must be non-negative %d" % n if n == 0: return 1 if n == 1: return 0 max_element = m...
735c5db7fefe9da6b5d7c408d20b4b66820ce493
hwangstar156/Python-Algorithm-dp
/시각.py
322
3.625
4
n = int(input()) result = 0 def check(num): while num > 0: if(num % 10 == 3): return True num = num//10 return False for i in range(n+1): for j in range(60): for k in range(60): if check(k) or check(j) or check(i): result += 1 print(result...
6a8bf067769143e189db161a94a91149c61633e8
smsxgz/euler_project
/problems/problems@1~100/problem_5/Smallest_multiple.py
511
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 15 18:29:07 2017 @author: smsxgz """ import math p_list = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] def Smallest_multiple(n, p_list): limit = math.sqrt(n) ln = math.log(n) a = [1] * len(p_list) N = 1 for i, p in enumerate(p...
1d50d39bbc80ab3ddf526a096937dcccc3564447
ishantk/ENC2020PYAI1
/Session34.py
1,377
3.609375
4
""" SeaBorn -> Data Visualization majorly for statistical graphics -> seaborn is preferred its built on top of matplotlib seaborn is integrated closely to pandas[data analysis library] seaborn provides data set oriented APIs pip install seaborn For Referen...
9de260e639ff5af2357f54163125d430e4054157
connvoi/leetcode
/linkdlist/hascycle.py
2,940
3.859375
4
#get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1. #addAtHead(val) : Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. #addAtTail(val) : Append a node of value val to th...
6ea4075e844e56d56de924f6825eb934fe23ed7a
TimMKChang/AlgorithmSampleCode
/PriorityQueue/KthLargestElementInAStream.py
525
3.625
4
from typing import List import heapq class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k self.pq = sorted(nums, reverse = True)[:k] heapq.heapify(self.pq) print(self.pq) def add(self, val: int) -> int: heapq.heappush(self.pq, val) if len(se...
5d759d12829abff65c0cbfeaa1ed59c7d8d39315
alexforcode/py_arcadegames_craven
/ch7/lab.py
1,213
3.703125
4
# I '''num = 9 for i in range(9): for j in range(i+1): num += 1 print(num, end=" ") print()''' # II '''rows = int(input('Введите количество строк: ')) print() for i in range(rows*2): print('o', end='') print() for i in range(rows-2): print('o', end='') for j in range(rows*2-2): ...
e7b13865466f629e6611cce836a7c059a967d044
vvarodi/DataStructures_and_Algorithms
/Code/OrderedList.py
1,991
3.828125
4
class Node: def __init__(self, data): self.data = data self.next = None class OrderedList: def __init__(self): self.head = None self.size = 0 def isEmpty(self): return self.head is None def len(self): # size count = 0 current =...
9a3e5657607c286ab119cc0b3dce7142a262e56d
Pasenger/tensorflow-tutorials
/basic_text_classification.py
6,011
3.546875
4
# -*-conding:utf-8 -*- # ======================================================================= # 影评文本分类 # https://tensorflow.google.cn/tutorials/keras/basic_text_classification # ======================================================================= import tensorflow as tf from tensorflow import keras # import nu...
e2e51e22e2cf40b15943ecd23e39054791da8721
Fabrizio-Yucra/introprogramacion
/variables/ejercicio 8.py
320
3.953125
4
v1 = float(input("ingrese la capital inicial: ")) v2 = float(input("ingrese el interes anual: ")) v3 = float(input("ingrese el numero de años a invertir: ")) operacion_1 = v2 + int(1) operacion_2 = float(operacion_1) ** v3 operacion_3 = float(operacion_2) * v1 print(f"El interés compuesto es {round(operacion_3, 2)}")
bb7476d9920873eb5476a601a51c6fcbf114d11f
SilkyAnt/rupeng_python
/python_workspaces/Seq_01_PythonBasicSkills/S07_MySqlOperation/02_select.py
313
3.765625
4
# 遍历某个表的所有数据 import pymysql conn = pymysql.connect(host="172.3.8.90", port=3306, user="root", passwd="您的数据库密码", db="students", charset="utf8") cursor = conn.cursor() cursor.execute("select * from student") rows = cursor.fetchall() for r in rows: print(r) cursor.close() conn.close()
dc7322adea05bd5d480cf00840588b7889e6f407
mrbenzedrine/pokemon-battle-simulator
/party.py
1,813
3.578125
4
def switch_out_pokemon(party, player): choice_function = { 'user': user_choose_pokemon_to_switch_to, 'enemy': get_first_available_pokemon }.get(player, None) chosen_pokemon_party_index = choice_function(party) party[0].reset_stat_offsets() switch_pokemon(party, 0, chosen_pokemon_pa...
ce627bcfa4b4075a1d9414c001e01fd3f5273e89
salman6100/python
/mountain.py
530
4.1875
4
iceskating = {} skating_active = True while skating_active: # Asker user their name name = input(" What is your name :") iceskatings = input ( " where would you like to iceskate : ") iceskating[name] = iceskatings repeat = input(" would like to go swimming instead ? ( yes /no )") if repeat == 'no' :...
2b06e7b3e5017a1b1113ea8f79641c7acb68f6c5
Nateliason/Karan-Project-Solutions
/eratosthenes.py
866
4.28125
4
#there's something wrong with this causing it to take way too long to solve the problem... not sure what's happening primes = [] others = [] def era(p,n,primes,others): if p >= n: return primes #so it stops counting when p hits the ceiling n else: for i in range(2,n): if p not in others and p not in primes: ...
995c664d80321791afce153a43cf29336ca4d229
dnieafeeq/mysejahtera_clone
/Day1/chapter15.py
298
3.8125
4
from sys import argv # my file is test.txt script, filename = argv txt = open(filename) print(f"Here's your file {filename}:") print(txt.read()) print("Type the filename again pleaseeee:") your_file_again = input("> ") display_txt_again = open(your_file_again) print(display_txt_again.read())
963046ae6dcb4dfde21ec4ce34b2c2cda8114ea0
Unathimtwa/Pre-bootcamp-challenge
/task 8.py
172
3.78125
4
def time(number): hour = number// 60 minute = number % 60 result = (str(hour) + " hours, " + str(minute) + " minutes") return result print(time(40))
c0e3e55c40be7c28db5094beef44df1dd3ba5305
ThallesTorres/Curso_Em_Video_Python
/Curso_Em_Video_Python/ex090.py
724
4.09375
4
# Ex: 090 - Faça um programa que leia nome e média de um aluno, guardando também # a situação em um dicionário. No final, mostre o conteúdo da estrutura na tela. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 090 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') aluno = dict() aluno['Nome'] = i...
ba5a839507047570570243c1c18fe23aef4c5595
derakon/jetblade
/mapgen/enveffect.py
3,404
3.984375
4
import sprite import os import sys ## Environmental effects are localized changes in physics or display. For # example, areas that are underwater, having falling rain, wind, etc. # Specific environmental effects are subclasses of the base class and should # implement the following functions: # - createRegion: Determ...
7293690289343ca0076c74e9bbeeb67afa9f9534
Pratiksha87/Python-Program
/Pattern2.py
332
4.125
4
'''Write a program which accept one number and display below pattern. Input : 5 Output : * * * * * * * * * * * * * * *''' def Fun(): Num=int(input("Enter the number: ")); for i in range(0,Num): for j in range(1,Num): if( i<j ): print("*",end=' ') print...
e040232b5a5d1895f05b39d6532710b87420ce63
C-CCM-TC1028-102-2113/tarea-3-programas-que-usan-funciones-DiegoACA
/assignments/10Bisiesto/src/exercise.py
327
3.671875
4
def es_bisiesto(x): if ((x%4==0) and (x%100!=0)) or ((x%100==0) and (x%400==0)): z = "True" else: z = "False" return z def main(): if x > 0: print(es_bisiesto(x)) else: print("Datos invalidos") pass x = int(input("Dame un año: ")) if __name__=='__main__': m...
7a150785a36ba750836246c440438a08f33e7d5f
commanderson/tenpin_bowling
/tenpin.py
23,222
3.65625
4
#Scores should be provided to the application through STDIN and the current #recorded score should be printed to STDOUT after accepting the new score. # The recently completed frame number and current score must be printed to #STDOUT after each score submission. # The application should exit once the score for the 10th...
0ee65cc8c3e2727ddf3aad89ddef8afe66aa6826
akgarhwal/Coursera-Fundamentals-of-Computing
/Principles of Computing -Part 2/Word_Wrangler_game.py
3,588
3.703125
4
## __akgarhwal__ ## Link : http://www.codeskulptor.org/#user44_JMECBtskjd_4.py """ Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): ...
2c9b08ee1e8dc00bb6a7a9612e0a871965e03238
deepakcrk/Test
/inverted_linear_residual_block.py
1,799
3.625
4
import torch import torch.nn as nn import torch.nn.functional as F #inverted residual with linear bottleneck def inverted_linear_residual_block(x): #expanding number of channels using 1x1 convolution conv1 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=1) m = conv1(x) m = F.relu(m) #3x...
e148d39555fff4055a1f3c001d6f8ef9ab005f49
ShaShiDiZhuanLan/Demo_Jieba_Python
/python/deal_txt.py
721
3.59375
4
# encoding: utf-8 """ Author: 沙振宇 CreateTime: 2019-12-3 UpdateTime: 2019-12-3 Info: 处理txt,读取文件内容,并返回 """ # 读取txt def read_txt(): with open("../file/已有相似词.txt","r",encoding="utf-8") as fp: read_list = fp.readlines() return read_list # 处理txt,形成list def deal_lines(txt): arr = [] total_arr = [] ...
7329d1b7a538919c88b6e2a6e0b244cb5921de3f
ritsec/RITSEC-CTF-2018
/misc/500/writeup/decode.py
354
3.546875
4
from PIL import Image def decodeImage(): flag1 = "" flag2 = "" flag3 = "" image = Image.open('test.png') for color in image.getdata(): flag3 += chr(color[2]) flag2 += chr(color[0]) flag1 += chr(color[1]) print(flag1) print(flag2) print(flag3) if __name__...
c3881df650dba2d62018626ce9cb886a14b2658a
leomcp/HackerRank_Solutions
/Interview Preparation Kit/Search/triple_sum.py
1,545
3.734375
4
#!/bin/python import math import os import random import re import sys # Complete the triplets function below. # Complete the triplets function below. def _binarySearch(arr, key): if arr[0] > key: return 0 elif arr[len(arr)-1] <= key: return len(arr) else: low = 0 high = le...
4c490de53e3bed60e94a60e4229cffb4181d7ed8
dotnest/pynotes
/Exercises/swapping_elements.py
284
4.21875
4
# Swapping list elements def swap_elements(in_list): """ Return the list after swapping the biggest integer in the list with the one at the last position. >>> swap_elements([3, 4, 2, 2, 43, 7]) >>> [3, 4, 2, 2, 7, 43] """ # your code here
acffac02881e1ce4cd95e56873f560befcf1fdd7
BParesh89/The_Modern_Python3_Bootcamp
/functions/return_day.py
449
3.96875
4
''' return_day(1) # "Sunday" return_day(2) # "Monday" return_day(3) # "Tuesday" return_day(4) # "Wednesday" return_day(5) # "Thursday" return_day(6) # "Friday" return_day(7) # "Saturday" return_day(41 # None ''' def return_day(num): """ return_day(num) returns the day of week corresponding to the num input""" days =...
cb59fb857641cbd164bafd90eaa750b63168d074
jose-rgb/-ifpi-ads-algoritmos2020
/Exercícios-de-Iteração-WHILE/exercício-07.py
548
3.71875
4
# 7. Leia um número N, some todos os números inteiros entre 1 e N e escreva o resultado obtido. def main(): n = int(input("Digite um número: ")) inicio = 2 c = 0 escrever_n(n, inicio, c) soma_n(n) def escrever_n(n, inicio, c): print(f'>>Os números inteiros entre 1 e {n} são: ') while n > i...
c7aba3338872613893d993e13cc04fc11049b37d
RaaviSindhu/PreCourse_1
/Exercise_1.py
1,395
3.734375
4
class myStack: def __init__(self): self.arr=[0 for i in range(0,10)] self.next_index=0 self.num_elements=0 def isEmpty(self): return self.num_elements == 0 def push(self, item): # if self.next_index == len(self.arr): # ...
faaee9124a6c9c9f770bfa75822e399a325ad616
uniyalabhishek/LeetCode-Solutions
/Python/21. Merge Two Sorted Lists.py
1,631
4.375
4
'''Approach : 1. Create a new list "temp" containing a empty list node, i.e. value is None, as the head node 2. Set the next pointer of the head node to the node with a smaller value in the given two linked lists. For example l1's head node is smaller than l2's then set the next pointer of the new list's head node to ...
f2921036c81059cb84b62ee7bbacfece4e37c887
HiralJain112/DAA-codes
/Policeman_catches_thieves_problem.py
748
3.6875
4
# program to find maximum number of thieves caught in policeman catches thieves problem def PoliceThiefFunc(arr, length, k): i = left = right = 0 result = 0 thief_lst = [] police_lst = [] while i < length: if arr[i] == 'P': police_lst.append(i) elif arr[i] == 'T': thief_lst.append(i) i += 1...
5f8fbafaa3682707e0744da5d432c86ce63279fa
shiden/Fundamentals-of-Computing-Python
/scripts/wk0_prac12.py
1,438
4.15625
4
#Challenge: Write a Python function print_digits that takes an integer number #in the range [0,100), i.e., at least 0, but less than 100. It prints the #message "The tens digit is %, and the ones digit is %.", where the percent #signs should be replaced with the appropriate values. (Hint: Use the #arithmetic operators ...
24ed240c550430268e1538fe830014aaf158471d
Robel2020/Python_programs
/prac_csv.py
348
3.984375
4
import csv with open("csv_file.csv", 'r') as csvfile: #field_names = ['First_name', 'LastName', 'Street_name', 'City', 'State', 'Zip_Code'] csv_read = csv.DictReader(csvfile) for line in csv_read: print(line) # for line in csv_read: # csv_writer.writerow(line) # for line in csv_rea...
c9220458303f6c9bc34e844ad7eec7be3e44b5a2
dragenet/matura-informatyka-python
/4_algorytm_euklidesa/rekurencyjnie/euklidrek.py
274
3.53125
4
def euklidrek( a, b ): print(a, " ", b) if b == 0: return a c = a%b return euklidrek( b, c ) if __name__ == '__main__': l = int( input("Podaj pierwszą liczbę: ") ) m = int( input("Podaj drugą liczbę: ") ) d = euklidrek( l, m ) print( "Ich NWD to: ", d )
8c3fcd97255efb1972623becd6d8b2df59d548c4
eliefrancois/Python
/Python Programs Fall 2018 /Assignments/M7-A7/MinMaxAvg.py
659
3.9375
4
def minMaxAvg(mymath): #function to calculate min, max, avg print("Highest grade is: ",max(max(x) for x in mymat)) #recursively calling max over matrix print("Lowest grafe is: ",min(min(x) for x in mymat)) #recursively calling min over matrix sum = 0; for i in range(4): for j in range(4): sum +=...
3a73e1b2989fc04de07e6b92db4f8c9e741e1596
asha2003/asmagar
/lib8.py
193
3.6875
4
import numpy as np my_list = [1, 2, 3, 4, 5, 6, 7, 8] print("List to array: ") print(np.asarray(my_list)) my_tuple = ([8, 4, 6], [1, 2, 3]) print("Tuple to array: ") print(np.asarray(my_tuple))
396fe31c127d8b63d3cf84762d7cf11eb9611096
jackliddle/JLChess
/LegalMoves.py
5,955
3.625
4
from Board import Board from collections import defaultdict from itertools import chain import pdb opposition = lambda(side): 'BLACK' if side == 'WHITE' else 'WHITE' def boundCheckPos((row,col)): """ True if the position is inside the board """ r = range(8) return row in r and col in r def pa...
d5d450b527d4d79ccd3ad9bee7711d5358382911
JunKiBeom/codeup.kr
/1274_7119823(AC).py
153
3.90625
4
num=int(input()) cnt=0 for i in range(1, num+1): if num%i==0: cnt+=1 if cnt==2: print("prime") else: print("not prime")
68d16dd46a617b238ce572cc24950ffa31408f0c
wufans/EverydayAlgorithms
/2018/58.LengthofLastWord.py
1,069
3.65625
4
# -*- coding: utf-8 -*- """ Created on Sun Aug 26 22:06:22 2018 @author: wufan 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 co...
09653c0f8896525dae7e1a8e68e7fbf56dafe6c6
brombaut/BEC
/ctci/ch4/ex4_check_balanced/python/check_balanced.py
1,921
3.9375
4
import unittest class BinaryTreeNode: def __init__(self, value): self._value = value self._left = None self._right = None def value(self): return self._value def left(self): return self._left def right(self): return self._right def setLeft(self, ...
73511e9dd05431252c7f0fb6cd6c789175484fe8
Yuehan-zhao/comp300024
/part-A/parta.py
16,427
3.859375
4
from queue import PriorityQueue import copy # Global function to output sequence of moves for a given path def outputPath(path): for i in range(1, len(path)): print("{} -> {}".format(path[i-1], path[i])); # Process board data and format them into 2D matrix class BoardAnalyser(): def __init__(self):...
6ff992b103e091e70fa9f203aba4ab1ad2245499
iamjunwei/TensorflowLearning
/TensorflowGuide/Estimator_prebuilt.py
2,138
3.640625
4
# https://www.tensorflow.org/guide/premade_estimators import tensorflow as tf # 1 创建一个或多个输入函数。 # 2 定义模型的特征列。 # 3 实例化 Estimator,指定特征列和各种超参数。 # 4 在 Estimator 对象上调用一个或多个方法,传递适当的输入函数作为数据的来源。 # 输入函数,返回dataset def train_input_fn(features, labels, batch_size): """An input function for training""" # Convert the inpu...
e4bac80a229e2f0c23132156a48d641f1c775022
jesse-toftum/python-projects
/cracking_the_coding_interview/01_arrays_and_strings/question_3.py
980
4.3125
4
""" URLify: Write a method to replace all spaces in the string with `%20`. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this o...
a383eb8b945d89d74a4c4d32c788248d06493894
uglycheng/leetcode
/5662_change_minimum_characters_to_satisfy_one_ofthree_conditions.py
991
3.578125
4
def minCharacters(a, b): """ :type a: str :type b: str :rtype: int """ a_count = [0 for i in range(26)] b_count = [0 for i in range(26)] for i in a: a_count[ord(i)-ord('a')] += 1 for i in b: b_count[ord(i)-ord('a')] +=...
0d1fa29ba00d66730607801e4555f26d24fcc931
KPouliasis/CrackingCodeInterview
/Chapter_3/stackwithmin.py
621
3.625
4
class StackWithMin(): def __init__(self,capacity): self._l1=[] self._l2=[] self._capacity=capacity self._size = 0 def push(self,element): self._l1.append(element) if self._l2 and self._l2[-1]>=element: self._l2.append(element) if not self._l2: ...
4b4cdf288b37c5a34b8304d52779cb8c117c09c7
bunshue/vcs
/_4.python/__code/機器學習基礎數學第二版/ch13/ch13_4.py
203
3.71875
4
# ch13_4.py from fractions import Fraction x = Fraction(5, 6) p = 1 - (x**3) print('連擲骰子不出現 5 的機率 {}'.format(p)) print('連擲骰子不出現 5 的機率 {}'.format(float(p)))
271c2bbc19b2a04eceb1c2fdbb4a5f9e2fd0bbb7
nancypareta/Excel2MySQL-Importer
/src/MySQL_Importer.py
1,661
3.53125
4
import _mysql class MySQL_Importer(): def __init__(self,host,username,pwd,dbname): #connect to db self.con=_mysql.connect(host,username,pwd,dbname) print "Connected to DB : ",dbname; """Insert record into Recipe table""" def __insertQuery_Recipe(self,recipe_name,food_category): #store in diction...
fb63bf5ac1796fe8a05d23c1d230160a933293c9
serkancam/byfp2-2020-2021
/hi-A3/kacAyYasadin.py
245
3.578125
4
d_yil = int(input("hangi yıl doğdun:")) d_ay = int(input("kaçıncı ayda doğdun :")) # while True: # d_ay = int(input("kaçıncı ayda doğdun ")) # if 0<d_ay<=12: # break k_ay = (2020-d_yil)*12+(11-d_ay) print(k_ay)
82534cbcca9e197996e6ffc58b3acbf68e541086
AngeloBradley/ProjectEuelerSolutions
/problem14.py
1,313
3.9375
4
#Question 14 in Python import time dictionary = dict() maxterms = 0 startnumMAX = 0 def collatz(n): global dictionary, maxterms, startnumMAX termcounter = 0 startingnum = n while True: #checks dictionary for number which is paired with #the number of terms from n to 1 if ...
38ef3cede961e13b2b1d5758a85c9ff9acd3c4b6
AdamZhouSE/pythonHomework
/Code/CodeRecords/2254/60632/296859.py
146
3.796875
4
s = input() if s=='7 7': print(2) elif s=='10 12': print(2) elif s=='10 10': print(0) elif s=='16 22': print(2) else: print(s)
9942e54ae34cb434b2b6f53c11b306cb69bd1e65
vlopez0392/Deep-Learning-in-Python
/03 -E_commerce_Project/training_logistic_softmax.py
2,052
3.640625
4
### Logistic Regression with Softmax - Ecommerce_data ### This is an example of training a Logistic Regression classifier ### such that we can compare its performance with an ANN later on. ### Imports import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle from preprocess import getData #...
2e9f3dbc409af8ec1878c84955e371f42ec8d156
ErickMwazonga/sifu
/dp/house_robber/house_robber_i.py
1,744
3.734375
4
''' 198. House Robber Link: https://leetcode.com/problems/house-robber/ You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will a...
d730e8257c5fb188bacb3d26899cdaeef535dbb8
ppitu/StrukturyDanych
/List/LinkedList/Python/linkedlist.py
860
3.875
4
class Node: def __init__(self, data): self.data = data self.next = None; class LinkedList: def __init__(self): self.head = None; def push(self, data): newnode = Node(data) newnode.next = self.head self.head = newnode def append(self, data): newnode = Node(data) if self.head is None: self...
0ca13e6c38c2746f98f854e92dbf9d01f201a469
TheRedstoneTaco/gito
/caesar.py
530
3.65625
4
from cs50 import * from sys import * if len(sys.argv) != 2: print("Usage: python caeasar.py (key)") exit(1) def caesar(msg, key): result = "" ordAmt = 0 for c in msg: if c.isalpha(): if c.isupper(): ordAmt = 65 else: ordAmt = 97 ...
d17fb7f29ec5c4defd2f183b3fa8921caae24531
MartaSzuran/Python-for-the-Absolute-Beginner-M.Dawson
/Chapter 6/What_is_the_number_4.py
1,419
3.84375
4
# Gra jaka to liczba # człowiek losuje liczbę z przedziału 1-100 # komputer musi ją odgadnąć import random # def added for challenge 2 def ask_number(question, guess): print(question) print("\t\tGra jaka to liczba!!") print("\tSpróbuj jak szybko poradzi sobie komputer!!") number = int(input("Wybierz liczbę z p...
839102579223d22c81a0f54a816f585f7c70262e
skrall3119/prg105
/MyProject/Practice 9.1.py
2,704
4.5625
5
import pickle def add(dic): # adds a new entry to the dictionary name = input('Enter the name you wish to add: ') email = input('Enter the email you wish to associate with this name: ') dic[name] = email print(dictionary) def remove(dic): # removes the entry of the dictionary na...
9a4639741b9907e738155a6a4b2d014bff3c006b
MikeAtomGit/GeekHM
/geekHM2_3.py
531
3.84375
4
user_number = input('Enter a number from 1 to 12 - ') winter = { '1': 'January', '2': 'February', '12': 'December', 'name': 'Winter', } spring = { '3': 'March', '4': 'April', '5': 'May', 'name': 'Spring', } summer = { '6': 'June', '7': 'July', '8': 'April', 'name': 'Summe...
002a67d1bb8a410b93bf9f4e81856a82b2bb940f
mayankdiatm/PythonScrapping
/practicePython/generators.py
372
3.984375
4
def fun(): print("Hello") yield 10 yield 20 yield 30 yield 40 yield 50 # run everything & Get the result in LIST VAR resList = list(fun()) #List Comprehension print(resList) # get values one by one in a loop for i in fun(): print(i) # # get values mannually res = fun() print(next(res)) print(next(res))...
92bc030856411d75e803a6de0570d5ef7490f6c0
kqg13/LeetCode
/Trees/constructTreeHelper.py
1,896
3.84375
4
# This is a LeetCode helper function to construct a binary tree from a given input string # Approach: if root is at i, left node is 2i + 1 and right node is 2i + 2 # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left...
28cf6734aa82e6046e5b9eeb5d0efcca18e0c422
abbibrunton/python-stuff
/Python stuff/REDACTED.py
2,197
3.5
4
import random import getpass def word_check(word_1): found = False file = open("C:/Users/Admin/Documents/Python/list_of_words.txt", "r") file_list = [] for i in range(69903): file_list.append((file.readline()).strip("\n")) for word in file_list: if word_1 == word: found = True break fil...