blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
32c179910080008ebe41364381adceea35184213 | sejongjeong/Algorithm-Baekjoon | /src/2108_통계학.py | 645 | 3.5 | 4 | import sys
import math
from collections import Counter
input = sys.stdin.readline
n = int(input())
num_list = [0 for _ in range(n)]
for i in range(n):
temp = int(input())
num_list[i] = temp
print(round(sum(num_list)/n))
num_list.sort()
print(num_list[int(n/2)])
def mode(x):
count_dic = Counter(x)
most_c... |
acc8b91a7053473fea2c945182098c08167e11cc | panditprogrammer/python-mysql | /py_db6.py | 549 | 3.65625 | 4 | #Extracting data from table with python
import mysql.connector
#conneting to database and select
mydatabase = mysql.connector.connect(host='localhost',
user='root',
password='',
database='pythondb')
#for any ... |
db051f889ee762f75c0f9a93768155286ee4ec40 | shivenpurohit/algorithmic-toolbox-coursera-UC-San-Diego | /week3_greedy_algorithms/4_maximum_advertisement_revenue/dot_product.py | 626 | 3.578125 | 4 | #Uses python3
import sys
def max_dot_product(a, b):
#write your code here
res = 0
while(len(a) > 0):
max_a = 0
max_b = 0
for i in range(len(a)):
if(a[i] > a[max_a]):
max_a = i
if(b[i] > b[max_b]):
max_b = i
re... |
47166f536c68baea2d0e2b99f33454ba93c2abd8 | sandysuehe/LintCode-Learning | /Algorithms/StringProcess/valid-word-abbreviation.py | 1,057 | 3.71875 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# Author: (sandysuehe@gmail.com)
#########################################################################
# Created Time: 2018-08-28 16:28:08
# File Name: valid-word-abbreviation.py
# Description: Valid Word Abbreviation
# LintCode: https://www.lintcode.com/problem/valid-wo... |
e48c32b7f889e6dc05c8f10c709a027abbac8fac | kudoxi/hanshoushou | /public/uploads/20180328/0853d54f58806ae2ecc7d6df1067bca7.py | 474 | 3.84375 | 4 | name = input("what is your name")
age = input("how old are you")#input 接受的所有数据都是字符串,即使你输入的是数字
death_age = 100
print(type(age)) # str
print ("my name is ",name," and I am ",age," years old,I can still live for ",str(death_age - int(age))," years") #python里字符串和数字无法拼接在一起
#或者
print ("my name is "+name+" and I a... |
fbaf13dae8cd7c6ac80fb75ef6896f4c985150ab | abhi-python/python-programs | /tryexceptprog.py | 215 | 3.828125 | 4 | print("Enter num 1")
num1 = input()
print("Enter num 2")
num2 = input()
try:
print("The sum of these two numbers is", int(num1)+int(num2))
except Exception as e:
print(e)
print("This should be executed") |
7e5f59e843b4ff68cf7edccc5442f2b63e65a150 | Nimor111/101-v5 | /week3/Tasks.py | 1,088 | 3.796875 | 4 | def gcd(a, b):
if a == b:
return a
else:
if a > b:
return gcd(a - b, b)
else:
return gcd(a, b - a)
def gcd_second(a, b):
if b == 0:
return a
else:
return gcd_second(b, a % b)
def simplify_fraction(fraction):
if fraction[0] == fracti... |
39dd771022b0c5d03e4853b16fa89443d64e862f | DillonSteyl/SCIE1000 | /Other/Multiple_Input/attempt.py | 234 | 3.90625 | 4 | number = eval(input('Please enter a number: '))
number2 = eval(input('Please enter a different number: '))
abb = int(number)
if (abb < 0):
abb *= -1
print(abb)
else:
print(abb)
print(number2)
print('Sum:', number2+abb) |
f40b748d889777bb3e16bebdaa67fc4c8e4e1d6f | prstepic/DataStructuresAndAlgorithms | /Queue.py | 503 | 3.515625 | 4 | class Queue:
def __init__(self) -> None:
self.queueList = []
def dequeue(self):
if(self.queueList):
return self.queueList.pop(0)
else:
return None
def enqueue(self, val) -> None:
self.queueList.append(val)
def first(self):
... |
3084dc5674d4c3d30ffd858106145c213158b115 | THAMIZHP/python-programing | /count the frquency of character in string.py | 357 | 4.3125 | 4 | '''
Write a Python program to count the number of characters
(character frequency) in a string.
Sample String : google.com'
Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}
'''
# Solution
q=input("Enter a String: ").strip()
def counter(a):
return(q.count(a))
i={}
for x in q:
... |
6be9422c0d8428dbff04205af84d13559b65110f | BayanFaisal/Word-Cloud-Python | /Tile of two cities-python.py | 1,156 | 4.34375 | 4 | # We use the text of the famous novel by Charles Dickens, A Tale of Two Cities. Credit to Project Gutenberg.
# We want to read and clean the input, then count the frequencies of each word.
from collections import Counter
file=open('98-0.txt', encoding="utf8")
# We want to use stopwords file <--- common words to ex... |
85cf6bce8f21e7abf00bdd2df443f05b9500c717 | pppoke/poke | /第九周-源码/源码/threading_ex1.py | 712 | 3.609375 | 4 | __author__ = "Alex Li"
import threading
import time
count = 0
def run(n):
print("task ",n, threading.current_thread(), threading.active_count() )
time.sleep(2)
print("task done",n)
global count
count +=1
start_time = time.time()
t_objs = [] #存线程实例
for i in range(50):
t = threading.Thread(t... |
d0b7b5a9ad9686a4016e1434f2d0c91f78a8dbec | Margasoiu-Luca/Chatbot-Project | /WeatherRecognition.py | 1,147 | 3.765625 | 4 | import requests
def chatbot():
print("Hello i am ChatBot. I can forecast the weather, tell the time")
print(" anywhere in the world and give you sports fixtures and news.")
command = input("What would you like? ").lower()
location = input("Enter Location ")
webadd = "http://api.openweathermap.org/d... |
23b44d25d065d0c7650736f4334a9fe32e9eeeee | juil/project-euler | /p001.py | 265 | 4.1875 | 4 | # Problem 1
# Multiples of 3 and 5
#
# Find the sum of all multiples of 3 or 5 below 1000.
def sum3or5(max):
sum = 0
for i in range(max):
if i%3==0 or i%5==0:
sum += i
return sum
# Test Cases
print sum3or5(10)
print sum3or5(1000)
|
72bf64382bfcd6a3d98090392941b0d3812c4e83 | Shaikhmohddanish/python | /python/dictionary/1.py | 376 | 4.4375 | 4 | #Dictionary is a {key,value} pairs
dict={"name":"ABC","Rno":43,"Branch":"EXTC"}
print(dict)
#Adding
#key=name,Rno,Branch
#Values=ABC,43,EXTC
dict["course"]="Engineering"
print(dict)
#Modify
dict["course"]="B-tech"
print(dict)
#Deleting
# key word ====> del (one or more elements)
#clear====> clear all the elements (funt... |
5dff9b8ba8378d3997fa94fdbafd7d83ad40d5df | vivekgupta8983/python_tut | /Python_Tutorials/number_opreations.py | 110 | 3.65625 | 4 | """
This Numiercal Operation
"""
exponents = (10 ** 5)
print(exponents)
remainder = (12 % 4)
print(remainder) |
4d9cfa7eaa895cc24905fab97a76ad72c14a3401 | tborisova/homeworks | /7th-semester/ai/hw2.3 (1).py | 3,249 | 3.515625 | 4 | from queue import *
from copy import deepcopy
number = int(input())
count_of_rows = int(number/2 - 1)
count_of_cols = int(number/2 - 1)
expected_matrix = [[0 for x in range(count_of_rows)] for y in range(count_of_cols)]
actual_matrix = [[0 for x in range(count_of_rows)] for y in range(count_of_cols)]
visited = {}
s... |
d0cba706ca49737a5d8a9d5c7f6fd8de831d3f7d | NirmaniWarakaulla/HackerRankSolutions | /Python/Python If-Else.py | 141 | 3.828125 | 4 | N = int(input())
if (N % 2 == 1) | (6 <= N <= 20):
print("Weird")
elif N >= 2 & N <= 5:
print("Not Weird")
elif N > 20:
print()
|
1d70db077c874f75b3911d94f58428037734fa66 | saurabhchris1/Algorithm-and-Data-Structure-Python | /Bubble_Sort/Bubble_Sort_Iterative_Optimized.py | 644 | 4.3125 | 4 | # Bubble Sort Iterative Optimized
# Print i,j will help you figure out calculations
def bubble_sort_iterative(num_arr):
len_arr = len(num_arr)
flag = True
for i in range(len_arr):
if not flag:
break
flag = False
for j in range(len_arr - i - 1):
print(i, j)
... |
4103a3049390234b0441d486683ffee6dbda97ae | HarshaaArunachalam/guvi | /ten.py | 90 | 3.78125 | 4 | num=int(input())
length=0
while(num>0):
length=length+1
num=num//10
print(length)
|
3d472d8c680add89e845a5be2d7ccaf6cdb7a52e | gmarson/Federal-University-of-Uberlandia | /Comparison of Sorting Algorithms/Trabalho_Final/Codigos/Quick/QuickSort.py | 475 | 3.625 | 4 | #@profile
def Particiona(A,p,r):
x = A[r] #pivo é o último elemento
i = p-1
for j in range(p,r):
if A[j] <= x:
i = i + 1
aux = A[i]
A[i] = A[j]
A[j] = aux
temp = A[i+1]
A[i+1] = A[r]
A[r] = temp
return i+1
#@profile
def quickSort(A,p,r):
if(p < r):
q = Particiona(A,p,r)
quickSort(A,p,(q-1))
... |
9cb346320683190c7f929882cf63f0b336188fd3 | owengmiller/rockpaperscissors | /rockpaperscissors(1.2.1).py | 2,274 | 4.09375 | 4 | import random
print('~Rock Paper Scissors~')
print('')
def getPlayerMove():
# Gets the player's move, allowing for variation in length of word.
print('Choose...\n Rock (R)\n Paper (P)\n Scissors (S)')
print('')
pDrop = input().lower()
if pDrop == 'r' \
or pDrop == 'ro' \
... |
4fdba5741ed99f4fb49d8552ccd523860a102363 | abzilla786/error-handling-exercise | /main.py | 1,377 | 4.03125 | 4 | from functions import *
order_list = []
food_list = []
order_no = 0
while True:
print('1. Create an order')
print('2. Display an order')
print('3. Number of orders')
print('4. Exit')
menu = int(input('Please select a menu number. e.g \'2\'\n'))
if menu == 1:
while True:
# ... |
4f8dc21888f92b5031c54c3877e3d0ef811c1ba2 | DeadManGTPS/wm_bot | /src/extensions/random_cog.py | 3,564 | 3.640625 | 4 | import random
from collections import Counter
from typing import Optional
import discord
from discord.ext import commands
class Plural:
"""Converts a text to plural when used in a f string
Examples
--------
>>> f"{Plural(1):time}"
'1 time'
>>> f"{Plural(5):time}"
'5 times'
>>> f"{Plu... |
d5e4d329a5b5ba003119f629c1c4163a58bf7266 | mclaveria/Project_Euler | /Problem029_Distinct_Powers.py | 469 | 3.5625 | 4 | #Michael Claveria
#Project Euler Problem 29 Distict powers
'''
Find the number of distinct terms generated by a^b for 2 <= a <= 100 and
2 <= b <= 100
'''
aList = range(2,101)
bList = range(2,101)
def distPow(list1, list2):
rList = []
for i in list1:
for j in list2:
#print (str(i ** j))
... |
300664997a8f5f68f798974f8335bdb67bf547ae | davidbailey/dpd | /dpd/mechanics/kinematic_body_with_acceleration.py | 2,709 | 3.9375 | 4 | import numpy
from .kinematic_body import KinematicBody
class KinematicBodyWithAcceleration(KinematicBody):
"""
A class to simulate a kinematic body. Provides methods to move the body with constant acceleration and decelerate the body with constant deceleration.
"""
def __init__(
self,
... |
8e08ca255a4e8f5c939db99f8f2fdb95241f40cf | EdouardPascal/projet | /test/union.py | 143 | 3.84375 | 4 | #Fonction union
def union (a,b):
i=0
d=len(b)
while i<d:
a.append(b[i])
i+=1
return a
a=[1,2,3,4]
b=[2,4,5,6,7,8]
print(union(a,b))
|
90c4d37e10b9273f90489f78e644a8799e01645b | chernyshevdv/py_training | /fill_matrix.py | 1,348 | 4.03125 | 4 | # fill matrix NxN with numbers in spiral
# create a matrix
# fill outer layer
# go with recursion
def fill_ring(matrix, start_x=0, start_y=0, start_value=1, n=0):
# fill top row
x, y, value = start_x, start_y, start_value
while x < len(matrix) and matrix[y][x] == 0:
matrix[y][x] = value
x +=... |
4491fcff1ed03fb796efab9a8bee866d86c55da3 | sparshagarwal16/Assignment | /Assignment17.py | 1,496 | 4 | 4 | import tkinter
from tkinter import *
import tkinter as tk
#Question 1
print("Question 1")
r=Tk()
r.title('HEY')
z=Label(r,text="HELLO WORLD",width=15,height=5,bg="blue")
z.pack()
button=tk.Button(r, text='Exit',width=15,activebackground='red',activeforeground="black",bg="red",command=sys.exit)
button.pack()
#Question 2... |
7cc34f1fb8444b81691ed66d01eaf8cf2e079608 | teretupiro/rpg_part2 | /zxc.py | 977 | 3.921875 | 4 | hello=input('Press \'Enter\' to start ')
feelings=input('\"Как ты себя чувствуешь?\" ')
help = ''
while help != 'да':
if feelings =='плохо':
print ('Я тебе сочувствую ')
elif feelings == 'хорошо':
print ('Это хорошо')
else:
print('Почему ты молчишь?')
help = input('Ты помо... |
8fc0486deda380f6c230a798bdcc1b6637192826 | DiegoDenzer/exercicios | /src/iniciante/distancia_dois_pontos.py | 769 | 3.65625 | 4 | """
Leia os quatro valores correspondentes aos eixos x e y de dois pontos quaisquer no plano, p1(x1,y1) e p2(x2,y2)
e calcule a distância entre eles, mostrando 4 casas decimais após a vírgula, segundo a fórmula:
Entrada
O arquivo de entrada contém duas linhas de dados. A primeira linha contém dois valores de ponto flu... |
3c6cc83b4108ad872af86ab35e9f66de034ccde7 | Mattie-07/DCWork.python | /thursdayEx4.py | 176 | 4.125 | 4 | #Make a string and remove any strings that happen to be duplicates and print that list.
name = "Matthew"
nameWithoutDups = "".join(dict.fromkeys(name))
print(nameWithoutDups) |
ea2adc00865b21977a5a854b4779f395d3848217 | Mondirkb/HTB-Writeups | /ForwardSlash/bruteForce.py | 1,169 | 3.6875 | 4 | #!/usr/bin/python
# from string import printable
def decrypt(key, msg):
key = list(key)
msg = list(msg)
for char_key in reversed(key):
for i in reversed(range(len(msg))):
if i == 0:
tmp = ord(msg[i]) - (ord(char_key) + ord(msg[-1]))
else:
tmp = ord(msg[i]) - (ord(char_key) + ord(msg[i-1... |
1b309d00df493d1c40c9e9fe6a5abe0448fd9bf0 | Class19-002/python | /4.py | 347 | 3.515625 | 4 |
import sys
argument=sys.argv[1]
number=int(argument)
end=range(1,(number+1))
def four():
for i in end:
if i%12 == 0:
dozen=i/12
print(str(dozen)+' dozen')
elif i%4 == 0:
print('square')
elif i%3 == 0:
print('triangle')
... |
b116930b70f79fdae156095cb25bc3e2475fceb2 | Phillyclause89/ISO-8601_time_converter | /time_converter.py | 3,094 | 3.890625 | 4 | # iso_time must be a timestamp string in ISO 8601 format and offset is to change the timezone
def time_convert(iso_time, offset=0):
# months dict for converting from numerical month representation to name
months = {1: "January", 2: "February", 3: "March",
4: "April", 5: "May", 6: "June",
... |
bbbdc3e97f085e8c90c1997957e0c8c2aed00f01 | sunchit17/June-LeetCode-30dayChallenge | /week3/Permutation_Sequence(day 20).py | 901 | 3.9375 | 4 | '''
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k wil... |
63f4faafaec5f9d553c25969e74cb94b873f5625 | AidenLong/ai | /test/test/test_find_2shape_array.py | 698 | 3.65625 | 4 | # -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
rows = len(array)
cols = len(array[0])
if rows > 0 and cols > 0:
row = 0
col = cols - 1
while row < rows and col >= 0:
if targ... |
540112a132623a1657fef3c8822e1307f989b072 | lsom11/coding-challenges | /hackerrank/python/cracking-the-coding-interview/chapter-1-arrays-and-strings/is_unique.py | 181 | 3.734375 | 4 | def is_unique(S):
dict = {}
unique = True
for char in S:
if char in dict:
unique = False
else:
dict[char] = 1
return unique
|
9f8672f4291bc754e839a9f440a3d99fb362c3e4 | AndreKauffman/EstudoPython | /Exercicios/ex013 - Reajuste Salarial.py | 239 | 3.765625 | 4 | salary = float(input("qual o salario? "))
increase = int(input("qual o aumento? "))
porcent = (salary * increase) / 100
value = salary + porcent
print("O salario que era {} com {}% de aumento fica {}".format(salary, increase, value))
|
a48a11fb259b1069b90c5f8745574ae226c05da9 | Arjun2001/coding | /codechef stacks.py | 684 | 3.546875 | 4 | def search(arr, st, en, key):
mid = st + (en-st)//2
if key < arr[mid]:
if key >= arr[mid-1] or st == en or mid == st:
arr[mid] = key
return arr
else:
return search(arr, st, mid-1, key)
else:
if st == en:
arr.append(key)
... |
df7e9413a592b28ba8661e96e4cb6839759dc471 | alpiges/LinConGauss | /src/LinConGauss/core/linear_constraints.py | 2,500 | 3.578125 | 4 | import numpy as np
class LinearConstraints():
def __init__(self, A, b, mode='Intersection'):
"""
Defines linear functions f(x) = Ax + b.
The integration domain is defined as the union of where all of these functions are positive if mode='Union'
or the domain where any of the functio... |
fb3924b99a3a27027984e8648ea070d4d64f1361 | chrisr1896/Exercises | /algorithms/dynamic_programming/palindromic_substring/solution/solution.py | 1,655 | 4 | 4 | def longest_palindrome_substr(str):
n = len(str)
if n == 0:
return 0
# We create an n by n table, wwhere table[i][j]
# will be True if substring str[i..j] is a palindrome
# and False otherwise. We initialise all values to 0.
table = [[0 for x in range(n)] for y in range(n)] ... |
7ceda05eb58317c1c306e7afd4eb25318aab0623 | ameyyadav09/daily-stuff | /collections/namedtuples.py | 257 | 3.75 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import namedtuple
N, Student= int(raw_input()),namedtuple('Student',raw_input().strip().split())
print (sum(int(Student(*raw_input().split()).MARKS) for i in range(N))/N) |
39c10ec6d03ad3994c39110adcce83e2269b3315 | JushBJJ/Everything | /numpy/ndarray.py | 158 | 3.921875 | 4 | import numpy as np
foo=np.array([1,2,3])
print(foo)
for i in foo:
print(i)
foo=np.array([[1],[2],[3]])
for i in foo:
for x in i:
print(x)
|
6d43bb9659589642d45e59a87dc9806989c86132 | Hieumoon/C4E_Homework | /Session05/Homework/Homework5_exercise7.py | 347 | 4.71875 | 5 | # Write a function that removes the dollar sign ('$') in a string, named 'remove_dollar_sign', takes 1 arguments: s, where s is the input string, returns the new string with no dollar sign in it.
def remove_dollar_sign(s):
new_s = s.replace("$","")
return new_s
s = input('Enter the string containing $: ')
p... |
0875ab01c3d3833e3c96dc323af8236176007136 | yuhanlyu/coding-challenge | /lintcode/climbing_stairs.py | 306 | 3.8125 | 4 | class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
x, y, a, b = 1, 0, 1, 1
while n > 0:
if n & 1: x, y = a * x + b * y, b * x + y * (a - b)
a, b, n = a * a + b * b, b * (2 * a - b), n >> 1
return x
|
eaa2d985b1037f28e57b6b7aef250f0c1fdd5476 | rohaneden10/luminar_programs | /functions/calculator.py | 434 | 3.953125 | 4 | def calculator():
print("1:add")
print("2:sub")
print("3:mul")
print("4:div")
a=int(input("enter 1st no"))
b=int(input("enter 2nd no"))
c=int(input("enter the choice"))
if(c==1):
print("addition",a+b)
elif(c==2):
print("difference",a-b)
elif(c==3):
print("... |
9fa723a51f75057d5eead30f70842787122a9a43 | NallamilliRageswari/Python | /Adam_Number.py | 184 | 3.96875 | 4 | n=int(input("Enter a number : "))
sum=0
product=0
while(n>0):
sum+=(n%10)
product+=(n%10)
n=n//10
if(sum==product):
print("Adam Number")
else:
print("not Adam Number")
|
ec37c5d0f4d8aa0030358850ee8628d7ddc95d11 | Rogalowski/Podstawy-programowania-w-Pythonie-egzamin-probny | /10_Egzamin_-_rozwiazanie/01_Zadanie_1/answer3.py | 394 | 4.09375 | 4 | def check_palindrome(text):
"""Check if given text is palindrome.
:param str text: some text
:rtype: bool
:return: True if given text is palindrome False elsewhere
"""
text = text.lower().replace(' ', '')
return text == text[::-1]
if __name__ == '__main__':
print(check_palindrome("Kob... |
ada4be9b85aab1e84dc646c42d0bea5383461ace | RanranYang1110/LEETCODE11 | /numSquare.py | 1,248 | 3.75 | 4 | #-*- coding:utf-8 -*-
# @author: qianli
# @file: numSquare.py
# @time: 2019/09/20
# def numSquare(n):
# if n == 1:
# return 1
# else:
# mm = 0
# while n > 1:
# t = n
# while t ** 2 > n:
# t -= 1
# mm += 1
# n -= t ** 2
# ... |
420843516d9fa428e8aa8a6004829ad66c6e5cb8 | JoshPennPierson/HackerRank | /Algorithms/Graph Theory/Even Tree.py | 2,795 | 4.0625 | 4 | #https://www.hackerrank.com/challenges/even-tree
def find_tree_size(node,edge_list):
#get the size of the tree from this node down
all_children_found = False
tree_list = [node]
while not all_children_found:
new_additions = 0
for i in range(len(tree_list)): #go through all the nodes in t... |
bd87ae9d100461a27a799310d8656ee316f919aa | megannguyen6898/dataminingcourse | /python-bootcamp-main/session4/intro_OOP/intro_classes.py | 1,041 | 4.0625 | 4 | # source: https://www.csdojo.io/class
class Robot: #module
#Initilize key vars using constructor
def __init__(self, name, color, weight): #methods with main components such as name color weight
self.name = name
self.color = color
self.weight = weight
self.height = 10
def in... |
ec3b61f279ce966427301c0e79d20495e519d0da | Montechiari/Socios_SBPC | /socios.py | 1,279 | 3.515625 | 4 | import sqlite3
import pandas as pd
ENDERECO = "./"
NOME_BANCO = "socios.db"
ARQUIVO_DADOS_CSV = "socios.csv"
class Socio():
def __init__(self, nome, email, ultimo_pago, local, instituicao):
self.nome = nome
self.email = email
self.ultimo_pago = ultimo_pago
self.local = local
... |
42063fb1552aaf03402b8eef3c2ef481f4c73b13 | coding-corgi/homework-prac-week3 | /prac1사칙연산 자료 딕셔너리.py | 565 | 3.515625 | 4 | # print('hello wolrd')
# a= 3
# b= '상하'
# c =True
#
# print(a)
# print(b)
# print(c)
#
# list_a = [1,2,3]
# # print((list_a))
# list_a.append(4)
# print(list_a)
dic = [{'name':'상하','height':183},{'name':'송영','height':1}]
print(dic)
dic[0]['age']=30
print((dic))
person = {'name':'지우','height':163}
print(person)
dic.app... |
5229f84b4bfacfe63f03aae1c9b528430257bcbc | nsafai/Data-Structures | /palindromes.py | 3,250 | 4.21875 | 4 | #!python
import string
import re
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters is ascii_lowercase + ascii_uppercase
LETTERS = set(string.ascii_letters)
def is_palindrome(text):
"""A string of characters is a palindrome if i... |
f392a4650c57f1b243defc2856664e415bd63d98 | liush79/codewars | /6kyu/what_is_the_pattern.py | 879 | 3.53125 | 4 | def check_pattern(pattern, sequence):
len_pattern = len(pattern)
if (len(sequence) - 1) % len(pattern) != 0:
return False
for i, s in enumerate(sequence):
if i == 0:
continue
idx = (i % len_pattern) - 1
if pattern[idx] != sequence[i] - sequence[i - 1]:
... |
dcd898b40ff05057d9cee6aad4ecab07d02e6350 | PitPietro/python-project | /math_study/numpy_basics/statistics/statistic_mean.py | 811 | 4 | 4 | import numpy as np
from math_study.numpy_basics.statistics.statistics import ordered_data
if __name__ == '__main__':
print('Numpy - Statistic - mean')
# https://numpy.org/doc/stable/reference/generated/numpy.mean.html
print('\nCompute the arithmetic mean of the whole array:')
print(ordered_data.mean(... |
b2f575108c84fbc8c21eedeb96a10690278e8099 | rollingball211/Algorithms | /알고리즘/week-1/sum1to100.py | 123 | 3.640625 | 4 | def sum(n):
sum=0
for i in range(1, n+1):
sum=sum+i
return sum
print(sum(10))
print(sum(100))
|
b95b374ac796d641f78c0613e15bf0d323c4a31f | Casper2nd/slope | /main.py | 814 | 3.8125 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from random import randint
import parser
from math import sin
from decimal import Decimal
formula = "sin(x)*x^2"
formula ... |
2878ab757a7bec39acf6cd01bef7d78b1a492892 | EndavaTraining/python_training | /python_fundamentals/generators.py | 564 | 4 | 4 | def sick_pets_identifier(pets):
"""
Generator for identifying sick pets
"""
for name, food in pets.items():
if food < 300:
yield {name: food}
pets = {
"IronMan": 100,
"CaptainAmerica": 350,
"BlackWidow": 250,
"Hulk": 800,
"AntMan": 300,
"Spiderman": 190
}
sick_pets = sick_pets_identifier(pets)
p... |
2ec81e3f1be9d2882ddfad3d53f8156fe2a65dd8 | gabriellaec/desoft-analise-exercicios | /backup/user_018/ch35_2020_03_22_19_00_27_065571.py | 163 | 4 | 4 | n = int(input('Digite um número: '))
s = 0
while n != 0:
s += n
n = int(input('Digite um número: '))
else:
print('A soma é igual a {}'.format(s)) |
31a3df580d643e6e4d47e44484984d70d4c5ef77 | 1san4ik/git_lessons | /mnozhestva-2.py | 1,332 | 4.1875 | 4 | # Задание 2
# Создайте программу, которая эмулирует работу сервиса по сокращению ссылок. Должна быть
# реализована возможность ввода изначальной ссылки и короткого названия и получения изначальной
# ссылки по её названию.
dict1 = {}
while True:
a = input("\nНажмите '1' - чтобы ввести ссылки в базу\nНажмите '2' - ч... |
2a21d36e22e43137a44f34a58501295a4ecdf941 | sylviocesart/Curso_em_Video | /Desafios/Desafio06.py | 368 | 4.03125 | 4 | """
Crie um algoritmo que leia um número e mostre
o seu dobro, triplo e raiz quadrada
"""
n = int(input('Digite um número: '))
d = n * 2
t = n * 3
# rz = n ** (1/2)
# Raiz quadrada usando a funcao pow
rz = pow(n, (1/2))
print('O número digitado foi: {}. O dobro dele é {}'.format(n, d), end=' ')
print('e o triplo é {} e... |
365c0f1e155f1b713963a454a7a1e2d5a7eaca96 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/largest-series-product/3d61f04624354421afe4846b347e1054.py | 822 | 3.84375 | 4 | def slices(digits, k):
# Raise ValueError if length argument is larger than number of digits
if (len(digits) < k):
raise ValueError("Error: Length argument does not fit the series.")
# Add list of k digits to series until no more k digit long slices left
series = []
i = 0
while i <=... |
d162504c9ffa2e5b2a85037c96aba299d9e87a1d | suyeonme/python-journey | /basic syntax/error_handling.py | 204 | 3.6875 | 4 | try:
division = 10/0
number = int(input('Enter a number: '))
print(number)
except ZeroDivisionError as err: # you can name an error using as
print(err)
except ValueError:
print('Invalid input') |
abf2513d019f52ed360c10bb3562541196127500 | ihFernando/Python | /encriptar.py | 544 | 3.5625 | 4 | palavra = input("Qual frase deseja criptografar? ");
def encriptar(k,m):
aux = ""
for letra in m:
# k[letra] -> Olha na tabela
aux = aux + k[letra]
return aux
def montarDicionario(gamma1, gamma2):
if len(gamma1) != len(gamma2):
return {}
else:
dic = {}
z = z... |
4e37689170d83d40a684e3e4e9ae804a7f10df98 | ckiekim/Python-Lecture-1903 | /Unit 19/judge_star_mountain.py | 198 | 3.8125 | 4 | count = int(input('높이를 입력하세요: '))
for i in range(count):
for k in range(count-1-i):
print(' ', end='')
for k in range(2*i+1):
print('*', end='')
print()
|
17bb2260d1a2edfb4bd5284dffd47ac6b3afbfee | MrDNA2018/data_structure_and_algorithm | /divide_and_conquer.py | 13,815 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# =============================================================================
# 分治一般形式: T(n) = k*T(n/m) + f(n)
# k为子问题个数,一般均分或者等比分
# n/m问题规模,一般情况下m已经确认了子问题的个数,可以通过变换减少为a个
# f(n) 为数据的处理,划分和综合工作量,可以增加预处理,从而减少在递归里面的操作
# 也就是把递归里面的操作尽量放在循环体外面处理
# ===========================================... |
f795cb2964f20a64945fa5072aecf33498a7e23c | DavidSuarezM/python-3 | /03_Taller.py | 372 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 15:20:56 2021
@author: David Suárez Molina
"""
nombre=input('Ingrese su nombre: ')
apellido=input('Ingrese su Apellido: ')
ubicacion=input('Ingrese donde vive: ')
edad=input('Ingrese su edad: ')
print('\nHola, mi nombre es', nombre,apellido, ", tengo",eda... |
fccce91d127bbcf1c155af0f146977f19d553720 | sankaku/deep-learning-from-scratch-py | /ch06/DropoutLayer.py | 849 | 3.8125 | 4 | # Layer for Dropout
# mod ch05.ReluLayer
import numpy as np
class DropoutLayer:
def __init__(self, dropout_ratio=0.5):
"""
initialization
dropout_ratio: this ratio of nodes are droppped out
"""
self.mask = None
self.dropout_ratio = dropout_ratio
def forward(s... |
d04f1da3c158ca87349f621803a34bda90e4b02c | EunhaKyeong/studyRepo | /python/2. 파이썬 프로그래밍의 기초, 자료형/formatting_upgrade.py | 957 | 4.375 | 4 | #고급 문자열 포매팅
#숫자 바로 대입하기
print("I eat {0} apples.".format(3))
#문자열 바로 대입하기
print("I eat {0} apples.".format("five"))
#숫자 값을 가진 변수로 대입하기
number = 3
print("I eat {0} apples.".format(number))
#2개 이상의 값 넣기
number = 10
day = "three"
print("I ate {0} apples. So I was sick for {1} days.".format(number, day))
#이름으로 넣기
print... |
771038cbcce90143026d673ebd776f0265c7b57d | shankar7791/MI-11-DevOps | /Personel/Nitesh/Python/Assignment11/program02.py | 198 | 4.03125 | 4 | from itertools import groupby
def rmc(input):
result = []
for (key,group) in groupby(input):
result.append(key)
print (''.join(result))
input = input("Enter Word Or Sentence: ")
rmc(input) |
52994bd0917b903ac022ce3d176d312d6f55e1aa | madhuripawar12/python_basic | /union_list.py | 184 | 3.75 | 4 | def Union(list1, list2):
final_list = list1 + list2
return final_list
list1 = [23, 15, 2, 14, 14, 16, 20 ,52]
list2 = [2, 48, 15, 12, 26, 32, 47, 54]
print Union(list1, list2)
|
996cf5620ada64bfccb8aafa1f2a0375f558f1ec | MeghaJK/Python_Assignment-CS043- | /arithmetic.py | 255 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 11 22:05:25 2020
@author: Megha
"""
a=int(input("enter 1st number"))
b=int(input("enter 2nd number"))
sum=a+b
diff=a-b
mul=a*b
print("sum=",sum)
print("difference=",diff)
print("product=",mul) |
e099f2b42ebad9e02d41a83d138689b40fe1aac1 | beetroot-academy-rivne/hw-bogdan-quiz | /hw11.py | 997 | 3.859375 | 4 | import json
def get_user_info():
user = dict()
user['name'] = input('Enter your name: ')
user['last_name'] = input('Enter your last name: ')
user['phone_number'] = input('Enter your phone number: ')
user['address'] = input('Enter your address: ')
save_data(user)
def save_data(user):
with open('user.json', 'w') ... |
4a79d6834e93c935fe76ad345c55ceab73f5093c | ESRIN-RSS/msg-data-tools | /check_msg_data_report.py | 12,271 | 3.546875 | 4 | """Monitor and report on the availability of MSG data in a local directory.
Each day should have 96 timestamp directories and each of those should contain 114 files.
So for each day, there should be 10944 H-0000-MSG* files.
You can use this script to simply report on missing data by email (useful for setting up via cro... |
70c4c508af6bd34e2f5ca618365321ee2ea87ee1 | Zihua-Liu/LeetCode | /148/148.sort-list.python3.py | 1,696 | 3.90625 | 4 | #
# [148] Sort List
#
# https://leetcode.com/problems/sort-list/description/
#
# algorithms
# Medium (31.28%)
# Total Accepted: 145K
# Total Submissions: 463.1K
# Testcase Example: '[4,2,1,3]'
#
# Sort a linked list in O(n log n) time using constant space complexity.
#
# Example 1:
#
#
# Input: 4->2->1->3
# Outp... |
bbbc226f4c38e98ebb6723158265270b30a90130 | shailis17/CS100H | /HW08_Problem2.py | 649 | 3.578125 | 4 | '''
Shaili Soni
CS100, H01
Oct 29, 2020
HW8, Problem 2
'''
def twoWordsV2(integer, firstLetter):
word1 = ''
word2 = ''
lst = []
run = True
while run:
word1 = input("Enter a " + str(integer) + "-letter word please: ")
if len(word1) == integer:
lst.append(... |
d613bcaf287e9d1cbf31960e565aeaf10d17a090 | linth/learn-python | /async_IO/coroutines/base_example/2_asyncio_async_blocking.py | 945 | 4 | 4 | '''
非同步阻塞 (synchronous + blocking)
- 使用 await 方式條列出來,皆會使用順序方式執行完畢。
[思考]: 嘗試 main1, main2 使用裝飾器去計算時間會有問題。
Reference:
- https://juejin.cn/post/7095400034165850148
'''
import asyncio
async def fn2():
print("fn2")
async def fn1():
print("start fn1")
await fn2()
print("end fn1")
# 請注意 main1... |
cc5c2c39ba63ce105d2c0b8c4c45667e9919555e | AnishaSabu/Python-Learning- | /dictionary.py | 817 | 4.28125 | 4 | num=int(raw_input("enter the number of groups: ")) #enter number of groups present
students_data={} #declare an empty dictionary
for i in range(1,num+1):
limit=int(raw_input("enter the number of student in %d group: "%i)) #enter the number of students in ith group
students_data[i]={} #to make each item... |
b3d5f787fca90dd4072445e4960dcefa74635482 | EydenVillanueva/Exercises | /Python/relativeSortArray.py | 406 | 3.609375 | 4 | def relativeSortArray(a1,a2):
if len(a1) < len(a2):
return []
cont, aux= 0,0
for i in range(len(a2)):
for j in range(len(a1)):
if a2[i] == a1[j]:
aux = a1[cont]
a1[cont] = a1[j]
a1[j] = aux
cont += 1
return a1
... |
ba42ac0913efa8e64bdf7bd4c86a90b3dbd5bb46 | acothaha/Learn-Python-3-The-Hard-Way | /ex45/fight.py | 584 | 3.65625 | 4 | from suit import suit
def fight(hero, foe, death):
if foe.hp <= 0:
print(f"\n\t\t\tYOU DEFEAT {foe.name}")
return 1
elif hero.hp <= 0:
death.enter()
exit(1)
else:
pass
print(f"\n\t\t\t{hero.name}: {hero.hp} HP VS {foe.hp} HP :{foe.name}\n")
... |
4aa127711a403de55b87de470186653e3442b95b | dylngg/weekly-programs | /week13/Alarm.py | 1,456 | 3.515625 | 4 | import time
import os
import threading
import argparse
import sys
class Alarm(threading.Thread):
def __init__(self, wakeupTime):
# init class
super(Alarm, self).__init__()
self.wakeupTime = wakeupTime
self.keep_running = True
# runs alarm clock
def run(self):
# check time
try:
while self.keep_ru... |
1a003b34530b74da5e6b2ccfa5303dfd0ff9f98f | jqjZhu/Dictionaries-word-count- | /wordcount.py | 448 | 3.9375 | 4 | def count_word(filename):
"""Count words in file."""
input_file = open(filename)
word_counts = {}
for line in input_file:
# The default argument in rstrip() and split()is whitespace.
line = line.rstrip()
words = line.split()
for word in words:
word_counts[word] = w... |
0f7e07c5f96939f5748c8a93a95564f1919750b0 | Akshen/TP | /BTIT.py | 397 | 3.59375 | 4 | '''
Binary Tree Inorder Traversal using Stacks
1
2 3
4 5 6 7
expected = [4, 2, 5,1,6,3,7]
'''
def inorderT(root):
stk = []
res = []
while root is not None and stk != []:
while root is not None:
stk.append(root)
root = root.left
root = stk... |
c3d68eb4e0ba48d0006c520c595ae40de648d143 | carltonf/pymotw-workout | /text/templates.py | 2,683 | 3.546875 | 4 | # TODO: string formats are very complex
# string_template.py
import string
values = { 'var': 'foo', 'var2': 'bar' }
t = string.Template("""
Variable : $var
Escape : $$
Variable in text: ${var}iable
Variable 2 : $var2
Escape : $$
Variable in text : ${var2}iable
""")
... |
1ee450026577c380d6ce30c73ca18af812495d19 | pittcat/Algorithm_Practice | /leetcode/deleteDuplicates-83.py | 716 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res ... |
b74a62f522f38c585549a37222f207e29ce76459 | VictorxSR/BlackJack | /Joc.py | 1,839 | 3.765625 | 4 | from Cartes import *
import random
class Joc:
def crearCartes(): # crear totes les cartes de poker
cartes = []
for x in range(1,13):
cartes.append(Cartes("Picas", x)) # es crea un objecte Cartes amb un string i un numero
for x in range(1,13):
cartes.appe... |
2851a7882f9e1d0fa1a6fcb1d0d7b6333e0f8136 | itibbers/nb | /CodingInterviews/reference/数组中重复的数字.py | 2,188 | 3.953125 | 4 | '''
题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。
也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},
那么对应的输出是第一个重复的数字2。
'''
'''
应该是在线编辑器的bug
思路一:
未通过
'''
# -*- coding:utf-8 -*-
class Solution:
# 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
# 函数返回True/False
def duplicate(self, numbers, dup... |
755b00e91ec28072644b1b471699d63b758e5c09 | sandeepbaldawa/Programming-Concepts-Python | /data_structures/disjoint_sets/merge_tables.py | 3,143 | 4.0625 | 4 | '''
Problem Introduction
In this problem, your goal is to simulate a sequence of merge operations with tables in a database.
Problem Description
Task. There are n tables stored in some database. The tables are numbered from 1 to n. All tables share
the same set of columns. Each table contains either several rows with r... |
653ab6bc60559666afc1d9c903a01ff6322ccc13 | lum4chi/chinltk | /tokenize.py | 898 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Francesco Lumachi <francesco.lumachi@gmail.com>
import nltk, string
def words(text):
""" Tokenize by word AND removed punctuation token """
return [w for w in nltk.word_tokenize(text.lower()) if w not in string.punctuation]
def filter_stopwo... |
b8220207d21e392a6586454b3f003ac8800f0af3 | Yanl05/LeetCode | /six_hundred_thirty_seven.py | 2,623 | 3.765625 | 4 | # -*- coding: UTF-8 -*-
"""
# @Time : 2019-07-13 09:44
# @Author : yanlei
# @FileName: six_hundred_thirty_seven.py
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
来源:力扣(LeetCode)
链接:https://leetcode-cn.co... |
fefa5c186aa06f148fd66a0c8ae7220e364f9e9c | DilyanTsenkov/SoftUni-Software-Engineering | /Python_Advanced/05_Functions Advanced/Lab/04_operate.py | 367 | 3.875 | 4 | from functools import reduce
def operate(opr, *args):
operators = {
"+": reduce(lambda x, y: x + y, args),
"-": reduce(lambda x, y: x - y, args),
"*": reduce(lambda x, y: x * y, args),
"/": reduce(lambda x, y: x / y, args)
}
return operators[opr]
print(operat... |
c40bb2fd8c2d832b63fc1cd49c3718f6d8b96a87 | ipcoo43/pythonone | /lesson145.py | 758 | 4.21875 | 4 | print('''
[ 범위 만들기 ]
range(<숫자1>) : 0부터 (<숫자1>-1)까지의 정수 범위
range(<숫자1>,<숫자2>) : <숫자1>부터 (<숫자2>-1)까지의 정수의 범위
ringe(<숫자1>,<숫자2>,<숫자3>) : <숫자1>부터 <숫자3> 만큼의 차이를 가진 (<숫자2>-1)까지 범위
[ 범위와 반복문 ]
for <범위 내부의 숫자를 담을 변수> in <범위>:
<코드>
''')
print(range(5))
print(list(range(5)))
for i in range(5):
print('{}번째 반복문입니다.'.format(i))... |
53e90cbfca12d204fa1f9bdc9e2ca7fb2e99d855 | ernestojfcosta/IPRP_LIVRO_2013_06 | /controlo/programas/poli_1.py | 959 | 4.125 | 4 | # -*- coding: mac-roman -*-
# condicionais - exemplo raízes de polinómio
# Ernesto costa - 2006
import math
def main():
""" Calculo das raízes reais de um polinómio.
"""
a,b,c = eval(input("Os coeficientes sff (a,b,c):\t"))
r1,r2=raizes(a,b,c)
if r1 == r2 == None:
print("Não tem raízes reais!")
elif r1 == r2... |
9c1861f3f4fd8d7390644ed6fd30b9b6f4cf6f0b | oleoalonso/atvPython-12-10 | /main.py | 1,547 | 3.640625 | 4 | from Hotel import Hotel
from Hospede import Hospede
from Reserva import Reserva
hotel = Hotel("Feras", "Centro Histórico", 25)
hospede = Hospede("Maria", "Feminino", 32)
reserva = Reserva("25/12/2021", "05/01/2022", "600")
# H O T E L
hotel.Abrir()
hotel.Endereco()
print(f"O Hotel {hotel.nomeHotel} possui... |
d9237b612cf82ce010dcbd3cc987db8976e889de | limpingstone/socionics-engine | /cognitive_function.py | 3,525 | 3.75 | 4 | #!/usr/bin/env python3
#
# cognitive_function.py - By Steven Chen Hao Nyeo
# The script that creates the eight cognitive functions in socionics
# Created: January 1, 2019
# Label - F or T or N or S
# Sublabel - i or e
class CognitiveFunction:
def __init__ (self, label, name, description):
self.label = label[0]
... |
dccb0d10eb58230d336d12a1a754d86935073c77 | mayankdiatm/PythonScrapping | /oddEven.py | 295 | 4.15625 | 4 | #!/usr/bin/python
import math
number = int(raw_input("Enter a number of your choice :"))
if number%2 is 0:
if number%4 is 0:
print("The number is even and is divisible by 4")
else:
print("The number you entered is even")
else:
print("The number you entered is odd")
|
7abddaf9df3bbcdbb7dc8dc64cd3a8abc7ec60a2 | reute/sys-python | /13/sortthings/sortthings.py | 1,838 | 3.59375 | 4 | import random, sys
def einlesen_datei(namen):
unsortiert = []
for index, zeile in enumerate(open(namen, "r", encoding='utf-8', errors='ignore')):
namen, hoehe = zeile.rstrip('\n').split(":")
hoehe = int(hoehe)
berg = namen, hoehe
if index < MAX_BERGE:
unsortiert.append(berg)
else:
r = random.randint(... |
332fb5c75048cf6b24ca940ae341f02fd69f200d | patthrasher/codewars-practice | /kyu6-6.py | 807 | 3.5 | 4 | def meeting(s) :
count = 0
how_many_names = s.count(':')
fn = []
ln = []
while count < how_many_names :
x = s.find(':')
y = s.find(';')
fn.append(s[:x].upper())
ln_range = s[x+1:y]
if y == -1 :
ln_range = s[x+1:]
ln.append(ln_range.up... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.