blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c6d3b340c05bfeb0dfe3a2f68a3097defbb7fbf2 | chaewon-chloe/DataScienceWithPython | /data_structure.py | 2,333 | 4.09375 | 4 | class Trie:
'''Reperesents a Trie data structure'''
def __init__(self):
self.root = dict()
def add(self,s):
### Defining a helper method
def add_helper(s):
if s == "":
return {"" : None}
return {s[0] : add_helper(s[1... |
15170bcc914db5d73263408477e3ba1d3f9b71c5 | alexeydariev/Network-Programming | /battleship/server.py | 9,024 | 3.6875 | 4 | import socket
import threading
from random import randint
import string
import sys
#Colors and styles for text output on the screen
class bcolors:
PINK = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#Board Cl... |
bd1e24068ecd48729fed593dcb5ac7dbab6f8999 | arkhoss/scripting | /python/intermediate/1.functions.py | 764 | 3.78125 | 4 | #! /usr/bin/python3
#Usage: functions.py
#Author: David Caballero <d@dcaballero.net>
#Version: 1.0
def function():
print("This is our first function")
def anotherfun():
print("This is our another function")
anotherfun()
function()
def returning():
return "I am a result!"
result = returning()
print(r... |
7c7b9df0d8d336686b3e90bec917b6d031765848 | martincastro1575/python | /6.- Dictionarys/Try Yourself/6.11 cities.py | 613 | 3.921875 | 4 | cities = {
'caracas': {
'country': 'venezuela',
'population': '6 millones',
'superfice': '777 Km2',
},
'buenos aires capital':{
'country': 'argentina',
'population': '2.89 millones',
'superfice': '203 Km2'
},
'monte video':{
'country': 'uruguay... |
1c9678c5acf892473d0299dd94ff29f9b8e5510d | uchenna-j-edeh/dailly_problems | /sorting_algorithm/calculate_inversion.py | 1,194 | 4.15625 | 4 | """
Author: Uchenna Edeh
We can determin how out of order an array A is by counting the number of inversions it has.
Two elements A[i] and A[j] form a inversion if A[i] > A[j] but i < j. That is, a smaller
element appears after a larger element.
Given an array, count the number of inversions it has. Do this faster th... |
f945755140235094396be57482b0f44d9f9b7002 | apesquero/URI | /PRINCIPIANTE/1000-1050/1012.py | 595 | 4.03125 | 4 | # -*- coding: utf-8 -*-
import math
PI = 3.14159
values = input().split(" ")
value_a, value_b, value_c = values
value_a = float(value_a)
value_b = float(value_b)
value_c = float(value_c)
triangle_area = (value_a * value_c) / 2
circle_area = (PI * (math.pow(value_c, 2)))
trapeze_area = value_c * ((value_a + value_b... |
35fe1e06e0905ef1f8defcfedcd1f931a64014f1 | Alf0nso/NN-Games | /Games/games_generator.py | 821 | 4.125 | 4 | # Tic tac toe
#
# @Author: Afonso Rafael & Renata
#
# Game generator. Functions related to
# generating various amounts of games to
# train the neural networks.
from itertools import chain
# Chain is used to produce the strings
# that are saved in the file
def gen_games(game, n_games, path=None,
file_... |
d7699cacdf1fd4c87c370f034d431a6eefd94df0 | Rkakani123/BEProject | /SignatureVerification.py | 917 | 3.59375 | 4 | from ECDSA import *
#Input for signature validation
inp = str(input("Enter Your Messgae : "))
msg = bytes(inp, encoding="utf-8")
if len(msg) == 0:
print("You have not entered anything!")
else:
#Public Key Expansion
inp1,inp2 = input("Enter Your Public Key : ").split(', ')
keys = [int(inp1),int(inp2)]
... |
35a828ae5a0e2b2e7ec0ec179a70670c28428ffe | DrDano/Mail_Merge_Project | /__MACOSX/Mail Merge Project Start/._main.py | 1,386 | 3.765625 | 4 | # TODO: Create a letter using starting_letter.txt
# for each name in invited_names.txt
# Replace the [name] placeholder with the actual name.
# Save the letters in the folder "ReadyToSend".
# Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
# Hint2: This method will also help y... |
a9a30863a4122c4178c62ca993ffd320953c02fc | AndrewTelleria/binary_search | /search/binary_search.py | 460 | 3.828125 | 4 | # List must be sorted
def binary_search(data, item):
if type(data) == list:
low = 0
high = len(data) - 1
while low <= high:
mid = (low + high) // 2
guess = data[mid]
if guess == item:
return mid
if guess > item:
... |
9ce4f734759fcaa0f21ce287afbe2d8200e865a7 | chasezimmy/fun | /product_of_array_except_i.py | 1,131 | 3.921875 | 4 | """
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected ... |
cfd8a788a31600ebc8d2049bc8cfb9522f3c5b71 | ampermetr/3_bars | /bars.py | 2,360 | 3.515625 | 4 | import json
def load_data(filepath):
with open(filepath, 'r') as file:
data = json.load(file)
return data
def get_biggest_bar(data):
maximum_seats = float('-Inf')
maximum_seats_name = []
for item in data:
if item["Cells"]["SeatsCount"] > maximum_seats:
maximum_sea... |
54690d5166adcca7296593e1e3ead51e91cfe100 | Sahanave/pythoncheatsheet | /cheatsheet.py | 7,153 | 4.21875 | 4 | import random
import sys
import os
#hey there!this is a some basic tutorial and some quick commands to help you in your
#work and in your project in case you are wondering how to use the commands
#Getting Started
#1)Task:if you want to print something quick on the screen
#2)Task:learn how to use lists
#3)Task learn ho... |
55227ab71ae88db2b47aad34010116fca3b7c112 | graywen24/Python3study | /week3/stringexercise/someStringprocess.py | 537 | 3.71875 | 4 | print(len("123456")) #6
# str(x) oppsite to eval()
print(type(str(1.23))) # ---> "1.23"
str([1,2]) #"[1,2]"
print(hex(425)) #十六进制小写 "0x1a9"
print(oct(425)) #八进制小写 “0o651”
##### unicode ######
#chr() #返回unicode符号
# ord() #返回值是unicdoe对应的十进制整数。
chr(1004) # return unicode
print("1+1=2"+chr(10004)) #1+1=2✔
pr... |
476939414b2c3ee57b3381374fe11e08a3603459 | KilburnBuilding/Leetcode | /234.py | 963 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
s... |
1ced413f4a4a3ce72b29a0896aec61319fc3b915 | alien18331/Sample_Code | /Function/Event/callback/callback.py | 565 | 3.515625 | 4 | from event import *
import time
import random
#中间函数
#接受一个生成偶数的函数作为参数
#返回一个奇数
def getOddNumber(k, getEvenNumber):
return 1 + getEvenNumber(k)
#起始函数,这里是程序的主函数
def main():
while True:
k=random.randint(0,1000)
if(k%100==0 and k>500):
i = getOddNumber(k, double)
print("k={0}, result={1}".format(k... |
840d379090a1f4b8e2a0dbf1934c6c06ce72b584 | axxypatel/LeetCode | /414_Third_Maximum_Number.py | 1,157 | 4.1875 | 4 | """
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum ... |
5ffb898f83ff100cfd7b5c0d8a3fc27dc962436a | Vitkof/3D_Engine | /matrixs.py | 2,001 | 3.640625 | 4 | import numpy as np
import pygame as pg
from math import sin, cos
# https://ru.wikipedia.org/wiki/Матрица_перехода
def displace(pos):
""" [x',y',z'] = [x,y,z]*T """
x, y, z = pos
T = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[x, y, z, 1]
])
r... |
3c574c3fbe9b154ae455c480d7131af6ac7ea878 | Peiyu-Rang/LeetCode | /125. Valid Palindrome.py | 1,004 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 21:36:47 2020
@author: Caven
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
n = len(s)
left = 0
right = n-1
while left < right:
while(left < right and not s[left].isalnum()):
left +=1
... |
5c73ed49b4a1494947210b66cb4d63ea1179ac06 | glet2024/100-Double-Pendulums-and-Lorenz-Attractor | /LorenzChaos.py | 2,064 | 3.953125 | 4 | import numpy as np, matplotlib.pyplot as plt, matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
x, y, z = 0, 1, 10 #setting the initial state of the system
rho, sigma, beta = 28, 10, 8 / 3 #the three parameters Lorenz's model utilizes
t0 = 0 #starting time
tf = 100 #ending time
d... |
3492cbd9910009fa95da990906392b18b829b795 | TomAlanCarroll/synthia | /synthia_assistant.py | 1,029 | 3.59375 | 4 | import speech_recognition as sr
import config
import json
def recognize_speech():
# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
try:
print("Starting speech recognition")
cred_json = json.loads(open(config.get('... |
27e9757b8a586173b91ab4a0fc5a30683a5093b7 | KarimDarbaki/python-challenge | /03-Python/Instructions/PyBank/Pybank_HW.py | 987 | 3.75 | 4 |
import os
# Module for reading CSV files
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
# Read the header row first (skip this... |
156f0422b2dcf4e5aaf228f0d2b8e47de8b2c5d6 | Elida2000/py-s7-c1-ejer01 | /cardex_app.py | 3,894 | 3.65625 | 4 | from prettytable import PrettyTable
import pymysql
"""
1. identificar cada parte de lo que esta en el codigo
"""
"""
connection = pymysql.connect(
esta creando la conexion entre mi programa python con la base de datos
mysql vean que se tiene los datos de conexion host, user, passwrd, el
eschema o la base de datos
"... |
8a96036d935fcb2406c6c1f810be88e8853bcd46 | ClaudioAresu/pythonbasic | /classcoordinate.py | 612 | 4.15625 | 4 |
class coord():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.coord = (self.x, self.y)
def move(self, x, y):
self.x += x
self.y += y
def __add__(self, p):
return coord(self.x + p.x, self.y + p.y)
def __sub__(self, p):
... |
677ce9c64f3b76da577ecaf7f9d61241d656d936 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/pybites/bitesofpy-master/!101-200/126/emoji.py | 1,305 | 3.875 | 4 | import sys
import unicodedata
START_EMOJI_RANGE = 100000 # estimate
def what_means_emoji(emoji):
"""Receives emoji and returns its meaning,
in case of a TypeError return 'Not found'"""
try:
return unicodedata.name(emoji)
except TypeError:
return 'Not found'
def _make_emoji_mappi... |
ed8d07ccc0cab88e5823c70735102fc7431d75c6 | rimachinz/pythoncodes | /regularexprssn/regularexprsn7.py | 317 | 3.96875 | 4 | # replace a string
import re
string ='''Computer science is
the study of the theory,
experimentation and engineering
that form the basis for the design
and use of computers.'''
regex = re.compile('\n') # newline replaced by space printing on a single line
substring = regex.sub(" ", string)
print(substring) |
5ccc4e9b0c1f80564fd3e075bee12ce3792e63d5 | kevinsay/pythonstudy | /test2.py | 506 | 3.609375 | 4 | class Dog:
def __init__(self, name):
self.name = name
pass
def eat(self):
print("%s is eating" % self.name)
def bulk(self):
print('1234')
dog = Dog("dahuang")
choice = input(">>:").strip()
if hasattr(dog, choice):
func = getattr(dog, choice)
func()
else:
setattr(dog,... |
7c80d152e1bea13d45d3401490c94f99a547a1bf | smalpple/python | /python_review/Advanced features/sorted.py | 305 | 3.671875 | 4 | L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
## 请用sorted()对上述列表分别按名字排序:
def by_name(t):
return t[0]
print(sorted(L,key=by_name))
### 再按成绩从高到低排序:重点是从高到低
def by_score(t):
return t[1]*-1
print(sorted(L,key=by_score)) |
6086fdc652c028bfc254ac9119f0d1bf50b2c61d | eBLDR/Project_Euler | /data/problems/016.py | 215 | 3.796875 | 4 | """
2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2**1000?
"""
from data.tools.tools import sum_digits
NUMBER = 2 ** 1000
print(sum_digits(NUMBER))
|
3073570c7679fec7c4b093164777deb57743cc37 | ejs/pythonroguelike | /levelmap.py | 1,532 | 3.703125 | 4 | class Tile(object):
# a tile of the map and its properties
def __init__(self, blocked, block_sight = None):
self.blocked = blocked
# all tiles start unexplored
self.explored = False
# by default, if a tile is blocked, it also blocks sight
if block_sight is None:
... |
db2e25f97183fa47d80c20da663861c294e47fb1 | Spas52/Python_Fundamentals | /Functions - Exercise/02. Add and Subtract.py | 385 | 3.9375 | 4 | first_number = int(input())
second_number = int(input())
third_number = int(input())
def sum_numbers(num1=first_number, num2=second_number):
result = num1 + num2
return result
def subtract(num3=third_number):
subtract_result = sum_numbers() - num3
return subtract_result
def add_and_... |
efe34c7f689a652139415adde6a8a0cf271e36ca | davisspe/Calculator- | /HW5.py | 19,221 | 4.03125 | 4 | #HW5
import math
import pdb
class Calculator:
class stack:
class node: ### stack design for our calculator
# push the position of every ( and pop when ) is found.
# --- code the rest of the class ---
# It's very similar to the queue in EX9_15
#'
#... |
6894989134906aa5121917728c0ddc1ce8bf3b2e | alvaroolt/Colecciones-y-diccionarios | /coleccionesYDiccionariospy/Ejercicio2.py | 770 | 3.796875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 3 abr. 2019
Realiza un programa que introduzca valores aleatorios (entre 0 y 100) en un
ArrayList y que luego calcule la suma, la media, el máximo y el mínimo de esos
números. El tamaño de la lista también será aleatorio y podrá oscilar entre 10
y 20 elementos ambos inclusiv... |
125cf6b989a657a77ed7e859410526faf38a71f2 | kidpeterpan/my-python-tutorials | /org/konghiran/lesson/_01_python_comparison_operators/_01_chain_comparison.py | 134 | 3.953125 | 4 | # and
# or
# not
print(1 < 2 and 2 < 3)
print(1 < 2 and 3 < 3)
print('h' == 'h' and 'H'=='H')
print('h' == 'h' and not('H'!='H'))
|
642a07388ccf0768c84191ca30ec2aacb84501bb | lafleur82/python | /dictionary_sort.py | 339 | 3.875 | 4 | from collections import OrderedDict
from operator import itemgetter
def dict_sort(my_dict, up_or_down):
new_dict = OrderedDict(sorted(my_dict.items(), key=itemgetter(1), reverse=up_or_down))
return new_dict
dict1 = {1: 3, 2: 5, 3: 4, 4: 7}
print(dict_sort(dict1, False))
print("\n")
print(dict_sort(dict1, ... |
7655571e9a7eb2be7ea69d8cee1a7fd47594d70e | anand-surya/ISTE-612-Project | /recommend.py | 1,713 | 3.578125 | 4 | import pandas as pd
from sklearn.feature_extraction import text
from sklearn.metrics.pairwise import cosine_similarity
# reading the lyrics csv file
# erroe_bad_lines will skip the rows with missing and damaged values
path = "azlyrics_lyrics_b.csv"
lyrics = pd.read_csv("azlyrics_lyrics_b.csv", error_bad_lines=False)
... |
54c3a9d2d6c997c57fe6fdcc435f0f7b7fb4d55b | piodossantos/LenguajesProgramacion | /UT1 - Programacion Imperactiva/InterpreteWhile.py | 13,580 | 3.515625 | 4 | from WhileExceptions import *
# Base classes
class Exp:
#constructor
def __init__(self):
...
def __repr__(self):
return self.__str__()
class Stmt:
#constructor
def __init__(self):
...
def __repr__(self):
return self.__str__()
#Sub classes
class Num(Exp):
... |
39af0b4b256350555621f2ebee3837282ba5e596 | AnumHassan/ASG | /Q_9.py | 54 | 3.671875 | 4 | St=str(input(" Enter a String: " ))
print(St*len(St)) |
f4e61c1dccddae2840a02e679e98c5d1b33d6644 | seanchen513/leetcode | /dp/0121_best_time_to_buy_and_sell_stock.py | 1,666 | 4.28125 | 4 | """
121. Best Time to Buy and Sell Stock
Easy
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot se... |
2a885c56adb9b75884f96f017b02c84838267ebf | dhumindesai/Problem-Solving | /educative/sliding_window/fruitsIntoBasket.py | 1,085 | 3.5 | 4 | def fruits_into_baskets(fruits):
basket1, basket2 = {}, {}
start, end = 0, 0
result = 0
for end in range(len(fruits)):
fruit = fruits[end]
if fruit in basket1:
basket1[fruit] += 1
elif fruit in basket2:
basket2[fruit] += 1
else:
if not... |
f8f4b6b00093d141d6f0e1fe1b254cd83f7fbee3 | fixmeplz/PythonEducation | /Последовательность.py | 897 | 3.765625 | 4 | #Программа, которая выводит часть последовательности
#1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется столько раз, чему равно n).
#На вход программе передаётся неотрицательное целое число n — столько элементов последовательности должна отобразить программа.
#На выходе ожидается последовательность чисел, записа... |
c329756ceb8deb74b499246e7c5823fd753101bd | JYleekr847/python_summer | /Chapter3/2.py | 832 | 3.90625 | 4 | # 파이썬에서 인자는 레퍼런스를 이용해 전달한다.
a = 10
b= 20
def sum1(x, y):
return x+y
print(sum1(a,b))
#정수형 변수는 변경 불가능한 변수
x = 10
def sum2(x, y):
x = 1
return x+y
print(sum2(x,b))
print(x)
# 리스트는 변경가능한 변수타입
# 함수가 종료된뒤 함수 내에서 함수 바깥의 값을 변경시킴, x[0]는 레퍼런스가 아닌 실제값의 주소를 의미한다.
def change(x):
x[0] ='H'
wordlist = ['J','A','M']
chang... |
3fd1dd766358307942bc29b2f3c15940fdbb3463 | alfix123456/Python | /TextGenerator.py | 359 | 3.953125 | 4 | """
This Program will generate random names and in future it will create password lists
"""
import string
import random
def Generator():
letter1=random.choice(string.ascii_lowercase)
letter2=random.choice(string.ascii_lowercase)
letter3=random.choice(string.ascii_lowercase)
name=letter1+letter2+letter3... |
858d871a5067c7cb6696a53512ce97dc7ebfa438 | C11611/practice | /functions/KNN.py | 1,945 | 3.53125 | 4 | from math import sqrt
import numpy as np
from collections import Counter
'''
def kNN_classify(k,X_train,y_train,x):
assert 1<=k<=X_train.shape[0],"k must be valid"
assert X_train.shape[0]==y_train.shape[0],\
"the size of X_train must equal to the size of y_train"
assert X_train.shape[1]==x.shape[0],\
"the feature... |
d556f9647d42dc198b46d26cb3cd5d927876adb1 | henryneu/Python | /sample/eun.py | 698 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from enum import Enum, unique
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
print(Month.Feb)
# @unique装饰器可以帮助我们检查保证... |
4a5db37e28e58df97177faba8ce4fdc8becc0879 | peanut996/Leetcode | /Python/剑指 Offer 45. 把数组排成最小的数.py | 474 | 3.59375 | 4 | #!/usr/bin/python3.7
# 剑指 Offer 45. 把数组排成最小的数
from typing import List
class Solution:
def minNumber(self, nums: List[int]) -> str:
# a+b>b+a 则a比b“大”
from functools import cmp_to_key
return ''.join(sorted(map(str,nums),key=cmp_to_key(lambda x,y: int(x+y) - int(y+x))))
if __name__ == '__main... |
ca70a38137ff25ad5eb84e0178b4cc4b2904672b | yosemitebandit/vebsite | /clamp_image_dimensions.py | 1,393 | 3.53125 | 4 | """Shrinks images.
Usage:
clamp_image_dimensions <source> <width> <height>
Arguments:
<source> the source image or a directory of images
<width> max width
<height> max height
"""
import os
from docopt import docopt
from PIL import Image
if __name__ == '__main__':
arguments = docopt(__doc__)
# Pro... |
93fc45855c14b3e76ae7306daa21264b65d4aa31 | uiandwe/TIL | /algorithm/alogorithm_test/14_Merge_Two_Sorted_Lists.py | 948 | 3.984375 | 4 | # -*- coding: utf-8 -*-
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# head = ListNode()
# pre = ... |
ddc11ba99c3efd553ccc50e338cb9b80e68b321b | Strugg1e/blog_for_thinkphp6 | /blog/小配置/selenium脚本/selenium_test1.py | 937 | 3.640625 | 4 | from selenium import webdriver
#豆瓣的测试selenuim操作
x = webdriver.Chrome()
# url = "http://www.luolidao.com/"
url = "http://movie.douban.com/"
x.get(url)
x.find_element_by_name("search_text").send_keys("鸡巴")
x.find_element_by_id("inp-query").send_keys("毛线")
class_name = x.find_element_by_class_name("item"... |
93d732d3e628258bea1873e3bda00b91179d8e53 | brukeg/pcg_python | /lab17-palindrome-anagram.py | 944 | 4.3125 | 4 | """
A palindrome is a word that's the same forwards or backwards. Two words are anagrams of eachother if the
letters of one can be rearranged to fit the other. Write a palindrome and anagram checker.
"""
def check_palindrome(word):
reverse = ''
word = input("Enter a word: ").strip().lower()
# a for loop for reve... |
f7b6da97cc463564b13c2ecfe2f7c795ccf28b3d | Programmer-Admin/binarysearch-editorials | /3 and 7.py | 511 | 3.890625 | 4 | """
3 and 7
Mutiples of three:
0,3,6,9,12,15,18,21,...
Mutiples of seven:
0,7,14,21,...
By removing 7 or 14, we fall back on a multiple of 21, which is also a multiple of 3.
In the general case ax+by = c where a,b,c are integers, check out linear diophantine equations:
https://brilliant.org/wiki/linear-diophantine... |
249b3a578b6190e7f7964e0ac655a66a420bc603 | polovinkinaaa/review1 | /projecti.py | 7,313 | 3.953125 | 4 | def caesar_encryp(key, text):
if key > 26:
key = key % 26
ans = ''
for symb in text:
if ord(symb) >= ord('a') and ord(symb) <= ord('z'):
if ord(symb) + key > ord('z'):
ans += chr((ord(symb) + key) - 26)
else:
ans += chr(ord(sym... |
754893c460fbf9f167e804a885ad178ff8d7fa64 | dawidbo/algorithms | /Codility/MaxProductOfThree.py | 682 | 3.9375 | 4 | '''
Yes, sorting the array and taking the last three elements (largest positive elements) will give you a candidate for the maximum product of three,
however take in mind that each int may be as low as -1000.
Therefore multiplying the two most negative values by the largest positive value is also a candid... |
946e0e08c23179eecb606ed5c52e8142a2fa4190 | BielMaxBR/Aulas-de-python | /AulasdePython/exercícios/ex041.py | 631 | 3.96875 | 4 | from datetime import date
atual = date.today().year
nascimento = int(input('diga o ano de nascimento do atleta:'))
idade = atual - nascimento
if nascimento < atual:
if idade <= 9:
print('seu atleta é MIRIM.')
elif idade <= 14:
print('seu atleta é INFANTIL.')
elif idade <= 19:
print('... |
1a72e62b9057f2bbae0a5441d803e1d59c575f81 | payam49er/pythonbasics | /variables.py | 211 | 3.84375 | 4 | x = 1 #int
y = 2.5 #float
name = 'Payam' #string
is_cool = True #bool
#multiple assignment
x,y,name,is_cool = (1,2.5,"Payam",True)
print(x+y)
#check type
print(type(x))
#casting
x = str(x)
print(type(x))
|
89c42793440bb94361624866422038f96908f8c1 | christinebramos/Embryo-Image-Analysis | /Python/findROI.py | 774 | 3.609375 | 4 | # script to find ROI coordinates
import numpy as np
import cv2
# function programmed to display coordinate on the image wherever clicked on
def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
print(x,' , ', y)
font = cv2.FONT_HERSHEY_SIMPLEX
strXY = str(x) + ', '... |
0e138f166c705e821bb0d2744af43d42bf0271e2 | ashisharora24/learning_tutorials_practice | /Data Structures and Algorithms in Python/12_Stacks/test.py | 280 | 3.546875 | 4 | def MissingNumber(li):
n=len(li)
for i in range(n-1):
for j in range(i,n):
if li[i] == li[j] and i!=j:
return li[i]
return 0
# Main
n=int(input())
arr=list(int(i) for i in input().strip().split(' '))
ans=MissingNumber(arr)
print(ans)
|
12858cef0042c1c9b3b0628d20f823a5a8535098 | erick4556/Python | /Python/Parte 2/Prueba_Funciones2.py | 697 | 3.84375 | 4 | class Main:
def eleve(self,el):
mul=1
num=int(input("Ingrese numero a elevar : "))
for x in range(el):
mul=mul*num
return mul
def suma(self):
suma=0
for x in range(0,5):
print(x)
suma+=x
print("La suma es : ",suma)
def nodev():
suma=0
for x in range(0,3):
print("Ingrese numero ",x+1," v... |
f78c6faa3bb456424a485ce08668052570007c62 | mattyice89/MadLibsGenerator | /MadLibs.py | 3,711 | 4.21875 | 4 | '''The Goal: Inspired by Summer Son’s Mad Libs project with Javascript.
The program will first prompt the user for a series of inputs a la Mad Libs.
For example, a singular noun, an adjective, etc. Then, once all the
information has been inputted, the program will take that data and
place them into a premade story temp... |
ca9087518229d834ab83c2501f1590f052430062 | saint-yellow/python-pl | /leetcode/dp/main-193.py | 1,152 | 3.578125 | 4 | from typing import List
class Solution:
def rob(self, numbers: List[int]) -> int:
return self.__method3(numbers)
def __method1(self, numbers: List[int]) -> int:
# 没得偷
if not numbers:
return 0
# 只有一家可偷
n = len(numbers)
if n == 1:
return ... |
49c98b71d4ed8d5a810e72af9591b72c9b38dd0f | kishorebolt03/learn-python-the-hard-way | /ITVAC/problem_solving/WORDPRINT.py | 2,415 | 3.703125 | 4 | ''' A A A A A
A A
A A
A A A A A
A A
A A
'''
def A(col):
for row in range(7):
for j in range(col+5):
if ((j==col or j==col+4) and row!=0) or ((row==0 or row==3) and (j>=col and j<=col+4)):
print("A... |
f56e165ef4db21e0f2b4f8ffe82707462e3b416d | bobreddy2009/111 | /PythonConcepts/file_homeworkq2.py | 714 | 3.890625 | 4 | f = open(file = "file_studentscores.txt",mode="a")
def input_info():
name = input("what is your name:")
english = input("whats is your English scores")
math = input("what is your math scores:")
physiscs = input("what is your physics scores:")
bioligy = input("what is your biology scores:")
chem ... |
5f50b308f0b18f1698c7e8969bcd5016eff1145a | elephantstone/cs50 | /pset6/crack.py | 776 | 3.890625 | 4 | import crypt
import sys
import string
'''
create a list containing all the upper and lower case characters
'''
l1 =['']
l2 = [i for i in string.ascii_letters]
li =l1+l2
print(li)
def main():
'''
hashed is the hashed password to be cracked
'''
if len(sys.argv)!=2:
raise IndexError
l1 =['... |
c74ec40e10d72ce52814df70b16214ce70c2a235 | moncada92/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 795 | 3.828125 | 4 | #!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""Test for integers"""
def test_max_integer(self):
"""Cases"""
self.assertEqual(max_integer([6, 7, 9]), 9)
self.asser... |
ea007077448e3e2a074f5006f7cbd4a244afc3ad | bowob-gotcha/special-octo-fortnight | /score.py | 709 | 4.0625 | 4 | #You can either try this one
score = input("Enter Score: ")
x = float(score)
try:
if x > 1.0 or x < 0 :
print("Out of Range")
elif x >= 0.9 :
print("A")
elif x >= 0.8 :
print("B")
elif x >= 0.7 :
print("C")
elif x >= 0.6 :
print("D")
elif x < 0.6 :
... |
05da0045eb02c2112361a04f663abcc30b49c53a | edwardmpearce/adventofcode | /2020/Day2/sol.py | 1,616 | 4.375 | 4 | #!/usr/bin/env python3
"""
--- Day 2: Password Philosophy ---
https://adventofcode.com/2020/day/2
Part 1: Count occurences of a character within a string and verify it lies within a given range
Part 2: Check whether a test character appears exactly once in a pair of positions in a string
"""
def main():
password_... |
b20ae63a924bae7faf14aa01187144cc9e90d5e4 | chaitanya9899/billing-software | /Customer-Billing-System--master/assignment_output.py | 924 | 3.8125 | 4 | from collections import Counter ## Counter is a container that will hold the count of each of the elements present in the container
user_names =[
## list items
"sachin tweet_id_1",
"sehwag tweet_id_2",
"sachin tweet_id_3",
"sachin tweet_id_4"]
def mainfunct... |
a9d3b9b41b9b8f561c7aceced98e194e23c80478 | jedzej/tietopythontraining-basic | /students/jemielity_kamil/lesson_02_flow_control/ladder.py | 138 | 3.90625 | 4 |
number = int(input('Integer: '))
for row in range(1, number + 1):
for i in range(1, row + 1):
print(i, end='')
print()
|
31ede9e5677451d01d9369e23bb1b158dff83a20 | kuangyl0212/PAAA | /src/test/resources/py-source-a/003py_source_file2.py | 980 | 3.59375 | 4 | """
2.(10分)在一个农场中,养了一群鸡和兔。一只鸡有两条腿,一只兔有四条腿。请编写程序,完成以下任务:
(1) 编写函数calculate(head, leg),其中形参head和leg分别表示农场中所有动物的头和脚的个数。通过该函数计算,在屏幕上显示鸡和兔的个数。
例如:向该函数传入实参10和32,屏幕显示结果为:
4 6
(注:4和6中间没有空格;表示鸡和兔的个数分别为4和6)
(2) 假设所有动物的头和脚的个数分别为12和32,调用(1)中的函数,打印鸡和兔的个数。
注:(1)题中动物个数需为整数。(2)编程题中的过程代码要同时写在纸质试卷上。
"""
def calculate(head,leg)... |
351a6e14f867e79b4cc5e9d50ce1a97ccca7ee70 | DanielFL0/Learning-Python | /exercise6-4.py | 1,182 | 4.625 | 5 | #6-4 Glossary 2: Now that you know how to loop through a dictionary, clean up the code from exercise6-3 (page 102) by replacing your series of print statements with a loop that runs through the dictionary's keys and values.
#When you're sure that your loop works, add five more Python terms to your glossary. When you ru... |
ea03689b8be9bd5fab6af7d4e20d2ceae0d8e88b | reesporte/euler | /3/p3.py | 534 | 4.125 | 4 | """
project euler problem 3
"""
def is_prime(num):
if num == 1:
return False
i = 2
while i*i <= num:
if num % i == 0:
return False
i += 1
return True
def get_largest_prime_factor(num):
largest = 0
i = 2
while i*i <= num:
if num%i == 0:
... |
b38328dac9a2fa9396b2bfc94eb776aae24fb02d | res0nat0r/exercism | /python/grains/grains.py | 430 | 3.84375 | 4 | """
Calculate the number of grains of wheat on a chessboard given that the number on
each square doubles.
"""
def square(number):
"""
:param int: number to square
:return: int
"""
if number not in range(1, 65):
raise ValueError("square must be between 1 and 64")
return pow(2, number... |
9aaf6ee019e07354bea2ed40b7a58592b92267ce | kishsal/ProgrammingWithPython | /Week2-PythonConcepts/Project3-CreateClassOfCars/Cars.py | 440 | 4.125 | 4 | # Creating a class, init function assigns values to object properties
class Cars:
def __init__(self, model, make, year):
self.model = "Ford"
self.make = make
self.year = year
def print_model(self):
print(self.model)
def print_make_and_year(self, make, year):
print... |
5f8b524942f1acd8510791970a97a7844a2c79e1 | AbhiniveshP/LeetCode-Extras | /Backtracking/46-Permutations.py | 904 | 3.578125 | 4 | class Solution:
def __backtrack(self, currentList: List[int], currentSet: set,
finalList: List[List[int]], nums: List[int]) -> None:
if (len(currentList) == len(nums)):
finalList.append(list(currentList))
return
for i in range(len(nums)):
i... |
82efaa585c1e2f1aa790f3149aa656780b3df4f6 | masenius/aveso-advent-of-code | /2016/davidm-python/d2c1.py | 591 | 3.71875 | 4 | #!/usr/bin/env python
f = open("d2.input", 'r')
pad = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
button = [1, 1]
code = ""
def move(button, direction):
if direction == 'U':
button[1] -= 1 if button[1] > 0 else 0
if direction == 'D':
button[1] += 1 if button[1] < 2 else 0
if direction == 'L':
... |
e80ff2c8414e34594c45d46e37200288dc29e6eb | thisishaykins/PyBasics | /tuples.py | 208 | 3.515625 | 4 | """
Tuples are list that can not be modified: cannot add new items, cannot remove exiting items. Tuples Immodifiable or
immutable lists. It can not mutated or change
"""
numbers = (1, 2, 3)
print(numbers[0]) |
b805d517f563d6e8f508b693f7856581944c129e | guandi97/Micropenguin | /Jerry/triangle_billiards.py | 5,987 | 3.609375 | 4 | from visual import *
# a program to illustrate a ball bouncing in a right triangle
# March 10, 2005 updated October 17, 2007
#Amy Kolan
#good starting conditions to show the hanging out effect
#ball.pos=(trix,9.5,0), ball.velocity=vector(-1,0.001,0)
clear="on"
trix=14.2
triy=10.
scene.center=(trix/2.,triy/2.... |
1a19a0a398330e6eac5e8700273bad477a074be7 | sarthikg/python-algorithms | /sorting-algorithms/selectionSort.py | 393 | 3.75 | 4 | def selectionSort(array):
start_length = 0
while start_length < len(array)-1:
smallest_index = start_length
for i in range(start_length+1, len(array)):
if array[i] < array[smallest_index]:
smallest_index = i
temp_value = array[start_length]
array[start_length] = array[smallest_index]
... |
d573e9ebfa74ff55ddc40666825f66bb96d41b0d | sergeLabo/formation_python | /py_8_class/py_82_exo_class/py_81_fifo/py_81_fifolist_enonce.py | 972 | 3.640625 | 4 | # replit_main
# # py_81_fifolist_enonce.py
"""
Créer une class pour créer des objets qui seront des instance de cette class.
Nous recevons des valeurs en OSC, par exemple une position en profondeur,
la distance de la personne par rapport à la caméra:
donc une seule valeur
ces valeurs sont soit int ou float
... |
c833d9dc0e2e177a54399f861bad5ba0f128a92e | BaijiaChen/NYC | /Version - 1.0.2.py | 8,473 | 3.890625 | 4 | # coding: utf-8
# Author: Baijia Chen
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib as mpl
# #__STEP ONE: Drawing design (Data Input & Check)__
#input data and check
data_input = pd.read_csv('input/nyc-rolling-sales.csv')
data_input.head(5)
# #__STEP TWO: Digging Foundatio... |
bd2d1b2f993b810d524220dbffe12fe8141787d5 | tastangh/Python-Learning-Projects | /Temel Veri Yapıları/2.dereceden denklem koku bulma.py | 796 | 4.09375 | 4 | """
2. dereceden bir bilinmeyenli denklemin köklerini bulma
Denklem : ax^2 + bx + c
Deltayı Hesaplama: b ** 2 - 4 * a * c
Birinci Kök : (-b - delta ** 0.5) / (2*a)
İkinci Kök : (-b + delta ** 0.5) / (2*a)
"""
""""Kullanıcıdan Denkelmin parametrelerini Alma Bölümü """""
print("a değerini giriniz!(Denklem : ax^2 +... |
5723dca9cdfcf2df4b6fdcbb6cdb21dbe56e3ae0 | Sadiya1noorain/ACS | /acs1.py | 204 | 3.84375 | 4 | n = int(input("Number of numbers in Series = "))
print('Enter the numbers')
a = []
for i in range(0, n):
numbers = int(input())
a.append(numbers)
print('The average of the numbers is ', sum(a)/n)
|
0cfbdd303f6f5bbe68e51e5304533e010b1978a0 | ankitsingh03/code-python | /gfgs/dictonary/14. using list.py | 328 | 3.53125 | 4 | arr = ['cat', 'dog', 'tac', 'god', 'act']
lst = ["".join(sorted(i)) for i in arr]
print(lst)
a = {i: lst.count(i) for i in lst}
print(a)
rev_A = sorted(a, key=lambda item: a[item], reverse=True)
print(rev_A)
nlst = []
for i in rev_A:
for j in arr:
if sorted(i) == sorted(j):
nlst.append((j))
prin... |
fd7b538d6ecafced1970e6f0470a5eb012428971 | CarterCompute/Python | /Challenge_Poem/Challenge_Poem/Challenge_Poem.py | 618 | 4.15625 | 4 | #Write a program that will display the following poem on the screen
#There once was a movie star icon
#who preferred to sleep with the light on.
#they learned how to code
#a device that sure glowed
#and lit up the night using python!
print("""There once was a movie star icon
Who preferred to sleep with the light on.
... |
b973932b34287d6dab98afd8784954a91fa779e0 | mcfarland422/python101 | /objects101.py | 637 | 3.8125 | 4 | # a class to make Atl United players
class Player(object):
EVERY class needs to start with def_init_
# this function gets run ONCE and only ONCE, when the object is made def_init_(self):
# you pass in args, when you make the object
# self is ALWAYS the first
# everything else is optional
def_ini... |
66a8fb4d391d341541fecd61f3e448dc13d161ed | xiaoxuexin/Artificial_Intelligence | /Map_Searching/unicost.py | 3,244 | 3.59375 | 4 | # Uniform Cost Search
from Graph import mapGraph
graph, dist = mapGraph()
class Node:
def __init__(self, city_name):
self.city_name = city_name
self.children = []
class Tree:
def __init__(self, city_name):
self.root = Node(city_name)
def bubble_sort(self, name_list):
c... |
02b6898176cba0c7c33d45770b43bdf9d13aa567 | MrWifeRespecter/TECHNOLOGY | /U4-4/U4-4/U4_4.py | 1,288 | 3.59375 | 4 | #här frågar jag efter bensinpris och ger en variable det värdet.
pris=float(input("Hur mycket kostar en liter bensin? "))
#här skriver jag if-satserna
if pris<10:
print("Det var billigt!")
#här la jag till en tom input bara för att användaren inte kunne se svaret innan konsollen stängdes om man inte anvädner ... |
af75b3ecfc8bce7fad1bf5fdcca9a0e78fbeb930 | aparjun/python | /Longest Common Substring.py | 646 | 3.828125 | 4 | #PF-Prac-45
def longest_common_substring(string1, string2):
x_longest=0
longest=0
l=len(string1)
for i in range(0,l):
for j in range(l-i,0,-1):
if(string1[i:i+j] in string2):
if(longest<j):
longest=j
x_longest=i+j
r... |
4a2852ed972127ed727343a736a63776d6c8a79d | han8909227/leetcode | /dynamic_programming/anagram.py | 378 | 4.03125 | 4 | """Given list of words, print all anagrams together."""
def anagram(words):
"""."""
word_dic = {}
for word in words:
word_str = ''.join(sorted(word))
word_dic.setdefault(word_str, [])
word_dic[word_str].append(word)
print(word_dic)
if __name__ == '__main__':
w = ['anagram'... |
d0b83bc7fe73262f16ca117c3f8a4460c783bf34 | rmalkmus/python | /contains.py | 385 | 3.921875 | 4 | #!/bin/python
import argparse
parser = argparse.ArgumentParser(description="Pass this a snippit of what word you'd like to search for")
parser.add_argument("snippit", help="the string you'd like to search for")
args = parser.parse_args()
snippit = args.snippit.lower()
words = open("/usr/share/dict/words").readlines... |
cd6e24a42c9892255c94fc059019c526026bf1d9 | GabriellyBailon/Cursos | /CursoEmVideo/Python/Mundo 2/ex040.py | 630 | 4 | 4 | #Ler duas notas, calcular a média e mostrar se o aluno foi aprovado, reprovado ou ficou de recuperação
nota1 = float(input("Digite a primeira nota: "));
nota2 = float(input("Digite a segunda nota: "));
media = (nota1 + nota2) / 2;
if media <= 5.0:
print(f"A sua média foi de \033[31m{media:.2f}\033[m pontos... |
755bb88ebd58c32ae0b8dd1965d127d5606a17e2 | adityagith/pythonprograms | /open file alternate method.py | 518 | 3.6875 | 4 | file1 = open("file1.txt","r")
list = []
a = []
for each in file1:
list.append(each)
for item in list:
print (item,end="")
file1.close()
file1 = open("file1.txt")
print("\n\n")
a.append(file1.readline())
a.append(file1.readline())
a.append(file1.readline())
a.append(file1.readlin... |
64352d3a486e42c89441250eb16c619a2b517e4e | Matuiss2/URI-ONLINE | /2000- 3000/2483.py | 153 | 3.828125 | 4 | loops = int(input())
ases = ""
for i in range(loops):
ases += "a" # adiciona "a", pela qntd definida no input
print("Feliz nat" + ases + "l!")
|
a095de1e9ebfe8afd0d4b84cd332a1ac9812b4eb | Anju-PT/pythonfilesproject | /advancedpython/oop/class/demo.py | 696 | 4.34375 | 4 | #class
#design pattern
#object
#real world entity
#reference
# name that refers a memory location of a object(temporary memory space)
# =to access class using object(unique references for each objects)
#class
#keyword class name must start capital letter
#syntax :: class Person:
# class Person:
# def print(sel... |
634ad2b048885cf00185db3034fb4576df56d015 | HalfMoonFatty/Interview-Questions | /110. Balanced Binary Tree.py | 709 | 4.0625 | 4 | '''
Problem:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
class Solution(object):
def isBalanced(self, root):
# helper function
... |
7e718cad87ef5a17d9c028c817b0ed10f0c089a8 | yanyong666/Python_Learning | /var.py | 891 | 4.34375 | 4 | # 基础
# 2.变量
# 标识符命名
# 数据类型
# 对象 Python 是强(Strongly)面向对象的,因为所有的一切都是对象, 包括数字、字符串与 函数。
# 案例:使用变量与字面常量
i = 5
print(i)
i = i + 1
print(i)
# 变量只需被赋予某一值。不需要声明或定义数据类型
print('''This is a multi-line string.
this is the second line.''')
# 逻辑行与物理行 这三句等价 在python 最好不要使用;分号 可以用\代替多行输出
i = 5; print(i);
i = 5;
print(i);
i = 5; print... |
8d6281cc7b07d7ac5894b3f82495af97a9424dd3 | RaduAlbastroiu/Python-Projects | /Home Projects/Homework number 1.py | 7,551 | 4 | 4 | #
# mainFile.py
#
# Created by Radu Gabriel Albastroiu
#
def matrixRead():
# input reading
print(" Add another matrix, after the last row of the matrix enter an empty row")
matrix = []
while True:
aline = input()
if not len(aline):
break
matrix.append(a... |
d9c74e2ab3da89078783810d98be015d533fffd2 | yukai-chiu/CodingPractice | /LeetCode/Explore/Recursion I/Pascal's Triangle II.py | 829 | 3.515625 | 4 | #Dynamic Programming
#Time: O(k^2)
#Space: O(k) + O(k) = O(k)
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex < 0:
return []
row = [1]
for r in range(1, rowIndex+2):
curr_row = [1] * r
for i in range(r):
i... |
5ca067002f0ffa87b5d6527a29fae88019dfa75a | vipinvkmenon/canddatastructures_python | /chapter15/example3.py | 651 | 3.71875 | 4 | # Chapter 15.3
# PROGRAMMING WITH STRUCTURES
class student:
name = 0
marks = 0
def main():
student1 = student()
student1 = read_student()
print_student(student1)
read_student_p(student1)
print_student(student1)
def read_student(): # A
student2 = student()
student2... |
20fcd5a8a19770e974b627125f9a0f932128783e | brady-wang/spider_python | /ai/3.py | 570 | 3.65625 | 4 | # *_*coding:utf-8 *_*
def binaery_search(list,item):
low=0
high=len(list)-1
while low <= high:
mid=int((low+high)/2)
guess=list[mid]
if guess == item:
return mid
if guess >item:
high=mid-1
else:
low=mid+1
return None
my_list=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.