blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d61f11456525b2d90b1a56e69ba87fd1c51965fb
patelrohan750/python_practicals
/Practicals/practical1_A.py
191
4.1875
4
#A.Develop a Python Program to Add Two Numbers. num1=int(input("Enter First Number: ")) num2=int(input("Enter Second Number: ")) print("The Addition of two Numbers is: ",num1+num2)
0759aee7ac2793f2d3d9fd0b67ded89f90ba49bf
javadeveloperethan/ddd
/aboutMe.py
263
3.765625
4
o = input("자신의 나이를 입력하세요 :") h = input("자신의 키를 입력하세요 :") w = input("자신의 몸무게를 입력하세요 :") print("제 나이는" + o + "이고," + "제 키는" + h + "이며," + "제 몸무게는" + w + "입니다")
a13984fa71b097435f1c0e795d046ba94879572f
JancisWang/leetcode_python
/67.二进制求和.py
943
3.75
4
''' 给定两个二进制字符串,返回他们的和(用二进制表示)。 输入为非空字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-binary 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def addBinary(self, a: str, b: str) -> str: if l...
f34ee47b0993ddc755461e315345130929e08a2c
carlosevmoura/courses-notes
/programming/python-curso_em_video/exercises/ex104.py
319
3.984375
4
def leia_inteiro(_texto): while True: numero = str(input(_texto)) if numero.isnumeric(): return numero else: print('Erro! Digite um número inteiro válido!') numero = leia_inteiro('Digite um número: ') print('Você acabou de digitar o número {}.'.format(numero))
919709209c6e243d30ff490decdbb715c585af15
Mirror-Shard/L3
/1 user.py
207
3.984375
4
name = str(input("Enter your name: ")) age = str(input("How old are you live? ")) adress = str(input("Where are you live? ")) print("This is " + name) print("It is " + age) print("(S)he live in " + adress)
03542820f283738423c28b2cf71e243c7458692d
shashank31mar/DSAlgo
/rotate_array.py
939
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 20 07:48:53 2018 @author: shashankgupta """ def swap(arr,ai,bi,d): for i in range(d): arr[ai+i],arr[bi+i] = arr[bi+i],arr[ai+i] def rotate_array(arr,d,n): ''' divide array in two parts A[1...D-1] and B[D....high] if A < B d...
52cbc851e57d9e0ca4237340a23f4250d3ae910b
vakaru2013/lwater
/water_model/fv2.py
14,269
3.703125
4
""" Feature vector model No.2 short target: calculate the rate of stock return, if it is good, I am a genius. a list, each item in it is a dict, its key is a feature vector, while its value is all lineidx whose fv equal to the key. then, a function, print info into a file like this: fv: [.....
ea9b3121115d5cebf26f298c127c56236607606a
thohidu/google-algorithms
/lesson_5/binary_tree_quiz.py
2,713
4.375
4
"""Your goal is to create your own binary tree. You'll need to implement two methods : search(), which searches for the presence of a node in the tree and print_tree(), which prints out the values of tree nodes in a pre-order traversal. You should attempt to use the helper methods provided to create recursive solution...
8935ff518a052b3d170f811f66cb7bec5a8170fa
keriber596/Piter_and_Starck
/starter_obj.py
1,140
3.65625
4
import pygame import classes import random #sprite_hero = classes.Sprites_hero() "_____________________________________________" width_window = 1000 height_window = 500 background = classes.Background(width_window, height_window, 0, 0) #все фоны "_____________________________________________" bullets = [] enemys = [...
09af33962d2c43d81cf5ced1d35760456c2b35e6
Yelchuri555/PythonPrograms
/StringProgram/UpperLowerCases.py
136
3.765625
4
userinp = raw_input("Enter a String :") upperCount = 0 lowerCount = 0 for i in userinp: if(i.isupper()): upperCount += 1
269d988c5629524a852c89c8d94f0aed7dd6914a
marceloccs/phytonAulas
/my_first_project/media.py
709
3.5625
4
#media, mediana, moda def media (lista): media = sum(lista)/float(len(lista)) return media def mediana (lista): list.sort(lista) if(len(lista)%2==0): return (lista[int(len(lista)/2)]+lista[int((len(lista)/2)+1)])/2 else: return lista[int((len(lista)+1)/2)] def moda (lista): li...
05da4dd28a64b06ea3c827850c6c8c9816972561
AshTiwari/Standard-DSA-Topics-with-Python
/Matrix/Search_Element_in_a_Sorted_Matrix.py
581
4.09375
4
# Search an element in a matrix which is sorted by rows. from binarySearch import lessThanEqualBinarySearch def binarySearch(matrix, m, n, element): i = j = 0 row_begs = [matrix[i][0] for i in range(m)] row_no = lessThanEqualBinarySearch(row_begs, element) if row_no != -1: for i in range(0,n): if matrix[row_...
f3fe2d5990ab69a0bc4548d15f66676ecef0a339
Abhay-official/Summer-Training
/Day06/Day6D.py
163
3.765625
4
x=[2,3,4,5] y=[-1,2,-2,1] z=[10,20,15,30,25,67] print("x:",x) print("y:",y) print("z:",z) res=[] for i,j,k in zip(x,y,z): res.append(i+j+k) print("res:",res)
70ffc495e659c54d8f43109b8310b3686c05171e
8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions
/Chapter10/0004_validate_us_social_security_number.py
436
3.96875
4
""" Program 10.3 Validate U.S.-based Social Security Number """ import re def main(): pattern = re.compile(r"\b\d{3}-?\d{2}-?\d{4}\b") match_object = pattern.search("Social Security Number" "For James is 916-30-2017") if match_object: print(f"Extracted Social Secu...
243c5ce189d452fe3e82b7ba77b9f1a719cc79ec
buraaksenturk/GlobalAIHubPythonHomework
/1_day/1_homework.py
666
4.15625
4
# Getting data from the user nameandsurname = str(input('What is your name and surname :')) age = int(input('How old are you :')) height = float(input('What is your height :')) study = bool(input('Are you study (True/False) :')) letter = list(input('What are your favorite letters :')) # Printing data types pri...
40ff6a91f38bea6d97fc1ed955c5308849dbfd9f
DmitryZiganurov/hse
/Test_I-3.py
1,800
3.78125
4
import matplotlib.pyplot as plt import numpy as np from collections import namedtuple #Графики левой и правой части уравнения и производной разности этих функций x = np.arange(0.6,0.7,0.001) plt.grid() plt.plot(x,np.cos(x)) plt.plot(x,np.sqrt(x)) #Корень уравнения приблизительно 0.642 #plt.plot(x,-np.sin(x)-...
3e0ee3cc9b14a4c1c4138fa5b180dd7aad2202b5
missuzundiz/GlobalAIHubPythonCourse
/Homeworks/HW1.py
306
3.78125
4
liste=["elma","armut","kalem","kitap"] liste1=liste[0:2] liste2=liste[2:5] print(liste2+liste1) sayi=int(input("Tek basamaklı bir tamsayı giriniz:")) try: if sayi>=0: print("Çift Sayılar:") for i in range (sayi): if i%2==0: print(i) except: print("Sayı Giriniz:")
fe41ef7e6948c8d6528ea2ba0350a32047020169
meghasundriyal/Python-Tutorials
/strings.py
598
4.25
4
#performing different string operations a = "Sample! String " #single line string b = '''This is an example of multiline string ''' #double quotes can also be used print(a) print(b) #strings are treated as array of byte characters in python print("a[1] : " ,a[1]) print("a[2:7] ...
5157e700f99bc0f49e35b4fc11f43e2c41f5ed88
chrisidakwo/Intro-to-Python
/Week 2 - Control Statements & Iterations/DaysInAMonth.py
1,037
4.4375
4
"""Display the number of days for a given month in a given year. RULE: Should be displayed as such: 'March 2005 has 31 days' """ import datetime def isleapyear(year): """ Returns True if the argument year is a leap year, else returns False""" leap_status = ((year % 100 != 0) if (year % 4 == 0) else (year % ...
ba97f6bc69874d143605a6109a204f13ae450796
sudarshannkarki/sda-project
/Ecommerce-site1/check.py
56
3.703125
4
# Display Hello! 3 times p = 3 q = 'Hello! ' print(q*p)
b774b3ed48516875dcf9bb4e57dcd5c3ca143461
shenbeixinqu/leetcode
/2-哈希表/350-两个数组的交集ii(easy).py
1,332
3.875
4
# 给定两个数组,编写一个函数来计算它们的交集。 # # # 示例 1: # # 输入:nums1 = [1,2,2,1], nums2 = [2,2] # 输出:[2,2] # # 示例 2: # # 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] # 输出:[4,9] # # 说明: # # 输出结果中每个元素出现的次数,应与元素在两个数组中出现次数的最小值一致。 # 我们可以不考虑输出结果的顺序。 # # 进阶: # # 如果给定的数组已经排好序呢?你将如何优化你的算法? # 如果 nums1 的大小比 nums2 小很多,哪种方法更优? # 如果 nums2 的元素存储在...
9378196a1a5edd07762d73c4f160b28d16242d82
max64q/Python_Practice
/Question 9.py
436
4.125
4
#Question 9 #Write a program that accepts sequence of lines as input and prints the lines #after making all characters in the sentence capitalized. #Suppose the following input is supplied to the program: #Hello world #Practice makes perfect #Then, the output should be: #HELLO WORLD #PRACTICE MAKES PERFECT ...
6711056af34bdb97ffda829077a430a6f7060ec2
CleverInsight/predicteasy
/predicteasy/core/nlp/spelling.py
1,074
3.578125
4
import io import pandas as pd from textblob import TextBlob class SpellCheck: def __init__(self, text, multiple=False, column=""): self.data = text self.multiple = multiple self.column = column def spell_apply(self, data): """ spell_apply takes incorrect text and correct the spell and returns it ...
2ab54f3b2b187c48cd164cafe50674d7aa8c93f4
valentinegarikayi/Getting-Started-
/OddorEven2.py
274
4.1875
4
#!/usr/bin/env python num = int(input('Give me the number to check: ')) check =int(input('Give me the number to divide: ')) if num % check ==0: print ('{} divides evenly into,{}'.format(check, num)) else: print ('{} doesnt divide evenly into,{}'.format(check, num))
75d80349388342e0bdd045c7f03e06e41f399e9f
peoolivro/codigos
/Cap2_Exercicios/PEOO_Cap2_ExercicioProposto07.py
537
3.921875
4
# Livro...: Introdução a Python com Aplicações de Sistemas Operacionais # Capítulo: 02 # Questão.: Exercício Proposto 7 # Autor...: Fábio Procópio # Data....: 18/02/2019 sal_base = 1500 comissao = 200 corretor = input("Digite o nome do corretor: ") qtd_vendas = int(input("Informe a quantidade de imóveis vendido...
600a67ec6403f2d942e835a8ca4eded853d3e229
cpeixin/leetcode-bbbbrent
/binary_search/search-in-rotated-sorted-array.py
1,337
3.78125
4
# coding: utf-8 # Author:Brent # Date :2020/7/6 1:06 PM # Tool :PyCharm # Describe :假设按照升序排序的数组在预先未知的某个点上进行了旋转。 # # ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 # # 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 # # 你可以假设数组中不存在重复的元素。 # # 你的算法时间复杂度必须是 O(log n) 级别。 # # 示例 1: # # 输入: nums = [4,5,6,7,0,1,2], target = 0 # 输出:...
1f8d4fb268cf11f32bb6795c7dc3d62fe231c031
antonioramos1/dataquest-data-analyst
/1-1-python-programming-beginner/challenge_--files,-loops,-and-conditional-logic-157.py
1,053
3.90625
4
## 3. Read the File Into a String ## filenames = open('dq_unisex_names.csv', 'r') names = filenames.read() ## 4. Convert the String to a List ## f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split('\n') first_five = names_list[:5] print(first_five) ## 5. Convert the List of Strings to a L...
056d758613051ac32c759837751124ff2e8fbc5e
SabiqulHassan13/try-web-scrapping-with-python
/web_scrapping_intellipaat/web_scrp.py
954
3.640625
4
# web scrapping intellipaat # import the libraries to query a website import requests from bs4 import BeautifulSoup import pandas as pd # specify the url web_link = "https://en.wikipedia.org/wiki/List_of_Asian_countries_by_area" link = requests.get(web_link) #print(link) soup = BeautifulSoup(link.content, 'html.par...
0dfb2ae2e43541d65aa0647f7ab59538cc5c4d33
mexicoraver83/cursopythonkmmx
/while_loop.py
122
3.90625
4
#! /usr/bin/python # -*- encoding: utf-8 -*- year = 2001 while year <= 2012: print "The year is: ", str(year) year += 1
d697da3cb1e867d846d338e404ee3bbcea870a70
yangyu2010/leetcode
/二叉树/236二叉树的最近公共祖先.py
1,516
3.5
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Yu Yang from TreeNode import TreeNode from TreeNode import preOrderTraverse from TreeNode import inOrderTraverse from TreeNode import postOrderTraverse class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNo...
e90a8f9476a4ee22ee9dfef2a3378f7856eaf2d2
Aasthaengg/IBMdataset
/Python_codes/p02880/s554734044.py
186
3.671875
4
N = int(input()) product = [] for i in range(1,10): for j in range(1,10): product.append(i * j) if N in product: result = 'Yes' else: result = 'No' print(result)
0e10c4407534e8943e57ba05a44fa6bc0df6e7dc
NataliiaBidak/py-training-hw
/Homework6/Task6.py
1,438
3.796875
4
""" Provided a text file with information about artists and songs: Joy Division - Love Will Tear Us Apart Joy Division - New Dawn Fades Pixies - Where Is My Mind Pixies - Hey Genesis - Mama """ from collections import defaultdict class Artist: def __init__(self, artist_name, songs): self.artist_name = art...
404a13fb0defb805471a150d9c6cc0ed2e311c10
ghostlyman/python_demos
/syntax/function/imooc_mh_20180126/demo_04.py
630
3.828125
4
# -*- coding:utf-8 -*- def my_sum(*args): return sum(args) def my_average(*args): return sum(args) / len(args) def dec(func): def in_dec(*args): # 参数预处理 print('in dec args =', args) if len(args) == 0: return 0 for val in args: if not isinstance(va...
5d9f2bd7d72dbc86307858e565ad994e65a29fd0
PaulineRoca/AIP2016
/Info-2/GUI/converter.py
1,291
3.84375
4
# /usr/bin/env python # Time-stamp: <2016-09-18 08:34:47 cp983411> # code adapted from http://www.tkdocs.com/tutorial/firstexample.html # import Tkinter import ttk def calculate(*args): try: value = float(feet.get()) meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0) except ValueError: ...
1b083db112cfc38a12c3de2aa3da72af47a5d79a
leonardolginfo/ExerciciosDEVPROPythonBrasil
/venv/EstruturaSequencial/exercicio11-int-float-calculos.py
652
4.34375
4
''' Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: o produto do dobro do primeiro com metade do segundo . a soma do triplo do primeiro com o terceiro. o terceiro elevado ao cubo. ''' num_1 = int(input('Digite o primeiro número: ')) num_2 = int(input('Digite o segundo número: ')) num...
125a682465cf5e7ce32e6d7ede5e5228edeeb50d
LeeJaeng/study
/python/basic/4_calupper.py
410
3.59375
4
def cal_upper(price): increment = price * 0.3 upper_price = price + increment return upper_price def cal_upper_lower(price): offset = price * 0.3 upper_price = price + offset; lower_price = price - offset; return upper_price, lower_price def main(): print(cal_upper(50000)) result...
2e87553b4b62596be4807ea68bdf86a6a4309b3c
padamowiczUWM/wd
/cw4.py
7,587
3.640625
4
# Zad. 1 # Wygeneruj liczby podzielne przez 4 i zapisz je do pliku. lista = [i for i in range(4, 100, 4)] with open("dane.txt", "w") as file: file.writelines(str(l) + '\n' for l in lista) # Zad. 2 # Odczytaj plik z poprzedniego zadania i wyświetl jego zawartość w konsoli. with open("dane.txt", "r") as f...
d985f7cfe12bca34653390725e6123f16b604fdd
ishakapoor4218/sample_python
/first.py
271
4.34375
4
print('Isha Kapoor') #this command is used to print anything print('Welcome to Python') print('Happy Sunday') num1 = 10 num2 = 20 num3 = (num1+num2)/2 total = 0 print(num3) total = 0 for x in range(1,6): print(x) t1 = total + x total = t1 avg = total/x print(avg)
d76c871a2ba6d481938abbc1078d7d3bf02a9347
whikwon/python-patterns
/behavioral/visitor.py
869
3.953125
4
from abc import ABC, abstractmethod class Salesman(ABC): pass class Door2DoorSalesman(Salesman): def visit_premium_customer(self): print("Hello sir, we have prepared a new product for you.") def visit_normal_customer(self): print("Hi, new product has been released. Would you take a look...
12338665dd5035e8afca2befb6ec3f0aef151304
jemtca/CodingBat
/Python/Warmup-1/not_string.py
342
4.40625
4
# this function return a new string where "not" is added to the front # if the string already begin with "not", the function return the string unchanged def not_string(str): s = "" if not str.startswith("not"): s = "not " + str else: s = str return s print(not_string("candy")) print(not_string("x")) print(n...
7385f3f9411492534b27caee2e54e699315fa10a
Wang-Yann/LeetCodeMe
/python/_1001_1500/1497_check-if-array-pairs-are-divisible-by-k.py
2,543
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Rock Wayne # @Created : 2020-07-10 18:59:15 # @Last Modified : 2020-07-10 18:59:15 # @Mail : lostlorder@gmail.com # @Version : alpha-1.0 """ # 给你一个整数数组 arr 和一个整数 k ,其中数组长度是偶数,值为 n 。 # # 现在需要把数组恰好分成 n / 2 对,以使每对数字的和都能够被 k 整除。 # ...
16c04687853a3ec86a89668d60947f87dd4bdb67
arrtych/python-algorithms
/s03.py
327
3.6875
4
# -*- coding: utf-8 -*- s = input("Введите строку: ") search = input("Введите искомый символ: ") count = 0 id = 1; while id != -1: id = s.find(search) if id >= 0: count += 1 s = s[id+1:] print ("символ(ы): " + search + " найден " + str(count) + " раз(а)")
b227d42585250ee3d85a9d415309f9b96e22c0bc
curiousTauseef/codility-python
/Lesson 03 - Time Complexity/PermMissingElem_2.py
279
3.578125
4
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 N = len(A)+1 missing = N for i in range(1, N): missing ^= A[i-1] missing ^= i return missing
a48092ca076b971fd209205613b3d258cefa22e5
LubbyAnneLiu/python_code
/python_NQueen4algorithm.py
1,205
3.734375
4
''' 201721198590 信息科学学院 刘璐 python 回溯法 爬楼梯问题 某楼梯有n层台阶,每步只能走1级台阶,或2级台阶。从下向上爬楼梯,有多少种爬法? ''' n = 6 # 楼梯阶数 x = [] # 一个解(长度不固定,1-2数组,表示该步走的台阶数) X = [] # 一组解 # 冲突检测 def conflict(k): global n, x, X # 部分解步的步数之和超过总台阶数 if sum(x[:k + 1]) > n: return True return False # 无冲突 # 回溯法(递归版本) def clim...
c9d9619629abb0fa21f842b22b428da09ae8bbed
GlobalCreativeCommunityFounder/InfiniteList
/InfiniteList/InfiniteList.py
8,460
4.15625
4
""" This file contains code for the data type "InfiniteList". Author: GlobalCreativeCommunityFounder """ # Importing necessary libraries import copy # import sys from mpmath import * mp.pretty = True # Creating InfiniteList class class InfiniteList: """ This class contains attributes of an infinite list...
071e3f75d0441c0786e4ed071eed6de167f39476
abingham/project_euler
/python/src/euler/exercises/ex0033.py
1,940
3.546875
4
"""The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples o...
ed02a18515b4d0ba1f5ad0f8448fc3905e11fed8
ys558/FluentPython
/2.2.4_生成器表达式.py
496
3.859375
4
symbols = '☚☟♫☯☳' # 2.5 生成器表达式tuple,array tuple = tuple(ord(symbol) for symbol in symbols) print(tuple) # (9754, 9759, 9835, 9775, 9779) import array array = array.array('I', (ord(symbol) for symbol in symbols)) print(array) # array('I', [9754, 9759, 9835, 9775, 9779]) colors = ['black', 'white'] sizes = ['S', 'M', '...
3ca0f34e40e3e74d8366f5f9da35a89cea7dfeed
brianeflin/HFPython
/ch02/vowels.py
259
4.4375
4
vowels = ['a', 'e', 'i', 'o', 'u'] vowels_found = [] word = input("Input a word for a vowel search: ") for letter in word: if letter in vowels and letter not in vowels_found: vowels_found.append(letter) for vowel in vowels_found: print(vowel)
ad6da095092f38892c9233aeb2b0f8675edeb8af
Songlynn/myMLLearning
/01LinearRegression/demo.py
1,316
3.984375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression import LinearRegression as lr # 1.数据处理 data = np.loadtxt('linear_regression_data1.txt', delimiter=',') print('Data:') print(data[0:5]) X = np.c_[np.ones(data.shape[0]), data[:, 0]] y = np.c_[data[...
e80853e568d3b11e2fe6ab68fa0a0fff3728e396
goncalossantos/Algorithms
/Challenges/CCI/Chapter 01/rotate_matrix_inplace.py
1,970
3.96875
4
class Rotation(): def rotate(self, i, j): return (j, self.N - i -1) def __init__(self, i, j, N): self.N = N self.get_coordinates_to_rotate(i, j) def get_coordinates_to_rotate(self, i, j): self.top = (i,j) self.right = self.rotate(i,j) self.bottom = self.ro...
a3fad8cbc734f44c42f63bf9a8a0e6045db29d3d
NicholasDowell/DataAnalysis
/DataCleaning.py
5,626
3.9375
4
# -*- coding: utf-8 -*- """ @author: Nicholas Dowell """ import pandas as pd #Part A - Read the file into a pandas dataframe df = pd.read_csv('m1_w2_ds1.csv') #Part B - use Class Labelling on any string '1 5 255' from sklearn.preprocessing import LabelEncoder #The column named 'PUBCHEM_COORDINATE_TYPE' is the only...
d6344c930d8f4d1262ebf8e401838c7c3155aac7
jochigt87/PythonCrashCourse
/Chapter8/8-8.py
826
4.5625
5
#!/usr/bin/env python # -*- coding: utf-8 -*- # User Album: Start with you program from Exercise 8-7. Write a while loop that # allows users to enter an album's artist and title. Once you have that # information, call make_album() with the user's input and print the dictionary # that's created. Be sure to include a qu...
84aeee91c58c3720f3e155714cde999e7ec0a8ec
theWellHopeErr/data-structures-and-algorithms
/1. Algorithmic Toolbox/Week 2 - Algorithmic Warm-up/3gcd.py
180
3.75
4
def gcd(a,b): if a == 0: return b if b == 0: return a a,b = b,a%b return gcd(a,b) if __name__ == "__main__": a,b = map(int,input().split()) print(gcd(a,b))
596deb171e3dc78af8a312611e0afd02604982fc
shants/LeetCodePy
/322.py
604
3.625
4
class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ tbl = [float("inf")]*(amount+1) tbl[0]=0 for i in range(1, amount+1): for j in coins: if i-j >=0 and t...
deffadfaae30fe43cf7200b5dde02f9cc441dc8d
sendurr/spring-grading
/submission - lab5/set1/RYAN W BARRS_9404_assignsubmission_file_lab5.py
228
3.59375
4
#1 def printstar(n): answer = n*"*" return answer print printstar(1), printstar(10), printstar(100) 2 def printstarx(n,rows=1): for i in range(rows): print ''*rows + '*'*n print printstarx(10) print printstarx(10,5)
45138350372cfae854f134ce0d7abc85bb28011a
omranzboon/Python-Course
/Week 1/Practise1-B.py
444
4
4
#!/usr/bin/env python # coding: utf-8 # In[4]: x=float(input("Enter your number ")) if x < -100 : result = -1*x print(result) elif x>=-100 and x<= -25 : result = x**4 print(result) elif x> -25 and x <= 0 : result = 3*(x**2) -1 print(result) elif x>0 and x<= 100...
1ace81ea0bbeecff60d63f3f6b5cbea7fa923df5
zeeshan495/Python_programs
/Algorithm/InsertionSort.py
600
3.765625
4
from Utility import * class InsertionSort: utility = Utility() print("enter the number of words for insertion sort : ") var_input = utility.input_int_data() if (var_input <= 0): print("please check the input : ") else: my_array = [None] * var_input print(" enter values ") ...
82a95867a93267fddfb1b8149f2632feaa4a1746
slowtrain/jython-study
/study/study04.py
439
3.734375
4
#-*- coding: utf-8 -*- from java.util import ArrayList class Lesson(object): def array1(self): arr = ['a','b','c'] arr.append('d') for ar in arr: print ar for number in range(len(arr)): print str(number)+' '+ arr[number] def array2(self): arr = ...
7b0f21c6daadddd2779ead82c07c74eae0978572
emmafine/graphes-eclairage
/Graph_Class.py
7,463
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 17 08:17:20 2020 @author: Asus """ import random class Vertex: def __init__(self, node): self.id = node self.light = 1 self.adjacent = [] def __str__(self): return str(self.id) + ' adjacent: ' + str([x.id for x in s...
0bf814f53e7edba8ec6c1d476c23772fa73c95a5
mattpopovich/TestMergeRepo
/CMPSC443/CTF/countingToFile.py
324
3.96875
4
# This is a python file to write binary values of 0-256 to a file 'count.txt' outfile = 'count.txt' fout = open(outfile, 'w') count = 0; # Loop through infile byte by byte while (count <= 255): # converts count to a 8-bit binary string binary = bin(count)[2:].zfill(8) fout.write(binary) count += ...
cce5df8e589d8a0874071d4ed165e446682e241b
endermeihl/deeplearning.github.io
/leetcode/isPalindrome.py
295
3.859375
4
def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False if x % 10 == 0 and x != 0: return False cur = 0 num = x while int(num) != 0: cur = cur * 10 + int(num) % 10 num /= 10 return cur == x isPalindrome(1,121)
d0e7b726aa7c97ef52e24d72b9146a6ba8f334af
avcopan/fermitools
/fermitools/math/findif.py
1,245
3.640625
4
import numpy import scipy.misc def central_difference(f, x, step=0.01, nder=1, npts=None): """differentiate a function using central differences :param f: the function :type f: typing.Callable :param x: the point at which to evaluate the derivative :type x: float or numpy.ndarrray :param step...
e3a0c6b88eb3ff3a0ead39f7388b4c5e1aca7d39
adepeter/sleekforum
/src/sleekapps/cores/utils/choice.py
985
3.578125
4
from collections import ValuesView from typing import Tuple, List, Dict class Choicify: """This is a utility class which returns tuple of choices calculates length of individual choices for use in CharField """ def __init__(self, choices: Tuple) -> None: self.__choices = sorted(choi...
9f6a663f6d0c00da2d7a78b838d60e8ab731fb10
sadullahmutlu/GAIH_Python_Course
/Homeworks/HW1.py
698
4.46875
4
odd_num = [0,2,4,6,8] even_num = [1,3,5,7,9] print("Odd Numbers: " , odd_num) #burayı tek satırda da aralarına \n koyarak da yazılabilir. print("Even Numbers: " , even_num, "\n") numbers = odd_num + even_num #İki listeyi birleştirdik. print("All Numbers:",numbers, "\n") new_list = [i*2 for i in numbers] #İk...
1a4e8cbacee031cd3ce3750d094ef2553972d0b5
AnshumanSinghh/DSA
/data_structure/queue/queue.py
1,048
4.53125
5
# Queue implementation in Python """ The complexity of enqueue and dequeue operations in a queue using an array is O(1). """ class Queue: def __init__(self): self.queue = [] # Add an element def enqueue(self, item): self.queue.append(item) # Remove an element def dequeue(sel...
2e9879692636e97c36e9b1ed536b218228cf8d62
SamIlic/AAT
/Algorithmic Trading/Bayesian Statistics/beta_binomial_MCMC.py
3,300
3.71875
4
# RUN TIME - ~ 2 min import matplotlib.pyplot as plt import numpy as np import pymc3 import scipy.stats as stats plt.style.use("ggplot") ### Specify & Sample Model # Set prior parameters # Parameter values for prior and analytic posterior n = 50 # number of coin flips z = 10 # number of observed heads alpha = 12 ...
d7269f0c1aaffa5129c3f5e18c4a3bba51d65620
drforse/snake
/game/types/food.py
908
3.84375
4
import turtle import random class Food(turtle.Turtle): def __init__(self, game, x: int = None, y: int = None, visible: bool = True, **kwargs): """ Food for the Snake :param x: x-coord where to appear, if None, it's chosen randomly :param y: y-coord where to appear, if None, it's ch...
02592aa520f5d50012b4e643a77ac89fb59f5109
daniel-reich/turbo-robot
/iuenzEsAejQ4ZPqzJ_19.py
656
4.0625
4
""" This is a **reverse coding challenge**. Normally you're given explicit directions with how to create a function. Here, you must generate your own function to satisfy the relationship between the inputs and outputs. Your task is to create a function that, when fed the inputs below, produce the sample outputs sho...
96cf21691b4f95085bf70e04bee5a350fce189c5
pennmem/ptsa_plot
/ptsa_plot/coords.py
1,409
4.09375
4
"""Coordinate system conversion utilities.""" import numpy as np def deg2rad(degrees): """Convert degrees to radians.""" return degrees / 180. * np.pi def rad2deg(radians): """Convert radians to degrees.""" return radians / np.pi * 180. def pol2cart(theta, radius, z=None, radians=True): """Co...
b07f1458f07d286d8bdb807d0af870c832367dfa
venkatsvpr/Problems_Solved
/LC_Capacity_to_ship_packages_within_d_days.py
2,143
4.375
4
""" 1011. Capacity To Ship Packages Within D Days A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load ...
4c86a9dc55134b7daae36bedcefc72dbfcfb3c1b
AlisonMcGuinness/UCDExercises
/mod5_3indexes.py
7,833
4.3125
4
import pandas as pd file = "C:\\Users\\Admin\\Documents\\UCD_Data\\temp.csv" temperatures = pd.read_csv(file, sep=",", parse_dates=['date']) temperatures['avg_temp_c'] = temperatures['temperature'] # Look at temperatures print(temperatures.info()) # Index temperatures by city temperatures_ind = temperatures.set_inde...
337e4ff8767b921cfbc8e96d45c40aadd76dde1e
igortereshchenko/amis_python
/km73/Savchuk_Ivan/3/task10.py
493
3.734375
4
x = int(input('please enter init coordinate x:',)) y = int(input('please enter init coordinate y:',)) x1 = int(input('please enter coordinate x1:',)) y1 = int(input('please enter coordinate y1:',)) d1 = abs(x/y) d2 = abs(x1/y1) d3 = abs(y+y1) d4 = abs(x+x1) if (x == x1) & (1 <= y <= 8) & (1 <= y1 <= 8): pr...
ea8dfb12fe58963c09f3c66d8cb691e12522e2ca
kiettran95/Wallbreakers_Summer2019
/week4/python/ReverseLinkedList_206.py
987
4.0625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: # 1st approach: recursion # root = [head] # def recurse_reverse(node: ListNode) -...
7f94413223fdca646f2481557083a675d8438b1c
denisAronson/morning_star
/utilites/gui_test.py
887
4.03125
4
#импортируем модуль для создания GUI from tkinter import * #создаем окно, задаем его размер и заголовок window = Tk() window.geometry('800x500') window.title("Мое перове GUI на питоне") #функционал кнопки def clicked(): lbl.configure(text='Зачем нажал') #добавляем текст, задем локацию lbl = Label(window, text="H...
c4c110e70287e360a6173f4d2842d81afe60c6df
v-franco/Facebook-ABCS
/strings & arrays/arrays_DS.py
451
3.90625
4
import math import os import random import re import sys # # Complete the 'reverseArray' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY a as parameter. # def reverseArray(a): # Write your code here return a[::-1] if __name__ == '__main__': ...
378d51fa1e9d5afdfe7c55c33d3887d6858ea344
nicoprocessor/Digital-Art-Collection
/Processing sketches/Line Stitching/cardioid_mesh/cardioid_mesh.pyde
1,023
3.703125
4
import math lines = 300 line_skip = 1 radius_x, radius_y = 900, 900 def frange(start, stop, step): while start < stop: yield start start += step def setup(): size(1200, 1200) background(51) ellipseMode(RADIUS) stroke(255) noFill() strokeWeight(1) # center the coordinat...
54917c736c892fa54304c8e32be483a174e8209b
willgood1986/myweb
/pydir/callable.py
645
4.21875
4
# -*- coding: utf-8 -*- class TestCall(object): ''' Use callable to test if a function is callable override __call__ to make a class callable ''' def __init__(self, name): self._name = name def __call__(self): print('My name is {name}'.format(name = self._name)) def __str_...
b98693c35d17c4d4f0f4f6be9323e824e25d1258
evelyn-pardo/segundo_parcial
/menu.py
1,062
3.859375
4
class Menu: def __init__(self,titulo,opciones=[]): self.titulo=titulo self.opciones=opciones def menu(self): print(self.titulo) for opcion in self.opciones: print(opcion) opcion=input("Elija opcion[1...{}]:".format(len(self.opciones))) menu1=Menu("...
323c30c40df31402b5bd8d72379a78d653e5c3a2
mikeckennedy/DevWeek2015
/python_demos/shopping.py
573
3.8125
4
class CartItem: def __init__(self, name, price): self.name = name self.price = price class Cart: def __init__(self): self.items = [] def add(self, item): self.items.append(item) def __iter__(self): return self.items.__iter__() def main(): cart = Cart() ...
e0f3f71e743669ba318ac8101bf3ce5872dd3783
h-mayorquin/text_to_image
/test_fonts.py
2,216
3.71875
4
""" This script produces the whole alphabet (and all the other symbols for a given font) for a given corpus. This serves as test for all the font parameters and the font itself. """ from PIL import ImageDraw from PIL import Image, ImageFont import numpy as np import matplotlib.pyplot as plt from random import sample #...
10fd0046689ab52ed47b6e6a3e171266c1962f76
DoAnhTuan98/doanhtuan-fundamental-c4e
/session3/list_intro.py
199
3.546875
4
# items = [] # empty list (rong) # print(items) # print(type(items)) items = ["bun dau","bun bo","bun rieu"] print(items[1]) items[1] = "bun bo nam bo" # thay doi bien print(items[1]) print(items)
1c6df9b7bd12317b23acf107c05cc505df78b1e9
vijaykumarrpai/mca-code
/3rd Sem/Python/Programs/day2-functions/displayNo.py
180
4.15625
4
# # WAP to read a number and display its value inside the function def value(): num = int(input("Enter the number : ")) return num print("The entered value is :", value())
229b042ca75f8c26a446adb6a4fa2dd74903005b
RushToNeverLand/DataMining-MachineLearning-LanMan
/L02-PythonBasic/code/rawinput.py
403
3.625
4
#!/opt/anaconda2/bin/python # -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('GBK') # 在当前笔记本电脑上 # sys.setdefaultencoding('utf-8') age = int(raw_input(u"请输入你的年龄: ")) if age >= 18: print u"你是个adult." elif age >= 12: # 可以有多个elif语句 print "You are a teenager." else: print...
4477299218318057350c7c317887103137ebf2d8
RoshanADK/Tensorflow-Learn-and-Code
/TFImageTranspose.py
976
3.75
4
# Lets make an use of matplotlib to Load Image using imread function import matplotlib.image as mp_image import matplotlib.pyplot as plt import tensorflow as tf # Lets read using imread() function filename = "TensorImage.jpg" # Take one image from the same directory or give relative path to an image ...
ecaed1679031dfef618084865187106973e68568
Aka-Ikenga/Daily-Coding-Problems
/merge_colors.py
1,324
4.03125
4
"""This problem was asked by Facebook. On a mysterious island there are creatures known as Quxes which come in three colors: red, green, and blue. One power of the Qux is that if two of them are standing next to each other, they can transform into a single creature of the third color. Given N Quxes standing in a line...
62e3fd42d51658190b0bc959184e1ea6a04a6f4b
danevputra/Python-ai-code
/hillclimbing.py
1,576
3.578125
4
# You can extend this code to implement: # Stochastic Hill climbing # Random-restart Hill-climbing import math fabs=math.fabs sin=math.sin cos=math.cos exp=math.exp pi=math.pi #scalar multiple for grad-ascent scalar=0.005 # I am doing gradient ascent here, since I want to maximize the function def grad_ascent(x):...
ee5c78045357d5d035e9561d2ebc0b9de254e0af
TangJiahui/cs107_system_devlopment
/pair_programming/PP9/fibo.py
1,055
3.734375
4
#group members: Gabin Ryu, Jiahui Tang, Qinyi Chen import reprlib class Fibonacci: def __init__(self, n): self.n = n def __iter__(self): return FibonacciIterator(self.n) def __repr__(self): return 'Fibonacci(%s)' % reprlib.repr(self.n) class FibonacciIterator: def __...
2665d438cbd264c04fb32ea7fc8100cf520abda9
falaybeg/BigData-MachineLearning-Notes
/Statistics-Notes/07-Regression/01-Linear Regression/01-Linear Regression.py
1,847
4.34375
4
''' Linear Regression ''' import pandas as pd import matplotlib.pyplot as plt import numpy as np # Load dataset df = pd.read_csv("linear_regression_dataset.csv") # Dataset is visualized by using Scatter Plot plt.scatter(df["Experience"], df["Salary"]) plt.title("Scatter Plot graphics for Experience and Salary", font...
1ed29f3c223416ecff54ccd119d79db8d7473a75
aalmsaodi/Algorithms
/after-session-3.py
2,444
3.546875
4
#BST: Implement Power Function ********************************* class Solution: # @param x : integer # @param n : integer # @param d : integer # @return an integer def pow(self, x, n, d): if n == 0: return 1 % d ans = 1 base = x while n > 0...
96a5b6e822ebe3d46bebbce0e3559b4697643298
dtekluva/class9_code
/Python-class-codes-master/beesolah.py
411
4
4
file = open('docword.txt','r') text = file.read() text = (text.split('\n')) #convert each newline into a list (split by newline \n) for line in text: splitted_line = line.split(' ') #convert each of the splited valeus into list of three numbers (split by spaces) single_value = splitted_line[1] single_v...
bd7acbecff8cb21655a61100fee24e3d71307c87
chhavimittal123/Hangman-Game
/main.py
1,030
3.953125
4
from replit import clear import random from hangman_words import word_list chosen_word = random.choice(word_list) word_length = len(chosen_word) end_of_game = False lives = 11 from hangman_art import logo, stages print(logo) display = [] for _ in range(word_length): display += "_" while not end_of_game: guess =...
d56699e55bc4f29e4383b426d2fe2458e1c1ba29
Pavel-Kuchmenko/FirstRepository
/HW2.1/HW2.1.py
6,353
3.84375
4
print("\"Homework #3\"\n05.06.2021\ ") print("-------------------------- START -----------------------------") integer1 = 300 integer2 = 55 float1 = 311.24 float2 = 575.59 result = 0 #-------------------------------------------------- ** --------------------------------------------------------- print("-----...
c77cbde04a5077ca91be7f0569c64630393e4855
Unkovskyi/PyBase08
/hw_3_1.py
1,659
3.9375
4
# Task_3_1 import string from string import whitespace, punctuation print('whitespace = {}'.format(repr(whitespace))) print('punctuation = {}'.format(repr(punctuation))) print('---------------------------------------------') def dict_(inp): # функция которая считает слова в веденной строке inp = inp...
7aade650f272934575a5351a6817d86caa197b6a
Antpoizen/Python-Programs
/Base conversions and decryption.py
6,766
4.40625
4
# ▄▄▄ ███▄ █ ▄▄▄█████▓ ██▓███ ▒█████ ██▓ ██████ ▓█████ ███▄ █ #▒████▄ ██ ▀█ █ ▓ ██▒ ▓▒▓██░ ██▒▒██▒ ██▒▓██▒▒██ ▒ ▓█ ▀ ██ ▀█ █ #▒██ ▀█▄ ▓██ ▀█ ██▒▒ ▓██░ ▒░▓██░ ██▓▒▒██░ ██▒▒██▒░ ▓██▄ ▒███ ▓██ ▀█ ██▒ #░██▄▄▄▄██ ▓██▒ ▐▌██▒░ ▓██▓ ░ ▒██▄█▓▒ ▒▒██ ██░░██░ ▒ ██▒▒▓█ ▄ ▓██▒ ...
6dcc01807ce1fe9e161edbce40b7d01c5f34789a
McKenzieGary/LearningPython
/Business & Finance/ChaseBankCSVAnalysis.py
763
3.6875
4
#when I run the script I'd like to export a CSV of all transactions from the month. #Date range: (complete) #Sum of outgoing: (complete) #Sum of incoming: (complete) #Net for the time period: (complete) #Total Balance: (complete) #present it somewhere. import pandas as pd df = pd.read_csv('Enter CSV Path Here') St...
ead272526a56d7f6c9e1db1ef750438d18506a05
aidataguy/python_learn
/lambda.py
372
3.75
4
#! /usr/bin/python3 # lambda arguments: expression cube = lambda x: x * 3 print(cube(9)) # filtering using lambda my_list = [10, 21, 44, 54, 72, 22, 30, 50] new_list = list(filter(lambda x: (x%2 == 0 ), my_list)) print(new_list) # map using lambda list_map = [10, 21, 44, 54, 72, 22, 30, 50] mapped_list = lis...
5c43871d33a0b6d5de424adc02b2e8f8e9914f41
lafetamarcelo/CoRoTContributions
/utils/visual.py
14,439
3.71875
4
""" This module simplifies the usage of the bokeh library by reducing the amount of code to plot some figures. For example, without this library, to plot a simple line with the bokeh library, one must do something like:: from bokeh.palettes import Magma from bokeh.layouts import column from bokeh....
8f6f1c0d061286714082808561826191e60c5e1b
ramankarki/learning-python
/computer_scientist/list_algorithms/quick_sort.py
659
3.90625
4
def quick_sort(array): if len(array) <= 1: return array else: pivot = array.pop() highest = [] lowest = [] for i in array: if i < pivot: lowest.append(i) else: highest.append(i) return quick_sort(lowest) + [pivot] + quick_sort(highest...
394878cb9f863fdfa16d2e49e4fef80c67a4a038
IanMadlenya/BYUclasses
/CS_598R/Week1/lagrange_4square.py
659
3.59375
4
from math import sqrt, pow import sys def n_4_squares(nn): """ Determine the number of ways the number n can be created as the sum of 4 squares. """ how_many = 0 n = nn for a in xrange(0, int(sqrt(n)) + 1): for b in xrange(0, min(a, int(sqrt(n - pow(a, 2)))) + 1): for c...
8ef74e48bbafe733aeedb7a2f69c1e4e8bc58edb
WilliamReynolds/exercism_python
/two-fer/two_fer.py
202
3.8125
4
import sys name = raw_input("What is your name?") def two_fer(name): if name: print("One for " + name + ", one for me.") else: print("One for you, one for me.") two_fer(name)