blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
08db9c054d738f65c7743e8c29df5b9b08d08e75
Pitrified/snippet
/python/logger-example/logger_main.py
3,655
3.75
4
# good guides # https://www.pylenin.com/blogs/python-logging-guide/ # https://realpython.com/python-logging/ import logging from logger_module import * from logger_class import * def setup_logger(): """setup the loggers for the main module a main_logger that prints to file a console_logger that prints t...
1f8dbde509272c7403244a7133dded6ee6355ad9
ericosur/ericosur-snippet
/Topics/boshiamy/find_spell.py
1,915
4.0625
4
#!/usr/bin/env python3 # coding: utf-8 ''' search radicals from Boshiamy.txt and show unicode code point ''' import sys import re from typing import List import unicode_blocks class Solution: ''' solution ''' def __init__(self): self.data_file = 'boshiamy_radicals.txt' self.fileobj = None ...
08cf6d58b1803a2025e3e50dad74fea1ff188c5b
Krosenblad/dataprocessing
/homework/scraper/tvscraper.py
4,807
3.84375
4
#!/usr/bin/env python # Name: Kajsa Rosenblad # Student number: 11361840 """ This script scrapes IMDB and outputs a CSV file with highest rated tv series. """ import csv from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import re TARG...
fb475df49cb549bdf1215266960cd30e7efde11d
cassianomaia/falsa-posicao
/posicao_falsa.py
1,063
3.859375
4
import math # Constante que define o numero máximo de iterações que o método irá realizar MAX_ITER = 1000000 # Função que será analisada def func(x): return (math.pow(x,3) - math.pow(x,2) + 2) # Função x³ - x² + 2 # Calcula a raiz da função(x) dado o intevalo [a,b] def posicaoFalsa(a, b): if func(a) * func(...
1bdc2f86719334f08d7afa6c4345cecb0c0d406f
CodersInSeattle/InterviewProblems
/problems/sorting/pancake_sort.py
815
4.25
4
""" Given an unsorted array, sort the given array using only a flip() operation: flip(arr, i): Reverse arr from 0 to i """ def flip(arr, i): # Implemented only for testing low, high = 0, i while low < high: arr[low], arr[high] = arr[high], arr[low] low += 1 high -= 1 def pancak...
808bae2834c04f1816c468f094115e02bbb007a0
green-fox-academy/Angela93-Shi
/week-03/day-04/movies_info.py
1,556
3.609375
4
movie_dict = {} movie_list = [ { "id":1, "title":"Glass", "year": 1987, "description":"Security guard David Dunn uses his supernatural abilities to track Kevin Wendell Crumb, a disturbed man who has twenty-four personalities." }, { "id":2, "title":"The Kid Wh...
cf8bff9829bc8c6e40ac3dacdc7a0d3ad320c4c0
Aasthaengg/IBMdataset
/Python_codes/p02406/s370570836.py
126
3.84375
4
n = int(input()) for i in range(1, n+1): if i%3 == 0 or str(i).find('3') != -1: print(f" {i}", end = '') print()
e26cef09e1b49c1a34fb1b5b435b00475ec21182
Iwata-Factory/IwataProject
/PYTHON/get_gps_for_plot.py
623
3.5
4
#!/user/bin/env python # coding: utf-8 def main(): f = open('gpslog.txt') data = f.read() # ファイル終端まで全て読んだデータを返す f.close() # 区切り文字はmacとwindowsで違うかも lines = data.split('\n') # 改行で区切る(改行文字そのものは戻り値のデータには含まれない) lat = [] lng = [] for i, line in enumerate(lines): if line == '*': ...
5f6ccab9deb209f4ceb68892a6732d39897c7f58
jorgeiksdh/HouseTextGame
/roomGenerator.py
2,790
3.703125
4
globalFlag = 1 points = [] area = [] doors = [(-2,3),(0,0)] entrance = () out = () while globalFlag == 1: print("1. Obtener las coordenadas del muro y del área del cuarto") print("2. Salir") choice = int(input("Selección: ")) if choice == 1: choiceFlag = 1 while choiceFlag == 1: ...
aa619eedc1911033b079bafe6392e98246a87ef9
Jongveloper/hanghae99_algorithm_class
/algorithm_practice/2609.py
722
3.578125
4
# 두 개의 자연수를 입력받아 최대 공약수와 최소 공배수 구하기 # 문제 접근 방식 : # 최대공약수: a 와 b의 최대공약수는 b 와 a를 나눈 나머지의 최대공약수와 같다. # 최소공배수: a 와 b의 최소공배수는 a*b/최대공약수(a,b)를 해주면 최수 공배수가 된다. # 최소공배수가 되는 이유는 이 수를 a와 b 모두 나누어떨어지고 나누어 떨어지는 수 중 가장 작은 수이기 때문이다. l, r = map(int, input().split(' ')) def gcd(a, b): mod = a % b while mod > 0: a = ...
c649f6449fce38e22bec8258d8621c32f18dc6a6
MultiRRomero/lightwall-pong
/server/game.py
1,730
3.625
4
#!/usr/bin/python import time """ This represents a ball object in pong """ class Ball: def __init__(self, position_x, position_y, direction, speed): self.px = position_x # x coordinate (in pixels) self.py = position_y # y coordinate (in pixels) self.dir = direction # ball direction (in...
ee68d0b52e43c6d61bc1f7496a9c63222f2c653f
alrahimi/PythonAbstractAlgebra
/FieldABC/GroupMultipicative/Semigroup.py
482
3.6875
4
from abc import ABCMeta, abstractmethod class Semigroup(metaclass=ABCMeta): @abstractmethod def mulop(self,x): pass def __init__(self,value): self.v=value def __mul__(self,rhs): print("SemigroupMul rhs=",rhs,"type(rhs)=",type(rhs)) #r = Semigroup(...
2eaad41d0bd687c9c8cd816bc723a95e5838e8ef
chantigit/pythonbatch1_june2021data
/Python_9to10_June21Apps/project1/functionapps/tasks.py
548
3.890625
4
#Task2: Power of a number def power(a,b): res=a**b print(res) #Task3: Biggest of 4 numbers def largestNumber(n1,n2,n3,n4): if n1>n2 and n1>n3 and n1>n4: print(n1,' is big') #Task4: Find factorial of a number def fact(n): f=1 for i in range(1,n+1): f=f*i print(f) #Task5: Print rev...
873658fb8d3233b62319ab25ac806b7336b54cc9
RonsonGallery/Steganography
/CaesarCipher.py
1,872
4.09375
4
#--------------------------------------- #-----------Caesar Cipher--------------- #--------------------------------------- # Ceaser Cipher class class CaesarCipher: # this method encrypt the plain text @staticmethod def encrypt(string,key): result = "" for char in string: if cha...
b21fb237714fa95523c292371984d174953a62de
souravs17031999/100dayscodingchallenge
/heaps_and_priorityQueues/check_binary_heap.py
739
3.96875
4
# Program for checking if given array forms binary heap or not. # idea is to check from last internal node that is at n//2 - 1 , to check # if at any node up the tree, we have if any voilation of heapify depending on # whether we are checking min-heap, or max-heap. # TIME : 0(N), space : 0(1). def left(i): return...
d4e244e3e61f34a7c9c534c6b2545fc1dce60269
adeneviyani/keamanan-perangkat-lunak
/Tugas program sederhana revisi.py
2,328
3.828125
4
# Tugas program sederhana # Nama : Ade Neviyani # Nim : 19051397018 # IDENTITAS MAHASISWA nama = input ("nama : ") nim = input ("nim : ") # deklarasi fungsi operator def fungsi_total_nilai (Nilai_Partisipasi,Nilai_Tugas,Nilai_UTS,Nilai_UAS): Nilai_Partisipasi = int (Nilai_Partisipasi) *0.2 Nilai_Tu...
72d89cda8da425b14453ec1b612eb658608a1a63
huanglun1994/learn
/python编程从入门到实践/第六章/6-7.py
812
3.953125
4
# -*- coding: utf-8 -*- my_girlfriend = { 'relationship': "My girlfriend's", 'first_name': 'Wang', 'last_name': 'Di', 'age': 23, 'city': 'Cheng Du', } me = { 'relationship': 'My', 'first_name': 'Huang', 'last_name': 'Lun', 'age': 23, 'city': 'Cheng Du', } my_friend = { 'relat...
9306a590261d23bcc5b3ecaa53d633392200444a
KennyMC155/JustTom.py
/main.py
469
3.765625
4
from funk import searchingGame, mathematicOper, main_menu import time print("Hello, my name is Tom, let's play") time.sleep(2) main_menu() gamenumber = int(input()) while gamenumber != 3: if gamenumber == 1: searchingGame() time.sleep(3) main_menu() gamenumber = int(input()) e...
aa4b1db7e0b217bb4563c2cb7f0646774d08f1f9
jacquerie/leetcode
/leetcode/0766_toeplitz_matrix.py
586
3.578125
4
# -*- coding: utf-8 -*- class Solution: def isToeplitzMatrix(self, matrix): for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i - 1][j - 1] != matrix[i][j]: return False return True if __name__ == "__main__": solutio...
8497a5bddc903b2af7fc14238d63be18de7aad29
aravind-sundaresan/python-snippets
/Interview_Questions/Goldman_Sachs_palindrome.py
1,440
3.9375
4
#!/bin/python3 import math import os import random import re import sys # Complete the detector function below. def detector(tweets): for tweet in tweets: cardinality = 0 suffix = tweet[-3:] tweet = tweet[:-3] length = len(tweet) palindrome_count = 0 if length > ...
d0af27f195c5445a729ae353470db9b36b8b2367
jacksonyoudi/python-note
/notebook/3-tier_architecture/python/object13.py
1,227
3.625
4
#!/usr/bin/env python # coding: utf8 class Employee(object): def __init__(self, name, job=None, pay=0): self._name = name self._job = job self._pay = pay def giveRaise(self, percent): self._pay = int(self._pay * (1 + percent)) def __str__(self): return...
1affb86447c912cf3edf945a5a6ce58745b7e1b3
JJUMPING/study_cs
/intro.py
7,681
4
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ a=3-2 type(a) print('jumping',a) b='23' bint=int(b) print(b*3) #%% def fc(C): f=1.8*C+32 print(str(f) + 'F') return str(f) + 'F' c2f=fc(35) print(c2f) #%% calculate the third side of a triangle #to be f...
446f52d457672ae9ef6536dceedade37605e59e3
gayathri1997/Python-Programming
/Strings/isAnagram.py
139
4.0625
4
string1 = 'abcdefg' string2 = 'gfedcba' if sorted(string1) == sorted(string2): print('anagram') else: print('not anagram')
e0bfc48f55be38e38c7c2396ef7a1fe194220653
dmunozbarras/Pr-ctica-5-python
/ej5-9.py
823
3.984375
4
# -*- coding: cp1252 -*- """DAVID MUÑOZ BARRAS - 1º DAW - PRACTICA 5 - EJERCICIO 9 Escriu un programa que et demani noms de persones i els seus números de telèfon. Per a terminar de escriure nombres i numeros s'ha de pulsar Intro quan et demani el nom. El programa termina escribint noms i números de telèfon. Nota: ...
e341a7d93fda1682d07d4226d396c120c334000e
981377660LMT/algorithm-study
/7_graph/环检测/1559. 二维网格图中探测环-并查集无向图环检测.py
1,808
3.78125
4
from typing import List # 你需要检查 grid 中是否存在 相同值 形成的环。 # 一个环是一条开始和结束于同一个格子的长度 大于等于 4 的路径 # 也可并查集(每次只并两个方向) class UnionFind: def __init__(self, n: int): self.n = n self.setCount = n self.parent = list(range(n)) self.size = [1] * n def findset(self, x: int) -> int: ...
e20f449601c10ecc3b21a9c44a692512f6c61290
Amr-Dweikat/Rest-Soap-api-testing-robot-framework
/venv/Lib/site-packages/JsonToDict/convertJsonToDict.py
1,473
3.828125
4
import json class ConvertJsonToDict(object): def __init__(self): pass import json def convert_json_to_dictionary(self,json_string): ''' Convert from Json To Dictionary. ''' dictData = json.loads(json_string) return dictData def __str__(self): return "This is a function that converts json to dic...
736475ae8596c8b6e8ce19a258dd1ca6868a5205
sinhasaroj/Python_programs
/SerializationandDeserialization/json_serialization.py
581
3.5625
4
import json d1 = {'a':100 , 'b':20} d1_json = json.dumps(d1) # dumps the dict object to a string loads does the vice versa print(d1_json) print( json.dumps(d1, indent=2)) d_json = ''' { "name":"John Clesse", "age":39, "height":4.5, "walksFunny":true, "sketches":[ { "title":...
f2a818e9a21dbfd1a24c2e5f2f0aeed52bec701a
zhweiliu/learn_leetcode
/Top Interview Questions Easy Collection/Strings/Reverse Integer/solution.py
1,021
4.5
4
from typing import List ''' Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x =...
419800d2294dc499a406721c1c0c0ca06e886253
SivaBackendDeveloper/Python-Assessments
/3.Loops/3qs.py
283
4.09375
4
#Program to equal operator and not equal 2.Operators def eane(a): while True: if a%2==0: # equal operator print(a," is even number") break elif a%2!=0: # not equal operator print(a,"is odd number") break eane(12)
4df908c5c1fd18b3cf46c84c850ded175acc7cf4
polynn970/challenges
/after17.py
635
3.734375
4
import re l = "Beautiful is beetter than ugly" matches = re.findall("Beautiful", l) print(matches) match = re.findall("beautiful", l, re.IGNORECASE) print(match) zen = """Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to...
0a3c976891136245c8882e76b802253428e5f786
ramonvaleriano/python-
/Livros/Livro-Introdução à Programação-Python/Capitulo 5/Exemplos 5/Listagem5_6.py
206
3.75
4
# Program: Listagem5_6.py # Author: Ramon R. Valeriano # Description: # Developed: 28/03/2020 - 21:16 # Update: end = int(input("Enter with number: ")) number = 1 while number<=end: print(number) number+=1
eb49b6b6d663cabb2dae61bf260fde6bb06fd1d7
Taylor-Zapalac/School
/Fall2018/FutureBalance.py
304
4
4
curBalance = float(input("Enter current bank balance:")) interestRate = float(input("Enter interest rate:")) time = int(input("Enter the amount of time that passes:")) def calcMoney(value, interest, time): return value * (1 + interest) ** time print(calcMoney(curBalance, interestRate, time))
7c9344867c71938fe2fa4c14465e70252db12983
Umang070/Python_Programs
/string_list & dictionary manipulatioin.py
1,319
4.0625
4
#!/usr/bin/env python # coding: utf-8 # ### String Manipulation # In[1]: st = "umang" type(st) # In[2]: #how many methods and functions are associated with string class dir(st) # In[10]: ste = "umang " ste.strip() #both side ste.rstrip() #right side ste.startswith('u') ste.find("g",2) #find "g" star...
54ecd51699f3fd77c68e21b6258060416b7331ea
Lalcenat/python-challenge
/PyBank/main.py
3,278
3.890625
4
import os # Module for reading CSV files import csv month_list = [] profit_loss_list = [] csvpath = os.path.join('Resources', 'budget_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: # ...
751cf75236891de8709d56d683f18aaa10c1177d
Maleriandro/sokoban
/deshacer.py
1,225
3.671875
4
from data_structures import Pila class Deshacer: '''Almacena historial de estados en forma de pila. Se puede agregar estados, sacar estados, comprobar si hay estados disponibles para deshacer, y vaciar el historial.''' def __init__(self): '''Inicializa historial de estados vacio''' self.a...
7473eb8a9ea9d4675bd2fbc33a82cf3364a44cb5
Axdliu/Hacker_ank
/Algorithms/Strings/Pangrams.py
227
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 03 22:34:22 2017 @author: User """ s = set(list(reduce(lambda x,y:x+y, raw_input().strip().split()).lower())) if len(s) == 26: print 'pangram' else: print 'not pangram'
d0dc1af5abd1bd35d60e5c309cc90ce0f9481e19
bibongbong/pythonCookBook
/src/2.4.StrSearchAndMatch.py
1,314
4.0625
4
# 字面字符串: str.find(), str.endswith(), str.startswith() # 复杂的匹配: 正则表达式和re模块 text1 = '11/27/2012' text2 = 'Nov 27, 2012' import re # \d+ 表示多个数字,\d+/表示多个数字加上/ # print yes if re.match(r'\d+/\d+/\d+', text1): print('yes') else: print('no') # 如果需要用同一个模式去匹配多个字符串,需要将模式字符串预编译为一个模式对象 # 同时利用括号去捕获分组,第一个括号gro...
8f7b0569fac8719b50951e5f29ef78d65a39c2a9
ER-Ameya/Chat-appication
/server.py
761
3.625
4
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket.AF_INET is used to load family address and socket.stream is use to stream the data host = socket.gethostname() #to get host name port = 4321 #To define port s.bind((host,port)) s.listen() print("Waiting for connection...") while True: #...
5af9c4c9b5d62b7349f1994751ed488489e5353d
sumanthneerumalla/Leetcode
/TwoSum.py
788
3.5625
4
#https://leetcode.com/problems/two-sum/ class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ locations = {} for i in range(len(nums)): num = nums[i] match = target - num ...
aef1bd3647a266a8cbfb8904440d05807ffb9b5d
sympy/sympy
/examples/intermediate/differential_equations.py
583
4.03125
4
#!/usr/bin/env python """Differential equations example Demonstrates solving 1st and 2nd degree linear ordinary differential equations. """ from sympy import dsolve, Eq, Function, sin, Symbol def main(): x = Symbol("x") f = Function("f") eq = Eq(f(x).diff(x), f(x)) print("Solution for ", eq, " : "...
1e7523050bb0c08143f74c6f5311b0db5e3c5f36
Hardcore30005/pythonintask
/PMIa/2014/PAVLINOV_G_P/Задание 6.py
790
3.890625
4
# 6. 14. # , 2014 , . # # 4.06.2016 import random mascots = ['','',' '] progSel = mascots[random.randint(0,2)] userSel = input(" . ? ") if userSel==progSel: print("! " + userSel) else: print("! " + userSel) input()
74dddb4286f56524bb8694fe11f35e44de52fb14
minhuan520/MH
/Day1/test07_yh.py
432
3.71875
4
import random root = random.randint(0, 2) a = '恭喜你,你赢了' b = '不好意思,你输了' player = int(input('请输入 0 剪刀 1石头 2布:')) while player == root: print('打平了,决战到天亮') player = int(input('请输入 0 剪刀 1石头 2布:')) else: if (player == 0 and root == 1) or (player == 1 and root == 2) or (player == 2 and root == 0): print(b...
288f23c256702dc86dfdbba940268cc6e7d326ac
alimaan2935/LOLO-Game
/highscores.py
4,288
3.984375
4
import json class HighScoreManager: """A HighScoreManager manages the recording of highscores achieved to a highscore file. """ _data = None def __init__(self, file="highscores.json", gamemode='regular', auto_save=True, top_scores=10): """Constructs a HighScoreManager usin...
6143a448b47af4db2b76ca66fcdeee3d03842c54
Larissa-D-Gomes/CursoPython
/introducao/exercicio024.py
365
4.15625
4
""" EXERCÍCIO 024: Verificando as Primeiras Letras de um Texto Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO". """ def main(): cidade = input('Digite o nome da cidade: ') print("O nome da cidade comeca com 'Santo'?",cidade.split(" ", 1)[0].upper() == 'SANTO'...
7429ef6a8c2382dfbcc832d898502c064bebc76a
hateka/python_training
/python_training/1-6.py
176
3.703125
4
import sys param = sys.argv if param[1] < param[2] and param[1] < param[3]: print 'Yes' elif param[1] < param[2] and param[2] < param[3]: print 'Yes' else: print 'No'
96704c270d3948c5ece24ef0da787397c2633d67
kavyababuk/NewPython
/Languagefundamentals/age.py
145
4
4
#create new variable age25,name=ajay #print ajay is 25 years old age=input("enter age") name=input("ener name") print(name,"is",age,"years old")
ac3e4d4c735c7759581b578aa4d905b142836f1c
miha6644/SecretNumberGame
/main.py
139
3.75
4
secret = "7" guess = input("What's the secret number between 1-15? ") if guess == secret: print("Correct!") else: print("Wrong!")
a154800314683ca377dbb5f85c1cc9144a1852ad
GolamRabbani20/PYTHON-A2Z
/PYTHON_TIPS&TRICKS/Loop.py
177
3.78125
4
odd_square = [] for k in range(50): if k % 2 == 1: odd_square.append(k**2) print(odd_square) odd_squares = [k**2 for k in range(51) if k % 2 == 1] print(odd_squares)
3623ff2f89f6e93d234e7ba8be62434c23f161d3
nmasamba/learningPython
/25_lambda_expressions.py
1,000
4.40625
4
""" Author: Nyasha Masamba Based on the lessons from Codecademy at https://www.codecademy.com/learn/python This Python program is introduces lambda expressions in Python. A lambda expression is simply an anonymous function. In Python, anonymous function is a function that is defined without a name. While normal f...
9a6191f1dfbbf79c9b28a1a3922a3b7ed6a0ff2e
qeetw/design_pattern
/signleton/app.py
659
3.734375
4
from singletion import Singleton def main(): first_instance = Singleton() second_instance = Singleton() if first_instance is second_instance: print('Same Instance') else: print('Difference Instance') print('first_data:', first_instance.get_data()) print('second_data:', second_...
83ce18fd76ed28ef27475fd0f26be647d0d95d80
andydevs/tketris
/tketris/game/mino.py
3,414
3.78125
4
""" Tketris Tetris using tkinter Author: Anshul Kharbanda Created: 10 - 11 - 2018 """ import numpy as np from random import choice as random_choice from ..numpy_algorithms import transform_tileset """ The tetris mino classes. In tketris, Minos are represented as objects containing the basic set of tiles comprising ...
e7b355c55713274ab2a8cfc6b848c5357a0e70f1
nioanna/python-helper-functions
/string/string.py
928
3.625
4
# Funkcija izdvaja ceo broj iz stringa from _typeshed import ReadableBuffer def izdvoji_int(a_string): numbers = [] for word in a_string.split(): if word.isdigit(): numbers.append(int(word)) return numbers # Ova funkcija iz datog stringa izdvaja cele brojeve def izdvoji_ceo_broj(t...
bf9286fb55b2a56883f0d48090eae880cf6541c2
darrencheng0817/AlgorithmLearning
/Python/leetcode/WiggleSortIi.py
732
4.03125
4
''' Created on 1.12.2016 @author: Darren ''' ''' Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... Example: (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. (2) Given nums = [1, 3, 2, 2, 3, 1], one possible a...
d991feb2e8c26ced330674dca2a27c80ee3972a5
Eroica-cpp/LeetCode
/021-Merge-Two-Sorted-Lists/solution01.py
1,367
4.0625
4
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: May 3, 2015 # Question: 021-Merge-Two-Sorted-Lists # Link: https://leetcode.com/problems/merge-two-sorted-lists/ # ======================================================...
4ee00049fd00a80a6e6553196166c12a89e88974
mbk282/PycharmProjects
/Homework/silvan_hw2.py
5,824
4.4375
4
#Assignment 2, Basic Probability Programming, November 2016 #------------------------------------------------------------ #1. Ask user for path to file and read file into text memory #take user input concerning the path to the file print("Hello, welcome to the wonderful world of counting words. Please tell me exactly...
d9510f7b2ea49c13697bbcfdafe5706f16bfd2bc
Shargarth/Python_exercises
/Tahtikuvio.py
103
3.671875
4
j = 1 for i in range(0,7): for i in range(0,j): print("*", end="") print("") j += 1
fb94008b187f52ec249e92030202e3ef91639778
riterdba/magicbox
/3.py
515
4.15625
4
#!/usr/bin/python3 # Простейшие арифметические операции. def arithmetic(x,y,z): if z=='+': return x+y elif z=='-': return x-y elif z=='*': return x*y elif z=='/': return x/y else: return print('Неизвестная операция') arif=arithmetic a=int(input('Введите перво...
830813767f150596bc4444e1b7c7bfba4326520d
BetterJiang/LeetCodeQuestions
/MaxCrossingSum.py
1,617
3.828125
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 23 21:18:50 2018 @author : HaiyanJiang @email : jianghaiyan.cn@gmail.com """ # -*- coding: utf-8 -*- """ Created on Fri Nov 23 20:54:29 2018 @author: HaiyanJiang @email: jianghaiyan.cn@gmail.com """ # A Divide and Conquer based program for maximum subarray sum problem...
50c357e9201f6f686191696395b12f4b765ffcb3
rakesh-chinta/calculator-app
/calculator.py
764
4.125
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x,y): return x * y def divide(x, y): return x / y print("1 for addition,2 for subtraction,3 for multiplication,4 for division") choice=input("enter your choice(1/2/3/4): ") num1=int(input("ente...
143b7c0660b7f2450644e380a5184ebfcf20cfb8
kien6034/CSFoundation
/1_Array/8_zero_matrix/main.py
1,133
3.75
4
#write an algorithm such that if an element in an MxN matrix is zero, its entire row and column are set to zero import numpy as np M = 8 N = 6 def find_zero(mtx): row = False col = False for i in range(0, M): for j in range(0, N): if mtx[i,j] == 0: if i == 0: ...
470c0c3879cfc06c82780441ab64777d6139b471
liyaSileshi/CS-1.2-Intro-Data-Structures
/Code/sample.py
1,226
4.0625
4
import sys from word_count import hist_dictionary import random from tokenize_word import tokens def sample_by_frequency(histogram): """ Input: dictionary histogram of a text file Return: a weighed random word """ tokens = sum(histogram.values()) rand = random.randrange(tokens) for key, va...
55c0bd78c570c434ba02fec397da17cbcd915b9f
tmz22/Financial_and_Poll_analysis
/PyPoll/main.pypoll.py
1,734
3.734375
4
import os import csv #Variables candidates = [] number_votes = [] percent_votes = [] total_votes = 0 #Path csvpath=os.path.join("Resources", "election_data.csv") #Csv reader with open(election_data,"") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = next(csvreader) #for row...
cb6350e4c192dd5fcb9030dc5d70cb51f2e72088
divyamvpandian/MyLearning
/Practice/mandn.py
524
3.625
4
import math def main(): t = int(input()) while(t>0): strin = input() m = strin.split(" ")[0] n = strin.split(" ")[1] result=addmandn(int(m),int(n)) print(result) t-=1 def countDigit(n): return math.floor(math.log(n, 10)+1) def addmandn(m,n): x=m+n i...
65f3d58264e3991d7f912eef63bebfffa8c984c4
jaysiyaram/Geeks_for_geeks-Placement_track_solutions
/max_absolute_diff.py
1,123
3.5625
4
#code import sys def calc_sum(arr): max_val = arr[0] tmpMax = [] curr_val = 0 for value in arr: curr_val = max(value, curr_val + value) if curr_val > max_val: max_val = curr_val tmpMax.append(max_val) return tmpMax def calc_max_absolute_diff(arr, arr_len):...
a0f1b8b151f1625d08d6884064f95fe3d41c5d20
ThanhThi94/baitap6
/chuyendoitiente/main.py
209
3.5625
4
import math usd = float(input("Nhập số USD cần đổi: ")) tg = float(input("Nhập tỉ giá USD/VND: ")) vnd = tg*usd print("Với {usd} USD sẽ đổi ra được {vnd} VND".format(usd=usd, vnd=vnd))
b6f5844c03c8ced466728257e5dcad29125bf91a
privateHmmmm/leetcode
/532-k-diff-pairs-in-an-array/k-diff-pairs-in-an-array.py
2,572
4.0625
4
# -*- coding:utf-8 -*- # # Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. # # # # Example 1: # # Input: [3, 1, 4, 1,...
30981b8a49cce692b4fd9279b1f7525b11d55526
gabriel-valenga/CursoEmVideoPython
/ex010.py
572
4.25
4
numero = int(input('Digite um número: ')) print('Tabuada do {}:'.format(numero)) print(' {} x 1 = {:2}'.format(numero,numero*1)) print(' {} x 2 = {:2}'.format(numero,numero*2)) print(' {} x 3 = {:2}'.format(numero,numero*3)) print(' {} x 4 = {:2}'.format(numero,numero*4)) print(' {} x 5 = {:2}'.format(numero,numer...
d55263edb2c44653a1ae3ca2ee6170cc87977764
Akankshya-ap/Pattern-Recognition
/practice/linear_reg.py
383
3.65625
4
import numpy as np import matplotlib.pyplot as plt x=np.random.normal(3.0,1.0,1000) y=100-(x+np.random.normal(0,0.1,1000))*3 plt.scatter(x,y) #plt.show() from scipy import stats slope,intercept,r_value,p_value,std_err=stats.linregress(x,y) print r_value**2 def predict(p) : return slope*p+inter...
6222a619fbfed08723e11870d312c6b4f87227ee
kenwoov/PlayLeetCode
/Algorithms/Easy/507. Perfect Number/answer.py
476
3.625
4
from typing import List class Solution: def checkPerfectNumber(self, num: int) -> bool: if num <= 0: return False sum = 0 i = 1 while i * i <= num: if num % i == 0: sum += i if i * i != num: sum += num // i...
3bc7a18ddbf5280769e54b4efefc1a0f3858062b
Filipchi/MisionTIC2022
/Ciclo l/Semana 4/Ejercicios_4_p1.py
3,558
3.796875
4
import os os.system("cls") from functools import reduce print("\n\t\t\t Funciones para Colecciones de Datos\n") # Problema # 1: # Utilizar la función incorporada map() para crear una función que retorne una lista con la longitud de cada palabra(separadas por espacios) de una frase. La función recibe una cadena...
6e1e2e3fb745317ecf51a6073eb1810411fb53b1
ssj018/homelab
/study/search_records.py
2,650
3.515625
4
import re import sys # 2014 # %book% # %title%abc%title% # %publish%2011%publish% # %author%qwer%author% # %book% # %book% # %title%def%title% # %publish%2012%publish% # %author%asdf%author% # %book% # %book% # %title%ghi%title% # %publish%2014%publish% # %author%zxcv%author% # %book% # %book% # %title%back to 2014...
42cfe8b33ed3a4e10a8786ec13f97f5c627e2bb4
SubhamSingh1/star
/PycharmProjects/asssgn4.py
210
3.8125
4
cp = int(input("Enter the cost price.")) sp = int(input("Enter the sale price.")) if cp>sp: print("The seller has incurred loss of rs.", (cp-sp)) else: print("The seller has made profit of rs.",sp-cp)
4b40c968d854821a5aa7955aade3cc03d299efb4
silastsui/interview-practice
/interview/zenefits_cardinality_sorting.py
645
4.15625
4
# Complete the function below. def cardinalitySort(nums): def get_binary_cardinality(num): """Gets binary cardinality of a number""" bin_rep = bin(num)[2:] return bin_rep.count('1') sorted_nums = [] binary_nums = {} for num in nums: num_ones = get_binary_cardinality(num...
ce1ed7c25a35ded729ff7b3b45bb03c17185782e
Wubuntu88/boolEQ
/boolEQ.py
13,805
4.1875
4
#!/usr/bin/python """ Author: William Gillespie Course: COSC 321 Date: 2015-04-18 This program accepts two inputs that are boolean expressions, prints out the truth tables for those functions, and prints out whether those functions are equal. The two inputs must have the same set of variables. Parentheses are ...
d784c7310908825f371cd1e33c3eb64557b2aa0e
vik-tort/hillel
/Test/Task_7(TEST).py
256
3.875
4
n=10 fibonnachi=[1,1,2] for num in range(3,n): fibonnachi.append(fibonnachi[num-1]+fibonnachi[num-2]) print(fibonnachi) sum_of_fib=sum(fibonnachi) print("Сумма первых 10 чисел ряда Фибоначчи равна %d" % (sum_of_fib))
fe7879d5a63dba07630206d20d53fb282468700b
gopinathdee/Python
/Basic/02-SimpleInterest.py
313
3.90625
4
intPrincipal = input("\nEnter Principal: ") intNumberOfYears = input("Enter Number of Years: ") floatRateOfInterest = input("Enter Rate of Interest: ") floatSimpleInterest = (int(intPrincipal) * int(intNumberOfYears) * float(floatRateOfInterest))/100 print ("Simple Interest is: %0.2f" %floatSimpleInterest)
2a2e15015f7ac190d804b8938060a3d0e35050fb
khasherr/SummerOfPython
/ReplacePI.py
590
4.125
4
#Sher Khan #This program replaces occurence of PI with 3.14 recursivelye def replacePI(s): #This checks if the the string is either empty or has 1 character returns the string itself if len(s) == 0 or len(s) == 1: return s #returns the string because its empty or has 1 character #If the index at ...
49f73092445c6e802699d34d1d07fcb60f4bd671
juanducal/glassnode
/glassnode.py
2,177
3.515625
4
import requests as req import datetime as dt import pandas as pd def date_to_unix( year = 2010, month = 1, day = 15, ): '''Returns the date (UTC time) in Unix time''' time = int((dt.datetime(year, month, day, 0, 0, 0).timestamp())) return time def glassnode( endpoint,...
6a863e8a911281bab429ca287d9a0f63d4912a3c
Anthonina/lesson1
/training_while_loop.py
524
3.953125
4
find_name = ['Вася', 'Маша', 'Петя', 'Валера', 'Саша', 'Даша'] print(find_name) x = 0 while x < len(find_name): # Пока индекс меньше количества элементов в списке... if find_name[x] == 'Валера': # Если элемент с индексом X равен значению "Валера" valera = find_name.pop(x) # Заводим переменную print...
78383c459dc59b059ef3e99d0b16176d4bcff283
ohdnf/algorithms
/leetcode/819_most_common_word.py
478
3.828125
4
from collections import defaultdict, Counter import re def most_common_word(paragraph: str, banned) -> str: counts = defaultdict(int) words = [word for word in re.sub(r'[^\w]', ' ', paragraph).split() if word not in banned] for word in words: counts[word.lower()] += 1 print(counts) return m...
133634207573fa7c3e921e76f08cfa60583b07d0
stephanbos96/programmeren-opdrachten
/school/les8/8.3.py
307
3.71875
4
def code(invoerstring): waarde = '' for c in invoerstring: o = ord(c) o += 3 nieuwe_char = chr(o) waarde += nieuwe_char return waarde text = input('Geef naam begin station en eindstation: ') antwoord = code(text) print('code is {}'.format(antwoord))
10e2ab5d028bf42dbec39e83a0272faa73994291
elenaborisova/Python-Advanced
/04. Tuples and Sets - Exercise/06_longest_intersection.py
913
4
4
def find_range_values(curr_range): return list(map(int, curr_range.split(","))) def find_set(curr_range): start_value, end_value = find_range_values(curr_range) curr_set = set(range(start_value, end_value + 1)) return curr_set def find_longest_intersection(n): longest_intersection = set() ...
702af67e205ca4594eb0a585aa7f0a60fdb9342a
yutanov/python-project-lvl1
/brain_games/games/brain_gcd.py
391
3.90625
4
import random COND = "Find the greatest common divisor of given numbers." def gcd(a, b): return gcd(b, a % b) if b else a def get_answer(): num_one = int(random.randint(1, 100)) num_two = int(random.randint(1, 100)) print("Question: {} {}".format(num_one, num_two)) divisor = gcd(num_one, num_tw...
8bc048cb658fde7125a191a77aeca46afc4f8057
Nazanin1369/miniFlow
/src/linear.py
732
3.53125
4
from node import Node class Linear(Node): """ Linear Transform function """ def __init__(self, inputs, weights, bias): Node.__init__(self, [inputs, weights, bias]) # NOTE: The weights and bias properties here are not # numbers, but rather references to other nodes. # Th...
ea349c92e4aff08ee0495d05ed7bf7a012ade899
opaulocrispim/criptografia_de_cifra
/criptografia.py
3,147
3.515625
4
import string from unidecode import unidecode def run(): contador = 0 alfabeto = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] alfabeto_chave = [] chave = str(input("Digite a chave: ")) ...
75d1a544e03efe812c087be56e4ea7440783bc84
kangli-bionic/algorithm
/lintcode/1479.py
1,315
3.78125
4
""" 1479. Can Reach The Endpoint https://www.lintcode.com/problem/can-reach-the-endpoint/description """ from collections import deque DIRECTIONS = [ (0, 1), (0, -1), (-1, 0), (1, 0) ] class DataType: ENDPOINT = 9 OBSTACLE = 0 class Solution: """ @param map: the map @return: can you...
4ff7875d4c0fef6509fc8d79b6331a875341afc1
fabioconde/desafio
/questao_1.py
763
3.921875
4
""" Dado um array de números inteiros, retorne os índices dos dois números de forma que eles se somem a um alvo específico. Você pode assumir que cada entrada teria exatamente uma solução, e você não pode usar o mesmo elemento duas vezes. EXEMPLO Dado nums = [2, 7, 11, 15], alvo = 9, Como nums[0] + nums[1] = 2 + 7 =...
c3aff3210a727a2f3a89afd37ca315dcc373eca3
Vixus/LeetCode
/PythonCode/Monthly_Coding_Challenge/May2020/ImplementTrie.py
2,115
4.21875
4
class Trie: """ Implement a trie with insert, search, and startsWith methods. Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("a...
9f84bb67de030e6765f6cc05c6e99f17dedb65ae
Nithya1999/project
/inn.py
173
3.5
4
#Nithya n=input().split() a=input().split() b=input().split() l=[] for i in a: if i in b: l.append(i) if(len(b)==len(l)): print('YES') else: print('NO')
3ff9daaafbf98110b26acfc83f0d0e5a410fb03f
kelpasa/Code_Wars_Python
/6 кю/Compare Versions.py
1,524
3.875
4
''' Karan's company makes software that provides different features based on the version of operating system of the user. For finding which version is more recent, Karan uses the following method: While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS versi...
4f16492049a00cb0482ef34b05ec3b622b5c2648
Max5249/tstp
/part_IV/algorithms/sequential_search.py
528
3.953125
4
# IF YOU ARE READING THIS YOU ARE READING # AN OUTDATED VERSION OF THE BOOK. # I am working with Amazon to resolve this. # The new version is much better and has correctly formatted code examples # In the book. # Please email me at cory@theselftaughtprogrammer.io # For an updated version def sequential_search(number_...
20dec344b403f8bc2bfe057a00e0c67278a46f09
ieeecomputeruni/taller-python
/archivos/11.py
655
4
4
# Listas L.append(object) #Añade un objeto al final de la lista. L.count(value) #Devuelve el número de veces que se encontró value en la lista. L.extend(iterable) #Añade los elementos del iterable a la lista. L.insert(index, object) #Inserta el objeto object en la posición index. L.pop([index]) #Devuelve el valor ...
ac653131cf052f16efe4470692a1c14d651d9a98
mas41672/Python
/ex8.py
737
3.8125
4
# -- coding: utf- 8 - formatter = "%r %r %r %r" # als prints are made of a str, percentage (%) and the input print formatter % (1, 2, 3, 4) # prints ints into the raw str print formatter % ("one", "two", "three", "four") #3 # prints str into raw formatter print formatter % (True, False, False, True) # # the %r prin...
0f9d6f596970ebfe42fbc3396c458e3118d171e7
vlgandara/programas-.py
/buzz.py
98
3.859375
4
n = int(input("Digite um número:")) if(n%5==0): print("Buzz") else: if(n%5!=0): print(n)
0e8ed33ac7e5043001467ccd5735844a27a8e8fc
ymadh/python-practice
/script.py
205
3.765625
4
students_count: int = 1000 print(type(students_count)) if students_count == 1000: print('yes') else: print('no') guess = 0 answer = 5 while answer != guess: guess = int(input("Guess: " ))
953775012d4026e812357a22f40eee49f18118ba
yuchen352416/leetcode-example
/chapter_01/example_0002.py
486
3.625
4
#!/usr/bin/python3 # 买卖股票的最佳时机2 def maxProfit(prices: list) -> int: if prices.__len__() < 2: return 0 sum = 0 for i in range(prices.__len__() - 1): if prices[i] < prices[i + 1]: sum += prices[i + 1] - prices[i] return sum if __name__ == '__main__': # arr = [7, 1, 5, 3, 6, 4] ...
e065555c5f291f462cfccbc461106026f6c0aa9f
snlab/odl-summit-2016-tutorial-vm
/utils/Maple_Topo_Scripts/exampletopo.py
1,676
3.640625
4
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo from min...
64eb29c7fe8b5ecfd600cd788ac7c00dc1d62c24
jeremy24/python-file-handling
/src/read_input.py
1,416
3.515625
4
# reads in the json data, and builds it into an object import json import os class Data: def __init__(self): self.data = [] self.length = 0 self.current_id = 0 def __str__(self): return "Data obj of length " + str(self.data.__len__()) def update(self): self.leng...
04ee555d3793396e25a2a0883ad4ef827ede61dc
cvsogor/Algorithms
/ESG_tests.py
6,008
3.96875
4
from unittest import TestCase # reverse all words in the sentence # ie.. I am a developer => developer a am I def reverse_sentence(sentence): words = sentence.split() words.reverse() return ' '.join(words) class TestReverseSentence(TestCase): def test_reverses_sentences_correctly(self): test_...
3ec40f7176e89a4a88962f7302628cbcaf89b0c8
FishingOnATree/LeetCodeChallenge
/algorithms/151_reverse_words_in_string.py
303
3.53125
4
import re class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return " ".join(re.sub(r"\s+", r" ", s.strip()).strip().split(" ")[::-1]) a = Solution() print(a.reverseWords(" the sky is blue ")) print(a.reverseWords(" a b "))