blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1a4bcb85cad52e4d3451c2e599e08481c15b3331 | mkaye5/LSCodingClub | /ls_coding_club_tkinter_tutorial_STUDENTS/character/character.py | 1,876 | 4.09375 | 4 | from PIL import ImageTk, Image
class Character():
def __init__(self, c, coords, type="circle", image="none"):
""" initializes an object of the Database class.
Parameters
----------
root : the tk class object defined
canvas : the canvas made
... |
b0a73287851bdf326b3c2c57dbe4f0053d6fa13e | HuzaifaHussain/CS5590PythonDeepLearning2018 | /Source code/task_1.py | 444 | 3.71875 | 4 | print('UMKC Library and Book shop\n')
Dictionary = {'python':50,'web':30,'c':20,'java':40}
list_A = list(Dictionary.values())
list_B = []
list_C = []
print('Please provide your range:')
Low = int(input('Low price :'))
High = int(input('High price:'))
for i in range(Low,High+1):
list_B.append(i)
for name, ite... |
37ac21685bae1ee8d237a0b5b3662b91060f8b18 | liuzhipeng17/python-common | /python基础/面向对象/继承/super函数用法.py | 1,704 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# 需求:子类调用父类的init方法
# 在子类的__init__调用父类的__init__,这种简单的情况当然是可以的,但是许多情况下会出现问题
# 应该采用super(),super可以调用父类的任意函数,不仅仅__init__
# 使用super()的形式:super(当前所在类名字,self对象).父类函数(该函数的参数,不要self)
# super(TimesFiveCorrect, self).__init__(value)
class MyBaseClass(object):
def __init__(self, value):
sel... |
ee9a1214dc50e023a59eb8d5a329aa1694e6e558 | Conquerk/test | /python/day06/code/lianxi6.py | 235 | 3.65625 | 4 | l=[]
l1=[]
l2=[]
while True:
x=int(input("输入整数:"))
if x==0:
break
l+=[x]
print("整数列表:",l)
l1=[x for x in l if x>0]
l2=[x for x in l if x<0]
print("正数列表:",l1)
print("负数列表:",l2) |
e0b94e3f32f23a8ca34070b77085d9f51c0960a2 | 1930346/Calendar-In-Python | /Calendario.py | 8,905 | 3.765625 | 4 | import os
from io import open
class Calendario(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
pass
#SETTERS -----------------
def setDay(self,day):
self.day = day
pass
def setMonth... |
15a95546b40f6881c08f6354f9bd3fe862fb87ed | Linda-Kirk/cp1404practicals | /prac_05/word_occurrences.py | 651 | 4 | 4 | """
CP1404/CP5632 Practical
Word Occurrences
"""
user_string = input('Text: ')
words = user_string.split()
print(words)
words_dictionary = {}
for word in words:
count_of_word = words_dictionary.get(word, 0)
if count_of_word is None:
words_dictionary[word] = 1
else:
words_dictionary[word] = ... |
9c4c365359227d78049871ee14590dd1f7122a68 | YANG007SUN/hackerrank_challenge | /medium/climbing_the_leaderboard.py | 546 | 4.15625 | 4 | # https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
# ===============================================================
# The key to this question is to add while loop inside for loop
# ===============================================================
def climbingLeaderboard(ranked, player):
# W... |
45d04c4ecf88273aa3e9e55c6bd36bb72e31ecff | Includegirl/pythonWorkshop | /session4/1_functions.py | 1,129 | 3.953125 | 4 | #Una función nos permite reusar piezas de código
##### EJERCICIO 1 #####
# Corre el siguiente código:
# http://bit.ly/1EG9hjy
# Discute con tus compañeros en la mesa
# qué pueden entender del código
# Sintaxis de una función
# La cabecera ('header') de una función, la cual incluye
# la pralabra reservada 'd... |
bcd82d8b718011e67c8fc17357441fe19ea00591 | ahpehgit/python-scripts | /exercises/py1.py | 345 | 3.890625 | 4 | temperatures = [10, -20, -289, 100]
def c_to_f(c):
if c < -273.15:
return "That temperature doesn't make sense!"
else:
f = c* 9/5 + 32
return f
with open("example.txt", "w") as myfile:
for t in temperatures:
tmp = c_to_f(t)
if type(tmp) == float:
myfile.write(str(tmp))
... |
be0a487a014ab9163f4f2ae8e27aea4d37ae3e5a | CarloShadow/CodesByCJ | /Python/Exercicios/Estruturas de repetição/Exer6.py | 168 | 3.859375 | 4 | soma = 0
for _ in range(1, 6):
num = int(input('Digite o número: '))
soma = soma+num
med = soma/5
print(f'Resultado: {soma}')
print(f'Média: {med:.0f}')
|
c9259ffb9f61de7c9530a3eea2a378970d4732c2 | sakiii999/Python-and-Deep-Learning-Lab | /Python Lab Assignment 1/Source/LA1_2.py | 674 | 4.15625 | 4 | sentence=input("Please enter the sentence: ")
list1=sentence.split()
var1=len(list1)
# If the input list is even,then the below if block is executed
if(var1%2==0):
x=var1/2
y=int(x-1)
print(list1[y]+" "+list1[y+1])
# If the input list length is odd,then the below else block is executed
else:
x=int(var1/... |
39b0b79626abc0fd55afe6975887a34edbbd0080 | kobaltkween/python3 | /Lesson 06 - Compiling and Flagging Regular Expressions/Homework/ccnSafety.py | 443 | 3.75 | 4 | import re
def ccnReplace(txt):
"""Return input text with phrase 'CCN REMOVED FOR YOUR SAFETY'
substituted for all but the last four digits of any credit
card numbers in the text."""
regex = re.compile(r"""
(\d{4}-){3} # 3 multiples of 4 digits followed by a dash
\d{4} ... |
112fae708ebfa128728e63e5ad8972cb9b1b6c4f | masoom-A/Python-codes-for-Beginners | /str_namespace.py | 211 | 4.125 | 4 | string=input("enter the string")
len=len(string)
for char in range(0,len):
#print(string[char])
if string[char]==' ':
print(string[char-1])
print(string[-1])
|
948fb8cd95591bd0b30999e2d29530f72dbc9d9a | anjalinirupa/NetPET | /NetPetExe/DJ.py | 1,889 | 4 | 4 | def main():
x=input("Enter Number of nodes: ")
y = input("distance from a to b: ")
z = input("distance from a to c: ")
v = input("distance from a to d: ")
w = input("distance from b to c: ")
u = input("distance from b to d: ")
t = input("distance from c to d: ")
graph = {'a':{'b'... |
c7e6e2a67d32e6b0e58c8a12fdc5bbd2a729b477 | JFincher42/PyMasterMind | /mastermind.py | 4,299 | 4.09375 | 4 | '''
Created on Oct 21, 2017
@author: jon
'''
# Imports
import random
# Program Constants
NUMBER_OF_DIGITS = 4 # How many digits is the secret code?
MAX_DIGIT = 6 # What is the largest digit we will use?
ALLOW_DUPES = False # Do we allow duplicates?
ALLOW_BLANKS ... |
3733c9004d429c9a091620d66af020cc434e085f | brandeddavid/MSFT-Cognitive-Services | /MSFT Translation API/clonedict.py | 2,341 | 3.59375 | 4 | """
Example application showing the use of the Translate method in the Text Translation API.
"""
from xml.etree import ElementTree
from auth import AzureAuthClient
import requests
import csv
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def GetTextAndTranslate(finalToken):
fromLangCode = "en"
... |
06da5fa654f7ad20c5c5c7d10058a847bf5fe1bf | AppliedAlpha/BOJ | /Submitted/13xxx/13705.py | 1,415 | 3.8125 | 4 | from decimal import *
getcontext().prec = 200
getcontext().rounding = ROUND_HALF_UP
pi = Decimal('3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446... |
934a0691629dfd1ac324cdd87c6583bba102358e | a-packer/python_syntax_practice | /24_remove_every_other/remove_every_other.py | 494 | 4 | 4 | def remove_every_other(lst):
"""Return a new list of other item.
>>> lst = [1, 2, 3, 4, 5]
>>> remove_every_other(lst)
[1, 3, 5]
This should return a list, not mutate the original:
>>> lst
[1, 2, 3, 4, 5]
"""
index_to_remove = range(0,len(lst),2)
new... |
e5b43cc993114db49af410b4d0601474f4778ecb | tetyorkin/Netology_Advance_PY | /1.3.Function2.0.args.kwargs/main.py | 2,737 | 3.625 | 4 | class Contact:
def __init__(self, name, last_name, phone, favorite=False, **kwargs):
self.name = name
self.last_name = last_name
self.phone = phone
self.favorite = favorite
self.kwargs = kwargs
def __str__(self):
user = {'Имя': self.name, 'Фамилия': self.last_na... |
49a1ef566e38daebf282aa2830692e8c83453a68 | hannes1903/Homework-and-Exercises | /vector_sub.py | 606 | 3.546875 | 4 | import math
import statistics
v1=[3, 5, 1]
v2=[6, 1, 8]
def vector_sub(v1, v2):
return [e1 - e2 for e1, e2 in zip(v1, v2)]
print(vector_sub(v1, v2))
v=[1,4,5,7,]
s=3
def scalar_mul(v, s):
return [e*s for e in v]
print(scalar_mul(v, s))
a=[1, 2, 3]
b=[4, 5, 6]
#sum of elementwise multiplications
def ... |
f4b137f40c81f579c75ffaf3dddefbb2901f833f | JFWCode/py-basic-app | /base/sort/insert_sort.py | 334 | 4.03125 | 4 | def insert_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
if __name__ == '__main__':
arr = [12, 213, 32, 324, 21, 2, 2, 0]
print(inse... |
048d042f4b588ab088c94b4365518cddaea47e7d | SergioGL8/Web-scraping-challenge | /Missions_to_Mars/scrape_mars.py | 4,650 | 3.734375 | 4 | # Misson to Mars
# Step 1 - Scraping
# -----------------
# Get the latest [NASA Mars News](https://mars.nasa.gov/news/) by scraping the website and collect the latest news title and paragragh text.
# Import Dependencies
import pandas as pd
from splinter import Browser
from bs4 import BeautifulSoup as bs
import datet... |
bd5daefdfaf57ba13543358499306479c8151b25 | DiegoEArriagaM/Curso-Python-J | /Hoja Trabajo 0.py | 320 | 3.84375 | 4 | print("Calculo del Indice de masa corporal (IMC)")
#Peticion del peso y la altura
peso=float(input("Por favor ingrese su peso en Kilogramos: "))
altura=float(input("Por favor ingrese su altura en metros: "))
#Calcular IMC
imc=peso/(altura**2)
#Mostrar el resultaro
print("Tu índice de masa corporal es ",round(imc,2)) |
db5feb45184bd25c419a21ac51ac6372c178cf63 | RAMKUMAR7799/Python-program | /Beginner/sumKnum.py | 101 | 3.65625 | 4 | var=[]
num=int(input("Enter the Number:"))
for i in range(0,num+1):
var.append(i)
print(sum(var))
|
87a6cb94e4572b02389f4b7d028c48f20f365463 | kojicovski/python | /exercises/ex85.py | 385 | 3.6875 | 4 | import random
num = []
li_even = []
li_odd = []
for i in range(7):
#add_num = int(input("Type a number"))
add_num = random.randint(1, 10)
if add_num % 2 == 0:
li_even.append(add_num)
else:
li_odd.append(add_num)
num.append(li_even[:])
num.append(li_odd[:])
print(f"Full list: {num}")
... |
fee4423a6420dae49b75d84ab58d3786f0d25461 | kanyu/61as | /schython/memoize.py | 518 | 3.78125 | 4 | # def __fib(x, memo):
# if x <= 1:
# return x
# else:
# return memo(x-1) + memo(x-2)
# def __factorial(x, memo):
# if x <= 1:
# return 1
# else:
# return x * memo(x-1)
def memoize(func):
d = {}
def memo(num):
if num in d:
return d[num]
else:
... |
41bae6481bf4d06f0950f00aeb2ce5087d1eb34d | madeibao/PythonAlgorithm | /PartC/py字符串的全排列.py | 212 | 3.78125 | 4 |
from itertools import permutations
string = list(input())
string.sort()
for item in permutations(string):
item = ''.join(item)
print(item)
print('')
# abc
# 输出结果:
abc
acb
bac
bca
cab
cba
|
eb8077087c6167e70e1be7b4706a1a67b0e18710 | maiconsaraiva/estudos_python | /colecao_tupla.py | 4,454 | 4.625 | 5 | """
Tupla (tuple)
Tuplas são bastante parecidas com listas.
Existem basicamente duas diferenças:
- As tuplas são representadas visualmente por parenteses (). É uma diferença visual
- As tuplas são imutáveis. Ou seja, é como se a tupla fosse uma constante de uma lista.
Uma vez que uma tupla é criada, não é possí... |
beab4c74bc9a51817fea5e7e4ea54aed4a5b4dca | Inferno-Dragon/Finance-Calculator | /finance_calculator.py | 1,836 | 4.40625 | 4 | # Finance Calculator
# This is a finance calculator depending on users input it will calculate total investment or bond costs.
# Printed out phrase
print("Choose either \'investment\' or \'bond\' from the menu below:\n"
"investment - to calculate the amount of interest you'll earn on interest:\n"
" bond ... |
035fa334002eb261876da4ac3bfca2d329e19e49 | anagha1999/CD-Project | /video_test_files/AST2.py | 79 | 3.875 | 4 | x=3
if(x <5):
print("small")
elif(x==5):
print("med")
else:
print("large")
|
e97f2df8cb046a0c7809b053d65155fe42bcd631 | PrimeshShamilka/mono_alphabetic_cipher | /monoalphabetic_cipher.py | 1,022 | 3.71875 | 4 | import sys, random
def converter(key,plain_text, mode, letters):
if mode == 'encrypt':
translated = encryptMessage(key, plain_text, letters)
elif mode == 'decrypt':
translated = decryptMessage(key, plain_text, letters)
return translated
def encryptMessage(key, message, letters):
... |
1a1c79dcf30da9672e38e650166a8e1c95bce194 | Casper-Smet/Paxos-Simulation | /lib/classes/network.py | 1,175 | 3.640625 | 4 | from classes.message import Message
class Network(object):
"""Network class for Paxos simulation."""
def __init__(self):
"""Initialiser for Network class."""
self.q = []
def queue_message(self, m: Message) -> list:
"""Adds Message m to back of queue.
:param m: Message
... |
f402457f87b788ea818d05e7276bfe2526f0a10c | Ramaiml/Ram_Projects | /objects/kingdom.py | 932 | 3.828125 | 4 | class Kingdom:
"""Defines a Kingdom.
:param name: Name of the kingdom
:param emblem: Emblem of the kingdom
:type name: str
:type emblem: str
"""
def __init__(self, name, emblem):
self.name = name
self.emblem = emblem
self._allies = set()
def send_ally_invite(se... |
da25a6153cdba2ba3d18b536cdb46d0b3d7d207a | chae-heechan/Python_Study | /5. 제어문/onelinefor.py | 443 | 3.875 | 4 | # 출석번호 1 2 3 4, 앞에 100을 붙이기로함
students = [1, 2, 3, 4, 5]
print(students)
students = [i+100 for i in students]
print(students)
# 학생 이름을 길이로 변환
students = ["Iron man", "Thor", "I am groot"]
print(students)
students = [len(i) for i in students]
print(students)
# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am gro... |
5fc2d9f782b2bd95a5ff9ebcffe61da420bd275e | grisha-dd/python | /lesson-2/2.3.py | 1,213 | 4.0625 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12. Сообщить к какому времени года относится месяц (зима,
# весна, лето, осень). Напишите решения через list и через dict.
month_list = ["январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август",
"сентябрь", "октябрь", "ноябрь", "дека... |
57950cea3e295b23da39e7c960ce3f5caf7c2353 | SunggookCHOI/algorithm | /programmers/lv3. 가장 긴 팰린드롬/solution.py | 421 | 3.53125 | 4 | def check(string):
string_len = len(string)-1
for i in range(len(string)//2):
if string[i] != string[string_len - i]:
return False
return True
def solution(s):
answer = 0
for i in range(len(s)):
for j in range(len(s)-1,i-1,-1):
if j-i+1 < answer : break
... |
0c98bdbd08c47c4cf5deebf0edffdd47895e03a4 | pmleveque/snippets | /exos/anagram.py | 811 | 4.28125 | 4 | """
Anagram
(A word, phrase, or name formed by rearranging the letters of anothe)
Give a list of strings, return a list of anagram sets just from the original input.
Example:
Input: ['cat', 'tablet', 'wolf', 'act', 'battle', 'flow', 'batlet', 'food']
Output: [['cat', 'act'], ['tablet', 'battle', 'batlet'], ['w... |
b0d99b703ee7f8c697a08a61902c5f3dfbffc508 | Clebom/exercicios-livro-introd-prog-python-3ed | /capitulo-09/ex09.py | 733 | 3.75 | 4 | # Crie um programa que receba uma lista de nomes de arquivo e os imprima, um por um
# fileList = ['ex01.py', 'ex02.py', 'ex03.py']
#
# for file in fileList:
# with open(file, 'r', encoding='utf-8') as archive:
# print(f'\nARQUIVO: {file + " ":-<91}')
# for line in archive.readlines():
# ... |
c8076134953d413b00d4ca26d5feca2e5e22fefc | weiguangjiayou/LeetCode | /LeetCode/LeetCode48rotate-image.py | 689 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File : LeetCode48rotate-image.py
@Author: sladesha
@Date : 2019/10/25 22:30
@Desc :
'''
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place ins... |
85613a1bf0fecf3b825c8247bc45cdf06db07210 | michoricardo/MichiganUniversityPythonMicho | /lecture6.2_pythonDataStructures_MetodosClaseSTR.py | 559 | 3.90625 | 4 | #Los metodos de la clase str
name='RiCaRdO'
print(name.lower())
print(name.upper())
if 'RI' in name:
print('si estoy!')
else:
print('No estoyyy')
posicion = name.find('d')
print(posicion)
replace=name.replace('R','F')
print(replace)
stringCespacios= ' Richi ' # 4 espacios antes y 2 despues
print(stringC... |
1594f4fbc5704c154fff3920b156c90f0489ec4d | WhiteBrownBottle/LeetcodeDaily | /easy/111.py | 997 | 3.75 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
depth_l = []
depth_r = []
def returnD... |
507dbc5547a8c7f22cb8e9a201b1697b5ab6f908 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/5ede767669d6478d876b134fcd2e788a.py | 649 | 3.90625 | 4 | #
# captainnurple's code for the Python "Bob" exercise.
#
def hey(what):
# Start by cleaning leading and trailing whitespace
what = what.strip()
# Now process for response.
# First test for empty string. If it's empty we're done
if not what: # empty strings are 'falsy'
return 'Fine. Be that... |
854f87ac086dfda2c929a41f1e7a532fd2b8c907 | hscaizh/programmer-on-the-way | /codility/lesson13/CountTriangles.py | 671 | 3.765625 | 4 | '''
题目:
这道题前面的课程似乎出现过
求一个数组中任意3个元素满足三角形两边之和大于第三边的个数,注意这里不需要考虑边长>0
时间复杂度要求 O(N^2)
思路:
排序之后从前往后扫,具体见代码
复杂度分析:
排序 O(N*log(N))
平摊分析 O(N^2)
共O(N^2))
实现见代码.
解题地址: https://codility.com/demo/results/demoF32ZZ7-8TX/
'''
def solution(A):
A.sort()
n = len(A)
result = 0
for x in xrange(n):
z = x
... |
744c1974e09f14c1bf3ce0031bf99e158f53460f | vasu-kukkapalli/python_git | /Udemy/forCountinuoeBreak_2.py | 611 | 4.09375 | 4 | ## for ... continue -> it prints out all letters of the string without 'o'
for letter in 'Python Go and Java Cobol':
if letter == 'o':
continue # go to the beginning of the for loop and do the next iteration
print(letter, end='')
## for ... break
sequence = [1, 5, 19, 3, 31, 100, 55, 34]
for item in s... |
23492510e537e9e9e85d655b94c4ad3d53299572 | adrianflatner/ITGK | /7AdrianFlatner/øving7/krypto.py | 847 | 3.578125 | 4 | import binascii
import random
def toHex(word):
return int(str(binascii.hexlify(word), 'ascii'), 16)
def toString(word):
return str(binascii.unhexlify(hex(word)[2:]), 'ascii')
def binary(msg):
msg = bytes(msg, encoding = 'ascii')
return msg
def encrypt(message,key):
m = toHex(bina... |
b56f70627255d921799b0250b61c7b5fd046520c | ShunKaiZhang/LeetCode | /integer_replacement.py | 954 | 4.3125 | 4 | # python3
# Given a positive integer n and you can do operations as follow:
# If n is even, replace n with n/2.
# If n is odd, you can replace n with either n + 1 or n - 1.
# What is the minimum number of replacements needed for n to become 1?
# Example 1:
# Input:
# 8
# Output:
# 3
# Explanation:
... |
64d86304b6775dc7b6dd9f16fc8acb11d9c78c8a | effyhuihui/leetcode | /uncategoried/pascal.py | 774 | 3.953125 | 4 | __author__ = 'effy'
'''
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
'''
class Solution:
# @param {integer} numRows
# @return {integer[][]}
def generate(self, numRows):
if numRo... |
8440dc55d618d76a5fac69926762f04ffb1fc307 | getabear/leetcode | /35. 搜索插入位置.py | 710 | 3.890625 | 4 | from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l,r=0,len(nums)-1
while l<=r:
mid=l+(r-l)//2
if nums[mid]==target:
return mid
elif nums[mid]<target:
l=mid+1
else:
... |
d8c6ba391f0854944f7334c4245d15e78c8c7834 | abdullahawan/cis125 | /loopAssignment/loop10.py | 222 | 3.71875 | 4 | # Muhammad Awan
# Loop Assignment #10
tuition = 6000.00
tuitionRaised = 0.02
for x in range(5):
tuition = (tuition * tuitionRaised) + tuition
print('Tuition for a semester in year', x + 1, 'is %.2f' % tuition)
|
d42daf57fd306d8fe5c382360cafbff3657af644 | tugrazbac/sorting_algorithm | /sorting_stacks.py | 1,214 | 3.65625 | 4 |
## Function
#
def PopPush(s1, s2):
if(not s1):
return False
item = s1.pop()
s2.append(item)
def Compare(s1, s2):
if(len(s1) == 0):
return False
if(len(s2) == 0):
return True
if(s1[-1] > s2[-1]):
return True
else:
return False
## Main
#
#S1 = [6,5,4,3,2,1] #11 Schritte
#... |
217f3cd6ff0a2b1a854efeb16dd49fa4505d3b7c | Mariamjaludi/algorithms-practice | /python/amazonsSortCenter.py | 1,481 | 4.5 | 4 | # Amazon’s Sort Center
# In Amazon’s sort center, a computer system decides what packages are to be
# loaded on what trucks. All rooms and spaces are abstracted into space units
# which is represented as an integer. For each type of truck, they have
# different space units. For each package, they will be occupying diff... |
ed7234bc238db85fd5b5cd7201b51c302da1f68d | Jadams29/Coding_Problems | /Map_Filter/Dynamically_Created.py | 607 | 3.90625 | 4 | # Dynamic Function
def get_func_mult_by_num(num):
def mult_by(value):
return num * value
return mult_by
generated_func = get_func_mult_by_num(5)
print("5 * 10 = ", generated_func(10))
def testing_function(number1):
def inner_func(number2):
return number1, number2
return inner_func
... |
5433e888669c2c35b96cd40ce55c72751578b5b4 | pirofex/quality-lab | /lab2/coverage/tests/test_parser.py | 1,838 | 3.6875 | 4 | import unittest
import calculator.parser as parser
class TestParser(unittest.TestCase):
def setUp(self):
self.parser = parser.Parser()
def testInt(self):
iExpr = "3//2"
oExpr = self.parser.parse(iExpr)
self.assertEqual(len(oExpr), 3)
self.assertEqual(oExpr[0].type, 'n... |
155bbaf64702a3061951723ff4c72009aba3470e | PedroSantana2/exercicios-em-python-wikipython | /primeira_lista/ex008.py | 522 | 3.9375 | 4 | '''
Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
'''
ganhos_por_hora = float(input('Digite a quantidade que você ganha por hora: R$'))
horas_trabalhadas = int(input('Digite a quantidade de horas trabalhadas no m... |
7373694c362f5c13ac5b9d01d5a0667b8476ace3 | Shanmuga-Priya-D/Python | /PANDAS/pan7.py | 728 | 3.625 | 4 | # TIME SERIES IS A SET OF DATA POINTS INDEXED IN TIME ORDER
print("1.DATETIMEINDEX")
import pandas as pd
df=pd.read_csv('E:\AAPL Historical Data.csv')
print(df)
print(type(df.Date[0])) # it gives the data type of column
df1=pd.read_csv('E:\AAPL Historical Data.csv',parse_dates=["Date"])# changes data t... |
d8033460dab59f8e10a1dd0e59375cf35dee0206 | prathap442/edureka-devops | /pythoncertificationtraining/module2/file1.py | 5,160 | 4.0625 | 4 | nums =set([1,1,2,3,3,3,4,4])
# The Set basically returns the unique keys back to us
print(nums)
'''
This is the problem2
'''
d = {
"john":40,
"peter":45
}
print(list(d.keys()))
'''
A website requires a user to input username and password to register.
Write a program to check the validity of passw... |
1a1a9b618cd4549905068baa7969287bcbfafe55 | YuYing-Liang/Data-Structures-And-Algorithms | /csc190/labs/lab 0/bc.py | 690 | 3.578125 | 4 | from stackLib import *
def bc(string):
#0th element = True or False
#1st element = pos where bracket fails
stack = stackLib([])
popped = ''
r_val = [True, -1] #if true, element 1 will return -1
for i in range(0, len(string), 1):
if string[i] == '(' or string[i] == '[' or string[i] == '{':
stack.push(string... |
7fd769ce18bff470657eba65626980ec3f9511c8 | boyangni/Sudoku-Solver | /Sudoku Solver.py | 4,516 | 3.921875 | 4 | import copy
'''template'''
# sudoku_list = [[0,8,5,0,0,0,2,1,0],
# [0,9,4,0,1,2,0,0,3],
# [0,0,0,3,0,0,7,0,4],
# [5,0,3,4,0,9,0,0,0],
# [0,4,0,2,0,6,0,3,0],
# [0,0,0,1,0,3,9,0,7],
# [6,0,8,0,0,5,0,0,0],
# [1,0,0,8,... |
96ec429019eb67297eb691d8107bec3bc6a21f6c | Diegokernel/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 353 | 3.828125 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
import sys
args_num = len(sys.argv)
if args_num == 1:
print("0 arguments.")
elif args_num == 2:
print("1 argument:")
else:
print("{:d} arguments:".format(args_num - 1))
for count in range(1, args_num):
print("{:d}: {}"... |
2262e95c0791e4d258379a8d3900f0cf48d1d250 | zeppertrek/my-python-sandpit | /pibm-training/sample-programs/lists_misc_example.py | 455 | 3.8125 | 4 | #lists_misc_example.py
# Initialize the list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
#
print (fruits.count('apple'))
#
print (fruits.count('tangerine'))
#
print (fruits.index('banana'))
#
print (fruits.index('banana', 4)) # Find next banana starting a position 4
#
fruits.reverse()
#... |
a61df10eeda80f53832d07c5a762ed2557a75f25 | RinniSwift/Advanced-Recursion-And-Graphs | /Tutorial/graph.py | 4,593 | 4.0625 | 4 |
import queue
'''
Properties
Vertex: vertex object containing an id and it's neighbors
id: string representation of vertex
neighbors: set of vertices adjacent to self
Graph: a graph class containing multiple vertexes and paths
vertices: [Vertex] list of all vertices in the graph
order: total n... |
c01ecae6be5b0fbd3b656874034db4b2f283a8d8 | erihucor/ScriptKryptonLevel3-4 | /codigoCompleto.py | 2,935 | 3.65625 | 4 |
def crearListasPorFrecuencia(s):
print("--Creando listas de frecuencia--")
L_letras = []
L_frecuencias = []
for letra in s.upper():
if letra.isalpha():
if letra not in L_letras:
L_letras.append(letra)
L_frecuencias.append(1)
else:
... |
f08dcd691491a5c9e48aece9ba823864e9a530e3 | jungimyang/Python_Github | /12_list_comprehension.py | 1,156 | 3.578125 | 4 | '''
컴프리헨션(list comprehension)
-> 리스트 안에 식, for 반복문 등을 지정하여 리스트를 생성하는 것 (리스트 표현식)
•[식 for 변수 in 리스트] -> a = [i for i in range(10)]
•list(식 for 변수 in 리스트) -> b = list(i for i in range(10))
range(10)으로 0부터 9까지 생성하여 변수 i에 숫자를 꺼내고, 최종적으로 i를 이용하여 리스트를 만든다는 뜻
'''
# 0부터 9까지 숫자를 생성하면서 값에 5를 더하여 리스트 생성
c = [i + 5 for i in ra... |
e15c59b71e270b82e85696732e7c7386625752de | hiratekatayama/math_puzzle | /leet/Valid_Sudoku.py | 1,185 | 3.640625 | 4 | import collections
class Solution(object):
def isValidSudoku(self, board):
boardMap = collections.defaultdict(list)
for x in range(9):
for y in range(9):
char = board[x][y]
if char != ".":
if char in boardMap:
f... |
025ba510b92fb834befb49aee25b60c41202d837 | adnansabbir/practicing_data_structure | /sorting/insertion_sort.py | 394 | 3.84375 | 4 | from sorting.test_sorting_algos import TestSorting
def insertion_sort(arr):
for index in range(1,len(arr)):
item = arr[index]
for index2 in range(index-1,-1,-1):
if item>=arr[index2]:
arr[index2+1] = item
break
else:
arr[index2],arr[index2+1] = arr[index2+1], arr[index2]
if index2 == 0:
... |
702a9b8f7136f3d9e6ef61d2c63db840f95d6a28 | algorithmstudy4/sw_test | / SK_coding/백준_대학생 기본반/올림픽2.py | 1,491 | 3.6875 | 4 | """
country_all, country = map(int, input().split())
gold = []
silver = []
bronze = []
same_gold_country = []
same_silver_country = []
for i in range(0, country_all):
num, a, b, c = map(int, input().split())
gold.insert(num-1, a)
silver.insert(num-1, b)
bronze.insert(num-1, c)
s1 = set()
s2 = set(... |
e6f898aaa3ce2a2386aaed316b90266e048439fc | chongt/CSCI4760 | /HW/3-UnitTesting/changemakertest.py | 1,133 | 3.828125 | 4 | #
# Test code for the ChangeMaker class, which computes change from
# a purchase as a list [quarters, dimes, nickels, pennies]
#
import unittest
import changemaker
class TestChangeMaker(unittest.TestCase):
def test_coinlist(self):
'''Test coinlist method, which
converts an integer number of cent... |
e62d366e53fc85c9f756d1c0b2ef6087d2e4d04b | daniel-reich/turbo-robot | /JQnFS4sEoEFX4vP3q_1.py | 1,042 | 3.9375 | 4 | """
**Mubashir** needs your help in a simple task of multiplication of elements
in a given list.
Create a function which takes a list of integers `lst` and a positive integer
`k` and returns the **minimum and maximum possible product of k elements**
taken from the list. If enough elements are not available in the ... |
911e9f387cf18ad499d4430a803203de67ccbf68 | felixb93/Hangman | /Hangman/task/hangman/hangman.py | 1,231 | 3.640625 | 4 | # Write your code her
import random
class Hangman:
print("H A N G M A N\n")
def __init__(self):
self.list = ('python', 'java', 'kotlin', 'javascript')
self.word = random.choice(self.list)
self.censored = "-" * len(self.word)
self.count = 8
def guess(self):
print(s... |
7b4b18ba4fa62238095674d4988c32f4217f2fd0 | zuobing1995/tiantianguoyuan | /第一阶段/day11/code/closure2.py | 269 | 3.640625 | 4 | # closure2.py
# 用闭包来创建任意的函数
# f(x) = ax2 + bx + c
def get_fx(a, b, c):
def fx(x):
return a * x ** 2 + b * x + c
return fx
f123 = get_fx(1, 2, 3)
print(f123(20))
print(f123(50))
f654 = get_fx(6, 5, 4)
print(f654(10)) # ...
|
973709b78d4d0b14bd039d29cd0bbf352d69fb8b | N-Wouda/ALNS | /alns/accept/AdaptiveThreshold.py | 2,257 | 3.953125 | 4 | from collections import deque
from statistics import mean
from typing import Deque, List
class AdaptiveThreshold:
"""
The Adaptive Threshold (AT) criterion of [1]. This criterion accepts a
candidate solution if it is better than an adaptive threshold value. The
adaptive threshold is computed as:
... |
a64473fda130d5a40a455ad4166f52eb3db9f057 | bwallace94/InterviewPrework | /Checkpoint2_Prettyprint.py | 520 | 3.515625 | 4 | class Solution:
# @param A : integer
# @return a list of list of integers
def prettyPrint(self, A):
num_rows = A * 2 - 1
result = []
for i in range(num_rows):
row = []
for j in range(num_rows):
r = i
if i >= A:
... |
d3d8edee2b567d8cef4097be10eeeae609c246f2 | StitchIQ/leetCode_step | /Math/leetCode_441.py | 881 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/19 18:37
# @File : leetCode_441.py
'''
思路,问题的本质是 n是否为等差数列的和
等差数列k*(+1) = 2n
使用2n开方,然后判断开方值是大于2n,来决定是否加 -1
'''
from math import sqrt
class Solution(object):
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
... |
6d18953f9ee343e6477327999a9889a6125d2694 | Pedro-H-Castoldi/descobrindo_Python | /pphppe/sessao12/xii_modulos_customizados.py | 950 | 4.40625 | 4 | """
Módulos Python nada mais são q arquivos Python, então podemos importar esses arquivos
para nosso programa (arquivos incluvive, q nós criamos)
# Importanto uma função customizada do módulo args
from args import multiplica
print(multiplica(1, 3, 3, 3, 2))
# Importando tudo de um módulo. Quando se diz tudo é TUDO... |
80c2921cd5fbcb3cdacbf0795f007aebec6a1c8f | amitsharma91/Python_Practical_MCA | /Python_Practical_Programs_2.7/assignment11.py | 209 | 3.875 | 4 | '''
Created on Mar 31, 2017
@author: developer.amit
Write a Python program to find validity of a string of parentheses, '(', ')', '{', '}', '[' and ']. These brackets must be close in the correct order.
'''
|
52279ed1b77603b314297552468035a444ee2692 | 111Virus/Pyton_works | /PyGame/SpaceInvador/main.py | 6,316 | 3.53125 | 4 | import pygame as py
# from pygame import mixer as mix
import random
import math
# Everything happening in the game window is called as event Ex:-pressing quit or shooting e tc.
# Initialize the pygame, creating the game window
py.init()
screen = py.display.set_mode((800, 600)) # This is for the game window size, mu... |
e50596c5028e8098d38592d3b4c1a54bb341ad9d | vukkeselj/py | /listcomp.py | 114 | 3.671875 | 4 | a = [1, 2, 3, 4]
# for x in a:
# print(x**2)
[print(x**2) for x in a]
[print(x**2) for x in a if x%2==0]
|
5e61fa473cac55b824175a018c624562fe96eb04 | aydanufuk/Python | /files/write.py | 130 | 3.84375 | 4 | #open the file foe writing
f = open("files/myfileWrite.txt","w")
s = input("please enter text: ")
f.write(s)
f.close()
|
8dde57bd8465ba57e0a8a672af3183c9be5f525a | YuyangZhang/leetcode | /164.py | 1,204 | 3.578125 | 4 | class Solution:
# @param num, a list of integer
# @return an integer
def maximumGap(self, num):
newNum=[]
gap=0
if len(num)<2:
return 0
for i in range(0,len(num)):
n=num[i]
if len(newNum)==0:
newNum.append(n)
... |
e6c6466cd92463aa542376e250cc95515d739502 | lukeb88/data_scientists_utils | /plots/time_series/seasonal_decomposition.py | 874 | 3.890625 | 4 | import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
def plot_seasonal_decomposition(dataframe, feature, figsize=(30, 10)):
'''
Plots the seasonal decomposition of a time series
Attributes:
- dataframe: (pandas.DataFrame)
- feature: (strin... |
2f85f2b3e618554f95e7b0dea51eaa5b1166412c | Arihant2001/Hacktoberfest-2022 | /PYTHON/valid phone number.py | 398 | 4.03125 | 4 | numbers = []
num = str(input("enter the number: "))
numbers.append(num)
for num in numbers:
if len(num)==13 or len(num)==12:
if num.startswith('+91'):
print(num," is indian. ")
elif num.startswith('0'):
print(num," is indian. ")
elif num.startswith('+1'):
... |
562733cc5d302da1e8a98289989188e3ccef2bda | yanaTKD/math_modeling | /lab_ex4.py | 156 | 3.828125 | 4 | n = int(input())
f1 = 1
f2 = 2
print(f1, f2, end=" ")
for i in range(3, n + 1):
print(f1 + f2, end=" ")
b = f1
f1 = f2
f2 = b + f1
|
0697f7d532d62535d3a09bbda625929ba2a26e45 | Fridayk7/Cracking-the-Coding-Interview-MY-SOLUTIONS- | /Chapter_2/Ch2_Partition.py | 855 | 3.671875 | 4 | class Node:
def __init__(self, dataval=None):
self.data = dataval
self.next = None
class SLinkedList:
def __init__(self):
self.head = Node()
def print_list(self):
node = self.head
while node is not None:
print(node.data, end=" ")
... |
38d316a833b84ab880610cc1a62cc24c3a08c526 | GRustle00/pathofpython | /crashcourse/name_cases.py | 499 | 4.0625 | 4 | name = 'Marlene'
print("Hello {} I like you and I love you!".format(name))
dog = 'SkottoChari'
breed = 'Daschund'
size = 'SMALL'
print ("My dog name is {} he is a {}, they tend to be very {}.".format(dog.title(), breed.upper(), size.lower()))
print("Corey House once said, \"Code is like Humor. If you have to explain... |
801cc4a2d59ee259599ec16891c452e835db9eb7 | karimeSalomon/API_Testing_Diplomado | /RolandoMamani/Python/Practice13_AgeInMinHrsAndDays/lib/AgePrinter.py | 258 | 3.78125 | 4 | def printAge(age):
if(age < 12):
print("is a child")
else:
if(age <= 17):
print("is teenager")
else:
if (age <= 29):
print("is young")
else:
print("is adult") |
d89e59f2f3ba5451b1cc9034dcb4fe686a9d4bee | kevinelong/PM_2015_SUMMER | /StudentWork/MattBishop/transform.py | 405 | 3.640625 | 4 | # Define the input data
data_list = [
{"id": 123, "Name": "abc" },
{"id": 234, "Name": "def" }
]
def transform(data_list):
data_dictionary = {}
new_id = 0
for x in data_list:
new_id = x.get("id", 0)
output_item = {}
output_item["Name"] = x["Name"]
data_dictionary[new... |
f7546397ba2f083ca5dd37bf714dc36ac38bf6ef | b1ueskydragon/PythonGround | /graffiti/stream_median_insertion_sort.py | 1,139 | 3.9375 | 4 | """
An algorithm that allows a number to be added
and yet keeps the entire list sorted .. insertion sort.
Find (using a binary search)
and insert the incoming number to the right place.
"""
class Solution:
def __init__(self):
self.res = []
@staticmethod
def get_pos(xs, low, high, value):
... |
daae9f083572b335656174d566f31f4ae345c931 | mastermanas805/Data_Structures_with_Graphs | /bfs.py | 1,083 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 31 16:49:27 2019
@author: Manas
This is a code for graph search by Breath First Search
"""
import networkx as nx
def BFS(G, s):
# Mark all the vertices as not visited
visited = [False] * (G.number_of_nodes())
# Create a queu... |
9bf7aa2c0fba061a9348e6178464aaa17e17dae6 | privateHmmmm/leetcode | /540-single-element-in-a-sorted-array/single-element-in-a-sorted-array.py | 712 | 3.8125 | 4 | # -*- coding:utf-8 -*-
#
# Given a sorted array consisting of only integers where every element appears twice except for one element which appears once. Find this single element that appears only once.
#
#
# Example 1:
#
# Input: [1,1,2,3,3,4,4,8,8]
# Output: 2
#
#
#
# Example 2:
#
# Input: [3,3,7,7,10,11,11]
... |
b4a5d312062961c30eba740c341115bb50e2607c | MansNotSpaghett/UTTT-bot | /rules.py | 851 | 3.546875 | 4 | def theWinner(arr):
y = arr
if y[0][0]==y[0][1] and y[0][1]==y[0][2] and y[0][0]!=0 and y[0][0]!=3:
return y[0][0]
if y[1][0]==y[1][1] and y[1][1]==y[1][2] and y[1][0]!=0 and y[0][0]!=3:
return y[1][0]
if y[2][0]==y[2][1] and y[2][1]==y[2][2] and y[2][0]!=0 and y[0][0]!=3:
return... |
b01b536524dea699e5f4025108b301c86185f54d | adelyalbuquerque/projetos_adely | /pescador.py | 354 | 3.5 | 4 | def peso_pescaria():
peso = float(raw_input("Quantos quilos foram pescados?"))
excesso_peso = peso - 50
if excesso_peso > 0:
multa_por_excesso = excesso_peso * 4
else:
multa_por_excesso = 0
print "Quilos excedidos: {}".format(excesso_peso)
print "Multa por excesso: {}".format(mu... |
9559efde14adc0e75fdadbc88eaecda65e861138 | fiskirton/Artezio-Academy | /Lesson VI/eveniterator.py | 539 | 4.09375 | 4 | """
Module contains a simple iterator
"""
class EvenIterator:
"""
Sequence iterator. Returns elements at even positions
"""
def __init__(self, iterable):
self.seq = iter(iterable)
def __next__(self):
num = next(self.seq)
if num:
next(self.seq)
else:... |
f10849187f3968fbb942ec6d69ae40942090cdd1 | sdksfo/leetcode | /easy_690. Employee Importance.py | 741 | 3.65625 | 4 |
"""
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordin... |
b2b64733f24e815ea5d9978838dcb8e9ef817f3d | joelwng28/Python-Programs | /RPG.py | 7,404 | 3.75 | 4 | # File: RPG.py
# Description: Creates a simple RPG game
# Student's Name: Zi Zhou Wang
# Student's UT EID: zw3948
# Course Name: CS 313E
# Unique Number: 86940
#
# Date Created: 6/10/2017
# Date Last Modified: 6/10/2017
# defines a Python class called Weapon
# @param name identifies the weapon's type
# each we... |
c60606a614f0f593e8929bacdbf9a1b0efd16050 | anondp/PythonExercises-with-Solutions | /Exercise 82.py | 199 | 3.765625 | 4 | # Question 82:
# Please write a program to print the running time of execution of "1+1" for 100 times.
from timeit import Timer
import time
t = Timer("for i in range(100): 1+1")
print(t.timeit()) |
c97959c4207fa443fbc7d396adf3d8e1fa769f78 | GabiGeron/Repositorio-de-Gabriel. | /compra y for.py | 144 | 3.6875 | 4 | mi_lista = {34,21,1876,73,12,43]
for item in mi_lista:
print("Tengo que comprar{}.format(item")}
print("Esta es la lista de la compra") |
016f8ec0f7381be2869f3a2843a8e165f09339bb | TonyFlury/TempDirectoryContext | /TempDirectoryContext/TempDirectoryContext.py | 4,549 | 3.65625 | 4 | #!/usr/bin/env python
"""
TemporaryDirectoryContext : Implementation of TemporaryDirectoryContext
Summary :
A context handler wrap around the tempfile module - to enable clean up and close down
Use Case :
As an application I want to be able to create and tear down temporary files so that
I can keep th... |
125f96bc563e349a618a9256fab90a9cd1c5c29d | wwyyzz/rename | /rename.py | 306 | 3.515625 | 4 | import os
path = r'E:/吴军·硅谷来信'
str = r'吴军'
pos = 21
os.chdir(path)
file_list = os.listdir(path)
print(file_list )
for filename in file_list:
if str in filename:
print(filename[pos:])
new_name = filename[pos:]
os.rename(filename, new_name)
print(file_list ) |
49971dedc081da493d8ed2f2f2a0620eaa5ac7a1 | sestissi16/DataStructuresProjects | /NotesMar3.py | 1,031 | 4.03125 | 4 | class Node():
def __init__(self, data, nextNode = "None"):
self.data = data
self.nextNode = nextNode
class circularSLL():
def __init__(self):
self.head = "None"
self.tail = "None"
self.size = 0
def add_head(self, e):
newNode = Node(e)
if self.size ==... |
90af275aab1b9522b63a86839c0ff4006cec1cd6 | yenniejun/covid-texting-service | /utility.py | 605 | 3.53125 | 4 | import string
import re
def clean_text(txt):
return ''.join(txt.lower().strip().replace(".","").replace(",",""))
# https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators
# 123,456,789
def format_num(num):
if num != None: return f'{num:,}'
else: return num
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.