blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a30bae8420b7636e3f9ea19131cf953c62925f94 | brntco/Euler-problems | /euler07.py | 263 | 3.609375 | 4 | list_target = 10003
prime_list= [2]
check = 3
while len(prime_list) < list_target:
p = True
for x in prime_list:
if check%x == 0:
p = False
if p == True:
prime_list.append(check)
check += 2
print(prime_list[10000])
|
1ccc95ab3cedbf03cd2bd2aa7584c977a011e766 | Abbath90/python_epam | /homework8/task2/president_db.py | 4,487 | 4.78125 | 5 | """Homework 2:
Preamble
We have a database file (example.sqlite) in sqlite3 format with some tables and data.
All tables have 'name' column and maybe some additional ones.
Data retrieval and modifications are done with sqlite3 module by issuing SQL statements.
For example, to get all data from TABLE1:
import sqlite3
... |
052b476977e7628c055e59ecf2bfdbaaf46b3421 | alfredholmes/tensorflow-btc-predictions | /predictor.py | 4,568 | 3.515625 | 4 | import tensorflow as tf
import csv, random
#Constants
#neural network takes data from the last input_length days
input_length = 10
#and gives output for the next output_length days
output_length = 1
#This is a first approximation, so just a standard neural network will be used, even though a RNN would be better
#netw... |
7e740dd4dbd2d083a67970f4a5bd21aa7d49736b | karolinanikolova/SoftUni-Software-Engineering | /1-Python-Programming-Basics (Sep 2020)/Course-Exercises-and-Exams/02_Conditional-Statements/01.Lab-06-Area-of-Figures.py | 1,888 | 3.5 | 4 | # 6. Лица на фигури
# Да се напише програма, в която потребителят въвежда вида и размерите на геометрична фигура и пресмята лицето й.
# Фигурите са четири вида: квадрат (square), правоъгълник (rectangle), кръг (circle) и триъгълник (triangle).
# На първия ред на входа се чете вида на фигурата (square, rectangle, circle... |
9d17cf9e96831970a3d5b42a19a3c69e7ba423f9 | junhaalee/Algorithm | /problems/4344.py | 316 | 3.703125 | 4 | test = int(input())
for i in range(test):
info = list(map(int, input().split()))
students = info[0]
score = info[1:]
avg = sum(score)/students
count = 0
for j in range(students):
if score[j]>avg:
count+=1
print(str('%.3f' % round(count / info[0] * 100, 3)) + '%') |
baa5cc07622f8b404232184c1f561f58584062ba | Jason-Hsuan/git_practice | /Desktop/github/cc.py | 98 | 3.640625 | 4 | def sum_number(x):
sum=0
for _ in range(x+1):
sum+=_
print(sum)
sum_number(10) |
c461ecf432de8675a7a61e9d1d7e0f9d18a1f873 | JonasKVJ/Population-Scraper-AWS-Lightsail | /population_comparator.py | 2,400 | 3.6875 | 4 | #Author: Jonas Stagnaro
#Date: 08-04-20
#Project: Population Comparison App
from bs4 import BeautifulSoup
from django.http import HttpResponse
import datetime
import requests
def index(request):
united_states_population_page = requests.get("https://en.wikipedia.org/wiki/United_States")
india_population_page... |
98a1d6cd8777e09651c54373ff1b88122586bd08 | big-Bong/AlgoAndDs | /PythonPractice/CTCI/4_2_MinimalTree.py | 653 | 3.75 | 4 | class Tree:
def __init__(self,num):
self.val = num
self.left = None
self.right = None
def minimalTree(arr):
if(not arr or len(arr) == 0):
return None
N = len(arr)
if(N == 1):
return Tree(arr[0])
return minimalTreeHelper(arr,0,N-1)
def minimalTreeHelper(arr,start,end):
root = None
if(start<=end):
... |
686cd92e4a242ea619466a81e8aee782efbcea82 | Dileep77/guvi | /prime.py | 133 | 3.5 | 4 | a=int(input())# your code goes here
c=bin(a)
if a==10:
print("no")
elif c[2]=='1' and c[-1]=='1':
print("yes")
else:
print("no")
|
fda54c05f5a7fec7d30d07fb6132ced4972e0418 | brunopmvs/Coursera | /ICC_USP_1/semana7/exercicio3.py | 532 | 3.921875 | 4 | def ePrimo(x):
divisor = x
primo = True
while (divisor > 2):
divisor -= 1
if x % divisor == 0:
primo = False
break
else:
primo = True
return primo
num = int(input("Infore um número: "))
divisor = 2
while(divisor <= num):
multipli... |
10036245ba6b17958bc9f2225524969d9657ceff | dagou/algorithm | /chapter7/quick_sort.py | 495 | 3.609375 | 4 | #encoding=utf-8
__author__ = 'zhuzhengwei'
def partition(A,p,q):
pivot = A[q]
i = p - 1
for j in range(p,q):
if A[j] < pivot:
i += 1
temp = A[j]
A[j] = A[i]
A[i] = temp
A[q] = A[i+1]
A[i+1] = pivot
return i+1
def quickSort(A, p, q):
... |
864ddda79f79279ef90311e9ba7a4c0c7553bcb8 | fclm1316/mypy | /oop/chapter12/yield_from_test.py | 1,077 | 3.859375 | 4 | #!/usr/bin/python3
#coding:utf-8
from itertools import chain
my_list = [1,2,3]
my_dict = {
"aaa" : "AAA",
"bbb" : "BBB"
}
def my_chain(*args,**kwargs):
for my_iterable in args:
for value in my_iterable:
yield value
def my_chain1(*args,**kwargs):
for my_iterbale in args:
yie... |
f3e9c9303ebcafca86c0a600d8ca0731d3a3d94c | danodic/-training_game_no_control | /maps.py | 4,237 | 3.5625 | 4 | """
This module contains the classes used to manage the maps in the game. Each map
is compound by 3 layers: background, foreground and a collision layer. Each one
of the layers can use a different tileset, that has to be imported from the
tiles module.
"""
import pygame
import csv
import math
from typing import Tuple,... |
e34c12eed295138ae7126584b4e4a9830f164b63 | uzhivaj/project1 | /main.py | 863 | 4.03125 | 4 | # we're going to start with the basics
# lets go
# introduction
print("hello friend!")
print("let's do some math today!")
print("..")
print("but only easy stuff please, I'm still learning.")
# main code
condition = 1
while condition < 4:
a = input("Enter a number: ")
b = input("add[+], subtract[-], multip... |
da726fee01ce16dfb6d1436dec7d9d887ac4ca18 | mkelleyjr/GradYear | /GradYear.py | 774 | 4 | 4 | # Michael L. Kelley Jr.
# 9/11/12
# GradYear.py
# A Python script to calculate the year a child should graduate high school
# Prompt the user to enter the child's current grade in integer form
CurrentGrade = int(input("Please enter current grade in integer form (Ex: 5). Grade: "))
# Prompt the user for the current y... |
2d794eaa99b422de6873ea1e5a38b3bbe75038b2 | jtonello/balena-sense2 | /sensor-w1/scripts/screen.py | 4,802 | 3.796875 | 4 | #!/usr/bin/python
# MBTechWorks.com 2016
# Control an LCD 1602 display from Raspberry Pi with Python programming
# Pinout of the LCD:
# 1 : GND
# 2 : 5V power
# 3 : Display contrast - Connect to middle pin potentiometer
# 4 : RS (Register Select)
# 5 : R/W (Read Write) - Ground this pin (important)
# 6 : Enable or S... |
69712a9dc2adf03f8b9487afdd35f28d478a8bc9 | Josuesp1620/Proyectos-Parciales-Python | /Proyectos-Parciales-Python/Tres en raya/funciones.py | 3,100 | 3.96875 | 4 | import random
def gana_user():
print("""
¡Felicidades!
o===========================o
| Usted ha ganado!! |
o===========================o""")
def gana_computer():
print("""
¡Ha sido derrotado!
o========================... |
e52d0369dd15091676b142a50560c3ee8d6d341c | dhackner/Fun-Puzzles | /LongestPalindrome/Words.py | 834 | 4.03125 | 4 | #!/usr/bin/env python
'''Find the longest palindrome in a text file.'''
__author__ = "Dan Hackner"
__maintainer__ = "Dan Hackner"
__email__ = "dan.hackner@gmail.com"
__status__ = "Production"
def isPal(inputString):
beg = 0
end = len(inputString)
while (beg < end):
if (inputString[beg].lower() !=... |
bb074178023d59563712236d716bf9344318edf8 | WarisAli-source/E-Box-Class-And-Object-Practice-Q1 | /Main.py | 2,676 | 3.6875 | 4 | class Hall:
def __init__(self):
self.Name=[]
self.ph_no=[]
self.Adress=[]
self.bookingDate=[]
self.Cost=[]
self.Owner=[]
print("Enter the number of Entries")
n=int(input())
for i in range(0,n):
print("Enter details of Hall",i+1)
... |
5db1beb4f6952cc07f28660fac04566dddd1882b | mikealfare/advent-of-code-2020 | /src/advent_of_code/day_01.py | 840 | 3.796875 | 4 | import math
from itertools import combinations
from pathlib import Path
from typing import Set
Expenses = Set[int]
def get_product_of_combinations_with_sum_limit(entries: Expenses, sum_limit: int, length: int = 2) -> int:
return math.prod({combo for combo in combinations(entries, length) if sum(combo) == sum_li... |
be6c09cd231d373c20b23aeaf65dafaca3e453b0 | Regato/exersise12 | /Exercise25.py | 711 | 3.625 | 4 | # Alphabet constant string and counting of letters from this string by len function:
alphabet_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
len_string = len(alphabet_string)
# List comprehension from alphabet_string letters:
alphabet_comp = [item for item in alphabet_string]
# For cycle with creating and writing of new file... |
e66aaeb73e37171fd35ba9da1e8fa353a3fa4801 | anniequasar/session-summaries | /online/meetup087_tim_libreoffice.py | 18,256 | 3.515625 | 4 | # -*- coding: utf-8 -*-
r"""MeetUp 087 - Beginners' Python and Machine Learning - 24 Nov 2020 - Python macros in LibreOffice
Youtube: https://youtu.be/841Fgt1sQsY
Source: https://github.com/anniequasar/session-summaries/raw/master/online/meetup087_tim_libreoffice.py
Sample: https://github.com/anniequasar/session-sum... |
c09ee21de5ee7750fb8f9c2458d5114f2de9c11c | django-group/python-itvdn | /домашка/starter/lesson 4/Dmytro Marianchenko/t_3.py | 177 | 3.921875 | 4 | print("Половина ёлки:")
print()
for i in range(1,7):
while i != 0:
print("*",end=" ")
i -= 1
print()
print()
print("C Новым Годом") |
5f6865ff290ceecec455d1016ce9fc5a282c92ce | kuroitenshi9/Python-compendium | /04/if/3.py | 856 | 4.28125 | 4 | '''
Stwórz skrypt, który przyjmuje 3 opinie użytkownika o książce.
Oblicz średnią opinię o książce. W zależności od wyniku dodaj komunikaty.
Jeśli uzytkownik ocenił książkę na ponad 7 - bardzo dobry, ocena 5-7 przeciętna, 4 i mniej - nie warta uwagi.
'''
print("Hey, this program allows you to check the opinion of book... |
f710ce4c272090f804af13b745b03f11a2427c2c | weronikadominiak/PyLadies-Python-Course | /1.05- OOP part 1/10.8.py | 1,519 | 3.71875 | 4 | # Stwórz - z wykorzystaniem klas i dziedziczenia - kalkulator objętości brył:
# sześcianu, prostopadłościanu, stożka i kuli.
# Powinien on wczytać od użytkownika opcję (0, 1, 2 lub 3) i w zależności od tego przyjąć
# 3 argumenty, 2 lub 1 i obliczyć objętość. Na wszelki wypadek wzory na objętość podane poniżej.
# Sześci... |
cd756fda7a2a3d9c228002cac54181324d1137db | nikitkokatsiaryna/pizza_bot | /pizzabot/point.py | 261 | 3.796875 | 4 | class Point:
"""
initializing points
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, point):
if type(point) != Point:
super()
return self.x == point.x and self.y == point.y
|
1666b4eeaa3da4840fe7c94caf46e862623f4da1 | jonaskrogell/adventofcode2018 | /5.py | 1,481 | 3.640625 | 4 | import sys
polymers = sys.stdin.read().strip()
def test(a, b):
if a.lower() != b.lower():
# A does not equal B at all
return False
if a.lower() == a and b.upper() == b:
return True
if a.upper() == a and b.lower() == b:
return True
return False
def collaps(polymers):
... |
e291483c04138914f6fb8b533378db20f6f8cac9 | yamaz420/python-classes | /classes-python/classes.py | 245 | 3.703125 | 4 | ### Classes
# class Student:
# pass # let us create an empty class/function and so on
# #this is a class
class Student:
def __init__(self):
print("The class Student has not been created.")
student = Student()
|
3b8696f186cb397773b37aa4c78956a49fdca28c | shalinie22/guvi | /codekata/absolute_beginner/factorial_of_a_number.py | 279 | 4.3125 | 4 | #Print the factorial of the integer.
#define the function for factorial of a number
def fact(n):
#assign the value for fa as 1
fa=1
#put for loop to find the factorial
for i in range (1,n+1):
fa=fa*i
return fa
#get the input from the user
n=int(input())
s=fact(n)
print(s)
|
17793b199475e14da0841cea616dc329afae0694 | f-bergener/terminal-blackjack | /blackjack.py | 6,763 | 3.625 | 4 | from random import *
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
class Player:
def __init__(self, name):
self.name = name
self.bet = None
self.bankroll = 5000
self.hand = []
self.count = None
class Dealer:
def... |
70374a2bd557ba08ce7391f2559e7fb54fe282c3 | AlphaVS-76/Calc_Module | /Lambda_Calc.py | 194 | 3.59375 | 4 | sum = lambda x, y: x + y
mult = lambda x, y: x * y
div = lambda x, y: x / y
diff = lambda x, y: x - y
mod = lambda x, y: x % y
# How to Use: print(<variable_name>(<arguments>))
|
fc4d927e9d824163ee523cf81fd1b6b5020a5b2b | nakfour/pythonhelpers | /classqueue.py | 754 | 3.796875 | 4 | from queue import Queue
class ClassQueue (object):
def __init__(self, size):
self.size = size
self.numberOfElements = 0
self.iQueue = Queue(maxsize=size)
def addData(self, data):
if self.iQueue.full():
return False
else:
self.iQueue.put(data)
... |
6e25b7c8289c75d24b4e21471e9d3522e9a875a6 | chenyanqi/S29 | /day09/222.py | 1,479 | 3.59375 | 4 | import json
def register():
username = input('请输入用户名:')
password = input('请输入密码:')
user_dic = {"username": username, "password": password}
with open('usermanage_json', mode='r', encoding='utf-8') as f:
for line in f:
dic = json.loads(line)
if username == dic['username']:... |
2f8c1486e09cdbad6a6398987aec99e7ced046e9 | kimyeonoo03/IGCSE-Computer-Science | /Arrays.py | 807 | 4.21875 | 4 | lunch = ["Potato", "Noodles", "Spaghetti", "Beef", "Rice", "Pad Thai", "Pork"]
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ways = ["Take a pack lunch.", "Go to cafeteria.", "Don't eat it.", "Throw it away.", "Eat little."]
print (lunch[1]) # Look up an element
'''
When printi... |
abb0e320b33b86e7c475b5278fc0455e716b84fd | yashjaiswal1/CTCI-DSA | /ds/LinkedList/partition.py | 2,182 | 3.984375 | 4 | # Partition the given linked list around the pivot (order of the elements is not of concern)
class LinkedList:
head = None
def append(self, new):
if(self.head == None):
self.head = new
else:
current = self.head
while(current.next != None):
cur... |
64af262b10e64ab87b76c55034dde51910bcaf3a | sam1208318697/Leetcode | /Leetcode_env/2019/6_02/Flower_Planting_With_No_Adjacent.py | 2,157 | 3.625 | 4 | # 1042. 不邻接植花
# 有 N 个花园,按从 1 到 N 标记。在每个花园中,你打算种下四种花之一。
# paths[i] = [x, y] 描述了花园 x 到花园 y 的双向路径。
# 另外,没有花园有 3 条以上的路径可以进入或者离开。
# 你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同。
# 以数组形式返回选择的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类。花的种类用 1, 2, 3, 4 表示。保证存在答案。
#示例 1:
# 输入:N = 3, paths = [[1,2],[2,3],[3,1]]
# 输出:[1,2,3]
... |
0bf1213ae3da08084e66c663a0271a2c56b0a998 | david12daniel/AzureTutorial | /geometries/circle.py | 414 | 3.6875 | 4 | import math
import geometry as geometry
class Circle(geometry.Geometry):
def __init__(self,radius):
self.radius=radius
super().__init__()
def print(self):
print(f'Geometry ID {geometry.Geometry.id} is circle with radius of {self.radius}')
def area(self):
return math... |
37fe38ce81a83b5cd4ca1b8cfeec04994579bd3f | daydaychallenge/leetcode-python | /00992/subarrays_with_k_different_integers.py | 2,276 | 3.984375 | 4 | from typing import List
class Solution:
def subarraysWithKDistinct(self, A: List[int], K: int) -> int:
"""
#### [992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/)
Given an array `A` of positive integers, call a (contiguous, not n... |
af456b3aac2f5bb8f3001c092a9e45177e84811c | creatoryoon/CSE2003_1_2021_1_Sogang_- | /실습/9장 실습_2-2.py | 302 | 3.734375 | 4 | N1, N2 = input("Enter N1, N2(0 < N1 <= N2) : ").split()
S = N1 = int(N1)
E = N2 = int(N2)
if N1%2 == 1 :
S = S + 1
if N2%2 == 0 :
E = E + 1
Sum = 0
for x in range(S,E,2) : #begin과 end-1이 짝수여야 한다.
Sum += x
print("Sum of even numbers between %d and %d is %d." %(N1,N2,Sum))
|
411c62f85064acbc4061bacc9d2384134f2bfc06 | irene-yi/Classwork | /Stacks.py | 711 | 3.671875 | 4 | class Stack:
def __init__(self):
self.items = []
#pushing in information
def push(self,items):
self.items.append(items)
def pop(self,items):
a = []
if self.items == a:
print('ERROR.SHUTDOWN')
return False
else:
self.items.pop(items)
def isEmpty(self):
a = []
if self.items == a:
print('tru... |
d4533cd8a80c9f7d00fb2ccc1c22320f17487d8d | Goorman/pygbm | /pygbm/pwl/predictor.py | 2,647 | 3.609375 | 4 | """
This module contains the TreePredictor class which is used for prediction.
"""
import numpy as np
from numba import njit, prange
PREDICTOR_RECORD_DTYPE = np.dtype([
('is_leaf', np.uint8),
('value', np.float32),
('left_coefficient', np.float32),
('right_coefficient', np.float32),
('count', np.u... |
ff97356c8ff88fcd2cb85454e48153f824db3e13 | FelixLiu1996/my_leetcode | /976.最大三角形周长.py | 383 | 3.734375 | 4 | class Solution:
def largestPerimeter(self, A) -> int:
A.sort()
while len(A) >= 3:
if A[-2] + A[-3] > A[-1] and A[-2] - A[-3] < A[-1]:
#return sum(A[len(A) - 3: len(A)])
return A[-1] + A[-2] + A[-3]
else:
A.pop(len(A) - 1)
... |
647f6977a10bb5fbe279469af656d16772dcbb35 | jakegoodman01/tempo | /tempo/piece.py | 387 | 3.734375 | 4 | from enum import Enum
class PieceType(Enum):
PAWN = 1
KNIGHT = 3
BISHOP = 3
ROOK = 5
QUEEN = 9
KING = 999
class Color(Enum):
WHITE = 1
BLACK = 1
class Piece:
def __init__(self, piece_type: PieceType, square: str, color: Color):
self.piece_type: PieceType = piece_type
... |
1fe4f77f7c57941ad54a4724b224e8901f09a48c | sangjianshun/Master-School | /data_structure/my_set.py | 3,322 | 4.3125 | 4 | # Python3 中有六个标准的数据类型:
#
# Number(数字)
#
# String(字符串)
#
# List(列表)
#
# Tuple(元组)
#
# Set(集合)
#
# Dictionary(字典)
## 1. 集合的创建
### 1.1 直接创建
set_master_school = {1, 2, "master", "school"}
### 1.2 通过set创建
set_master_school = set(("123")) # 注意,创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
set_master_school = set((... |
361a697ca7732aa8e2d158ca2b7b93889586326a | muztim/100-days-of-code-python | /Projects/Day_23/turtle-crossing/car_manager.py | 882 | 3.859375 | 4 | from turtle import Turtle
from random import choice, uniform, randint
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager():
def __init__(self):
self.all_cars = []
self.moving_rate = STARTING_MOVE_DISTANCE
def create... |
de066c2c0fc30feb9dfdbfbbf6555eaacd63e5b7 | alee86/Informatorio | /Practic/Funciones/ejercicio04.py | 554 | 4.21875 | 4 | '''
Ejercicio 4: Mediana de tres valores
Escriba una función que tome tres números como parámetros y devuelva el valor medio de esos parámetros
como resultado. Incluya un programa principal que lea tres valores del usuario y muestre su mediana.
Sugerencia: El valor medio es el medio de los tres valores cuando se orden... |
4a48f92898c004ec9f2db2657c897bef3c10dbe5 | HecFranco/course_python | /04_DataBase/Examples/62_Database_06_Fecth_Data.py | 517 | 3.71875 | 4 | # Importamos el módulo
import sqlite3
# Nos conectamos a la base de datos ejemplo.db (la crea si no existe)
conexion = sqlite3.connect('usuarios.db')
# Creamos el cursor
cursor = conexion.cursor()
# Recuperamos los registros de la tabla de usuarios
cursor.execute("SELECT * FROM productos")
# Recorremos todos los regist... |
b090cfd573c73b2e7943c0445ee557dcca550e40 | YEAJIN-KIM/git_yeajin | /5_4/5_4.py | 610 | 3.71875 | 4 | class Shape:
name=None
area=0
def __init__(self,name,area):
self.name=name
self.area=area
def showMe(self) :
print("도형이름",self.name," 도형 면적",self.area)
class Circle(Shape):
rad=0
def __init__(self,name,rad):
self.name=name
self.rad=... |
e00eefe5eb76b1fcd308e4d5c770c724d99f3049 | monster-yjz/learning_1 | /练习/day2_练习2圆半径计算.py | 141 | 3.765625 | 4 | pi = 3.14
d = float(input('请输入直径'))
D = d * pi
S = pi * (d / 2) ** 2
print('圆的周长为%s' % D)
print('圆的面积为%s' % S)
|
6746a8473eef4c0acce242a1b6d14184e57ad20b | s3kim2018/Calculus-Problem-Generator | /interface.py | 3,343 | 4.3125 | 4 | from generator import *
import random
def product_rule():
string = ''
string += random_function_generator()
string += " "
string += '*'
string += " "
string += random_function_generator()
return string
def quotient_rule():
string = ''
string += random_function_generator()
str... |
b84a075b7f5cb5237de1f40cfe6d2170b1a1475a | sabbir-ul-alam/pythonHackerRank | /ClassesDealing with Complex Numbers.py | 1,732 | 3.859375 | 4 | import math
class Complex(object):
real=None
imaginary=None
def __init__(self, real, imaginary):
self.real=real
self.imaginary=imaginary
def __add__(self, no):
r=self.real+no.real
i=self.imaginary+no.imaginary
return Complex(r,i)
def __sub__(self, no):
... |
5eca0fbb7c53205a9e7313a1e78386d96d9f59e3 | ahwang1995/Cracking-the-Code | /Chapter 1/oneAway.py | 617 | 3.875 | 4 | #check two strings are one or zero edits away
def oneAway(str1,str2):
#make sure the lengths of the strings don't differ bby more than one
diff = abs(len(str1) - len(str2))
if diff > 1: return False
list1 = list(str1)
list2 = list(str2)
diff2 = 0
#remove matching characters from each list one at a time
while(le... |
644d2426330825f3a6be9e4a491c8ec96713296c | frossi01/bai-tap | /Bai4.20.py | 514 | 3.796875 | 4 | import math
def combination(n,r):
return int(math.factorial(n)) / (math.factorial(r)) *math.factorial(n-r)
def for_test(x,y):
for y in range(x):
return combination(x,y)
def pascals_triangle(rows):
result = []
for count in range(rows):
row = []
for element in range(coun... |
826273e042f4c2ee21c9e5fadb7bb358424891bd | sqatools/selenium-automation-nov20 | /BatchNov2020/PythonPrograms/test_package/operation.py | 410 | 3.78125 | 4 | """
1. user one function from one file to another file
import modulename
2. user specific variable or function from another module
from module import <function> <variable>
from module import *
3. Scope of global variable will be accessible across all the module.
4. We can access local variable out side of module a... |
05a4d9bb39cfd39aba620efe3f10c193b8442047 | zhanghui0228/study | /python_Basics/module/package/day04--datetime_module.py | 6,273 | 4.53125 | 5 | #datetime模块
'''
timedelta 对日期/时间进行加减操作时使用
datetime.datetime.now.date date类表示一个日期
datetime.strftime 将datetime对象格式化成字符串
datetime.strptime 将字符串按照一定的格式转换成datetime对象
datetime.datetime.now.time 表示一个时间的类
datetime.now 系统当前的时间
datetime.datetime.now.day ... |
899067c6ba21987348b7275b4b39961e23a540a0 | Priktopic/python-dsa | /nearest_sq.py | 173 | 3.578125 | 4 | ## if limit is 40, your code should set the nearest_square to 36.
limit = 40
num = 0
while (num+1)**2 < limit:
num += 1
nearest_square = num**2
print(nearest_square)
|
95c4bbfdac9e7e75af5bba11f0eccfccc6bc4193 | Anshum4512501/dsa | /arrays/rearranging_array.py | 756 | 3.65625 | 4 | # Rearranging array as a[i] = i
# Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
# Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
# Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
# 11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
# Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
# 11, 12, 13, 14, 15, 16, 17, ... |
bb5b43e5548b72784c591bcfd4f7121b828ddc5f | svyatoslavn1000/algorithms_and_data_structures | /les_1/les_1_task_3.py | 554 | 4.15625 | 4 | # Задани 3.
# Определить,
# является ли год, который ввел пользователь, в
# исокосным или не високосным.
year = int(input("Введите год: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"Год {year} високосный")
else:
print(f"Год {year} не високосный")
... |
44744f5965ce24482a57dc55b1580edc75ee23a9 | krnets/codewars-practice | /7kyu/Regexp Basics - is it a vowel/index.py | 423 | 3.796875 | 4 | # 7kyu - Regexp Basics - is it a vowel?
"""Implement the function which should return true if given object is a vowel
(meaning a, e, i, o, u), and false otherwise."""
import re
def is_vowel(s):
return bool(re.match('[aeiou]', s, re.I)) and len(s) == 1
q = is_vowel(""), False
q
q = is_vowel("a"), True
q
q = is_... |
feb7d7df1d8b2e26254ffa7372053c035084fc12 | kiranmai524/python_tutorial | /exercise20.py | 991 | 4.1875 | 4 | from sys import argv #import of system statement
script, input_file = argv # unpacking
def print_all(f): #definition
print f.read() # read the content of the file and print d same
def rewind(f): # redefining seek function
f.seek(0) # set the cursor position to the starting of the file
def print_a_line(lin... |
0c294fd26379365956a413b1b4e4fed6085693c3 | guoweifeng216/python | /python_design/pythonprogram_design/Ch6/6-3-E25.py | 1,368 | 4.15625 | 4 | import turtle
def main():
## Draw the flag of Burkina Faso.
t = turtle.Turtle()
t.hideturtle()
t.down()
drawFilledRectangle(t, 0, 50, 150, 50, "red", "red")
drawFilledRectangle(t, 0, 0, 150, 50, "forest green", "forest green")
drawFivePointStar(t, 65, 33, 40, "yellow", "yellow")
def drawFi... |
c18094b3bdac0abd2de53099fb4f3aa3e937f765 | cyvtorefiel/LIS161B | /2.2.py | 335 | 4 | 4 | fname = input("Enter filename: ")
try:
fhandle = open(fname)
except:
print("File not found")
exit()
count = 0
for line in fhandle:
if line.startswith('From '):
email = line.split()[1]
count += 1
print(email)
print("There are {num} lines in file: {fname}".format(num = count, f... |
3e3ef677423b07e8dffc126d2f9ac37888ed21ec | sarthakkhandelwal7/LearningBasics | /dynamic_programming/robot_in_a_grid(recursion).py | 394 | 3.59375 | 4 | def find_path(m: int, n: int, dp):
if n == 0 or m == 0:
return 1
dp[m][n] += find_path(m - 1, n, dp) if dp[m - 1][n] == 0 else dp[m - 1][n]
dp[m][n] += find_path(m, n - 1, dp) if dp[m][n - 1] == 0 else dp[m][n - 1]
return dp[m][n]
if __name__ == '__main__':
m = 3
n = 2
dp = [[0 for... |
4b6510776a5c2b231a2546a6a0b3530e04175b73 | yeetFBI/basicpython | /practice4.py | 1,223 | 3.96875 | 4 | from math import pi
import replit
import time
def clear():
replit.clear()
def wait(float):
time.sleep(float)
def main():
clear()
global a
a = float(input("Radius of Circle or Sphere: "))
if a != "":
clear()
choice()
elif a == "":
error()
def choice():
print("Radius: " + str(a))
... |
0b1871d1c6bf96ce4c4810c9dd34e213d2532ad4 | DarrenSMU/code-solutions | /interview/Shopee Techops/1/Solution.py | 305 | 3.734375 | 4 | def thousand_number_separator(number) :
string = ""
counter = 0
for i in range(len(str(number))-1,-1,-1):
if counter % 3 == 0 and i != len(str(number))-1 :
string = "," + string
string = str(number)[i] + string
counter += 1
return string
print(thousand_number_separator(131312)) |
4d95f7ab78be504f286755c7d1de42f78d250c7f | Laxmaan/Ecosystem-Simulator | /agent.py | 2,714 | 3.78125 | 4 | """from queue import PriorityQueue
import numpy as np
class AStarPoint():
def __init__(self,point, parent=None):
self.x = int(point[0])
self.y = int(point[1])
self.parent = None
self.f = -1
self.g = -1
self.h = -1
def __str__(self):
return f"({self.x}, {s... |
b11dd48d187ec0086a6774d47dec7c160d879215 | DJSwitchCase/python-practice | /Practice2/pr2right.py | 3,140 | 3.53125 | 4 | # 2.1
def step_one(tree, x):
if type(tree[x[1]]) is dict:
return step_three(tree['yacc'], x)
else:
if x[1] == 'vhdl':
return tree['vhdl']
elif x[1] == 'scaml':
return tree['scaml']
def step_three(tree, x):
if type(tree[x[3]]) is dict:
return step_two... |
082938ea1055f058f07999d9c42f53a9d4f7deb8 | AasifMdr/LabExercise | /LabTwo/Qn14.py | 63 | 3.5 | 4 | '''
What is the result of float (1)?
'''
x = float(1)
print(x) |
9988d34056c009b9cce3bbe15e5504b5de686024 | razorwu1994/BrandY-RW-3 | /src/priority_queue.py | 2,384 | 3.984375 | 4 | import itertools
import heapq as hq
from cell import Cell
REMOVED = '<removed-cell>' # placeholder for a removed cell
class PriorityQueue:
"""
Priority queue using heapq as a min binary heap.
Attributes:
heap = list of entries arranged in a heap
entry_finder = mapping of cells to entries
cou... |
4413742bebecd1c296d22cfd728809c964e4f616 | zonghui0228/rosalind-solutions | /code/rosalind_inv.py | 1,041 | 3.6875 | 4 | # ^_^ coding:utf-8 ^_^
"""
Counting Inversions
url: http://rosalind.info/problems/inv/
Given: A positive integer n≤105 and an array A[1..n] of integers from −105 to 105.
Return: The number of inversions in A.
"""
def MergeSortCountInversions(arr):
if len(arr) == 1:
return arr, 0
else:
a = arr... |
b1583ac34ed2b946f49454626bdb9a7b48962f5f | karbekk/Python_Data_Structures | /Interview/Python_Excercises/Files/file_open_and_print_with_\n.py | 249 | 3.65625 | 4 | ''' file handlers are used for file opening '''
''' Note that below lines are printed with extra new line
bcz one line from end of file having a \n character
and other new line is from print'''
f = open(filename,'r')
for line in f:
print line
|
78252fd311907ccd096a5121842eac1f96db6089 | KenHollandWHY/stepicproblems | /src/stepic/suffixtree2.py | 2,969 | 3.609375 | 4 | '''
Created on 4 Mar 2015
@author: Andy
'''
from itertools import chain
from _functools import partial
class AbstractNode(object):
def __init__(self, childNodes=None):
self.childNodes = childNodes if childNodes else {}
def isRoot(self):
return False;
class SuffixTree(AbstractNode):
... |
3625b5c1587d524b01f9800d28b18ffbbfa43e7a | HighLive/DreamChat | /back-end/pythonProgram/test1.py | 279 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 8 17:35:57 2021
@author: jinh2
"""
import sys
def getUrlLength(url):
lenOfURL = len(url)
print("Length of URL: " + str(lenOfURL))
def main(argv):
getUrlLength(argv[1])
if __name__ == "__main__":
main(sys.argv) |
e0b74a9aba74478aacc6e95eb2f9f34151130dad | NeSergeyNeMihailov436hdsgj/SummerP | /1A/29.py | 844 | 3.8125 | 4 | import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
n=1
p=30
for row in range(2):
print(" "*p+"xxx"*n)
n+=2
p-=3
if n==5:
n=13
p+=1
for row in range(3):
print... |
a6696cb13ded247ef0e6fa035dc4f8194e93d78e | 108021076/RSA | /test.py | 2,721 | 3.703125 | 4 | import random as rand
import sys
class RSA:
def __init__(self):
print("q and p")
print(self.radList())
self.p,self.q = map(int,input().split())
self.N = self.q * self.p
self.N1 = (self.p - 1) * (self.q - 1)
print("e :")
print(self.repr(self.N1))
... |
753ee6b54c051bc405d0dd577a99e2f9813a7eea | sudosubin/pirogramming-10th | /python/mit/mit-1/ps1a.py | 1,116 | 4.09375 | 4 | # total_cost: 구매하려는 집의 총 금액
# portion_down_payment: 계약금의 비율 (25%)
# current_savings: 현재까지 저축한 금액
# current_savings*r/12: 매달 저축액의 이자
# r: 0.04 (연 이율)
# annual_salary: 연봉
# portion_saved: 저축 비율
# monthly_salary: 월급 (연봉/12)
R = 0.04
current_savings = 0
annual_salary = int(input("Enter your annual salary: "))
monthl... |
8b45d7509de6fea78eccf4262edea2ad331c3759 | samuelwinchester/HackerRank | /IfElse.py | 256 | 4.125 | 4 | #!/bin/python3
N = int(input())
if N % 2 != 0:
print("Weird")
elif N % 2 == 0 and N < 6 and N > 2:
print("Not Weird")
elif N % 2 == 0 and N < 21 and N > 6:
print("Weird")
elif N % 2 == 0 and N > 20:
print("Not Weird")
|
47ff667d8c94d5db8368583dd0162f7afb1afec2 | akhilpm/M.tech-Assignments | /GeneticAlgorithms/knapsack.py | 4,678 | 3.703125 | 4 | #!/usr/bin/python
#import math
'''
implementation of 0/1 knapsack problem with GA
profit & weight values are supplied from an array stored in the program
Notations,GA methods & operators used
--population size = 8
--representation of a chromosome = a string of length same as no of items
with values ranging from 0... |
30c21357ed0eac55c5be7d84283bbeeebe21d533 | temitopeakinsoto/Sorting | /src/searching/searching.py | 810 | 4.1875 | 4 | # STRETCH: implement Linear Search
def linear_search(arr, target):
# TO-DO: add missing code
for (index, item) in enumerate(arr):
if item == target:
return index
return -1 # not found
list_items = ["issp", "top", "Shoe", "Temp", "top", "Shoe"]
targ = "issp"
print(linear_search(list_items, targ)... |
b5580f19e00f0e255ba8933a1379ddf3bcc90138 | joyfulflyer/billboard-reader | /tests/testSongSearch.py | 1,329 | 3.640625 | 4 | import unittest
from context import reader
import reader.songSearch as songSearch
from reader.song import Song
class TestSongSearch(unittest.TestCase):
def test_remove_dupes(self):
date = "date"
artistName = "artiist"
start = [
Song(0, "firstName", artistName, date),
... |
f31bdca05b16a6eaec8a7a40eab92a89b7eef598 | aliaksandrazaronak/Basics-of-Python | /tasks/Module_4/task_1.py | 726 | 3.5 | 4 | import re
import pyinputplus as pyip
PLACEHOLDERS = ('ADJECTIVE', 'NOUN', 'VERB')
def mad_libs(file_for_read, file_for_write):
"""Read content from file, replace words of speech with entered ones and save outcomes to new file."""
with open(file_for_read, "r") as rf, open(file_for_write, "w") as wf:
... |
ca509e86eaeb7cf5c107579b76bb854d2d1ced5e | iremiseton/TicTacToe | /game.py | 1,633 | 3.796875 | 4 | class game:
def playGround(self, board): #Prints out the board.
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
pr... |
ead67175dbdc6286f97ca1a2b68724ed1ad4ed99 | jakubclark/schnapsen | /schnapsen/api/util.py | 2,501 | 3.859375 | 4 | """
General utility functions
"""
import importlib
import math
import os
import sys
import traceback
from api import Deck
def other(
player_id # type: int
):
# type: () -> int
"""
Returns the index of the opposite player to the one given: ie. 1 if the argument is 2 and 2 if the argument is 1.
... |
f635592cf93ee2a07e4cea327757a61ec95a70ee | kashyap1123/Numerology | /Num_BasicTypes.py | 6,378 | 3.578125 | 4 | """
Num_BasicTypes.py
~~~~~~~~~~~~~~~~~~~~~~
Some basic data types and routines for numerology.
We define a DoB holder. Now on top of this, we will have a data type to hold all
important metrics that we compute - for example, progress number, radical years,
etc.,
We will then define getters for computing these."""
... |
aa03766c0ce20d1dcffda2217bb6ae810cebf661 | rmitanch/your-face | /Transform_rgb2gray.py | 776 | 3.671875 | 4 | import sys, os
import numpy
import matplotlib.pyplot
import matplotlib.image
from PIL import Image
imagePath = sys.argv[1]
def rgb2gray(rgb):
return numpy.dot(rgb[...,:3], [0.299, 0.587, 0.114])
# read from file
imgfile = Image.open(imagePath)
img = numpy.array(imgfile)
# read from file option2, use matplotlib,... |
4d7413e7ce97e51bd6ecf2e025dfa946ab2bf821 | rrwt/daily-coding-challenge | /daily_problems/problem_0_to_100/problem_47.py | 1,014 | 4.15625 | 4 | """
Given an array of numbers representing the stock prices of a company in chronological order,
write a function that calculates the maximum profit you could have made from buying and
selling that stock once. You must buy before you can sell it.
For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you ... |
7df4a38d95fb1c271f8e5455ae1b785868cc39f4 | bvsbrk/Learn-Python | /Control Flow/functions.py | 207 | 3.921875 | 4 | def calculate_fib(n):
a, b = 0, 1
l = []
while a < n:
l.append(a)
a, b = b, a + b
return l
a = calculate_fib(int(input('Fibonacci series below ? ')))
print(a)
print(len(a))
|
3df0e23e4125c0183c036e6231cdf906d212e4e1 | YuriSpiridonov/30-Day-LeetCoding-Challenge | /Week 5/BinaryTreeMaximumPathSum.py | 1,221 | 3.75 | 4 | """
Task 29:
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some
starting node to any node in the tree along the parent-child connections.
The path must contain at least one node and does not need to go through
the root... |
7cc6367bb2c6b8f45557c4c2f6ad8ed653531f7e | monteua/Python | /List/5.py | 440 | 4.0625 | 4 | '''
Write a Python program to count the number of strings where the string length is 2 or more and the first and last
character are same from a given list of strings. Go to the editor
Sample List : ['abc', 'xyz', 'aba', '1221']
'''
def count_strings(lst):
count = 0
for i in lst:
if len(i) >= 2 and i[0... |
41b619e2310b56d683fe48c0593e518e480a45fa | 2017100235/Mix---Python | /Skill curso em video - Python - mundo 1/desafio 08.py | 218 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 00:43:02 2019
@author: juan
"""
metro = int(input("Valor em metro: "))
print("valor em centimetros ",metro * 100,"cm")
print("valor em milimetros ",metro * 1000,"mm") |
4a6093a00b85a36acce5cfaca9868e2da30324a5 | martinber/agglomerate | /agglomerate/util.py | 3,482 | 3.53125 | 4 | import os
import fnmatch
import PIL
def get_matching_paths(path):
"""
Returns a list of paths that were matched by the given path. e.g. *.png
Supports unix style wildcards, e.g. file_*, sprites/*.png or ./f.png
Adds ./ at the beggining of the path if given path doesn't have
directory
:param... |
f2967b83146d662e3546225b04f6ac4b995e85a7 | jaganbecs/Python | /revdigi.py | 259 | 3.8125 | 4 | x=12345
x_string = str(x)
# uses reversed() directly on the string
x_reversedobject = reversed(x_string)
x_reversedlist = list(x_reversedobject)
x_reversedstring = "".join(x_reversedlist)
x_reversed = int(x_reversedstring)
print x_reversed
|
4f6f4af5a8486561a961be7a211c667a6472bc78 | dongbo910220/leetcode_ | /Graph/802. Find Eventual Safe States Medium.py | 973 | 3.765625 | 4 | '''
https://leetcode.com/problems/find-eventual-safe-states/
'''
class Solution(object):
def eventualSafeNodes(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[int]
"""
visited = [-1] * len(graph)
res = []
for i in range(len(visited)):
... |
72726a42c17b10a15eaa9b58b2bd7221f054e847 | piyush09/LeetCode | /Search a 2D Matrix II.py | 779 | 3.921875 | 4 | def searchMatrix(matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if (matrix is None or len(matrix) < 1 or len(matrix[0]) < 1):
return False
row = 0
column = len((matrix)[0]) - 1
# Iterating till col is greater than 0 and till last row ... |
ea25d9dea9c61f96f20161ec5c0e59420adc9790 | rutuja5544/Python_practice | /values5.py | 730 | 4.03125 | 4 | a=int(input(" a : value\n"))
b=int(input(" b : value\n"))
c=int(input(" c : value\n"))
d=int(input(" d : value\n"))
e=int(input(" e : value\n"))
if a!=b!=c!=d!=e:
if a>b:
if a>c:
if a>d:
if a>e:
print(f" {a} a greatest \n")
else:
print(f" {e} e greatest \n ")
elif d>e:
... |
a6faa12056eac7b4171d64fd1d774a2b3496657a | jaimersoncorreia/cg | /aulas/parteI/004salario_real.py | 301 | 3.953125 | 4 | salario = int(input('Salário? '))
imposto = input('Imposto em % (Ex.: 27.5)? ')
if not imposto:
imposto = 27.5
else:
imposto = float(imposto)
print("Valor real: {0}".format(salario-(salario*imposto*0.01)))
print("Imposto Alto" if imposto*0.01 > 0.27 else "Imposto Baixo")
print(imposto)
|
f5b7940372d78051cb02dbec4f43923ecbc68d46 | jskyzero/Python.Playground | /projects/example/socket/server.py | 1,709 | 3.765625 | 4 | #!usr/bin/env python
# -*- coding: utf-8 -*-
import socket
# server config
HOST = ""
PORT = 9100
class ServerSocket(object):
"""A Server Socket Class"""
def __init__(self):
"""Initial a ServerSocket object"""
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def b... |
7e17e24febdfc740cd877f7328d48c0215d8cd4f | axd8911/Leetcode | /2nd_try/0099_Recover_Binary_Search_Tree.py | 1,066 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify... |
9505ca835e99d0b708fbbe92a01f5e2283fb7f6f | DomWat/udemy-projects | /hundred-days-python/week1/day5.py | 6,868 | 4.40625 | 4 | # for loops, range, and code blocks
# # Loops
# # for item in list_of_items: do something
# fruits = ['apple', 'peach', 'pear']
# for fruit in fruits:
# print(fruit)
# print(fruit + ' Pie')
# # coding challenge 1 (average student height) *can't use len or sum functions after the initial type change
# # get a... |
b4228c51613df47cb1a0aaa66a8913dd278cc54d | bunshue/vcs | /_4.python/__code/Python-3-Data-Analysis-Basics-master/LinearRegression1.py | 5,979 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
'''
AI 三步驟
打造函數學習機
fit
predict
'''
print('------------------------------------------------------------') #60個
print('線性迴歸')
points = 11
x = np.linspace(0, 10, points)
y0 = x
plt.plo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.