blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
845afa79098673df25b04509c3d4f6d5fa5ece88 | cmulliss/gui_python | /revision/fns2.py | 258 | 3.90625 | 4 | def add(x, y):
result = x + y
print(result)
add(5, 3)
# positional arguments
def say_hello(name, surname):
print(f"Hello, {name} {surname}")
name = input("enter your name: ")
surname = input("enter your surname: ")
say_hello(name, surname)
|
530395a78cb52fe90e3e14aa9826fe2296e91ec7 | rakesh-29/data-structures | /data structures/searching/binary search/interview problems on binary search/find index of last occurance of an element in an array.py | 650 | 3.6875 | 4 | def last_ocuurance(list,searchnumber):
left_index=0
right_index=len(list)-1
count=0
while left_index<=right_index:
mid_index = (left_index + right_index) // 2
mid_number = list[mid_index]
if mid_number==searchnumber:
count=mid_index
left_index... |
cb846597571710f580b0b9b5c883f284004d5fa6 | Dolj0/Data-Analysis-with-Python-2021 | /part01-e11_interleave/src/interleave.py | 389 | 4.21875 | 4 | #!/usr/bin/env python3
def interleave(*lists):
listForZip=[]
returnList=[]
for x in lists:
listForZip.append(x)
zipped = list(zip(*listForZip))
for x in zipped:
for i in x:
returnList.append(i)
return returnList
def main():
print(interleave([1, 2, 3], [2... |
8733471d811c3d78abc78b6a48110351b12c3e72 | evil1086/Part-2---Regression | /multipleLinearRegression.py | 1,321 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 08:34:32 2019
@author: user
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#IMPORT DATASETS
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 4].values
# tranform categorical data
... |
ac93cc8a77a26fbf7205c3060eb217770ef5fb2f | huanglun1994/learn | /python编程从入门到实践/第八章/8-8.py | 779 | 4 | 4 | # -*- coding: utf-8 -*-
__authour__ = 'Huang Lun'
#定义一个函数,接受三个参数表示歌手名和专辑名和歌曲数,歌曲数为可选形参,返回字典
def make_album(singer, album, quantity=''):
music_album = {'Singer': singer.title(), 'Album': album.title()}
if quantity:
music_album['Quantity'] = quantity
return music_album
#利用循环提示用户输入信息,并提示退出条件
while True... |
742349631149c8f17ef4c0a30793a20f937b81d4 | Fengyongming0311/TANUKI | /小程序/001.ReverseString/把GBK字节转换为utf-8字节.py | 516 | 3.71875 | 4 |
#encode 是编码
#decode 是解码
"""s = "周杰伦"
bs1 = s.encode("GBK")
bs2 = s.encode("utf-8")
print (bs1)
print (bs2)
"""
#把一个GBK字节转化成utf-8的字节
gbk = b'\xd6\xdc\xbd\xdc\xc2\xd7'
s = gbk.decode("gbk") #解码 因为原编码就是GBK所以用GBK方式解码
print (s)
utf8 = s.encode("utf-8") #用utf-8编码
print (utf8)
don = utf8.decode("utf-8")
print ("###... |
48ed34932b355c2afef1caaabe7e499e885ee279 | NiltonGMJunior/hackerrank-problem-solving | /algorithms/warmup/plus_minus.py | 481 | 3.703125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def plusMinus(arr):
positive_ratio = sum([elem > 0 for elem in arr]) / n
negative_ratio = sum([elem < 0 for elem in arr]) / n
zero_ratio = sum([elem == 0 for elem in arr]) / n
print("{:.6f}\n{:.6f}\n{:.6f}".format(
positi... |
d50e7a7f736db28ecd3776c1bdcf283c7910fe90 | italormb/Exercicio_python_basico | /Curso_de_Python_3_Basico/Fase_10/desafio29.py | 247 | 3.90625 | 4 | #desafio 29
velocidade=float(input('Escreva a velocidade do seu carro em km/h:'))
if velocidade>80:
multa=(velocidade-80)*7
print('A multa vai custar {}' .format(multa))
else:
print('Respeitou a leis de transito, Parabéns!!!')
print('DETRAN') |
0abb270ac131411e6f5ab261ea5053c6fa984f49 | hightechfarmer/ControlPyWeb | /build/lib.linux-x86_64-2.7/controlpyweb/abstract_reader_writer.py | 719 | 3.859375 | 4 | from abc import ABC, abstractmethod
class AbstractReaderWriter(ABC):
@abstractmethod
def read(self, addr: str) -> object:
"""This method provides a response to a read request, based on last load"""
pass
@abstractmethod
def read_immediate(self, addr: str) -> object:
"""This me... |
6f63b41f54e15eeb762ded0454162a430eb57779 | zhuxingyue/pythonDemo | /python基础/day08/hm_05_函数demo3.py | 295 | 3.953125 | 4 | def printLine(char, times):
print(char * times)
def printLines(char, times):
"""打印多行分割线
:param char: 分割线样式字符
:param times: 分割线个数
"""
row = 0
while row < 5:
printLine(char, times)
row += 1
printLines("_", 20)
|
4d728a78c6b284d56b4a501c0c60203839ebbde6 | codafett/python | /uncategorised/combine_words.py | 486 | 3.5625 | 4 | def combine_words(word, **kwargs):
if "prefix" in kwargs:
return "{0}{1}".format(kwargs["prefix"], word)
if "suffix" in kwargs:
return "{0}{1}".format(word, kwargs["suffix"])
return word
print(combine_words("child")) # 'child'
print(combine_words("child", prefix="man")) # 'manchild'
prin... |
d0c20901a2ea5c875f268a206cd074eafb306f2e | KillianWalshe/PE | /5.py | 639 | 3.6875 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
match=0
while match==0:
for num in range(1,1000000000):
count=0
for i in range (1,21):
... |
eb86a94f7bd3cf72a74275dcd08023e987d3177e | shahuji/hello-world | /part-2/s1.py | 2,203 | 3.734375 | 4 | #
# import operator
# print('practical 1')
#
# print("Hello World")
#
# dict = {3: 40, 1: 20, 4: 50, 2: 30, 0: 10}
# print("before editing dict => ", dict)
# dict1 = sorted(dict.items(), key=operator.itemgetter(1), reverse=False)
# print('after editing in ascending order dict => ', dict1)
# dict2 = sorted(dic... |
7bb5f16f017c36e032eb95cbe1d47f26a50c490a | jakobtsmith/team-14 | /PythonScripts/TicTacToe/Board.py | 9,640 | 3.625 | 4 | import random as rand
from os import system
from collections import defaultdict
class BoardEnvironment:
def __init__(self):
"init board"
def set_players(self, AI):
self.AI = AI
self.reset()
def reset(self):
self.turn = 'X'
self.board = list('---------')
i... |
7dc8aa7ef76707d4b9dbb97af7cad34923ec4506 | buribae/aoc-2020 | /01.py | 2,700 | 4.0625 | 4 | from common.util import *
# --- Day 1: Report Repair ---
# After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island.
# Surely, Christmas will go on without you.
# The tropical island has its own currency and is entirely cash-only.
# The gold coins used there h... |
3aa0ab289bfe53bcbc2e72f84a2de0a4d665f3b7 | dubesar/WebScraping | /code/commands.py | 1,285 | 3.8125 | 4 | soup.title
(gives the title tag of the page)
soup.title.string
(gives the string in the title tag)
soup.a
(gives the output - <a id="top"></a>)
So to get all the links on the page we have:
soup.find_all("a")
(This gives all the links on the page)
soup.find_all('table')
(This gives all the tables on the page)
Inord... |
f8d13f48a1dc6474cf4a88d1bba6dec34b59f045 | kewaltakhe/csa1 | /base_conversion_related/setclear.py | 1,550 | 3.75 | 4 | from binary import dtb,btd
def mask_generator(n):
return 1<<n
def main():
num=int(input("Enter a number in decimal <= 65535 :"))
if num>65535:
print("ERROR! Decimal number should be <= 65535.\n\n")
return 0
print("The number in 16 bit binary form is:{0}\n".format(dtb(num)))
print("\t\... |
60aee1f64b4f376e30f153d3e16da773aa8b0e1e | eqtstv/Advent-of-Code-2020 | /day_02/day2_1/day2_1.py | 418 | 3.53125 | 4 | def get_data(filename):
with open(filename, "r") as f:
data = [line.strip() for line in f]
return data
data = get_data("input.txt")
parsed_data = [
[line.split()[0].split("-"), line.split()[1][0], line.split()[2]] for line in data
]
valid = 0
for i in parsed_data:
letter = i[1]
count =... |
6c310fa4948a9ce49ea7d0236b33ed6e0abc91c8 | zabsec/Python101-for-Hackers | /comprehensions_demo.py | 1,605 | 4.65625 | 5 | list1 = ['a', 'b', 'c'] # This is a normal list. From this we can create a list comprehension.
print(list1)
list2 = [x for x in list1] # It iterates over each element in list1 and adds it into list 2. This is called a
# comprehension.
print(list2)
list3 = [x for x in list1 if x == 'a'] # We can add conditionals in... |
0df6a597f689b5bfa7d544a3af9853a3bdbef420 | Lorranysousc/ExerciciosDeRepeticao | /ex14.py | 492 | 4 | 4 | '''Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a quantidade de números impares.'''
num_par = num_impar = 0 #Ambas variáveis iniciam o programa valendo 0.
for cont in range (1, 11):
num = int(input(f'Digite o {cont}º número: '))
if num % 2 == 0:
num_p... |
c5e15c515e4ab2dbbf20f91e38b1546c5c3bcef5 | Lixinran1213/python | /Chapter 7/7.3.1.py | 599 | 3.5 | 4 | unconfirmed_user= ['alice','briand','canndace']
confirmed_user = ['yemao','dali']
#
while unconfirmed_user:
#pop()以每次一个的方式从列表unconfirmed_user的末尾删除用户
#将被删除的用户存在user里
user = unconfirmed_user.pop()
print("verifying user: "+user.title())
#将被删除的用户加到列表confirmed_user里
confirmed_user.append(user)
#循环到unconfirmed_user里没有元素,程... |
da56cfc6f82b42c9b16ac712aaf93e97a08d19d0 | vyasvalluri/Python_Practice | /DiceSimulator.py | 1,063 | 3.6875 | 4 | import random
from os import system
ans = "y"
while ans == 'y':
x = random.randint(1,6)
system("clear")
if(x == 1):
print("---------")
print("| |")
print("| O |")
print("| |")
print("---------")
if(x == 2):
print("---------")
print(... |
20163ed56874b72221e274827ea240c3334c4cf7 | amelialin/tuple-mudder | /Problems/palindrome_in_string.py | 1,590 | 4.25 | 4 | # Write a function to find the longest palindrome in a string.
from palindrome import palindrome
def palindrome_in_string(string):
""" Trying out using doctest.
>>> palindrome_in_string("aba")
'aba'
"""
for i in range(len(string)):
for j in range(i + 1):
substring = string[j:len(string) - (i - j)]
if pal... |
169aacc77484e1c7baa9c81190a0f7081ee87c0c | chammansahu/100days-of-python | /day 1 fundamentals/2variables.py | 350 | 3.75 | 4 | # variable are declared directly without any keyword
#global variable scope
name="chamamn"
age=29
def printAges():
#local scope
#using global keyword
localName="chamamn"
LocalAge=29
#casting of variable
x=str("some value")
y=int(100)
#get the type
print(type(x))
print(type... |
7979918df76db87aad086767513ceeb6f291d552 | AreebHamad/a-level_compsci | /LinkedList_OOP_01.py | 562 | 3.84375 | 4 | class Node():
def __init__(self, data, pointer):
self.data = data
self.pointer = pointer
lengthOfList = int(input("Length of list: "))
linkedList = [Node("", i+1) for i in range(0, lengthOfList)]
freePointer = 0
linkedList[lengthOfList].pointer = None
def addLinkedList(linkedList, freePoin... |
b329740a001807d25868e71032c07fca5fb7345b | hackfengJam/EffectivePython | /di2zhang/test22.py | 526 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__Author__ = "HackFun"
__Date__ = '2017/9/28 11:54'
# # 方法一
# NAME, AGE, SEX, EMAIL = xrange(4)
#
#
# student = ('hackfun', 16, 'male', '1@1.com')
#
# print student[NAME]
# # 方法二
from collections import namedtuple
Student = namedtuple('Student', ['na... |
cfb644388d2e13ef5a5014c8ee44bfb560e034d3 | Kiran-RD/leetcode_solutions | /538_Convert_BST_to_Greater_Tree.py | 1,804 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Using reverse inorder traversal
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
self.curr_sum ... |
d2a8f4e4e1cd8afcc0353abfc6fe6aff9bb4160e | esharma3/Python-Challenge | /PyBank/main-PyBank.py | 1,915 | 3.53125 | 4 |
import os
import csv
revenue, change_in_revenue, date = [], [], []
total_revenue = 0
count = 0
in_filepath = os.path.join('Input & Output', 'budget_data.csv')
out_filepath = os.path.join('Input & Output', 'budget_data_analysis.csv')
with open(in_filepath, newline = '') as in_file:
reader = csv.reader(in_file... |
a93a63a0610b3be5d371a6dca3913196c26e8d31 | lucaspessoafranca/python-exer | /Mundo_1/31_aumentos_Multiplos.py | 523 | 3.875 | 4 | # Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.
salario = float(input('Digite o seu salário:'))
if salario > 1250:
aumento = salario + (salario*0.10)
... |
debe63d349344cf54cc6af5c8172072d16b5e653 | jappanrana/practice | /python/BrainF*ck/using1memory.py | 760 | 4.15625 | 4 | # ord(value) is inbuilt function for getting ASCII value of char
x = input("Enter your string to be printed:")
x = list(x)
currentvalue = 0
# empty list for storing ascii value
asciilst = []
# getting ascii value of every char
for item in x:
asciilst.append(ord(item))
# declaring empty list for storing BF cod... |
5658c65b585356e5eade12097d9df667d54ea0c0 | proTao/leetcode | /1. backtracking/046.py | 616 | 3.671875 | 4 | class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(nums) == 0:
return []
visited = {i:False for i in nums}
def deeper(path):
if len(path) == len(nums):
... |
d582dca5551134f9fad17d83c350e95e272b3a88 | trgomes/estrutura-de-dados | /aula7/merge_sort.py | 1,777 | 3.59375 | 4 | import unittest
def _merge(seq_esquerda, seq_direita):
n_esquerda = len(seq_esquerda)
n_direita = len(seq_direita)
lista_mesclada = [0] * (n_direita + n_esquerda)
i_esquerda = i_direita = 0
while i_direita + i_esquerda < len(lista_mesclada):
if i_esquerda < n_esquerda and (i_direita == n_d... |
8a7e4ab827e50758e0a4129c2d5c69f55cba4714 | Michelmat359/hackathon_python | /kata2/if2.py | 625 | 3.921875 | 4 | '''
Escribir un programa para una empresa que tiene salas de juegos para todas las
edades y quieren calcular de forma automatica el precio que debe cobrar a sus clientes
por entrar. El programa debe preguntar al usuario la edad del cliente y mostrar el precio de la entrada.´
Si el cliente es menor de 4 años puede entr... |
7908e615a7cb72ec98c3163aa81d64a21a7c9862 | mic0ud/Leetcode-py3 | /src/841.keys-and-rooms.py | 1,907 | 3.640625 | 4 | #
# @lc app=leetcode id=841 lang=python3
#
# [841] Keys and Rooms
#
# https://leetcode.com/problems/keys-and-rooms/description/
#
# algorithms
# Medium (61.81%)
# Likes: 677
# Dislikes: 61
# Total Accepted: 56.4K
# Total Submissions: 90.1K
# Testcase Example: '[[1],[2],[3],[]]'
#
# There are N rooms and you star... |
6cb4ecf952e7f331c1de84db64ada117e9a4e213 | zuzanadostalova/Python-for-biologists | /06_Conditional_tests.py | 2,601 | 3.59375 | 4 | # Conditional tests
# print(df["Drosophila melanogaster"][4]) Drosoph. ananassae
# print(df["Drosophila melanogaster"][4][1]) second letter "r" in Drosoph. ananassae
data = open("data.csv")
for line in data:
column = line.rstrip("\n").split(",")
species = column[0]
sequence = column[1]
gene = column[2]... |
3f4d212cb84b70adde0275725133b4106cddcdc9 | hanv698/PythonDjangoLuminar | /designs/sample.py | 115 | 3.625 | 4 | def sub(num1,num2):
#if num1<num2:
#(num1,num2)=(num2,num1)
return abs(num1-num2)
print(sub(10,20)) |
7dc058ecdafb6638b319d64cec6f98906cac81c9 | annekadeleon/Codeacademy-Learn-Python-2 | /A_Day_at_the_Supermarket.py | 708 | 3.9375 | 4 | #list called shopping_list
shopping_list = ["banana", "orange", "apple"]
#dictionary called stock
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
#dictionary called prices
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
#function called compute_bill takes one argument, a list called food... |
84400b981fded289d90bc98cd2bc360c38638286 | adharris/euler | /problems/problems_000_099/problems_030_039/problem_037.py | 1,513 | 3.703125 | 4 |
import click
from tools.primes import unbounded_sieve_of_eratosthenes
from tools.numbers import digit_count
@click.command('37')
@click.option('--verbose', '-v', count=True)
def problem_037(verbose):
"""Truncatable primes.
The number 3797 has an interesting property. Being prime itself, it is
possible... |
6d5382d36d2e8184524f2c3eb771df29e8ebced5 | joshloh/WikiScrape | /src/get_links3.py | 5,593 | 3.546875 | 4 | # Code written by:
# Joshua Loh, Denton Phosavanh
# 2016
# Webcraping
import urllib.request, urllib.error, urllib.parse # Load web page
from bs4 import BeautifulSoup # Easier scraping
from bs4 import SoupStrainer # More efficient loading
# Other
import argparse
import textwrap
import sys
from unidecode import u... |
1c50a574d0b057c5e6692afa6f23c72ad9a53ba8 | Maze-Solving-AI-Team/DevelopmentFiles | /intersection.py | 29,542 | 4.34375 | 4 | '''
=INTERSECTIONS=
intersections solves a maze by marking intersections and paths traveled
blue=intersection
red=path the AI came into the intersection from
green=path the AI has used already(hit dead end and came back to intersection)
- \/ this is repeated until the end \/ -
AI moves until it finds an inte... |
ec5c1f67132ee49f005cbcd923334e483c984434 | moorea8239/cti110 | /M5HW1_Moore.py | 608 | 4.34375 | 4 | #CTI 110
#M5HW1 - Distance Traveled
#10/29
#moorea
#Write a program that displays the distance traveled after the user inputs
#speed and number of hours.
def main():
#have the user input speed of vehicle in mph
milesPerHour = int(input("What is the speed of the vehicle in MPH?: "))
#hav... |
4e61fa92218f561ac7180e945b06a87a0272ec88 | gorahohlov/Python_course | /Python1_lss1/P1_lss1_tsk3.py | 140 | 3.8125 | 4 | # -------------
b = int(input('Введите целое число от 1 до 9: '))
print(b * 3 + b * 2 * 10 + b * 100)
# -------------
|
9cc1ec31e16dc8ffc259d2cc788888d9dda9d248 | LucaOnline/theanine-synthetase | /parse_fasta.py | 998 | 3.875 | 4 | """The `parse_fasta` module exposes functions for reading FASTA files."""
from typing import Iterator, Tuple
def parse_fasta(filename: str) -> Iterator[Tuple[str, str]]:
"""
Parses the FASTA file with the provided filename. Returns
an iterator of tuples, structured with the sequence name
in the first... |
85038eafdfd46210409de3a7ded0cd1f247da93e | AndresFernandoGarcia/Practicals | /Practical 2/Prac2_exceptionsdemo.py | 1,156 | 4.375 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
This error will occur when the input is the right type but an inappropriate value therefore the error appears.
If the input was dog, the int() function tries to convert the string to a number but it can't since the letters
c... |
e9abb38eed2b2beba42ff069d457afa1ac2a3fa9 | Jfeng3/careercup | /Others/insert_in_ordered_circular_linkedlist.py | 2,341 | 4.03125 | 4 | '''
link: http://www.careercup.com/question?id=13273690
user: jfeng
company: Walmart
type: Linkedlist
desc: Insert an element in a ordered (ascending) circular linked list. After inserting return the node with the smallest element.
'''
class ListNode:
def __init__(self,val):
self.val = val
self.next... |
a59f9281c5e32aaf1affc706fa3aa2d58135ccd9 | ultimatumvizz/python50 | /py31.py | 519 | 3.734375 | 4 | # ramanujam numbers-------------these are numbers of kind in which a number can be represented as the pair of sum of 2 cubic numbers
from itertools import permutations
liz=[i for i in permutations(range(1,200),2)]
sumCubes=dict()
raman=dict()
for i in range(0,len(liz)):
a=liz[i][0]**3
b=liz[i][1]**3
if a+b not in s... |
de33940247b998407b926b39b02da0c8609d9e08 | Lingrui/Leetcode | /Algorithms/Easy/Judge_route_circle.py | 331 | 3.828125 | 4 | #!/usr/bin/python
class Solution:
def judgeCircle(self,moves):
'''
:type moves: str
:rtype: bool
'''
return len(moves)%2 == 0 and moves.count('U')==moves.count('D') and moves.count('L')==moves.count('R')
if __name__ == '__main__':
x = str(input("input moves:"))
print("Is it a circle? :",Solution().judgeC... |
7da15d1eba348deafe0ffd6a618d3ffeadb9263a | Srikesh89/PythonBootcamp | /Python Scripts/skyline.py | 451 | 3.859375 | 4 | #Skyline Exercise
def myfunc(string):
skyline_string = ''
string_length = len(string)
current_index = 0
while(current_index < string_length):
if(current_index%2==1):
#do odd letter
skyline_string += string[current_index].lower()
else:
#do even
... |
585b244c094c2ada3452650ea213e9a40b2befdb | stdlibz/PythonTraining | /Devisors | 218 | 3.921875 | 4 | #!/usr/bin/python
def Devisors ( num ):
i = 1
list = []
while ( i <= num ):
if ( num % i == 0 ):
list.append(i)
i+=1
list.append(num)
return list
print Devisors(int(raw_input("Please enter a number: ")))
|
107916219a279eaca959b402a1fee20c69a179df | newkeros/Projet_2 | /parserbook.py | 2,413 | 3.53125 | 4 | """Parse all data needed and put it in a dictionary"""
from request import request
def get_title(article):
"""Return the title of a book"""
title = article.find("div", class_="col-sm-6 product_main").h1.text
return title
def get_product_upc(article):
"""Return the product UPC from a book"""
tab... |
e9c47823e93bb34ac4ff04d266b3c11cb23c2407 | acemodou/Working-Copy | /DataStructures/v1/code/leet/Heaps/sort_k_sorted.py | 2,299 | 3.53125 | 4 | def sortKSortedArray(array, k):
minHeapWithKElements = MinHeap(array[: min(k+1, len(array))])
sortedIdx = 0
for idx in range(k+1, len(array)):
array[sortedIdx] = minHeapWithKElements.remove()
sortedIdx +=1
minHeapWithKElements.insert(array[idx])
while not minHe... |
9285b96e7a8ce6217001078068f5f73beb8c41be | daniel-reich/turbo-robot | /FqFGnnffKRo8LKQKP_5.py | 651 | 3.96875 | 4 | """
**Mubashir** needs your help to filter out **Simple Numbers** from a given
list.
### Simple Numbers
89 = 8^1 + 9^2
135 = 1^1 + 3^2 + 5^3
Create a function to collect these numbers from a given range between `a` and
`b` (both numbers are inclusive).
### Examples
simple_numbers(1, 10) ➞ [1, 2, 3,... |
7c2c89201ae56cc533e38875660eac92d1306d8a | silazor/IS211_Assignment1 | /Assignment1_part1.py | 654 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class ListDivideException(Exception):
"""An error occurred"""
def listDivide(numbers, divide = 2):
cnt = 0
for num in numbers:
if num % divide == 0:
cnt += 1
return(cnt)
def testlistDivide():
try:
prin... |
3eab2b3db912a7efa5c6914e9479eb5227401a32 | danielsunzhongyuan/my_leetcode_in_python | /sqrtx_69.py | 532 | 3.53125 | 4 | class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if 1 <= x <= 3:
return 1
if x in (4, 5):
return 2
start, end = 1, x
while (start + 1 < end):
mid = (start + end) / 2
if mid * ... |
19fc2e99243b186c116bc839e0db8442c25279a4 | law-lee/runestone | /gates.py | 5,434 | 3.796875 | 4 | class LogicGate:
'''A logic gate should contain name and output'''
def __init__(self,n):
self.name = n
self.output = None
def getName(self):
return self.name
def getOutput(self):
self.output = self.performGateLogic()
return self.output
class BianryGate(LogicGat... |
7f87ec226c74829e0639256310d321de0cd42e2b | YajithVishwa/Python-Lab | /poly area.py | 739 | 3.796875 | 4 | class triangle():
def area(self):
a=10
b=20
c=(a*b)/2
print("Area of triangle is",c)
def perimeter(self):
a=10
b=20
c=30
d=a+b+c
print("Perimeter of triangle",d)
class frustum():
def area(self):
import math
pi=m... |
121c33ff9a1cefb2d44eb7005e2accaf19d4645d | saikrishna6415/python-problem-solving | /starnumpyramid.py | 303 | 3.984375 | 4 | n = int(input("enter number : "))
for i in range(1,n+1):
print((n-i)*" ",end=" ")
for j in range(1,i+1):
if i %2==0:
print(str(j)+" ",end="")
else:
print("* ",end="")
print()
# enter number : 5
# *
# 1 2
# * * *
# 1 2 3 4
# * * * * * |
3490e91a6f2cf3cf3af3f835be6b75a90af7644e | Utpal18/LabWork | /LAB WORK 2/positive neg.py | 177 | 4.03125 | 4 | num=int(input('enter num'))
positive=False
if num>0:
positive=True
print(positive)
elif num<0:
positive=False
print(positive)
else:
print('number is zero')
|
c772393eea5a4197c983120eaaecebaf981917ee | jphouminh71/csci1200_ArtOfComputationalThinking | /Labs/Lab 10/Lab10.zip/player.py | 1,197 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 17 00:30:06 2017
@author: ioanafleming
"""
class Player():
def __init__(self, is_human, is_next, total_score, hold_value): #constructor
self.is_human = is_human # a boolean value
self.is_next = is_next # a boolean valu... |
2607028b8a400adbfcbb7ed4505b204bc814d1a9 | lattrellsapon/chatbots | /Old/smartbot/src/webscrape/webscrape.py | 933 | 3.515625 | 4 |
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.aut.ac.nz/study/study-options/engineering-computer-and-mathematical-sciences/courses/bachelor-of-computer-and-information-sciences/software-development-major'
# Opening up connection, grabbing the page
uClient = u... |
aaa4e1b9ded1849555f7d4a912f8a17a7efdceb1 | forever0136789/python-100 | /python-57.py | 393 | 3.6875 | 4 | from tkinter import *
canvas = Canvas(width=300, height=300, bg='green')
canvas.pack(expand=YES, fill=BOTH)
x0 = 263
y0 = 263
y1 = 275
x1 = 275
for i in range(19):
#实际上画的是线段,这里19条连成了一个更长的线段
canvas.create_line(x0,y0,x1,y1, width=1, fill='red')
x0 = x0 - 5
y0 = y0 - 5
x1 = x1 + ... |
9e515f231d03ebdd252ef8057dfe3198c6a7217d | m-wrzr/code30 | /solutions/13/solution.py | 2,459 | 3.609375 | 4 | # solution is not really efficient, workaround with deadline for execution if a partial solution is not promising
# maybe revisit and fix, but the problem is not that interesting imo
from math import sqrt
from itertools import count, islice
import signal
# returns the value of a jamcoin in base x - output as base 10... |
a15c7b9f125b2a9fc451a29deecadead648bae6a | Rushi4001/python-practice-programming | /decorator.py | 325 | 3.921875 | 4 |
def subtraction(a,b):
return a-b
def ourdecorator(fun_game):
return fun_game(1,5) #but we dont want given value not in negative format then we another function in next code
def main():
ret=ourdecorator(subtraction)
print("subtraction is ",ret)
if __name__=="__main__":
m... |
62c946d80e36d2a66d3e9fb37e37b0cc8081813e | JaredJWoods/CIS106-Jared-Woods | /ses8/PS8p3 [JW].py | 576 | 4 | 4 | def examAverage(exam1, exam2):
average = (exam1+exam2)/2
return average
print("Would you like to check your exam average?")
choice = input("Type 'yes' or 'no': ")
print()
while choice == str("yes"):
exam1 = float(input("Enter your score for the 1st exam: "))
exam2 = float(input("Enter your score for the 2nd ... |
eddab909503972bc2ad68924b397033619437227 | LijaAlex12/Python3 | /tuples.py | 270 | 3.59375 | 4 | # tuples
# immutable but member objects may be mutable
x=()
x=(1,2,3)
# parenthesis optional
x=1,2,3
# single item tuple
x=2,
list1=[]
x=tuple(list1)
# del(x[1]) error
# x[1]=8 error
# 2 item tuple:list and int member objects mutable
x=([1,2],3)
del(x[0][1])
print(x) |
878a3fff897acdcec74837286c54734f4a15e92c | johanqr/python_basico_2_2019 | /Semana1/Practica03.py | 402 | 3.609375 | 4 | #Para revisar los tipos de datos
#numero entero
#definir un numero entero
mi_variable = 123456
#ver contenido de variable
print(mi_variable)
#Caso 1
print('El valor de la variable llamada mi_variable es', mi_variable)
#Caso 2
print('El valor de la variable llamada "mi_variable" es', mi_variable)
... |
7c9502ffa7067462bb259e360e5ebeb7ffae7ac7 | JorgeOrobio/COMPUTACION_GRAFICA_2019_2 | /Clases/Clase9/rosa_polar_giro.py | 1,032 | 3.53125 | 4 | import pygame
from libreria import*
#colores
if __name__ == '__main__':
pygame.init()
pantalla = pygame.display.set_mode((ancho,alto))
Puntos = Puntos_A_Pantalla(Rosa_polar(6,200))
pygame.draw.polygon(pantalla, color_aleatorio(), Puntos,3)
pygame.display.flip()
fin = False
while not fin... |
e7f056fd19368a5b0fb2e125f3278aa9cb907450 | deepak8910/python_practise | /tree.py | 748 | 3.671875 | 4 | class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
node0 = TreeNode(3)
node1 = TreeNode(4)
node2 = TreeNode(5)
node0.left = node1
node0.right = node2
print(node0.right.key)
tree_tuple = ((1,3,None), 2, ((None, 3, 4), 5, (6, 7, 8)))
print(tree_tuple)... |
9227303f43bf0f124d5419357a01f2c3d8f33c52 | dbswl4951/programmers | /programmers_level4/도둑질.py | 772 | 3.546875 | 4 | '''
[ POINT ]
1) 첫번째 집을 턴 경우 => 마지막 집 못 털음
2) 첫번째 집을 털지 않은 경우 => 마지막 집 털 수 있음
두 개의 경우로 나눠서 생각해야 함
'''
def solution(money):
# 첫번째 집 턴 경우
dp=[0]*len(money)
dp[0],dp[1]=money[0],money[0]
# 범위에서 마지막 집 제외
for i in range(2,len(money)-1):
dp[i]=max(dp[i-2]+money[i],dp[i-1])
result=max(dp)
... |
90d02e1ee6cc96f1093cd290d2397cbedba18b0a | JohnnyFang/datacamp | /foundations-of-probability-in-python/03-important-probability-distributions/07-smartphone-battery-example.py | 1,054 | 4.5 | 4 | """
Smartphone battery example
One of the most important things to consider when buying a smartphone is how long the battery will last.
Suppose the period of time between charges can be modeled with a normal distribution with a mean of 5 hours and a standard deviation of 1.5 hours.
A friend wants to buy a smartphone... |
b929110288a0919bd57de700743345139eae5e7b | AnmolKhawas/PythonAssignment | /Assignment2/Q6.py | 179 | 4.4375 | 4 | num=int(input("Enter a number:"))
if(num%5==0 and num%3==0):
print('The given number is divisible by 3 and 5')
else:
print('The given number is not divisible by 3 and 5')
|
55ecef47e8d569f7ceb5a10847a6ccbe30bd8dbc | pyCERN/algorithm | /UVa/10000-/11000-11099/11060.py | 1,317 | 3.640625 | 4 | # Topological Sort
from collections import deque
def topsort(queue, in_edge, out_edge):
for key in in_edge.keys():
if in_edge[key] == []:
queue.append(key)
while queue:
queue = sorted(queue, key=lambda x: bev_order[x], reverse=True)
bev = queue.pop()
print(' ' ... |
7f81fe997557159ebcc69bc983c2822bf03f7893 | windanger/Exercise-on-internet | /25.py | 263 | 3.859375 | 4 | #题目:求1+2!+3!+...+20!的和。
#程序分析:此程序只是把累加变成了累乘。
def resut(i) :
total = 1
while i :
total = total * i
i -=1
return total
adds = 0
for i in range(1,21) :
adds += resut(i)
print(adds) |
49b12030a56d3acf17cc8b07a2e71816b8d50946 | aboubakrs/365DaysofCode | /Day13/Day 13 - Exo4.py | 499 | 4.125 | 4 | #Les Fonctions avec Paramètres !
print("Exercice : C'est ma Premiere Fonction avec Parametre")
#Définition Fonction
def tableMultiplication(inVariant):
print("La table de Multiplication par ", inVariant)
n = 1
while(n <11):
print(inVariant, "*", n, "=", inVariant*n)
n = n + 1
#Utilisation ... |
0a0ca9327a6eb0e1da13c5e6164900e12277c493 | RochesterinNYC/Project-Euler | /euler_5.py | 624 | 3.5 | 4 | import euler_ops
import sys
import math
number_max = 20
increment = euler_ops.mult_primes(number_max)
count = increment
min_divisor = math.floor(number_max / 2)
divisor = 0
is_evenly_divisible = False
current_divisible = True
while is_evenly_divisible is False:
current_divisible = True
divisor = min_divisor
... |
e7471a9cfaae9a394955bd8c829068c02ba02167 | HLAvieira/Curso-em-Video-Python3 | /Pacote-download/aulas_python_cev/ex_29_multa_km.py | 207 | 3.765625 | 4 | velocidade = float(input('Digite a velocidade do carro em Km/h ::::: '))
if velocidade > 80.0:
print('você foi multado em R${:.2f} '. format((velocidade-80.0)*7))
else:
print('Velocidade permitida') |
c30732766a93210946afd895b1a4c982de45b489 | rjcmarkelz/QB3_Python_Course | /ex3.2.1.py | 4,174 | 4.03125 | 4 | delimiter = ","
string_to_split = "I am a well-written sentence, and so I \
dependably have punctuation. "
list_from_string = string_to_split.split(delimiter)
print "clause one %s" % list_from_string[0]
print "clause two %s" % list_from_string[1]
###
list_from_string = string_to_split.split(' ')
for word in list_from... |
01789d46c1ad86d62f861f304161d73c6a85c8e8 | Chethanr2/pro1 | /Excerise/argv.py | 332 | 3.546875 | 4 | n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
count = 0; sum = 0
avg = student_marks[query_name]
for i in avg:
count = count + 1
sum = sum + i
val = sum / count
print("{:.2f}".... |
32ace55d77aa28e2744c4785053be6d6874e833d | abobakrh/Problem-Solving | /odd_even_linklist.py | 746 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
is_odd = True
odd_list = ListNode(0)
odd_head = odd_list
even_li... |
3a75c782311cca7c22ea8fd36e2824a567c199a7 | ltrujello/Rational_Series | /rational_interpolating_functions.py | 2,448 | 3.609375 | 4 | import math
from loewner_matrix import rational_interpolate
from polynomials_and_series import p_over_q_vals, series
from decimal import *
def rational_interpolate_function_vals(x_data, p, q, return_approximation = False):
'''
Let x_data = [x_1, x_2, ... , x_n]. Let p, q be some functions.
This function a... |
3739d789f66541308c07ac8c4a2ccfdcfba110a3 | ShuweiLeung/Accurate-Positioning | /Positioning.py | 1,246 | 3.578125 | 4 | #Premise: suppose data is stored in JSON file.
import json
import geoip2.database
class Geo:
def obtainGeo(self, path):
"""
:param path the file path of your JSON file
:return:
"""
input = open(path, "r")
for line in input:
obj = json.loads(line)
ip = obj["ip"]
#load exte... |
a417b8085ba4b75ce5421b90016231ba75a53733 | ironboxer/leetcode | /python/1109.py | 1,951 | 3.625 | 4 | """
https://leetcode.com/problems/corporate-flight-bookings/
1109. Corporate Flight Bookings
Medium
555
105
Add to List
Share
There are n flights, and they are labeled from 1 to n.
We have a list of flight bookings. The i-th booking bookings[i] = [i, j, k] means that we booked k seats from flights labeled i to ... |
d8ce865ec0ffd3f50f33679d5e2c27f0d0749607 | akotwicka/Learning_Python_Udemy | /dziedziczenie.py | 1,825 | 3.6875 | 4 | class Cake:
bakery_offer = []
def __init__(self, name, kind, taste, additives, filling):
self.name = name
self.kind = kind
self.taste = taste
self.additives = additives.copy()
self.filling = filling
self.bakery_offer.append(self)
def show_info(self):
... |
6f6a6dde82e4c5507fb1b2691a62ff1645dd5849 | Vk-Demon/vk-code | /ckcompany16.py | 376 | 3.546875 | 4 | nnum=int(input()) # Given a number N and array of N integers, print the difference between the indices of smallest and largest number(if there are multiple occurances, consider the first occurance).
lt=[int(i) for i in input().split()]
for i in range(0,nnum):
if(lt[i]==max(lt)):
x=i
break
for i in range(0,nn... |
88f1829d01b84a9e2f26ccbc72a08abdd5e5c706 | asefrind/madlib-shapedraw | /ShapeDraw.py | 968 | 4.1875 | 4 | # Shape Drawing
def TriangleDraw():
print(" /|")
print(" / |")
print(" / |")
print(" /___|")
def SquareDraw():
print("----------------")
print("| |")
print("| |")
print("| |")
print("| |")
print("-... |
0e7f5c15b99aa1fb921652ac76e83d216db9f506 | WinrichSy/Codewars_Solutions | /Python/6kyu/TotalPrimes.py | 1,339 | 3.984375 | 4 | #Total Primes
#https://www.codewars.com/kata/5a516c2efd56cbd7a8000058
import math
import itertools
#Used for caching values
primed = {}
def is_prime(num):
maximum = math.ceil(math.sqrt(num))
if num%maximum == 0:
return False
for i in range(3, maximum, 2):
if num%i == 0:
return... |
c2502c543ef130a14513bc9f8134d7f4c4358718 | Olga404/Node | /main.py | 7,643 | 4.0625 | 4 | class Node():
def __init__(self,value, next_node=None):
self.value = value
self.next_node = next_node
#print(self.value)
def print_list(lst):
tmp=lst
while tmp.next_node!=None:
print (tmp.value,end='->')
tmp=tmp.next_node
print (tmp.value)
def print_rec(lst):#рекурсивно обращается к по... |
15b7d4632ed2c70f90d48d42f3223414e0ad0373 | PC-coding/Exercises | /data_structures/linked_lists/2_search_item/solution/solution.py | 455 | 3.96875 | 4 | # Write your solution here
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class linkedList:
def __init__(self, head=None):
self.head = head
def search(self, x):
current_node = self.head
while not current_node is None:
if curr... |
b10f23f87c3eee2b27adefca83d7d6886ad4b88c | BlackBloodLT/URI_Answers | /Python3/1_INICIANTE/uri1002.py | 880 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Área do Círculo
A fórmula para calcular a área de uma circunferência é: area = π . raio2.
Considerando para este problema que π = 3.14159:
- Efetue o cálculo da área, elevando o valor de raio ao quadrado e
multiplicando por π.
Entrada
A entrada contém um valor de po... |
e0d4bcf086f5186be4855598622a6936796c9360 | jnoriega3/final-project | /new.py | 1,619 | 4.21875 | 4 | import random
from random import shuffle
words=("github", "shell", "bacon", "variables", "boolean values", "operators", "functions", "lists", "the none value", "global scope", "for and while loops", "in and not operators")
#Codinng Joke (meant for word scramble ...My code is not working, I have no idea why---M... |
73e03491435f4f8de13335c2bde385df516d90b0 | iulian39/UBB | /1st year/First Semester/Fundamentals of programming - python/Lab5-7/BookClass.py | 8,870 | 3.71875 | 4 | import copy
class Book:
def __init__(self, repo):
self.__repo = []
self.__availableBooks = []
self.__repo = copy.deepcopy(repo)
self.__availableBooks = copy.deepcopy(repo.getAll())
def AddNewBooks(self, ID, title, description, author):
'''
Adds a new book to th... |
b62b47d5fce39cc1310af6f1d3be347ca2e15baa | ArpanMajumdar/tech-knowledge-base | /languages/python/python-examples/src/formatting_and_linting_demo.py | 240 | 3.609375 | 4 | # Type hints
def print_hello(name: str) -> str:
"""
Returns a greeting message
:param name: Name of person
:return: Hello message
"""
msg = "Hello " + name + " !"
print(msg)
return msg
print_hello("Arpan")
|
3f8a0444948177807771a6134dfdf5a026f91c0d | DJSiddharthVader/PycharmProjects | /PythonPractice/2. Even or Odd.py | 935 | 4.3125 | 4 | '''Ask the user for a number. Depending on whether the number is even or odd, print out
an appropriate message to the user. Hint: how does an even / odd number react differently
when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two numbers: one number... |
b84b69e4445cac8c2923c8f474ba1ba48120c3a6 | schwerdt/Yahoo_and_API | /exercise1.py | 3,568 | 3.9375 | 4 | import urllib
import sys
import csv
import datetime
#The base url for yahoo finance to get stock prices is stored as a global
#Update it here if it ever changes
yahoo_url ="http://real-chart.finance.yahoo.com/table.csv?s="
def compute_stock_data():
#Ask the user for a ticker symbol, starting and ending dates
ti... |
47a2d5d72dd29ea7c960619de24a87a5b4e4a2c2 | nightjuggler/puzzles | /honeycomb.py | 3,045 | 3.96875 | 4 | #!/usr/bin/python
#
# This is a constant time solution to the honeycomb cell distance puzzle at https://affirm.com/jobs
# by Pius Fischer -- March 1, 2013
#
import math
import sys
def get_xy_for_cell(cell):
assert isinstance(cell, int) and cell > 0
# Determine which ring the cell is located in.
# Ring 0 consists o... |
00d4f0bc4f4deb099352d73d9084f2bdafe0c94b | kathuman/Python3_Essential_Training | /04 Syntax/syntax-objects.py | 701 | 4 | 4 | #!/usr/bin/python3
# syntax.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Egg: #class is like a blue print, which defines how the object is created.
def __init__(self, kind = 'fried'): # this is a constr... |
9b82bb8c64299540e0bb9659d1944cac8c0370dc | Graziellah/BootCampPython | /d01/ex00/book.py | 1,303 | 3.671875 | 4 | from recipe import Recipe
import datetime
import time
class Book:
def __init__(self):
self.name = ""
self.last_update = ""
self.creation_date = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
self.recipes_list = {
"starter": {},
"lunch": {},
... |
8c7032d85476c0f3d4d4d80c3d58e953e16d30f9 | volkir31/university | /lab1/31_task.py | 264 | 3.90625 | 4 | max_digit = 0
index_of_digit = -1
max_digit_index = -1
while True:
digit = int(input())
index_of_digit += 1
if digit > max_digit:
max_digit = digit
max_digit_index = index_of_digit
if digit == 0:
break
print(max_digit_index) |
453dd5c39ad68db8772b6c6b42c72055d6324a1f | UmangAgrawal1998/cancer | /SpeechAVA.py | 482 | 3.859375 | 4 | #Importing the Pyttsx3 module for text to speech conversion
import pyttsx3
#Function to convert text to speech passed as value
def speech(text):
engine=pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
rate = engine.getProperty('rate')
engine.setProperty... |
77db21342482e78e1960c72c312b72e7be1abb56 | irakliintskirveli/python-challenge | /ananlyzePyPoll/main.py | 487 | 3.640625 | 4 | import os
import csv
# Files to load (Remember to change these)
file_to_load = "election_data_2.csv"
#open the csv file
with open(file_to_load) as election:
reader=csv.reader(election)
#skipp headers, 1st row
#Set empty list variable
next(reader)
totalvotes = [ ]
#loop through the row to count vote ID
for r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.