blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
61da1347e699023ecb5755ca9ed3d17b97aad0df | SrilekhaSundara-git/Srilekha | /learn-to-code-with-python-incomplete/22-Decorators/nested_function.py | 343 | 3.859375 | 4 | def parent(num:int)->str:
print("You're inside the parent function")
def child1()->str:
return f'{num}, You are in child1'
def child2()->str:
return f'{num}, You are in child 2'
if isinstance(num, int):
if num == 1:
print(child2())
else:
print(chil... |
fc0ec0e7e126c01954ab076c9c4898f29d70cc05 | TehraniZadehAli/Python | /listSlice.py | 169 | 3.59375 | 4 | orgList = [11, 45, 8, 23, 14, 12, 78, 45, 89]
l1 = orgList[0:3]
l1.reverse()
print(l1)
l2 = orgList[3:6]
l2.reverse()
print(l2)
l3 = orgList[6:9]
l3.reverse()
print(l3)
|
d98a5a96690f1f74757c4ec565bb6e024ff1d53f | lorenzoMcD/Algorithms-and-Data-Structures | /Algorithms and Data Structures/Searching Algorithms/Search_Naive_String.py | 594 | 4.15625 | 4 |
# code taken from https://www.geeksforgeeks.org/naive-algorithm-for-pattern-searching/
def Search(txt,pat): # function takes in long string , and pattern to search for
m = len(pat) # will len both strings
n = len(txt)
# A loop to slide pat[] one by one
for i in range(n - m + 1):
j = 0
... |
07bcefd720eef856c5db504e9a323764dd8d7c19 | apjemran/PythonLearning | /basics/tuples.py | 837 | 4.09375 | 4 | '''
Created on 22-Sep-2020
@author: mohd.e.khan
'''
tup = ("Test", 1, 2.0)
print(tup)
print(tup[0])
print(tup*3)
tup + ("Test1",3)
print(tup)
tup1 = ("Test", ("Nested","Tuples", 1))
for item in tup1:
print(item)
print(tup1[1][0])
tup2 = ("Single Element Tuple",) # Create single ele... |
65961762baabfb015af706c33be60ab6783334b0 | zxcvbnm123xy/leon_python | /python1808real/day6/day6-2-set.py | 2,858 | 4.03125 | 4 | """
集合: 顶层是字典实现 set
"""
# 集合:字典中所有的value为None,相当于使用key组成集合
# 集合的规则跟字典的key的规则一致
"""
特点:
1. 不能重复
2. 集合的元素是不可变类型
3. 集合是无序
"""
# 集合无论如何也不能使用索引去获得元素。
# java中集合 是list(列表)是同一类,跟python不同。注意区分
# 一、创建集合
# 语法:名字={元素,}
# 语法:名字=set(序列)
a={1,2,3,5,6}
b=set([2,3,4,5,4])
print(a,b)
print(type(a),type(b))
# 创建的时候会直接去掉重复的元素。
print(len... |
7876daf8d5c0f8dd8c89ed220224043a852c1b0b | rajrohan/Trump-card-game-marvel | /main.py | 666 | 3.6875 | 4 | """
Main script that starts a new game.
"""
import deckgame as marvel_deck
def main():
"""
Starts a new game.
"""
while True:
new_game = input("Do you want to start a new game (Y for Yes, N for No)?")
if new_game.lower() == 'y':
start_game = True
eli... |
980875a058cb1e3056c61164831ac34742f9db75 | libohan0532/Randomwalk | /1demension.py | 590 | 3.609375 | 4 | import random
i=0#走路的计数器
j=0#设置初始位置
k=0#设置随机方向和大小
sum=0 #总位移的计数器
count=0 #walk2函数调用次数
lst = [-1,1]#配合随机数生成器
def walk1(i,j,k):
global sum
while i<1000:
k=random.choice(lst)
j=j+k
i=i+1
print(k)
print(str(j),'某一次实验的位置变化')
sum = j#记录该次实验的位移
sum2=0
while coun... |
1fbeca8988db8d05ce94a97b9adb57d7c6f40fc8 | makhalif/python | /day 3/love.py | 842 | 3.890625 | 4 | print("Love calculator")
nam1 = input("Enter your name: ")
nam2 = input("Enter their name: ")
names = nam1+nam2
name = names.lower()
# print(name)
t = name.count("t")
r = name.count("r")
u = name.count("u")
e = name.count("e")
true = t + r + u + e
l = name.count("l")
o = name.count("o")
v = name.count("v")
e... |
9c91faf72af67c5286f6949629a70967aacb0ab2 | shell-escape/EMAP_python_April2021_homeworks | /homework_2/task_1.py | 4,434 | 4.25 | 4 | """
Given a file containing text. Complete using only default collections:
1) Find 10 longest words consisting from largest amount
of unique symbols
2) Find rarest symbol for document
3) Count every punctuation char
4) Count every non ascii char
5) Find most common non ascii char for document
""... |
759fee8f08342a87a86b6928614304f2ed6688d7 | Durgadevi23/guvi1 | /code-katta/string/string_comparison.py | 177 | 4.15625 | 4 | #Program to find two string or equal or not
#Get input from user
S1,S2=map(str,input().split())
#check two input are equal or not
if(S1==S2):
print("yes")
else:
print("no")
|
e517bc3f169707c4bf2f9a8b2bcfa10fb0fa073c | herereadthis/Sagaxus | /demos/libraries/scipy/scipy_histogram_stats.py | 1,874 | 3.75 | 4 | '''
Generate a bunch of random numbers from a normal distribution, then determine
the distribution from the samples, and get stats from
'''
import scipy.stats
import numpy as np
import matplotlib.pyplot as plt
population_mean = 0
population_std = 1
# Grab a bunch of samples from a normal distribution with mean = 0, v... |
16366ed8b61d1f5f5ad4575ad97712b0f2d1d79e | NataliaWiniarska/python_1 | /project1.py | 596 | 3.890625 | 4 | def adding_report(report = "T"):
total = 0
items = "Items"
while True:
answer = (input("Enter a integer or \"Q\": ")).upper()
if answer.isdigit() == True:
total += int(answer)
items += "\n" + answer
elif answer.startswith("Q"):
... |
b23c32a58286b441eb2532aaf1eb1f7cd5d00adc | MdEstiakAhmed/python | /loop/multipliction table.py | 73 | 3.515625 | 4 | n=int(input())
m=1
while m<=10:
print(n,"*",m,"=",n*m)
m+=1
|
3c41cd6d25bfb1b25549ed459113d7e9be298be7 | simplesmall/Python-FullStack | /Day0625/Day23_11嵌套.py | 900 | 4.4375 | 4 | """
创建三个学校的设施内容是一致的
"""
class School(object):
def __init__(self, name, address):
self.name = name
self.address = address
def speech(self):
print('讲课')
obj1 = School('北京校区', '沙河')
obj2 = School('上海校区', '浦东新区')
obj3 = School('深圳校区', '南山区')
class Teacher(object):
... |
d03079cf100b02acf21e22651248e0f81d0f1cfa | syurskyi/Python_Topics | /100_databases/001_sqlite/examples/PYnative/004_INSERT query.py | 1,312 | 3.546875 | 4 | import sqlite3
def insertVaribleIntoTable(id, name, email, joinDate, salary):
try:
sqliteConnection = sqlite3.connect('SQLite_Python.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_insert_with_param = """INSERT INTO SqliteDb_developers
... |
c2da9efa0ee554c97805b9dd4cda4e8e57e6ecf3 | bmartin5263/Uno_Basic | /deck.py | 1,188 | 3.640625 | 4 | from card import Card
import random
class Deck():
''''shuffle' (bool) : shuffle deck.'''
colors = ('red', 'yellow', 'green', 'blue')
values = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'R', '+2')
def __init__(self, populate):
'''Initializes proper deck of 108 Uno Cards.'''
... |
3882aaf94b19967a1d1eff23fa4862ea71de3b38 | zhangchizju2012/LeetCode | /868.py | 506 | 3.921875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 8 18:04:13 2018
@author: zhangchi
"""
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
row = len(A[0])
result = [[] for _ in range(row)]
... |
f3f5a923c9b772c58bbd63cf2623b27169939beb | szymonlipinski/hackernews_analysis | /old_utils/build_sql_from_csv.py | 2,676 | 3.609375 | 4 | #!/usr/bin/env python
import csv
import re
import click
def get_type(data: list) -> str:
"""
Tries to find a proper type for the passed values.
It uses a couple of regular expressions, like the ints should have only numbers,
floats have numbers with one dot.
If they don't fit, then the defa... |
4e2fe5bf91eb13491ba8b8194bd5bf737b35a915 | rayvantsahni/Mini-Projects-and-Games | /GAMES/The Waiting Game/waiting_game.py | 762 | 4.0625 | 4 | import random
import time
def waiting_game():
goal_time = random.choice([2, 2.5, 3, 3.5, 4, 4.5, 5])
print("Your goal is", goal_time, "seconds.\n")
input("----Press Enter key to begin----\n")
start = time.perf_counter()
input("...Press Enter key after " + str(goal_time) + " seconds..... |
cd668a106f9fbe98d7e6ab33c39055065853ca1a | amsenthilkumar/ZenClass | /python programs/loops/sumofeven.py | 73 | 3.640625 | 4 | n=int(input())
i=2
sum=0
while(i<=n):
sum=sum+i
i+=2
print(sum) |
bc5b0e2edeb384706b41b81c50b473af593694d7 | chyu/Python-practice | /subAverageList.py | 659 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 3 22:05:54 2018
@author: chakyu
"""
#---- Start Program ----
#---- Start calc average function ----
def calcAverage(numlist):
average = sum(numlist)/len(numlist)
return average
#---- End calc average function ----
num = input('Please e... |
efc657bf82e49c685bd69d0bb58f3ea94cce8452 | zlogdanbr/mypython | /src/ebook.py | 747 | 3.515625 | 4 | import sys
import os
import pathlib
from pathlib import Path
mydir = "C:\\Users\\Administrador\\Biblioteca do calibre"
myext = "zip"
myextfinal = ".cbz"
def list_files(dir):
for root, dirs, files in os.walk(dir):
for name in files:
fext = getextension(name)
if ( fext... |
9cd6e8948cc8750dda80e02ad4edb6ed7c562c7c | theknightsofni/ATBS | /mclip.py | 705 | 3.71875 | 4 | #! python3
# mclip.py - A multi-clipboard program
# Send automatic messages when busy during a conference call
TEXT = {'agree': """Yes, I agree. That sounds good to me.""",
'busy': """Sorry, I'm in the middle of a conference call. Can I follow up with you after?""",
'thank': """Thank you!"""}
... |
561c53e73ada2daa43d13a089c3f3892b2f12ed6 | mikkkee/algo | /data_structures/stack.py | 931 | 4 | 4 | __author__ = 'Jianfeng'
"""Stack - First In Last Out (FILO).
Stack operations:
1. is_empty()
2. push()
3. pop()
"""
class Stack(object):
def __init__(self):
self._stack = []
def __repr__(self):
return str(self._stack) + ' <- Top'
def is_empty(self):
if self._stack:
r... |
ff3deababa77c3add73416cb33e70a10688ab67e | BahytMaralbek/Webka2021 | /W9/308.py | 178 | 3.765625 | 4 | def x_or(x,y):
if x==1 and y!=1:
return 1
if x!=1 and y==1:
return 1
else:
return 0
a = list(map(int,input().split()))
print(x_or(a[0],a[1]))
|
2d1686e7cc358108ee6539430a338e3ea962ec21 | helgefmi/aoc2020 | /day21/part1.py | 1,593 | 3.6875 | 4 | #!/usr/bin/env python3
from collections import defaultdict
def parse_food_list(cts):
ret = []
for line in cts.splitlines():
a, b = line.split(' (contains ')
ingredients = set(a.split(' '))
allergens = set(b[:-1].split(', '))
ret.append((ingredients, allergens))
return ret
... |
08b8c24349ece2473be4b425434a76c65b987040 | ZhongxuanWang/Python-Cluster | /Matrix/Demo.py | 881 | 3.84375 | 4 | """
This Demo is for matrix class written by Daniel Wang for interpretation
"""
from Matrices import Matrix
import numpy as np
def main():
mat1 = Matrix(mat=np.array([[1, 2, -3], [4, 0, -2]]))
mat2 = Matrix(mat=np.array([[5, -4, 2, 0], [-1, 6, 3, 1], [7, 0, 5, 8]]))
mat3 = Matrix(mat=np.array([[-1, 3, 1... |
3330ebc55a4e696d02f5bcf2aa102c911e0da164 | AmberHsia94/ml-basics | /knn.py | 2,862 | 3.765625 | 4 | # coding=utf-8
'''
The implementation of KNN algorithm.
(1)收集数据:确定训练样本集合测试数据;
(2)计算测试数据和训练样本集中每个样本数据的距离;
(3)按照距离递增的顺序排序;
(4)选取距离最近的k个点;
(5)确定这k个点中分类信息的频率;
(6)返回前k个点中出现频率最高的分类,作为当前测试数据的分类。
@Author: AmberHsia
@Date: 18.11.2018
'''
import time
import pandas as pd
import numpy as np
import operator
from sklearn.metric... |
d6408c1d638476dab3aaf69d1af6fe2f53d82b91 | sarthaksaini7/python | /learn11.py | 361 | 4.1875 | 4 | weight = input("Please enter your weight ")
unit = input("Please enter L for lbs & K for kilograms ")
if unit.upper() == "L":
weight_kg = int(weight) * 0.45
print(f'You are {weight_kg} kgs')
elif unit.upper() == "K":
weight_lbs = int(weight) * 2.2
print(f'You are {weight_lbs} lbs')
else:
print("Pl... |
01e7238cc8a691a826b151db9963e6ac26da72f4 | MinxZ/assignment | /Py4evon/Python assn0/smallest.py | 295 | 3.71875 | 4 | smallest = None
count = 0
sum = 0
print 'Before'
for value in [1,2.5,3.0,4.0,5.0]:
count = count + 1.0
if smallest == None:
smallest = value
elif value < smallest:
smallest = value
print smallest,value
sum = sum + value
print 'After',smallest,sum/count
|
048cc42db337b183332e3f76321672fd426dfd08 | Korred/advent_of_code_2019 | /day_01/task_2.py | 530 | 3.703125 | 4 | mass_data = []
# read input data
with open('task_1_input.txt', 'r') as data:
for line in data:
mass_data.append(int(line))
# additionaly calculates additional fuel needed for the initially added fuel
def required_fuel(mass):
fuel_values = [(mass//3)-2]
while True:
fuel_to_add = (fuel_value... |
e02066058e1bef34820460420424e18448a3cfa3 | manutdmohit/pythonprogramexamples | /findnumberofoccurencesofeachcharacterinstringdictionary1.py | 131 | 3.78125 | 4 | word=input('Enter any string:')
d={}
for ch in word:
d[ch]=d.get(ch,0)+1
for k,v in d.items():
print(k,'occurs',v,'times')
|
7dcbb47a11dce7c68d0cc435e90658521497930e | santoshdkolur/didactic-lamp | /dnaIterative.py | 476 | 4.1875 | 4 | '''
Write a program to print a dna structure
'''
#AUTHOR : SANTOSH D KOLUR
def dna(n):
for _ in range(n):
for i in range(8,0,-2):
print(' '*int((8-i)/2),'*','-'*int(8-(((8-i)/2)*2+2)),'*',' '*int((8-i)/2))
for i in range(2,9,2):
print(' '*int((8-i)/2),'*','-'*int(8... |
385d454153df8003c260ccccd6b29f50b99ac816 | hanrick2000/LeetcodePy | /test/interval/insert_interval.py | 848 | 3.671875 | 4 | import unittest
from leetcode.interval.insert_interval import Solution, Interval
class TestSolution(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test_insert_interval_1(self):
intervals = [Interval(1,3),Interval(6,9)]
newInterval = Interval(2,5)
expected... |
7406407ea7e4a74407e47617a7daa8970e9a774b | nguyenhuuthinhvnpl/machinelearning | /basics/my_pet_turtle.py | 562 | 3.6875 | 4 | import turtle
# what is written on that line is for human only, not for pythons
# the previously-written turtle programs
# (): the to the named action
# Turtle: special named action for creating an action
zacy = turtle.Turtle()
zacy.shape("turtle")
zacy.speed("slowest")
# repeates 4 times
def small_square():
... |
c0956b8e2577212d6460b38b5b369233620914fd | AlbyAa03/Compiti_Vacanze | /sistemi/armstrongNumber.py | 369 | 3.734375 | 4 | def armstrong(numero):
somma = 0
cifre = len(str(numero))
for cifra in str(numero):
somma += int(cifra) ** cifre
if somma == numero:
print("è un numero di Armstrong")
else:
print("non è un numero di Armstrong")
def main():
armstrong(9)
armstrong(153)
armstrong(15... |
1ac927fc05eb38972a83ca626cc8f45774c7bc42 | eileendwyer/my_comprehensions | /other_peoples_date.py | 998 | 3.828125 | 4 | import datetime
dates = ["2015 - 08 - 01", .....]
["Monday", "Tuesday", ...]
for date in dates:
date_list = [int(date_number) for date_number in date.split("-")]
date_obj = datetime.date(*date_list)
dow_index = date_obj.weekday()
#print(date)
print(days[dow_index]
#= =============================... |
5eb458c4c699d494d1d03826026faaae367ef62b | jingxiufenghua/algorithm_homework | /leetcode/leetcode378.py | 790 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :algorithm_homework
@File :leetcode378.py
@IDE :PyCharm
@Author :无名
@Date :2021/5/13 11:40
'''
from typing import List
import heapq
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
... |
118ff31809eeeb15e022b234f0545d8de1fbd8cd | shehryarbajwa/Algorithms--Datastructures | /sorting_algorithms/bubble_sort_2.py | 1,263 | 3.828125 | 4 | ###Problem 2
###Sam doesnt always go to sleep in the same hour.
# Given the following times Sam has gone to sleep, sort the times from latest to earliest
sleep_times= [(24,13), (21,55), (23,20), (22,5), (24,23), (21,58), (24,3)]
def bubble_sort_2(l):
for iteration in range(len(l)):
for index in range(1, ... |
2dc10a96172b6b135dd243efcf98c6deb1c9454b | priyesh16/algo2 | /hamming.py | 4,768 | 3.703125 | 4 | #! /usr/bin/env python
import sys
import itertools
def uniqify(a):
return list(set(a))
def printbinary(obj):
if type(obj) is int:
print bin(obj)
if type(obj) is list:
for line in obj:
print bin(line),
print "\n"
if type(obj) is dict:
for key, value in obj.iteritems() :
for item in value:
p... |
e90806de3e0dfd52086e674f033b77e92a56fa04 | darraes/coding_questions | /v1/_Base/combinations.py | 450 | 3.671875 | 4 | def combination_i(array, start, depth, stack):
#validations
if depth < 0 or depth > len(array): raise
if depth == 0:
print stack
return;
else:
for i in range(start, len(array)):
stack.append(array[i])
combination_i(array, i + 1, depth - 1, stack)
... |
c22f126ef72186fd6290a2af4d07d3d6eb863168 | js-stark/Black-Hat-Python-Learnings | /level2/md5hash.py | 719 | 3.8125 | 4 | import hashlib
from termcolor import colored
hashvalue = input('Enter the MD5 hash value of Password: ')
wordlist = input("enter the path for passwords list to check: ")
def findmd5password(hashvalue,wordlist):
with open(wordlist,'r') as file:
passwords = file.readlines()
for passwords in password... |
06b59b6942533af4e4eeb060d993f024a975c77c | enyapynot/python | /showme-the-money.py | 357 | 3.875 | 4 | payrate = eval (input ("whatchoo git an hour?"))
hours_worked = eval (input ("how many hours you sweated yo ass for?"))
if hours_worked <= 40:
final_pay = hours_worked * payrate
else:
final_pay = hours_worked * payrate
overtime = (hours_worked - 40) * 0.5 * payrate
final_pay = final_pay + overtime
pri... |
b0c027cbcf25b43439fe4b9946efe883c59c4e25 | joonluvschipotle/baekjoon | /10991.py | 162 | 3.703125 | 4 | a = int(input())
for i in range(1,a+1):
for j in range(0,a-i):
print(" ", end="")
for k in range(0,i):
print("*", end=" ")
print("")
|
d6110d0ac6aa3e54e150d6e66a863d0f72caa98d | Vilquid/Python-learning | /Sheet_FR.py | 4,526 | 3.859375 | 4 | # DATA SCIENCE CHEAT SHEET - Français
# s - Une variable string
# i - Une variable integer
# f - Une variable float
# l - Une variable list
# d - Une variable dictionnaire
# LISTS
l.pop(3) # Renvoie le quatrième élément de l et le supprime de la liste
l.remove(x) # Supprime le premier élément de l égal à x
l.reverse... |
56ce37bbee77aeac86628a5a96cd226a81f53224 | ecgaebler/Practice | /LeetCode/0434.py | 548 | 3.9375 | 4 | def countSegments(s):
segments = 0
last_char_was_space = True
for char in s:
if char == " ":
last_char_was_space = True
else:
if last_char_was_space:
last_char_was_space = False
segments += 1
return segments
#TESTING CODE BELOW TH... |
42c5dbae69edc01cf274b644e3ed06b7e4c22be7 | thec4iocesar/python3 | /pythyon_old/repeticao.py | 503 | 3.84375 | 4 | #!/usr/bin/python3.7
idade = int(input('Digite sua idade: '))
habilitacao = (input('Voce e habilitado? Sim ou Nao? '))
dirigir = False
if habilitacao.lower().strip() == 'sim':
habilitacao = True
else:
instrutor = input('Voce esta acompanhado de um instruto? Sim ou nao?')
if instrutor.lower().strip() == '... |
b7e5242c452f07f190e3f6c2015682b0e4f1b9ff | saikiran-gutla/Selenium | /tabs.py | 752 | 3.515625 | 4 | """This program is used to switch between the tags among the browsers"""
from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\Selenium Drivers\geckodriver-v0.26.0-win64\geckodriver.exe")
driver.get("http://demo.automationtesting.in/Windows.html")
driver.find_element_by_xpath("//*[@id='Tabbed']... |
7f8e8dff5a47100d64cfca79665d98623bc7bed6 | pjgaudre/Numerical-Algorithms | /LU_LUP.py | 1,549 | 3.578125 | 4 | import numpy as np
from copy import copy
def LU(A):
'''
This algorithm is the LU decomposition of a matrix WITHOUT PIVOTING.
Input: A : Matrix of size n by n.
Ouput: L : Lowertriangular matrix of size n by n. (L*U = A)
U : Uppertriangular matrix of size n by n.
'''
... |
9380c00d943a0f20bb86b2ed23a2b848388bcf20 | agnes-sharan/simpleRaft | /Annotated simpleRaft/boards/board.py | 874 | 4.15625 | 4 | # class MyClass(object): = new-style class
# class MyClass: = OLD-STYLE CLASS
# Used when defining base class objects
class Board(object):
# Python decided to do methods in a way that makes the instance to which the method
# belongs be passed automatically, but not received automatically: the first parameter
# of me... |
e3dece28c9dad0ccb5b6156756e192fcf3fea935 | Chaosame/leetcode_PYTHON | /树/102. 二叉树的层序遍历.py | 1,140 | 3.875 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 层次遍历需要将借助队列 python中是list 用pop 出首个元素
"""
这里的要点在于 我需要先把每层的节点先加入一个列表在放入结果中 那么我需要把他们按顺序查出所有孩子 之后再统一删除 这和单纯的层次遍历是不同的 单纯的层次遍历只需要 每次把队列第一的pop掉即可... |
d28188d65d19a4ca7f5e16f063b3e8996621eb77 | navarenjini20/renjini | /input constrains.py | 219 | 3.703125 | 4 | n = int(raw_input())
# input the array
arr = [int(x) for x in raw_input().split()]
# initialize variable
summation = 0
# calculate sum
for x in arr:
summation += x
# print answer
print(summation)
|
4f8184170ccf30b418750d1f394301633dcecfbe | jedzej/tietopythontraining-basic | /students/hyska_monika/lesson_11_argparse_math/selective_copy.py | 2,258 | 3.78125 | 4 | """
Program walks through a folder tree and searches for files
with a certain file extension (such as .pdf or .jpg).
Copy these files from whatever location they are in to a new folder.
"""
import shutil
import os
import argparse
import sys
def check_arg(args=None):
parser = argparse.ArgumentParser(description='S... |
85ca601a54cbf961a67e8cd8c4fb9eb4f8dec3ef | q2806060/python-note | /day09/day09/exercise/mymax2.py | 886 | 3.953125 | 4 | # 练习:
# 已知内建函数max帮助方档为:
# max(iterable)
# max(arg1, arg2, *args)
# 仿造max, 写一个mymax函数,功能与max完全相同
# (要求不允许调用max函数)
# print(mymax([6, 8, 3, 5])) # 8
# print(mymax(100, 200)) # 200
# print(mymax(1, 3, 9, 5, 7)) # 9
def mymax(*args):
# print('args=', args)
# 当元组长度为1时,传入的是一个列表
if le... |
46dd90549f43756c4216fac728384629137d99c2 | bill090/bill090-Python | /Python with AI - Level 2/datetime/datetime-ex4.py | 210 | 4.0625 | 4 | import datetime
today = datetime.date.today()
day = datetime.timedelta(days = 1)
yesterday = today - day
tomorrow = today + day
print(f"""Today is {today}.
Tomorrow is {tomorrow}.
Yesterday was {yesterday}.""") |
f1885f8d485373f660e259238384844188e10afb | 9car/IN1000-2 | /trix_tasks/week_1/high_num.py | 636 | 3.734375 | 4 | # 01.18 Størst verdi
'''
Skriv et program som tar inn tre forskjellige tall og finner den største verdien.
Hvor mange ganger den gjentas
'''
cpt = 0
a = int(input("Verdi 1: "))
b = int(input("Verdi 2: "))
c = int(input("Verdi 3: "))
if a >= b and a >= c:
largest = a
print(f"Det største tallet er {a}")
elif ... |
8c83ba158b9f29292a60311be9f69bd514a98ac1 | hgrecco/dedup | /dedup | 30,136 | 3.640625 | 4 | #! /usr/bin/env python
"""
===========================
dedup: a deduplication tool
===========================
Find and delete duplicated files.
Use cases
---------
Find duplicates in a specific folder and create a script to delete them:
dedup find -o byedups.sh /your/folder
Find duplicated mp3 in a folder (an... |
a1d46a6a3b6db7e2817034bf2c4804b69701ed26 | oasisvegapunk/vim_config | /.vim/dirs/backups/Lab04_Pattern_gen.py~ | 1,831 | 3.640625 | 4 | #! /usr/bin/env python3
import random
import math
TESTSIZE = 100
def in_number_gen(number):
in_number_list = [None]*number
for i in range(number):
in_number_list[i] = random.randrange(-16,16)
# print(in_number_list[i])
return in_number_list
def mode_gen():
return random.getrandbits(2)
... |
2174f028cfed0006fb71a4640a011c9c20d01d99 | ChunGang5/mygit | /day6.py | 1,596 | 4 | 4 | #!/usr/bin/env python
# -*- coding : utf-8 -*-
"""
输入M和N计算C(M,N)
m = int(input("请输入m"))
n = int(input("请输入n"))
fm = 1
for num in range(1,m+1):
fm *= num
fn = 1
for num in range(1,n+1):
fn *= num
fmn = 1
for num in range(1,m-n+1):
fmn *= num
print(fm // fn // fmn)
#函数形式的
def factorial(num):
resert =... |
ec5c66d3515be0851b33e37a1b8052e092c32228 | MuhammadMoustafa/Notes | /1_thread_lock/thread1.py | 697 | 3.59375 | 4 | import threading
x = 0
COUNT = 100000
def adding_2():
global x
for i in range (COUNT):
x += 2
def adding_3():
global x
for i in range (COUNT):
x += 3
def subtracting_1():
global x
for i in range (COUNT):
x -= 1
def subtracting_4():
global x
for i... |
bf6be7b302f9aad3c66b296ec1a27ed9311d223c | cortelucas/curso-python | /Lista de exercícios/ex-004.py | 549 | 4.1875 | 4 | # Faça um programa que leia algo pelo teclado e mostre na tela o seu tipo primitivo e todas as informações possíveis sobre ele.
valor = input('Digite algo: ')
print(f'O tipo primitivo deste valor é {type(valor)}')
print(f'Só tem espaços? {valor.isspace()}')
print(f'É um número? {valor.isnumeric()}')
print(f'É alfabét... |
605d31b526962a43f51d869d2e388703cd556c19 | sultanovacoder/python | /Car.py | 1,109 | 4.21875 | 4 | class Car():
"""класс по созданию автомобиля"""
def __init__(self,make,model,year):
print('Приобрели новый авто')
self.make = make
self.model = model
self.year = year
self.odometr = 0
def descriptionName(self):
"""возвращаем описание автомобиля"""
des... |
31470b5594ab736cb858e387f1a82f517d1eef58 | nosbod18/Alien-Crash | /choose_path_1.py | 7,372 | 3.96875 | 4 | # 2/8/20
# Evan Dobson
# Project: Alien crash
# Module: choose_path_1
import time
import random
import variables as var
def choose_path1(): # defines a function to allow the player to choose a path
time.sleep(7)
print("After walking for a while, you come across a lone farm house. Smoke is coming out of the c... |
26c5aa2a1b98574c1556a229e24e9a78568b1807 | jbagur/MapReduceAmigos | /RedAmigos.py | 3,213 | 3.8125 | 4 | #! python2
# Se esta utilizando un hash bang para que corra en python2
#Tareas de Mapeo
#1.Librerias
#Intertools: This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.
#sys: This module provides access to some ... |
b72fa2ec0e71ed86848176fae511776c4f8f72a2 | Ashutosh-kumar-2020/Desktop-assistant-jarvis | /translate.py | 1,149 | 3.625 | 4 | # import modules
from tkinter import *
from englisttohindi.englisttohindi import EngtoHindi
# user define funtion
def eng_to_hindi():
trans = EngtoHindi(str(e.get()))
res = trans.convert
result.set(res)
# object of tkinter
# and background set for grey
master = Tk()
master.configure(bg = 'li... |
0c077a9252c39aa127f47c7adcb1ec80effae1e1 | abboliwit/kompendietoliver | /kompendie/kompendie/kap.2/2.5.py | 736 | 3.8125 | 4 | print("hur många barn vill ha ...")
korv2 = int(input(" 2 vanliga korvar>"))
korv3 = int(input(" 3 vanliga korvar>"))
vKorv2 = int(input(" 2 veganskaa korvar>"))
vKorv3 = int(input(" 3 veganska korvar>"))
print("inköp")
antal_korv = round((korv2*2)+(korv3*3)+3)/8#räknar yt mägden korvar
antal_vKorv = round((vKor... |
a4b438d1b9025c3bb0206f299df7b9f5258ccd9d | p-stets/python6 | /python/lesson4/practice/pif.py | 123 | 3.5 | 4 | '''
Таблица пифагора
'''
for num in range(1, 11):
lst = [num * x for x in range(1, 11)]
print(lst)
|
e89fe9c4a77cd4cb9dffaaba4bdefedbaedc5350 | LyaisanN/Homework_Figure | /src/Rectangle.py | 469 | 3.734375 | 4 | from src.Figure import Figure
class Rectangle(Figure):
name = 'Rectangle'
def __init__(self, height, width):
self.height = height
self.width = width
super().__init__(name='Rectangle', area=None, perimeter=None)
# *** Вычисление площади и периметра прямоугольника ***
rectangle = Rect... |
e655ba8b70135fa85828dbc5143ee8e9285d1b48 | Kenkron/timeshift | /csvExtractor.py | 692 | 3.703125 | 4 | #imports the csv library
import csv
#open the output file for writing
f = open('extractOutput.txt','w')
#create a hash table for the values that have already been processed
values = {}
#open the input file
inputFile=open('timezone.csv')
#extract the lines of the input file
inputLines=csv.reader(inputFile);
#go through ... |
209c704360538e8d0ff49abad96342e7b70a1b2b | sohitmiglani/Applications-in-Python | /Binary Search Tree.py | 1,898 | 3.890625 | 4 | class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.l_child is None:
root.l_child = node
else... |
d5323b613ed874878e54e13ec1dfb4a3d19580c9 | carloshenrique051994/Uri | /Python/1008 - Salario.py | 193 | 3.765625 | 4 | numeroFunc = int(input()) #numero funcionario
horasTrabalhadas = int(input())
valorHora = float(input())
print('NUMBER = {}\nSALARY = U$ {:.2f}'.format(numeroFunc, horasTrabalhadas*valorHora)) |
44f61919c7bcb54fa07e5a7f4a7ef4c406301bdb | kbdnr/csci_crypto | /assg4/lfsr.py | 2,116 | 3.640625 | 4 | #Kevin Bednar - CSCI 4905 - Assignment 4
def binEnc(character):
#Encode plaintext into binary
if character == ' ': tInt = 26
elif character == '?': tInt = 27
elif character == '!': tInt = 28
elif character == '.': tInt = 29
elif character == "'": tInt = 30
elif character == '$': tInt = 31
else: tInt =... |
00e609ad79ffb9df6df21e173ab730889d53b851 | kakts/cracking-the-coding-interview | /ch01/ch01-2/counter.py | 1,114 | 3.671875 | 4 | # Counterを使った解答
import sys
from collections import Counter
args = sys.argv
if len(args) != 4:
raise Exception('''
Please input the target string. \n
eg: $ python 1-2.py testa testb y
if use ignoreCase mode please input y in the third argument.
''')
text_a = args[1]
text_b = args[2]
isIgnoreCase = (a... |
ae24a714b239d3d047926e7c6249c122518faf9d | joseespiritu/CursoPythonPi | /0015Generadores.py | 743 | 4.0625 | 4 | # GENERADORES
# SE CONSTRUYE UN OBJETO GENERADOR ITERABLE
# EN VEZ DE REGRESAR UN RETURN REGRESA UN YIELD
# EL PROGRAMA QUEDA EN STAND BY, SE DEVUELVEN LOS VALORES DE UNO EN UNO
# LA VENTAJA ES LA EFICIENCIA
# FUNCION
#def generaPares(limite):
# num=1
# miLista=[]
# while num<limite:
# miLista.append(... |
08ed7790789e812546bdac8547519a7b28657f57 | nwgdegitHub/python3_learning | /05-类的多态.py | 1,006 | 3.78125 | 4 | class Student(object):
mobile = '18856425363'
def __init__(self, name, age, weight):
self.name = name
self._age = age
self.__weight = weight
@classmethod
def get_mobile(cls):
return cls.mobile
@property
def get_weight(self):
return self.__weight
# ... |
a2926392258d7f10b303f8246d0d5b3fd1a217e8 | chanwanxiang/isMe | /Read-Search-Ask/Python/黑马2020/1-Python核心编程/1-基础语法/18-概念内容/1-装饰器/2-装饰器.py | 869 | 3.765625 | 4 | # 装饰器
# 1. 定义
# 装饰器就是给已有函数增加额外功能的函数,它本质上就是一个闭包函数
# 装饰器的功能特点:
# 1. 不修改已有函数的代码
# 2. 不修改已有函数的调用方式
# 3. 给已有函数增加额外的功能
# 2. 示例代码
# 定义装饰器
def decorator(func):
def inner():
# 对已有的函数进行装饰
print('登录验证完成')
func()
return inner
# 如果闭包函数的参数有且只有一个并且是函数类型,那么这个闭包函数称为装饰器... |
d0f9921f971209df2783a2c2efd78e77cda52280 | ReisRibeiroRafael/AfroDev | /maiorNumeroEntre3.py | 3,430 | 4.03125 | 4 | from tkinter import messagebox
from tkinter import simpledialog
from tkinter import*
root = Tk()
root.withdraw()
def is_float(valor):
try:
float(valor)
except:
return False
return True
def is_int(valor):
try:
int(valor)
except:
return False
... |
b8fb2b106a3fbfd8e848becb67a4e46d8996a207 | manosxatz/python | /lesson09/exercise06.py | 608 | 4.1875 | 4 | while True:
string = input("Give name: ")
string = string.strip()
if string.isalpha():
name = string.capitalize()
print(f"Name entered: {name}")
break
else:
print("only characters please! ")
while True:
string = input("Give surname: ")
string = stri... |
67bc395ea13d00c858373f9bd9656bc7debe9bac | brunomilitzer/python-fundementals | /basicprograms/averageofnumbers.py | 153 | 4.125 | 4 | a, b, c = [int(x) for x in input("Enter three integer numbers: ").split()]
average = (a + b + c) / 3
print("Average of the three numbers is: ", average) |
cb1b45e77ab27c469a1a32d6920e810bcc4519a1 | vingiarrusso/cs_fundamentals | /practice_problems/keys_and_rooms.py | 479 | 3.546875 | 4 | """
leetcode 841
"""
def canVisitAllRooms(rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
l = len(rooms)
room_was_entered = [False] * l
entered_rooms = 0
key_ring = [0]
while len(key_ring):
key = key_ring.pop()
if not room_was_entered[key]:
room_was_ent... |
cab3920406064c380aea0ebe672c3dfe26164543 | melisarv/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 246 | 3.796875 | 4 | #!/usr/bin/python3
'''function inherits_from'''
def inherits_from(obj, a_class):
''''returns True if the object is an instance of the specified class'''
if type(obj) is a_class:
return False
return isinstance(obj, a_class)
|
45cc9a9e9c45426785daba8b29898870cf73621c | jason-padilla/DSFundamentals | /Leetcode/Blind75/191E-NumOf1Bits.py | 727 | 3.921875 | 4 |
'''
191 NUMBER OF 1 BITS
Write a function that takes an unsigned integer and returns the number of '1' bits it has
Input: n = 00000000000000000000000000001011
Output: 3
Input: n = 11111111111111111111111111111101
Output: 31
'''
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
... |
7ffaf9c1f724b9b787ff9a22dedc0da73581a852 | conradbm/streamml2 | /streamml2/database/database_connection.py | 3,038 | 3.875 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
return conn
... |
9755f233f539f45d806517286a6ccbe2aecb560c | Vivekyadv/InterviewBit | /Two Pointers/Sorting/1. pair with given diff.py | 1,466 | 3.609375 | 4 | # Given 1-D unsorted array having n integers, find if there exists a pair
# whose difference is B
# Example: arr = [5, 10, 3, 2, 50, 80] B = 78
# pair = (80,2)
# Method 1: Brute-force method
def solve(arr, B):
n = len(arr)
for i in range(n):
for j in range(n):
diff = arr[j] - arr[i]
... |
f5f6e535d7e29ae4702397499f726eff5096348a | shahidul2k9/problem-solution | /leetcode/1274. Number of Ships in a Rectangle.py | 1,349 | 3.640625 | 4 | # """
# This is Sea's API interface.
# You should not implement it, or speculate about its implementation
# """
#class Sea:
# def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool:
#
#class Point:
# def __init__(self, x: int, y: int):
# self.x = x
# self.y = y
class Solution:
def countShips(self,... |
82954d3d8d5dd100fb708a63f1361613ef709d2c | HenriqueNO/Python-cursoemvideo | /Desafios/Desafio_051.py | 297 | 3.640625 | 4 | prim = int(input('Informe o primeiro termo da pogressão aritmética: '))
razao = int(input('Informe razão da pogressão aritmética: '))
termo = 10 * razao
for c in range(prim, termo, razao):
print('{}{}{}'.format('\033[1;34m', c, '\033[m'), end='\033[1;31m->\033[m')
print('\033[1;33mFim.') |
d14d5275abe51b9daa87f0dd6f1eb6f8fc045e07 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4155/codes/1674_1079.py | 415 | 4 | 4 | from math import *
A = float(input("Lado 1: "))
B = float(input("Lado 2: "))
C = float(input("Lado 3: "))
print("Entradas:", A, ",", B, ",", C)
if ((A >= 0) and (B >= 0) and (C >= 0)):
if((A < B + C) and (B < C + A) and (C < A + B)):
s = (A + B + C) / 2.0
area = sqrt(s * (s - A) * (s - B) * (s - C))
r = roun... |
559816a15de467e518ccac157e30d79d585b9c8e | rallen0150/class_notes | /practice/sort_by_letter.py | 251 | 4.0625 | 4 |
def sort_by_letter(sentence):
words = sentence.split(' ')
words.sort()
sorted_words = ','.join(words)
return sorted_words
sentence = input("Type in words seperated by spaces:\n").lower()
words = sort_by_letter(sentence)
print(words)
|
d9af6ff888ba8f281d4c65ca5d124f861c63207c | hangdinh9199/HangDinh-D4E11 | /Assignment 1/areaofcircle.py | 71 | 3.640625 | 4 | n = input('enter radius ')
area = 3.14*int(n)**2
print('Area = ', area) |
d876632fa0e874e1f7c2ba991dfe7e831dcd09fc | dbialon/blackjack | /blackjack.py | 3,987 | 3.84375 | 4 | from typing import List
from itertools import product
from random import shuffle
from time import sleep
deck = []
player_hand : List[str] = []
dealer_hand = []
players = [player_hand, dealer_hand]
def generate_deck(deck: List[str]) -> None:
deck.clear()
ranks = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J... |
a00da0c9300d38df3fa8ce86d2a15ba540b1064d | MEAJIN/Python | /10주차/9/p8.py | 730 | 3.765625 | 4 | it = {}
it = [{'Name':'홍길동','Tel':'010-1111-0001','Dept':'그린화학과'},
{'Name':'홍길서','Tel':'010-1111-0002','Dept':'컴퓨터공학과'},
{'Name':'홍길남','Tel':'010-1111-0003','Dept':'전자공학과'},
{'Name':'홍길복','Tel':'010-1111-0004','Dept':'바이오생명공학과'}]
print("리스트 데이터")
print(it)
print()
print("전체 학생 이름")
for key in i... |
7f71836294d3a8b0f391746abb845da3152ea4c2 | david-weir/Programming-3-Data-Struct-Alg- | /week3/check_brackets.py | 1,052 | 3.9375 | 4 | class Stack(object):
def __init__(self):
self.l = []
def push(self, other):
self.l.append(other)
def pop(self):
return self.l.pop()
def top(self):
return self.l[-1]
def is_empty(self):
return len(self.l) == 0
def __len__(self):
return len(sel... |
793e33bd9e336c44c9b9cda0ebf1f647912658e9 | tedye/leetcode | /tools/leetcode.098.Validate Binary Search Tree/leetcode.098.Validate Binary Search Tree.submission10.py | 842 | 3.921875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @return {boolean}
def isValidBST(self, root):
# attempt one recursive
if not root: ret... |
2df73ce8b90bc033e587047e85174b4f8eb3231d | PamelaPaprasz/greenfoxExercises | /week-02/day2/animals-and-legs.py | 228 | 3.734375 | 4 | print("How many chickens you have?")
user_input1 = int(input())
print("How many pigs you have?")
user_input2 = int(input())
legs = user_input1 * 2 + user_input2 * 4
print("Your animals have " + str(legs), " legs in all. ")
|
6640501d7ea97f68a0a1c49c7fb897f0c4caf8c2 | Jboyblastmk3/Grokkers-Grok-Learning-Archives | /2021/Beginners/2.1 Q4.py | 221 | 3.984375 | 4 | print('There are lots of different animals around the world.')
animal = input('What is the best animal? ')
if animal == 'kangaroo':
print('The kangaroo is the national animal of Australia.')
print('What a fun animal!')
|
ec75776e56658be65a3fd0753077b48774aa1c57 | ugaemi/algorithm | /pythonCodingInterview/ArrayAndString/9.py | 575 | 4.0625 | 4 | import unittest
def rotation_string(s1, s2):
"""
s2가 s1을 회전시킨 결과인지 판별
:param s1: 첫 번째 문자열
:param s2: 두 번째 문자열
:return: 회전시킨게 맞다면 True, 아니면 False
"""
if s2 in s1 + s1:
return True
return False
class Test(unittest.TestCase):
def test_rotation_string(self):
self.asse... |
74a32ab308039727ab7dec7b498442c1af2159ba | heyang930520/Leetcode | /src/leetcode/ShuffleAnArray.py | 667 | 3.71875 | 4 | import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.nums
... |
0e687aad876c061a37595596c0e1c3fa169f3c20 | gakshay198/python101 | /ex13.py | 812 | 3.953125 | 4 | # sys is Package.
# argv is a module.
from sys import argv
script, first, second, third, fourth = argv
# command line argumnts are taken as strings
print("The script is called :", script)
print("The first variable is called:", first)
print("The second variable is called :", second)
print("The third variable is calle... |
f865d11508ed722439228027809b46b8c7a88b52 | Kiriyamaku/learning_algorithm | /7_14_longest_public_prefix.py | 649 | 3.734375 | 4 | class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result=[]
for index,letter in enumerate(strs[0]):
print(strs[1:])
for word in strs[1:]:
print(word)
print(ind... |
7ea0ad3ef892f99e0358b8827a6985e65e399c89 | abdullah-alanazi/Python | /hw4-4.py | 610 | 3.734375 | 4 | import os
import pickle
def green_pickle(n,a,c):
func = fi()
info = (n , a , c)
func = list(func)
func.append(info)
func = tuple(func)
file1 = open('infoF.txt', 'wb')
try:
pickle.dump(func , file1)
finally:
file1.close()
# read from file
def fi():
if (os.path.exists('infoF.txt')):
filez = open('infoF.tx... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.