blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f3059d2733e8637518dc102b66b596bfb07f9c5d | sanskarjain2507/full-stack-development | /python/list40.py | 86 | 3.765625 | 4 | list=['L1','L2']
if 'L1' in list:
print("present")
else:
print('not present')
|
00b1230c16298db372c1cec1696b6a7c7f0b3d28 | Cptgreenjeans/python-workout | /ch03-lists-tuples/e12b2_popular_shells.py | 445 | 3.5 | 4 | #!/usr/bin/env python3
"""Solution to chapter 3, exercise 12, beyond 2: shells_by_popularity"""
from collections import Counter
import operator
def shells_by_popularity(filename):
shells = Counter(one_line.split(':')[-1].strip()
for one_line in open(filename)
if not one_... |
06cded12396dc422c4d93af4d15efd991e619b51 | janania/python | /exercises/find_less.py | 263 | 3.734375 | 4 | l = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_lis = []
def less_five (lis):
for num in lis:
if num < 5:
new_lis.append(num)
new_lis.sort()
else:
continue
print(set(new_lis))
less_five(l)
|
1799e4d81d75ce5a5ad2c35cb1baad155c9c0369 | yimonima/git | /python_for_pygame/DrawCircle.py | 687 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#导入包
import pygame,sys
from pygame.locals import *
#屏幕初始化
pygame.init()
screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Draw Circle")
#事件处理机制
while True:
for event in pygame.event.get():
if event.type in (QUIT,KEYDOWN):
sys.ex... |
7a44934a650fb7fe441710674a70c580b46a93da | espiercy/py_junkyard | /python_udemy_course/51 class.py | 284 | 3.90625 | 4 |
#create class. You need to begin with an uppercase letter
class Person:
name=""
age=0
def show(self, n, a):
self.name=n
self.age=a
print(self.name, self.age)
#instance of class
p1=Person()
#method call
p1.show('Evan',22)
print(p1.name, p1.age) |
597c3444a008ff67fe262213bb9d9136bc55f9a7 | whitepaper2/data_beauty | /leetcode/057_insert.py | 1,230 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 下午1:05
# @Author : pengyuan.li
# @Site :
# @File : 057_insert.py
# @Software: PyCharm
from typing import List
def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""
note: 顺序插入,遇到重叠的则合并
:param inte... |
10eb30511f29adce39b1e02ef82f976bc2ba792d | disatapp/Operating-Systems | /Operating Systems/Homework2/Problem4.py | 726 | 4.15625 | 4 | # Pavin Disatapundhu
# disatapp@onid.oregonstate.edu
# CS344-400
# homework#2 Question4
import math
import sys
def findprime(prime):
i = 0
n = 2
isprime = True
while i < prime:
for j in range(2,int(math.sqrt(n)+1)):
if (n % j) == 0:
isprime = False
if isprime... |
06f5133e6d93d8bcc620da508f43474fc1984ab8 | brcsomnath/competitive-programming | /graph/maze.py | 1,251 | 4.25 | 4 | '''
The Maze II
There is a ball in a maze with empty spaces and walls. The ball can go through
empty spaces by rolling up, down, left or right, but it won't stop rolling until
hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, find... |
32da9e6b13808d61df60c7fa9cfa924b011efd30 | steja2891/Python_Practice-coding-files- | /min,max,avg.py | 312 | 3.515625 | 4 | n = int(input())
s = set()
l1 = []
for i in range(n):
l1.append(list(map(str, input().rstrip().split())))
print(l1)
dict = {"A":0,"B":0,"C":0}
for i in range(n):
if int(l1[i][2][0]) > int(l1[i][2][2]):
dict[l1[i][0][0]]
elif int(l1[i][2][0]) == int(l1[i][2][2]):
else:
print(dict)
|
f752a9b5302e2a7c036c474477dc8ba912402d44 | goaguilar/GoAguilar_CS50_Projects | /goaguilar-cs50-2017-fall-sentimental-credit/credit.py | 844 | 3.703125 | 4 | from cs50 import get_int
sum1 = 0
sum2 = 0
print("Number: ")
card = get_int()
tempcard1 = card
tempcard2 = card//10
while tempcard1> 0:
sum1 += tempcard1%10
tempcard1 //= 100
while tempcard2>0:
if ((tempcard2 % 10) *2 > 9 ):
sum2 += ((tempcard2 % 10)*2) // 10
sum2 += ((tempcard2 % 10)*2)... |
e2b65e7caccb22dc37c1ff3402e20bca6c40f370 | andyballer/playingWithPython | /TypingDistance.py | 1,075 | 3.90625 | 4 | '''
Created on Nov 26, 2012
@author: Andy
'''
#returns the number of keys one has to traverse in order to type a message.
#uses a linear "keyboard" input to check how far apart the letters are
def minDistance(keyboard,word):
counter = []
library = []
for index, letter in enumerate(keyboard):
lib... |
0964c7b91b40a532ae1b5316d82105cd22b310bc | thiago-ximenes/curso-python | /pythonteste/aula13.py | 142 | 4 | 4 |
soma = 0
for c in range(0, 3):
n = int(input('Digite um valor: '))
soma += n
print('Fim')
print('O simatório foi: {}.'.format(soma)) |
da0370eeb4848ab5518ebbf2e7baae6891aecddb | b1ueskydragon/PythonGround | /codeit_kr/merge-sort.py | 1,657 | 4.21875 | 4 | def merge(list1, list2):
"""
merge binary lists.
each lists should be sorted.
this yields a new merged list.
:param list1: sorted list
:param list2: sorted list
:return: merged list
"""
merged = []
while list1 and list2:
if list1[0] <= list2[0]:
merged.appe... |
10a70e468758e501105cf77324bcd6a0efd7de82 | snarkfog/python_hillel | /lesson_09/number_digit.py | 1,519 | 4.28125 | 4 | """
10. Написать функцию, циклически сдвигающую целое число на N разрядов вправо или влево, в зависимости от третьего
параметра функции. Функция должна принимать три параметра: в первом параметре передаётся число для сдвига, второй
параметр задаёт количество разрядов для сдвига (по умолчанию сдвиг на 1 разряд), 3-й бул... |
7f9dbc50455ea03dc54045b90141a0a3df33104b | FluTheFire/Python-Algorithm-30-Days-Challenge | /Day-5 Longest Common Prefix [Runtime 20 ms].py | 377 | 3.640625 | 4 | def longestCommonPrefix(strs):
if strs == []:
return ""
s1, s2 = min(strs), max(strs)
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
return s1[:i]
raw_list = ["flower","flow","flight"]
raw_list2 = ["dog","racecar","care"]
raw_list3 = []
raw_li... |
6c7ee61b2c7663d223bbcd1b02d146e9c4a6e532 | maddalen-ma/LorenzAttractor | /lorenz/solver.py | 12,539 | 3.65625 | 4 | """
This file may contain the ODE solver
"""
import numpy as np
np.seterr(over='raise') # raise error for floating-point overflow
class lorenz_solver(object):
"""
This is a class for managing parameters and calculating trajectories of a
Lorenz attractor.
The lorenz_solver class is const... |
acbb3a30aaf6bd23138080044f720044915bdc72 | williamsyb/mycookbook | /algorithms/BAT-algorithms/Search & Sort/1-归并.py | 2,112 | 3.71875 | 4 | """
一、介绍
基本思想:
将数组array[0,...,n-1]中的元素分成两个子数组:array1[0,...,n/2]
和array2[n/2+1,...,n-1]。分别对这两个数组单独排序,然后将已排序的
两个子数组归并成一个含有n个元素的有序数组
二、步骤
递归实现
三、时间复杂度:O(N*logN)
四、归并排序的两点改进
* 在数组长度比较短的情况下,不进行递归,而是选择其他排序方案,如插入排序
* 归并过程中,可以用记录数组下标的方式代替申请新内存空间;从而避免array和
辅助数组间的频繁数据移动
"""
def merge(left, rig... |
6f4555f3ded92b1d7eff489dededda89818cb45e | secfordoc23/MyFirstRepository | /GroupAssignment/Starbucks Junior.py | 3,077 | 3.59375 | 4 | """
Program: Starbucks Junior
File: StarbucksJunior.py
Author: Jason J Welch, Rita Allen, Eric Gavin
Date: 9/26/2019
Purpose: we are selling coffee for $2.00, tea for $1.75, and latte for $4.00;
in three sizes: tall with price factor of 1, grande with price factor
of 1.5, venti for... |
677ef0a1c3dd7e2decc85beb533637cdf4f5622b | bofh69/aoc | /day10/part1.py | 2,307 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
def read_file(file):
file = open(file, "r")
text = file.read()
file.close()
return text
if len(sys.argv) != 2:
raise Exception("Expected one argument")
inp = read_file(sys.argv[1])
inp = inp.split('\n')
width = len(inp[0])
height = len(inp) - 1
astroids = []
... |
f502fe63b3d08f80e0b12ca7bb3557642d12eb40 | sumaiyasara/guvi-codekata | /evenno.py | 175 | 3.625 | 4 | lower_limit, upper_limit = input().split()
lower_limit= int(lower_limit)
upper_limit= int(upper_limit)
for i in range(lower_limit+1,upper_limit):
if(i%2 == 0):
print(i)
|
27fefeb76f0706781727f804484bb57a412e7268 | daozun/Python | /base_python/video/video_if_and_or.py | 464 | 3.671875 | 4 | # python的逻辑运算符
py = input('你python学好了么:')
js = input('你前端精通了么:')
money = int(input('你的财产总和:'))
if py == '是' and js == '是' and money > 10000:
print('你可以进京了')
else:
print('再好好学学','厉害了,我的哥')
# 在Python中 and表示两个条件同时满足是才为真(js中的&&),or表示只要一个条件为真就为真(js中的||),还有一个not是取反的意思。 |
3da128dde82f6a0ea72c28abee7d7e4e3834ff96 | GwangWoon/_python | /GW0921/GW0921/GW0921.py | 1,537 | 3.6875 | 4 | #class Movie :
# '''영화클래스입니다.'''
# title = "앤트맨"
# director = "모름"
# def __init__(self, title, director) :
# self.title = title
# self.director = director
# print(self.title + " 생성")
# def showInfo(self) :
# print(self.title + ", " + self.director)
# def __del__(self) : ... |
b59cf7393aae35a9b2a81e2acdb188c0160c980d | ad-vasilchenko/Avito_Python_Exam | /utils.py | 882 | 3.546875 | 4 | import time
from typing import Callable
def time_report(str_in: str, str_out: str) -> Callable:
"""
Этот декоратор выводит выводит комментарий о начале работе функции
и о времени её работы
"""
def outer_wrapper(func: Callable) -> Callable:
def inner_wrapper(*args, **kwargs):
... |
b3e6a1ed4b2aa616179807ff3ded322e9e0ee0e1 | udhayprakash/PythonMaterial | /python3/10_Modules/15_turtle_module/traffic_light.py | 2,135 | 3.921875 | 4 | #!/usr/bin/python
"""
Purpose: Traffic Light Simulation
"""
import turtle
def draw_signal_stand():
"""Draw a nice housing to hold the traffic lights"""
tess.pensize(3)
tess.color("black", "white")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(157)
tess.circle(40, 180)
... |
c4bcd6eb8ed1961d0c1983d8f9a639321f7792cb | vilhelmp/adapy | /adapy/libs/date.py | 1,956 | 3.640625 | 4 |
def jd2gd(jd):
"""
From http://www.astro.ucla.edu/~ianc/python/_modules/date.html
Task to convert a list of julian dates to gregorian dates
description at http://mathforum.org/library/drmath/view/51907.html
Original algorithm in Jean Meeus, "Astronomical Formulae for
Calculators"
... |
387230b3f4f9ff9377f48b56b6bd620667227731 | skenpatel4/internship_tasks | /day03/task1.py | 317 | 3.96875 | 4 | a = int(input("enter five numbers : "))
b = int(input("enter five numbers : "))
c = int(input("enter five numbers : "))
d = int(input("enter five numbers : "))
e = int(input("enter five numbers : "))
print(a)
print(b)
print(c)
print(d)
print(e)
average = (a+b+c+d+e)/5
print("Average is = ",average) |
5c79cda3ef553592e4bff67785da79cc6694cf98 | jewells07/Python | /OS_module.py | 973 | 3.765625 | 4 | import os
# print(dir(os)) #It will show which function what OS module can do
# print(os.getcwd()) #It will get current directory (on which folder are you)
# os.chdir("c://") #It will change current directory (You can search file in this path )
# print(os.getcwd()) ... |
7dc8a7f5dc74c312a47f39792c7c3031a87d75d0 | nbtt/sokoban_solver | /make_game.py | 2,517 | 3.796875 | 4 | # Usage:
# space: toggle pen up/pen down. default is pen up (green)
# arrow key (up/down/left/right) to move
# press number key to change the pen:
# 0: ground or nothing
# 1: wall
# 2: box
# 3: goal
# 4: box on goal
# 5: player
# 6: player on goal
# Enter: Save and exit
from os import system
from pynput import keyboar... |
fc03eb379c22988723aee8c2309b6f8a9d020326 | Ni3h/CodeWars | /Mumbling.py | 530 | 3.53125 | 4 | """
Solution for the Mumbling question on codewars
https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/python
Pretty simple, only 'complex thing' is to ensure that the - does not get
added to the first iteration of the newString
@author Ni3h
"""
def accum(s):
newString = ""
for i, letter in enumer... |
1c652f2548d6aa8e5c9d548df3d272049dda7886 | Larissa-D-Gomes/CursoPython | /introducao/exercicio057.py | 447 | 3.875 | 4 | """
EXERCÍCIO 057: Validação de Dados
Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'.
Caso esteja errado, peça a digitação novamente até ter um valor correto.
"""
def main():
leitura = input('Digite o sexo [M/F]: ')
while leitura != 'M' and leitura != 'F':
leitur... |
a9c2bc08b10542fcd15a4028d16cd2872312d50b | edzzn/hackerRank-interview-preparation-kit | /array/3-new-year-chaos.py | 689 | 3.65625 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/new-year-chaos
def minimumBribes(q, n):
diff = 0
for i in range(n):
item_to_find = n - i
correct_index = n - i - 1
current_index = q.index(item_to_find)
index_diff = correct_index - current_index
diff += index_diff
... |
ecc9f65ea8209c6a18b6512602ad1c212e3ad58d | Aasthaengg/IBMdataset | /Python_codes/p02664/s409260937.py | 447 | 3.609375 | 4 | a = input()
t = list(a)
if t[len(t)-1] == "?":
t[len(t)-1] = "D"
if t[0] == "?":
if t[1] == "D" or t[1] == "?":
t[0] = "P"
else:
t[0] = "D"
for i in range(1, len(t)-1):
if t[i] == "?" and t[i-1] == "P":
t[i] = "D"
elif t[i] == "?" and t[i+1] == "D":
t[i] = "P"
eli... |
845719d60a2a83a26a7f90e157cbb24ccc5166d6 | BIGSergio123/Uece | /Silva.py | 225 | 3.84375 | 4 |
"""
program that says if you have Silva / SILVA in your last name
by: BIG
"""
N = str(input("digite seu nome completo:"))
palavras = N.split()
if 'Silva' or 'SILVA' in palavras:
print('sim')
else:
print('Não')
|
6a0d623bfc87bff605d8a60d7850d23c1ff06ea2 | khourhin/pyGen | /common.py | 396 | 3.734375 | 4 | #-------------------------------------------------------------------------------
def get_lst_from_file(infile):
"""
From a file with one entry per line, get a python list of these entries
"""
with open(infile, "r") as f:
elmt_l = [ line.strip() for line in f]
return elmt_l
#----... |
b5f6a0217fbe9261e63dfdd25e31c7912058d1cb | apoorva9s14/pythonbasics | /mysamples/decorator.py | 462 | 4.1875 | 4 | #Difference between functions and generator
def g():
print('inside generator')
yield 1
g()
#The function call does not print 'inside generator'
#When the generator function is called, the function code is not executed
#Instead the function call returns a generator object
def f():
print('inside funct... |
efd6348454b0d1363ab8829e262e158894537bdc | patricksile/code_folder | /code_wars/5kyu_ascii_hex_converter.py | 1,620 | 4.28125 | 4 | #!/usr/bin/env python3.5
# Solution: ASCII hex converter
"""
Write a module Converter that can take ASCII text and convert it to hexadecimal.
The class should also be able to take hexacadecimal and convert it to ASCII text.
Example:
<code>
Converter.to_hex("Look mom, no hands") => "4c6f6f6b206d6f6d2c206e6f2068616e6473... |
8f7ab9d04f9b8e6a8cee051a2342845fe6c71b2a | lachesischan/comp20008-2021a1 | /parta1.py | 831 | 3.515625 | 4 | import pandas as pd
import argparse
import sys
url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
df = pd.read_csv(url)
#add 'month' column into dataframe
df['date']= pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
#Select range of dates and columns needed and create a new dataframe
sele... |
e10462eaa91dbb0d7659187bcb45d116982c8fd4 | MichelleZ/leetcode | /algorithms/python/expressionAddOperators/expressionAddOperators.py | 1,520 | 3.65625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/expression-add-operators/
# Author: Miao Zhang
# Date: 2021-01-30
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
res = []
for i in range(1, len(num) + 1):
if i == 1 or... |
1013d8dc6a389fba6c2a6dce26e477ba0128cd24 | PPR123/Python_Programs | /ex009.py | 1,569 | 3.84375 | 4 | import math
import time
import emoji
import random
print(emoji.emojize(":car:"*random.randint(30,35),use_aliases=True))
print("Criando um usuário para jogar adivinhação em Python")
print(emoji.emojize(":car:"*random.randint(30,35),use_aliases=True))
n = 0
pnome = str(input("Digite seu Primeiro nome: ")).upper()... |
6374c04153457fd58a775611bbd43e18f326b4ac | mitant127/Python_Algos | /Урок 1. Практическое задание/task_9.py | 1,256 | 4.1875 | 4 | """
Задание 9. Вводятся три разных числа. Найти, какое из них является средним
(больше одного, но меньше другого).
Подсказка: можно добавить проверку, что введены равные числа
"""
NUMB_1 = int(input('Введите первое число: '))
try:
NUMB_1 = int(NUMB_1)
except ValueError:
print('Вы ввели не число')
NUMB_2 = int... |
7c58e4eb58790ad4a670a7d3e6ab1152369c806b | epanepucci/slic | /slic/utils/readable.py | 745 | 4 | 4 |
AVERAGE_WEEKS_PER_MONTH = 365.242 / 12 / 7
# each tuple gives a unit and the number of previous units which go into it
UNITS = (
("minute", 60),
("hour", 60),
("day", 24),
("week", 7),
("month", AVERAGE_WEEKS_PER_MONTH),
("year", 12)
)
def readable_seconds(secs):
# adapted fr... |
67dbbc1e80d646e0e892d64b7408b38a89112f12 | Anil-account/python-program | /square.py | 544 | 3.59375 | 4 | #to find power
# d=dict()
# for x in range(1,5):
# d[x]=x**2
# print(d)
#copy
# d1 = {'a':100, 'b':200}
# d2 = {'x':300, 'y':200}
# d = d1.copy()
# d.update(d2)
# print(d)
a=[]
dict ={'roll no' : [1,2,3,4,5], 'name' : ['ali','katy','sam','hasley','poppey'],'mark' : [55.0,99.8,78.0,67.0,45.0],'sex':['male','... |
27212e85be48301f2b7aeecdfcb4e29016f777c5 | taech-95/python | /Beginner/CoffeeMachine/main.py | 3,485 | 3.75 | 4 |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
"milk": 0,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
}... |
8c5617b2811f20964956d698cda2e6ff64c8c803 | lapis2002/word-concordance | /a4/concordance.py | 3,700 | 3.59375 | 4 | import sys
import re
PATTERN = r'''^((\w|\-)+$'''
class KWOC:
def __init__(self, filename, exceptions):
self.text = (self.get_content(filename))
self.exclusion_words = self.get_exclusion_words(exceptions)
def get_content(self, filename):
input_txt = open(filename, "r")
... |
3520fd2169e9e2256c8a7d315c0e2670befc572d | caiquemarinho/python-course | /Exercises/Module 04/exercise_01.py | 124 | 4.09375 | 4 | """
Create a program that reads a int number and prints it.
"""
num = 4
print(f'Your number is {num}')
print(type(num))
|
dcf4adb951d4f0fd4cd967e54daf85fe85b1a5f4 | VictorYXL/Machine_Learning | /FP Growth/Node.py | 852 | 3.734375 | 4 | class Node:
def __init__(self, name, parent):
self.name = name
self.count = 1
self.parent = parent
self.children = {}
self.next = None
def inc(self, num = 1):
self.count += num
def show(self, ind = 1):
print("Deep %d: %s, %d" % (ind, self.name, self.co... |
5d4c83a85d8b52be9848d9de1e9a6fcdeda732d9 | sysPursuer/learnPy | /FurFunction.py | 544 | 3.71875 | 4 | #在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,
#这5种参数都可以组合使用。但是请注意:
#参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
def f1(a,b,c=0,*agrs,**kw):
print('a=',a,'b=',b,'c=',c,'agrs=',agrs,'kw=',kw)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
f1(1,2)
f1(1,2,3)
f1(1,2,3,'a','b')
f1(1,2,3,'a','b',x=99)
... |
85d3120f72558edc3a788fc6037d212f3ffb016b | tacenee/AFR | /剑指offer66/python/13调整数组顺序使奇数在偶数前面.py | 425 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
# 类似于选择排序,从后往前,如果前偶后奇就调换两个数字的位置
for i in range(len(array)):
for j in range(i, 0, -1):
if array[j] % 2 == 1 and array[j - 1] % 2 == 0:
array[j], array[j - 1]... |
e2fca34394b09139da83a774ee39aebd49eb7c59 | KobiShashs/Python | /25_Advannced_Generators/4_pipelining_generators.py | 197 | 3.78125 | 4 | #integers (1-10) ----> squared(x^2) ----> negated(x*(-1))
integers = (i for i in range(1,11))
squared = (x * x for x in integers)
negated = (-y for y in squared)
for num in negated:
print(num) |
ffc61527526f16747b5b78d77af95036c644dffe | daniel-reich/ubiquitous-fiesta | /d6wR7bcs4M6QdzpFj_3.py | 298 | 3.609375 | 4 |
def repeat(lst, n):
k = lst[:]
for _ in range(n-1):
lst.extend(k)
return lst
def add(lst, x):
lst.append(x)
return lst
def remove(lst, i, j):
k = j - i + 1
for _ in range(k):
lst.pop(i)
return lst
def concat(lst, lst2):
lst.extend(lst2)
return lst
|
509b01b157f6d6a4dabdf57ad3726dc717b0b2b9 | moki298/HadoopMapReduce | /reducer.py | 1,760 | 3.78125 | 4 | #!/usr/bin/env python
from operator import itemgetter
import sys
#Declaring and intializing the variables
word = None
cur_count = 0
cur_word = None
max_sub = 0
max_sub_name = None
min_sub = 1
min_sub_name = None
list = []
for line in sys.stdin:
#stripping the whitespaces in data
line=line.strip()
... |
3cd1eb502fee193f0576b6f81032c9842a8927dd | ronek22/ProjectEuler | /Python/027.py | 642 | 3.8125 | 4 | '''Quadratic primes'''
from math import sqrt; from itertools import count,islice
def isPrime(n):
return n>1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
primes = set()
for i in range(1,10000):
if isPrime(i):
primes.add(i)
max_count = 0
formula = ""
max_a = 0
max_b = 0
for a in range(-999,1000)... |
6991b76e5b0501ef85bf4a1353d0bc9eb17b3623 | tegarimansyah/malas-cli | /malas-cli/malas_config/plugins/tegarimansyah/hello_world.py | 427 | 3.546875 | 4 | import click
from PyInquirer import prompt
questions = [
# Learn more in https://github.com/CITGuru/PyInquirer#question-types
{
'type': 'input',
'name': 'name',
'message': 'Your name?',
}
]
@click.command()
def command():
"""Do some greeting"""
answers = prompt(questions)
... |
fb890e9a8982ba826473ce5e78d0e6edfcfa4e1a | sreenivasgithub/tusk | /firstfile.py | 153 | 3.703125 | 4 | def add(a,b):
return a+b
obj = add(10,20)
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf') |
c387d1ddd8f3f9977a625db4d677fd9a388346c1 | noeljt/ComputerScience1 | /hws/hw4/hw4_part3.py | 815 | 3.515625 | 4 | """
Horror Movie Stuff.
Author: Joe Noel (noelj)
"""
def block(s, length):
sen = list(s)
sen.append(" ")
mystr = ""
line = []
n = 0
while n < (length*10):
line.append(n)
n += 1
while (mystr.count("\n")) < 9:
for x in line:
if (x+1) < len... |
d94cb3983ea29c2ff19b1e2369fcf13ba9d4c2f7 | palobde/INF8215---Introduction-to-AI | /Solving Travelling salesman problem using_Astar_2opt alg/code/A_star/A_star.py | 2,580 | 3.5625 | 4 | import time
time.clock()
import queue as Q
from Graph import Graph
SOURCE = 0
from Solution import Solution
class Node(object):
def __init__(self, v, sol, heuristic_cost=0):
self.v = v
self.solution = sol
self.heuristic_cost = heuristic_cost
def explore_node(self, heap):
f... |
e0d57e7e726eef80279eba9e511275b4cf20e506 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/point-mutations/44a2c3f5f71d4cf582bf2ba94e385d4d.py | 312 | 3.78125 | 4 | #!/usr/bin/env python
class DNA:
def __init__(self, sequence):
self.sequence = sequence
def hamming_distance(self, other_sequence):
distance = 0
for n1, n2 in zip(self.sequence, other_sequence):
if n1 != n2:
distance += 1
return distance
|
d6e793f67717eb8c3f673b6bab3eeb1b2b7183d6 | PythonCore051020/HW | /HW01/zoreastr/task_2.py | 183 | 3.78125 | 4 | print("What is your name?")
a = input("")
print("How old are you?")
b = input()
print("Where do you live?")
c = input("")
print("Hello",a,".","Your age is",b,".","You live in",c,".") |
ee50cdc39d432cd8ea9e2a41277a84621056236b | KomalNimbalkar30/Hackerrank-Python-Solutions- | /Collections_deque.py | 609 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import deque
n=int(input())
d = deque()
for _ in range(n):
s=input().split()
if s[0]=='append':
d.append(s[1])
elif s[0]=='appendleft':
d.appendleft(s[1])
elif s[0]=='pop':
d.pop... |
bfe030e6142ae90f6cd997ef3a25045b3f5077e6 | leo-ware/leetcode | /14. Longest Common Prefix.py | 587 | 3.828125 | 4 | """
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
"""
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not len(strs):
... |
0730e6de761ab9080d6b3ec960e8e893c2290c70 | historybuffjb/leetcode | /problems/middle_of_the_linked_list.py | 1,011 | 4.28125 | 4 | """
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
"""
from test_utils import ListNode
def middle_node(head: ListNode) -> ListNode:
"""
Explanation
We could just loop through all the nodes puttin... |
e73a60c5f5846da19d9afe6386ac2759322c21bd | 0gravity000/IntroducingPython | /05/050501.py | 1,135 | 3.8125 | 4 | # 5.5.1 setdefault()とdefaultdict()による存在しないキーの処理
periodic_table = {'Hydrogen': 1, 'Helium': 2}
print(periodic_table)
carbon = periodic_table.setdefault('Carbon', 12)
carbon
periodic_table
helium = periodic_table.setdefault('Helium', 947)
helium
periodic_table
#
from collections import defaultdict
periodic_table = d... |
23623ffa940cfd772b6b56ff445330b963e7f8bf | nandoribera/PYTHON | /binario.py | 239 | 3.84375 | 4 | print("CONVERSOR DE BINARIO A DECIMAL")
print("Introduce el número binario")
binario = input()
binario = list(binario)
binario.reverse()
x = 0
num = 0
while x < len(binario):
if binario[x] == "1":
num += 2 ** x
x = x + 1
print(num) |
20e411ed4e52cb501b8daed143fd4e2068774011 | deanjingshui/Algorithm-Python | /8_动态规划/337. 打家劫舍 III.py | 2,446 | 4.5 | 4 | """
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。
除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列
类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
输出: 7
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1... |
f0890b75c3c25dfcbb281f0881f8e215f9a72c1e | AK-1121/code_extraction | /python/python_23844.py | 138 | 3.515625 | 4 | # Python create tuples using function returning multiple values
new_list = [(name, value) + extra_info(name) for name, value in old_list]
|
998d2eed70afbff9022441332b85b2b50b446942 | alienlien/algorithm | /python/02/binary.py | 549 | 4 | 4 | #!/usr/bin/env python3
import math
def binary_search(in_list, x):
length = len(in_list)
if length == 0:
return []
if x < in_list[0]:
return [-1, 0]
if x > in_list[-1]:
return [length-1, length]
start = 0
end = length
while ((end - start) >= 2):
middle = m... |
bf03ac3b62b7740f12ddf5e5b10a706c788b9eea | chowdhurykaushiki/python-exercise | /PracticePython/Exercise25.py | 1,985 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
You, the user, will have in your head a number between 0 and 100.
The program will guess a number,
and you, the user, will say whether it is too high, too low, or your number.
At the end of this exchange,
your program should print out how many guesses it took to get your number.
"""
class... |
86f2116cf4d058acb5de42cd3cda7fdd628f1c3b | Vovanuch/python-basics-1 | /elements, blocks and directions/strings/string_template_format.py | 643 | 3.984375 | 4 | '''
strings format
'''
sentence = 'Moscow is the capital of Russia'
template = '{} is the capital of {}'
print(sentence)
print(template.format("Minsk", "Resp.Belarus'"))
print(template.format("Tegeran", "Iran"))
#print(str.format.__doc__)
# directly change the order of arguments
print()
print('directly change the ... |
38f35b84329018a569bf06546d9501866416c778 | AmineAouragh/PONG-2.0 | /testscreen.py | 1,838 | 3.8125 | 4 | # Import the pygame library and initialise the game engine
import pygame
import colors
from paddle import Paddle
from ball import Ball
pygame.init()
class GameScreen:
sprites_list = []
left_paddle = Paddle(colors.WHITE, 20, 120)
right_paddle = Paddle(colors.WHITE, 20, 120)
ball = Ball(colors.WHITE, ... |
504cececc991d8b0ef9ae42ad1502ec66e0ac9f8 | AnanyaDoshi728/PL_mini_project | /main.py | 11,109 | 3.609375 | 4 | from sqlite3.dbapi2 import connect, register_adapter
import tkinter as tkinter_instance
from tkinter import *
from tkinter import messagebox
import sqlite3
import main_window
import colors
#login window
def render_login_window():
def on_click_confirm_login():
try:
db_connection =... |
153d9116d2f7969c27601a20ee8b065e72078120 | DanielBarcenas97/AlgorithmsAndDataStructures | /AlgorithmsPython/topoSort.py | 2,073 | 3.53125 | 4 |
class vertex:
def __init__(self,i): #Constructor
self.id=i
self.visitado=False
self.nivel=-1
self.vecinos=[]
#self.costo=9999999
def agregarVecino(self,v):
if v not in self.vecinos:
self.vecinos.append(v)
def eliminarVecino(self,v):#Pasar a graph, recibe vertices
if v in self.ve... |
93685a98fb920de46ffb4dd0b0f0108b88b695fe | abrarulhaque/spaceinvader | /bullet.py | 1,080 | 4.0625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""a class to manage bullet fired from the ship"""
def __init__(self,ai_settings,screen,ship):
"""create a bullet object at the position of the ship"""
super(Bullet,self).__init__()
self.screen=screen
#create ... |
f61ad8aa893fb2c0e98e41baad68a7b5762de883 | DongusJr/HangmanPA6 | /Game_folder/Game.py | 2,110 | 4.0625 | 4 | #Imports
from Game_folder.Score import Score
# Main
class Game:
''' Class that holds information for each game played
Class variables
---------------
is_win : bool
Indicates wheter player won or not
guess_tuple : tuple with ints
Holds how many wrong guesses ... |
efdae5745f07197c04066fddf01005962b9475f5 | smossavi7/steamlite_examples | /streamlit_example.py | 1,542 | 3.796875 | 4 | import streamlit as st
import pandas as pd
import plotly.express as px
st.write('# Avocado Prices dashboard') #st.title('Avocado Prices dashboard')
st.markdown('''
This is a dashboard showing the *average prices* of different types of :avocado:
Data source: [Kaggle](https://www.kaggle.com/datasets/timmate/... |
bfd5842f9ae67b3fde89300a6bb032836c84966c | ShivaLuckily/pythonBasicProgramming | /overRiding.py | 484 | 4.09375 | 4 | '''class overiding:
i=10
def display(self):
print("parent class")
class over(overiding):
i=20
def display(self):
print("child class")
c=over()
c.display()
print(c.i)'''
######## overloading #########
class overloading:
def display(self,a=None,b=None):
if a!=None and ... |
fdaa15e5b0952ae7bdf12060e374888d06b2e82d | zlatnizmaj/Xu_ly_anh | /Moj Python/Numpy/linspace().py | 1,249 | 3.859375 | 4 | """
numpy.linspace() in Python
About :
numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) :
Returns number spaces evenly w.r.t interval.
Similiar to arange but instead of step it uses sample number.
Parameters :
-> start : [optional] start of interval range. By default start = 0
-> ... |
90ba8a1c99afb6741f8bf660242753587862477a | srijan-singh/Hacktoberfest-2021-Data-Structures-and-Algorithms | /Data Structures/Disjoint Set/DisjointSet.py | 1,834 | 4.28125 | 4 | class DisjointSet:
"""
Disjoint Set data structure (Union–Find), is a data structure that keeps track of a
set of elements partitioned into a number of disjoint (nonoverlapping) subsets.
Methods:
find: Determine which subset a particular element is in. Takes an element of any
subset as an argument and returns... |
7fe5c6afef908698c2c8bce79bb860b1a273cd2d | cryjun215/c9-python-getting-started | /python-for-beginners/06 - Dates/format_date.py | 669 | 4 | 4 | # 현재 날짜와 시간을 얻으려면 datetime 라이브러리를 사용해야합니다.
from datetime import datetime
# now 함수는 현재 날짜와 시간을 리턴합니다.
today = datetime.now()
# 일, 월, 년, 시, 분, 초 function 사용해 날짜의 일부만 표시할 수 있습니다.
# 이 모든 함수는 정수(integer) 값을 반환합니다.
# 다른 문자열에 연결(concat)하기 전에 문자열로 변환해야 합니다.
print('Day: ' + str(today.day))
print('Month: ' + str(today.month))
... |
def1708abba279cbeb55d25f527ec2bdf7b2e9bb | karthiklingasamy/Python_Sandbox | /B02_T3_Strings_WorkingWithTextualData.py | 282 | 3.703125 | 4 | greeting = 'Hello'
name = 'karthik'
# print(dir(name)) # It will show us all the methods and attributes that we have access [to] with [that] variable now
# print(help(str)) # To get more info about string class
print(help(str.lower)) # To get specific info about function |
ee99597f8e3de1a02f8340162e108342dd8a4d8d | ducdmdo/algorithms | /python/udacity_recursion.py | 316 | 3.625 | 4 | def get_fib(position):
if position == 0:
return position
print ("position = 0")
if position == 1:
return position
print ("position = 1")
print ("position is at %s" % position)
result = get_fib(position-1) + get_fib(position-2)
return result
print (get_fib(8))
|
8b1cbfc51f482f7d7cb099980f6287d8d57c340a | zubrik13/coding_intrv_prer | /repeated_string.py | 557 | 3.828125 | 4 | """
There is a string, s, of lowercase English letters
that is repeated infinitely many times.
Given an integer, n, find and print the number of letter a's
in the first n letters of the infinite string.
"""
s = "abcac"
n = 14
multiplicator = n // len(s)
count_a = 0
for letter in s:
if letter == "a":
co... |
180a12e149dafd29a46ba2e0cdab9c461e001ca7 | serashioda/code-katas | /src/sort_cards.py | 1,614 | 4.15625 | 4 | """Implementation of the Sort Cards Kata."""
class PriorityQueue(object):
"""Priority list queue."""
def __init__(self, iterable=None):
"""Construct priority queue."""
self.queues = {}
self.num_items = 0
if iterable is not None:
for data, priority in iterable:
... |
90c15631f2c5034457375a217f6f0e603e70daba | sachinjose/Coding-Prep | /PythonPrep/Object Oriented Programming/R2_4.py | 448 | 3.71875 | 4 | class Flower:
def __init__(self):
name = ''
petals = 0
price = 0.0
def updatename(self,a):
self.name = a
def getname(self):
print (self.name)
def updatepetals(self,a):
self.petals = a
def getpetals(self):
print(self.petals)
def updateprice(self,a):
self.price = a
def getprice(self):
prin... |
969e1452da763ad2bf042c2c0aa5370cf14a4e73 | szbrooks2017/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 265 | 4.03125 | 4 | #!/usr/bin/python3
def uppercase(str):
for c in range(len(str)):
if (ord(str[c]) >= 97) and (ord(str[c]) <= 122):
alpha = chr(ord(str[c]) - 32)
else:
alpha = str[c]
print("{}".format(alpha), end='')
print('')
|
86d6588dc43d50a8cd91e34d0303f5bed249e4e4 | Ruhshan/back-to-basics | /1.Arrays&Strings/IsUnique.py | 304 | 3.90625 | 4 | def is_unique(str):
is_present = [False]*26
for c in str:
if is_present[ord(c)-97]:
return False
else:
is_present[ord(c)-97]=True
return True
if __name__ == "__main__":
print(is_unique("abcdef"))#True
print(is_unique("ttxder"))#False |
a83fd596c85f121e2ca3ce9d9a9659c9808f8bb7 | alparty/labs | /techlead/versions.py | 2,140 | 4.0625 | 4 | """Version numbers are strings that are used to identify unique states of software products. A version number is in the format a.b.c.d. and so on where a, b, etc. are numeric strings separated by dots. These generally represent a hierarchy from major to minor changes. Given two version numbers version1 and version2, co... |
5c77b47e726d715deb742f9d05579a7d869c0263 | trezum/ML-Course | /lektion7/opgave3.py | 2,215 | 3.546875 | 4 | from sklearn import datasets
from sklearn.cluster import KMeans # This will be used for the algorithm
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from sklearn.model_selection import train_test_split
from sklearn.neighbors im... |
750a635c96b09b84a321099570a2148c065a4ed3 | itorres1994/MapReduce | /MRTemperatureObservations2.py | 1,357 | 3.640625 | 4 | from mrjob.job import MRJob
import sys
class MRTemperatureObservations2(MRJob):
def mapper(self, key, line):
# sys.stderr.write("MAPPER INPUT: ({0},{1})\n".format(key, line)) # displays intermediate values of mapper
data = line.split(',') # take the input from the text file and parse it with re... |
907416a2984b91061abaed2120e8ec9892be6b31 | gstamatakis/python_algorithms | /n_queens/SimulatedAnnealing.py | 5,124 | 4 | 4 | import time
from random import randint
from random import random
import numpy as np
class SimulatedAnnealing:
def __init__(self, suppress, t0, tmin, cool, eps, sn=100):
self.board = None # The Queens are represented in this 1d array. The array position and the cell number are the Queen's 'coordinates' ... |
9777569b94a94a42b5740654833ff33c79a480af | ivni195/mat1-projekt | /fermat_factorization.py | 801 | 4.21875 | 4 | #! /usr/bin/python3
import math
# Try to find factors of the form n=(a-b)(a+b) for an odd n.
def fermat_factorize(n):
a = int(math.ceil(math.sqrt(n)))
b2 = a * a - n
# Look for a such that b = a^2 - n is a perfect square.
while math.sqrt(b2) != math.floor(math.sqrt(b2)):
a += 1
b2 = a ... |
e92b0c4092082f76504bc5dae481b7c3398da37c | jocelo/rice_intro_python | /practice_excercises/week_5a/02_circle_clicking.py | 1,178 | 4.09375 | 4 | # Circle clicking problem
###################################################
# Student should enter code below
import simplegui
import math
# define global constants
RADIUS = 20
RED_POS = [50, 100]
GREEN_POS = [150, 100]
BLUE_POS = [250, 100]
# define helper function
def dist(p, q):
return math.sqrt((p[0] - q[... |
6d183d6a339d306e249739a2c9f5b73e037a95b9 | Sqweejum/Ch.01_Version_Control | /1.2_turtorial.py | 1,253 | 3.9375 | 4 | '''
Modify the starter code below to create your own cool drawing
and then Pull Request it to your instructor.
Turtle Documentation: https://docs.python.org/3.3/library/turtle.html?highlight=turtle
'''
import turtle
tina = turtle.Turtle()
tina.shape('turtle')
tina.penup()
tina.right(90)
tina.forward(180)
tina.right(... |
147d6849ff8a19775e6018581b42d2a760a527bd | unicoe/LeetCode | /python_src/349. Intersection of Two Arrays.py | 429 | 3.765625 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
so easy。。。
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
resSet = set()
for i in nums1:
for j in nums2:
if i == j:
r... |
06f920a352b1713c50882d5d6371a756e50b373f | ankushSsingh/allassigns | /redeem/q3.py | 569 | 3.765625 | 4 | #!/usr/bin/env python
def printtree(arr,left,right):
l=right-left
if(l==0):
#print arr[right]
return
for i in range(left,left+int(l/2)):
print " ",
print arr[left+int(l/2)]
printtree(arr,left,left+int(l/2))
printtree(arr,left+int(l/2)+1,right)
def main():
str=raw_input().split(' ')
arr = [int(num) fo... |
e3a9e43537bb6de62f980f2cb4d3655bc5797d5e | jagrvargen/coursera_algos_datastructures | /week_2_exercises/lcm_naive.py | 224 | 3.640625 | 4 | def lcm_naive(a, b):
if a < b:
a, b = b, a
min = a * b
for i in range(min, a, -1):
if i % a == 0 and i % b == 0:
min = i
return min
print(lcm_naive(int(input()), int(input())))
|
1343cfd2e6c1f2f0125a06993d197c35e66905f1 | mghasemi19/python_sample | /Basic/D5_String.py | 4,111 | 4.03125 | 4 | s = 'abcde'
print(s[1:3]) # bc
print(s[1:-1]) # bcd
print(s[1:4]) # bcd
print(s[::-1]) # edcba
s = 'shirafkan'
print(len(s)) # 9
print(max(s)) # s
print(min(s)) # a
print(ord('s')) # 115
print(ord('a')) # 97
print(chr(97)) # a
s = 'python'
print( 'th' in s) # True
print( 'xh' n... |
a7dfc4f96f6a666e5cf9f3d07a253a770442b344 | WillyNathan2/Python-Dasar | /PR04_2072037/PR04A_2072037.py | 774 | 3.71875 | 4 | #File : PR04A_2072037.py
#Nama : Willy Natanael Sijabat 2072037
#Deskripsi : Membuat program value total bintang(*) maupun garis lurus (|) , sama dengan n
# Dengan Ketentuan perjarak dari variabel m dengan memberikan tanda garis lurus
# (|)
# n = integer
# m = integer
... |
56f27a334e7529aa2a0c457ec5ba93ef52f3e974 | AlexNewson/ProjectEuler | /python/000-050/euler016.py | 347 | 3.640625 | 4 | import time
import euler
euler.print_problem(16)
start = time.time()
# ==================================================
number = 2**1000
n = 0
for i in str(number):
n += int(i)
print("The Answer is: %i" % n)
# ==================================================
end = time.time()
time = end - start
print("Thi... |
756487450d6ddb1f86497cabce3606d32b8e00ec | elviswong-cn/python_basic | /part1_basic/chapter1_basic.py | 800 | 3.859375 | 4 | #1.1
# print(2+3*6)
# print((2+3)*6)
# print(48565878 * 578453)
# # 幂
# print(2 ** 8)
# print (23 / 7)
# # 取整
# print( 23 // 7)
# # 取余
# print ( 23 % 7)
# print(2+2)
#1.3
# print('Alice' + 'Bob')
# # 字符串打印5次 * Int
# print('Alice' * 5)
#1.4
# spam = 50
# print(spam)
# eggs = 2
# print(spam + eggs)
# spam=spam+e... |
7df2dec29d404117970e06425342547fc28853ae | will-i-amv-books/Functional-Python-Programming | /CH4/ch04_ex2.py | 3,440 | 3.9375 | 4 | #!/usr/bin/env python3
"""Functional Python Programming
Chapter 4, Example Set 4
Definitions of mean, stddev, Pearson correlation
and linear estimation.
http://en.wikipedia.org/wiki/Mean
http://en.wikipedia.org/wiki/Standard_deviation
http://en.wikipedia.org/wiki/Standard_score
http://en.wikipedia.org/wiki/Normal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.