blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8412fc54c3a6e4bba5290a15761faae55f025565 | Jamshid93/TaskBook | /PythonNew/list.py | 1,304 | 3.890625 | 4 | # Pythonda "list" degan ma'lumot turi mavjud ko'pchilik buni "MASSIV" deb xam yuritadi
# "list" lar xam raqamlardan ya'ni 1,2,3,4,5,...... va xam so'zlarni qabul qiladi
# listlar bilan bir qancha funksiyalarni amalga oshirishimiz mumkin
# listlar xar doim "[]" shu kabi qavs ichiga yoziladi
# listlarning bir qancha met... |
868fdd66bd8d61d20fe2418df564835daf4f254d | Wonji1/coding-test | /programmers/programmers_lv2/tuple.py | 345 | 3.78125 | 4 | s = "{{2},{2,1},{2,1,3},{2,1,3,4}}"
def solution(s):
answer = []
a = s[2:-2].replace('},{', '-').split('-')
a.sort(key = len)
for i in range(len(a)):
b = a[i].split(',')
for j in range(len(b)):
if int(b[j]) not in answer:
answer.append(int(b[j]))
return a... |
68018993a7bf763fc421d2e68860ca7857ab6179 | ankiwoong/Algorithm_learning_with_data_structure | /Chap01/print_stars2.py | 321 | 3.59375 | 4 | # * 를 n 개 출력하되 w개마다 줄바꿈하기 1
print("*를 출력합니다.")
n = int(input("몇 개를 출력할까요?: "))
w = int(input("몇 개마다 줄바꿈할까요?: "))
for i in range(n // w): # n // w번 반복
print("*" * w)
rest = n % w
if rest: # if 문 판단 1번
print("*" * rest)
|
ddbcc55f4473332a00deb3c21ceb69e8e1f5a1fb | cnbjljf/just_fun | /ATM/shop/shopping_cart.py | 3,265 | 3.640625 | 4 | #!/usr/bin/env python
import collections
import re
import pickle
import sys
import os
path=os.path.dirname(os.path.dirname(__file__))
sys.path.append(path)
from login.account_caozuo import account_opration
ac=account_opration()
#定义一个商品列表
goods_list={'house':3000000,'car':150000,'lumia950xl':4500,'sufface':9200,'shirt... |
4151edd0fa9afa17ad11c2632b6c066f2c70fff6 | bissessk/COVID-19-Predictions-using-SIRD-dynamics-and-Machine-Learning | /CovidData.py | 6,379 | 3.625 | 4 | import pandas as pd;
import numpy as np;
class CovidData:
'''
The CovidData Class creates objects that allow the user to retreive specific information from the daily updated COVID19 time series data made available from John Hopkins University
'''
def __init__(self):
'''
Constr... |
669b0b516e36d8d7176827610d51911b3f0cd37a | safakhan413/interview-faangs | /ELPI/Linked Lists/linked_list.py | 1,540 | 4.0625 | 4 | """ Python program to reverse sublist """
# Linked List Node
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
# Create & Handle List operations
class LinkedList:
def __init__(self):
self.head = None
# Method to display the list
def printList(self):
... |
db0e972e3248d3a998ff6fff6b3b9007310137ec | Varunram/AlgoStuff | /dp/count_till_number.py | 261 | 3.65625 | 4 | def counter(arr, n):
count = [0 for i in range(n+1)]
count[0] = 1
for i in range(1,n+1,1):
for j in arr:
if i>=j:
count[i] += count[i-j]
print count
print count[n]
arr = [1,5,6]
n = 7
counter(arr,n)
|
57658f27b9e7dc84b73a372ed4bba0ba76c25e58 | Shinkovatel/python_lesson | /lesson 3/lesson 3.py | 897 | 3.828125 | 4 | # вывод одного слова
print('hello')
# вывод нескольких слов
print('hello, World')
# любой набор символов
print('wdskbakdb $ gdfnd')
# выводим целое число
print(100)
# выводим число с плавающей точкой
print(90.45)
# выводим истину
print(True)
# выводим ложь
print(False)
# выводим None
print(None)
# Как в... |
889fc1352dfd3d02a3de8d074f7c716f16c3c90d | l-damyanov/Python-Advanced---January-2021 | /exam_preparation/list_pureness.py | 728 | 3.53125 | 4 | def best_list_pureness(*args):
numbers = args[0]
counter = args[1]
values = []
value = 0
for i in range(len(numbers)):
value += numbers[i] * i
values.append(value)
for _ in range(counter):
numbers.insert(0, numbers[-1])
numbers.pop()
value = 0
for i in... |
5bb1b0a6dc25261a4e3f1e3920dd420f8868886d | muchanem/python-1 | /multi | 369 | 3.859375 | 4 | #!/usr/bin/env python3
import colors as c
import sys
print(c.clear + c.red + 'Multiplication Table' + c.reset)
if len(sys.argv) < 2:
number = input(c.orange + 'PLease Enter a Number: ' + c.reset )
else:
number = sys.argv[1]
for count in range(12,0,-2):
print(c.yellow, count, c.green, 'x', c.blue + numb... |
e530e5f2a029f35483b46617b836613383d3c740 | CarolynMillMoo/PANDS | /Week04-flow/lab4.1.grade.py | 516 | 4 | 4 | #This program reads in a students percentage
#and prints out the corresponding grade
#Author: Carolyn Moorhouse
percentage = float(input("Enter the percentage: "))
if percentage < 0 or percentage > 100:
print("Please enter a number between 0 and 100")
elif percentage < 39.5:
print ("Fail")
elif percentage <... |
6a9573d123ee3c2eab2c86427659496281d46515 | satyam93sinha/PythonBasics | /PythonGitPrograms/5-Inheritance, Multiple Inheritance.py | 426 | 3.84375 | 4 | class Base1:
a, b = 5, 9
print('Base1, a:{}, b:{}'.format(a, b))
class Base2:
#print("Base2.mro:{}".format(Base2.mro()))
a, c = 2, 3
print("Base2, a:{}, c:{}".format(a, c))
class Child1(Base2):
d, e = 1, 'go'
print("Child1, d:{}, e:{}".format(d, e))
class Child2(Child1, Base2, Base1):
pr... |
4f542bbb6b5aecce9e8c20fa121deed6b93ab7c7 | tranqui/monte_carlo | /montecarlo.py | 7,587 | 4.125 | 4 | #!/usr/bin/env python3
"""Monte Carlo simulation of hard spheres.
This is an example completed implementation of the Metropolis-Hastings algorithm for teaching.
This code is not intended to be given to students until after they have attempted writing their own
versions.
authors: Joshua F. Robinson <joshua.robinson@br... |
26628e3645e92d2167c98952b3b960e9b8e95162 | pawelstaporek/kurs_python | /02_kolekcje/wyr_list_zad1.py | 392 | 3.796875 | 4 | """
stwórz tabliczkę mnożenia - listę list
dla liczb od 1 do 10
zrób to przy pomocy pętli
powtórz przy pomocy wyrazenia listowego
"""
tabliczka = []
for i in range(1,11):
row = []
for j in range(1,11):
row.append(i * j)
tabliczka.append(row)
print (tabliczka)
tablica = [[i*j for j in range(1,11)]... |
4976723934665a9ec4f0a545a454f7d78c1d7352 | weiyuyan/LeetCode | /每日一题/April/23. 合并K个排序链表.py | 2,639 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:ShidongDu time:2020/4/26
'''
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
'''
from typing import List
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
... |
c38cb6f204f5a4861ac4a5bc6be50f6465dec918 | SJHBXShub/Are-you-happy | /code/learn.py | 203 | 3.5625 | 4 | import numpy as np
import pandas as pd
a = [0] * 3
b = [1] * 5
c = []
c.append(a)
c.append(a)
df4 = pd.DataFrame({'col1':[1,3],'col2':[2,4]},index=['a','b'])
s = 'a'
print(np.sum(b))
#print(b.mean(1))
|
55e5b8b68cd33c2a99d6ba6fc35fa9a063e0b4e4 | MarkCBell/bigger | /bigger/load/ladder.py | 3,281 | 3.78125 | 4 | """ Example ladder surfaces. """
from __future__ import annotations
from typing import Tuple, Iterable
import bigger
from bigger.types import FlatTriangle
from bigger.triangulation import Triangle
from .utils import integers, extract_curve_and_test
Edge = Tuple[int, int]
def ladder() -> bigger.MCG[Edge]:
"""T... |
fe4a3d616363b910218db8e13a0c4c6d4d53fbc8 | vaishnavimecit/StudentRepository_SSW810 | /HW11_StudentRepository.py | 12,629 | 3.71875 | 4 | """ Name: Vaishnavi Gopalakrishnan
CWID: 10444180
Assignment: 11 """
from collections import defaultdict
import os
import sqlite3
from prettytable import PrettyTable
from typing import Tuple, Iterator, List, Dict
from HW08_StudentRepository_Vaishnavi_Gopalakrishnan import file_reader
class Student:
"""
... |
0cce60490ec5ed4063ab40defae82131c8fa6b92 | tgwings8/PG-TM | /TM secret word.py | 1,088 | 3.796875 | 4 | import random
words = ["cat","dog","skate","Lacrosse","Hockey"]
hint1 = ["Puck","Ice","Ball","bark","meow"]
hint2 = ["paw","whiskers","fast","cold","grass"]
number = random.randint(0,4)
secretword = words[number]
guess = ""
counter = 0
while True:
print("Guess the secret word!")
print("Type 'hint1... |
821ca7c555be769e9f8b47509e54010f174fe436 | HenriBranken/Advent_of_Code_2017_python_3 | /day_12/day_12_a.py | 2,480 | 3.546875 | 4 | # .-------------------------------------------------------------------------------------.
# | Puzzle Author: Eric Wastl; http://was.tl/ |
# | Python 3 Solution Author: Henri Branken |
# | GitHub Repository: https://github.com/HenriBra... |
dfa8c6c55adb576b4ed98be846a14cc1b8536729 | green-fox-academy/FKinga92 | /week-02/day-02/factorio.py | 177 | 4.09375 | 4 | # - Create a function called `factorio`
# that returns it's input's factorial
def factorio(num):
fact = 1
for i in range(1, num+1):
fact *= i
return fact
|
2574c1d52f5a730a50452a00191087fed6351043 | Serios7/practice5 | /circle.py | 247 | 3.640625 | 4 | import figure
from math import pi
class circle(figure.figure):
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * pi * self.radius
def area(self):
return pi * self.radius**2
|
e100f8207fb85f162f5d0058cb2ff6c156af9568 | giveseul-23/give_Today_I_Learn | /80_pythonProject/mss02.py | 332 | 4.125 | 4 | # 제곱 처리
# print(3**2)
# print(pow(3, 2))
def mss_calc(v1, v2):
return v1 + v2, v1 * v2, v1 ** v2, pow(v1, v2)
a = int(input("숫자1 입력 : "))
b = int(input("숫자2 입력 : "))
r1, r2, r3, r4 = mss_calc(a, b)
print(a, '+', b, '=', r1)
print(a, '*', b, '=', r2)
print(a, '^', b, '=', r3)
print(a, '^', b, '=', r4)
|
36ce6fe31378b9a00eb96bea19792feeb69459cb | kaisersamamoon/py-notes | /作业/任务1.py | 124 | 3.59375 | 4 | print ("求斜边长度")
print ("已知 a=3, b=4 ")
a,b = 3,4
c = ((a ** 2 + b ** 2) ** 0.5)
print ("c的长度:", c )
|
dc2bb4eca9a560c5b36c46a662bc8ca72973a26c | asgards1990/advancedAlgorithmsLearning | /Projet Euler/projectEuler32.py | 3,055 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 08 15:48:26 2014
@author: su.yang
"""
#A quick review (compute 99*99 and 111*111) shows only a 2 digits times a
#3 digits giving a 4 digits can be ok, above 5 digits can not be obtained.
#now under 3 digits can not be obtained because we can easily show hat
#the product... |
417e2a236c5c8c3ee08d3db10dbf8baa21cf7134 | joaovicmendes/mdisc-trabalho | /src/ex25.py | 1,378 | 3.921875 | 4 | from math import sqrt, floor, log10
# Dado um inteiro x, calcula o número de digitos
def num_digitos(x):
return floor(1 + log10(x))
# Dado inteiro x, returna o x-ésimo valor da sequência de Fibonacci
# Solução não ideal para o problemas, pois calcula fib(x) em tempo exponencial
def fib(x):
if x == 1 or x == 2... |
617f55d3240e84954080b71810889a6cbf8680ef | robbailiff/python-codes | /american_blackjack.py | 11,175 | 3.84375 | 4 | """
I have developed an American Blackjack game using OOP and has Aces count as 1 or 11 (this was very tricky for me to work out).
Here are the general rules of the game:
- The player aims to as close to 21 as possible
- The player can choose to hit (take a card) to improve their hand
- If the player goe... |
ff74eead82c3f916f20a9fd84f2d49d41a33168c | lekasankarappan/PythonClasses | /Day10/Assignment.py | 164 | 3.8125 | 4 |
Name=[]
file=open("List.txt",'w+')
for X in range(0,10):
Name.append(input("Enter ur name:"))
file.write(str(Name))
file.close()
#print(Name)
#print(list(ra |
ce097c295bb0ab95123debba4051e49ed0960abc | IndraWirananta/k-Nearest-Neighbour | /KNN.py | 7,074 | 3.828125 | 4 | import pandas as pd
from math import sqrt
def getdata(filename, sheet):
xlsx = pd.read_excel(filename, sheet)
return xlsx
# Mencari nilai maks dan min tiap kolom
def find_minmax(dataset):
data_minmax = []
for i in range(
2, len(dataset[0])
): #rangenya dari 2 sampai length karena 2 ... |
9fbc2a7135d9d45fcef8e958e7f84bd9750953a9 | lvah/201903python | /day04/code/14_局部变量.py | 494 | 3.609375 | 4 | def save_money(money):
"""
存钱
:return:
"""
# 局部变量, 只在当前函数中生效;
allMoney = 100
print("存钱前:", allMoney)
allMoney += money
print("存钱后:", allMoney)
def view_money():
"""
查询金额
:return:
"""
# 局部变量, 只在当前函数中生效;
allMoney = 100
# NameError: name 'allMoney' is not de... |
440a03efd63109acab897711ea6105a233433a11 | yanghongkai/yhkleetcode | /stack/deserialize.py | 4,285 | 3.921875 | 4 | # 385 迷你语法分析器 https://leetcode-cn.com/problems/mini-parser/
class NestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""
self.val = ""
# nested_list 中并不一定只有一... |
5fca4c4aee8d2ebe13ef01bb68dfa12c7010b12c | DmitryVlaznev/leetcode | /946-validate-stack-sequences.py | 1,669 | 3.765625 | 4 | # 946. Validate Stack Sequences
# Medium
# Given two sequences pushed and popped with distinct values, return
# true if and only if this could have been the result of a sequence of
# push and pop operations on an initially empty stack.
# Example 1:
# Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
# Output: true
#... |
da4aa28633587a0702e95df1fd45ab23f30e7a9b | 707amitsingh/ds-algo-python | /powerOfNumber.py | 166 | 3.8125 | 4 | def power(n,p):
assert p >= 0 and int(p) == p, "Power should be a positive integer"
if(p == 0):
return 1
return n*power(n,p-1)
print(power(25,1)) |
edb66ab29d711822c059c5635b24f41a64257c28 | hooyao/Coding-Py3 | /LeetCode/DataStructure/BinaryTree/ConstructTree_From_Inorder_Preorder.py | 2,315 | 3.609375 | 4 | import sys
from BTreeUtils import BTreeHelper
from BTreeUtils import TreeNode
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder, inorder):
... |
40fe3117a86a1ec1452d77edfae45643b791ce25 | maurovasconcelos/Ola-Mundo | /Python/ex031_discantia_precoviagem.py | 279 | 3.890625 | 4 | distancia = int(input('São quantos km de viagem? '))
print('Você está prestea a fazer uma viagem de {}Km'.format(distancia))
if distancia <= 200:
preco = distancia * 0.50
else:
preco = distancia * 0.45
print('E o preço da sua passagem será d R${:.2f}'.format(preco)) |
795229e3ea995a24f87919d4a796c50c0acb5325 | ChetverikovPavel/Python | /lesson10/task3.py | 1,065 | 3.625 | 4 | class Cell:
def __init__(self, numb):
try:
self.numb = int(numb)
except ValueError:
print('None')
self.numb = None
def __str__(self):
return str(self.numb)
def __add__(self, other):
return Cell(self.numb + other.numb)
def __sub__(sel... |
54e620ecb7d1415c50600fdbd076e4d7358f8a9a | zconn/PythonCert220Assign | /students/DiannaTingg/lessons/lesson08/assignment/inventory.py | 2,048 | 4.0625 | 4 | """
Lesson 08 Assignment
Functional Programming
"""
import csv
from functools import partial
# pylint: disable-msg=line-too-long
# pylint: disable-msg=invalid-name
def add_furniture(invoice_file="", customer_name="", item_code="", item_description="", item_monthly_price=""):
"""
Updates the master invoice f... |
3d80ed0013b2c9eb7bb11be70c467e8537356c88 | UNREALre/LeetCode | /linked_lists/LinkedListCycle.py | 2,506 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head... |
27b3a72665e6d222124706ebcaac1811b610c15c | TonyCWeng/Practice_Problems | /leetcode/python/704_binary_search.py | 1,033 | 3.890625 | 4 | def search(numbers, target):
if not numbers:
return -1
left = 0
right = len(numbers) - 1
midpoint = (left + right) // 2
if numbers[midpoint] > target:
return search(numbers[:midpoint], target)
elif numbers[midpoint] < target:
right = se... |
e262377fb836b19a18937e514fd6348f0da6ed30 | EmmanuelSHS/LeetCode | /other_palindrome_int.py | 704 | 3.6875 | 4 | #!/usr/bin/env python
# coding=utf-8
class Solution:
def isPalindrome(self, num):
n = len(str(num))
if n in [0, 1]:
return True
p1, p2 = 0, n-1
while p1 <= p2:
if str(num)[p1] != str(num)[p2]:
... |
27228054199ac36a1a23bb906a2bd66f9f256719 | gabriellaec/desoft-analise-exercicios | /backup/user_068/ch39_2020_04_13_12_08_31_503836.py | 323 | 3.5625 | 4 |
n = c
conta_maior = 0
numero_maior = 0
while 1 < n < 1000:
cont = 0
while i > 1:
if n % 2 ==0:
n = n/2
else:
n = 3*n + 1
cont += 1
if cont>conta_maior:
conta_maior = cont
numero_maior = n
print(numero_maior... |
1bb9cfb1d085fb6af9f12c0f8232782f0e47d76b | phamvubinh/working_space | /python/python_basic/time/time.py | 215 | 3.53125 | 4 | #!/usr/bin/python
import time
print time.time()
print time.localtime(time.time())
print time.asctime(time.localtime(time.time()))
print "delay 5 second"
time.sleep(5)
print time.asctime(time.localtime(time.time())) |
8e9951b4883c488868bfb14814a4fafc4ef80ed4 | M-Rasit/Python | /Python_Assignments/pythonassignment_9.py | 229 | 3.921875 | 4 | user_name = "Joey"
query = input("Please enter the user name: ").title().strip()
if query == user_name:
print("Hello, {}! The password is: W@12".format(query))
else:
print("Hello, {}! See you later.".format(query))
|
a8e509702056f8e5c356a3c65dad0062a090a0f8 | IlyaZuna/Python_2_course | /laba_1-main/2.py | 599 | 3.65625 | 4 | '''print("Введите числа для сравнения")
i = 15
print(end ='>> ')
a = input()
while i > 1:
print(end ='>> ')
b = input()
if a < b:
print ('True')
else:
print ('False')
a = b
--i'''
print("Введите числа для сравнения")
try:
arr = (input().split(' '))
except TypeEr... |
d295f0a75731097f8a719c00e4f9985ffa056b6e | flyingdutch20/quick_python | /test_14.py | 614 | 3.78125 | 4 | def my_div(num, denom):
try:
res = num / denom
print("Divide {0} by {1} results in {2}".format(num, denom, res))
except ZeroDivisionError:
print("Sorry, I'm not able to divide {0} by {1} as I am not allowed to divide by zero".format(num, denom))
except:
print("Sorry, I'm not ... |
3487795f61e44534bf624814ffe9ec4f420efa42 | yzjbryant/YZJ_MIX_Code | /Python_Code_Beginner/算法图解/hm_21.py | 293 | 3.5 | 4 | from numpy import *
e = eye(4)
print(e)
x = random.rand(4,4)
print(x) #4*4随机数组
#矩阵matrix 等价于Matlab中的matrices
#数组array
#mat()将数组转化为矩阵
randMat = mat(random.rand(4,4))
print(randMat)
#.I 操作符实现了矩阵求逆的运算
|
0d261212bf48c33b4f528a5ed305b74cf519a1bf | vshkodin/problem-solving-with-algorithms-and-data-structures-using-python | /array_front9.py | 577 | 3.5 | 4 | def func(array):
for i in range(4):
if array[i]==9:
return True
return False
print(func([1,2,3,9,1]))
print(func([1,2,3,6,1]))
def func(array):
if [x for x in range(4) if array[x] == 9]: return True
else: return False
print(func([1,2,3,9,1]))
print(func([1,2,3,6,1]))
print(func([1,9... |
c9bd84ce59b2b391a935bdc7ba28877102e0d412 | ch1huizong/study | /lang/py/cookbook/v2/05/qsort.py | 648 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
"""快速排序"""
def qsort(L): # 使用列表推导
if len(L) <= 1: return L
return qsort([ lt for lt in L[1:] if lt < L[0]]) + L[0:1] +\
qsort([ ge for ge in L[1:] if ge >= L[0] ] )
def qsort_v2(L): # 使用语句
if not L: return L
pivot = L[0]
def lt(x): return x<pivot
def ge(x): ret... |
460a10965246214da1226400a838d1dcb823ee45 | sdivakarrajesh/Interview-Prep-questions | /Frequently asked/Two strings with common substring/answer.py | 378 | 4.03125 | 4 | def check(str1, str2):
letterDict = {}
for i in str1:
letterDict[i] = 1
for i in str2:
if i in letterDict:
return True
str1 = input()
str2 = input()
ans = check(str1,str2)
if ans:
print("YES")
else:
print("NO")
#simplest answer
#the smallest substring possible is a sin... |
73809600a065c7da67ce28ad0d5092e74fa23b35 | felipeazv/python | /math/sum_digits_of_squared_naturals.py | 2,142 | 4.125 | 4 | import math
import matplotlib.pyplot as plt
pwr = 2
start = 3
end = 100
iterations = 0
x_axis = []
y_axis = []
def run():
global x_axis
global y_axis
global iterations
for number in range(start, end):
iterations += 1
calculated_squared_sum = 3 if number % 3 == 0 e... |
4a3d634ed3dc04a1709f8595afa659e4efeb7438 | aboudeif/Search-and-Sort-C | /Linear Search.py | 753 | 4.21875 | 4 | items = ["Mohamed", "Ahmed", "Ali","Gaber","Fathy","Omar","Sayed","Hassan","Raouf"]
print ("List items are: " , items )
print ("please type the name you want to search for: ")
ele=input ()
# You can switch between 2 methods of linear search, change the switch value to select method 1 or 2
switch =2
if switch ==... |
143569e73751b84bac48115d0ee012e56c5dddd5 | toebgen/exercises | /data_structures/my_matrix.py | 4,116 | 3.640625 | 4 |
class MyMatrix():
"""
Class defining matrix as list of rows, containing list of values
"""
def __init__(self, rows=None, cols=None, init_type=None):
if rows == None:
self.mat = [[]]
else:
if cols == None:
cols = rows
self.mat = [[init... |
46deff42a85ae35a51716f2bd7ee8be3a5859d27 | turbobin/LeetCode | /回溯算法/combine_sum3.py | 970 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
216. 组合总和 III
找出所有相加之和为 n 的 k 个数的组合。
组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
- 所有数字都是正整数。
- 解集不能包含重复的组合。
示例:
输入: k = 3, n = 7
输出: [[1,2,4]]
"""
class Solution:
def combinationSum3(self, k, n):
result = []
arr = []
def dfs(target, start=1):
... |
d46639458c326af6e5de19f0219e63aec9aafffc | HariPavanSabinikari/MyPythonExamples | /MyPythonExamples/MyBasicExamples.py | 969 | 3.609375 | 4 | import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
#List Example
thislist = ["apple", "banana", "cherry"]
print(thislist)
#To import
#Camel case importing
import camelcase
c = camelcase.CamelCase()
txt = ... |
c475f07532dc7e8725d7bc05711eb07e7e69d47d | aman-sood/Python_Learning | /Byte of python/variabile_parameters.py | 310 | 3.703125 | 4 | # Taken from Byte of Python
def total(initial=5, *numbers, **keywords):
count = initial
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
# initial = 10, *numbers = 1, 2, 3 and **keywords = 50 , 100
print(total(10, 1, 2, 3, vegetables=50, fruits=100))
|
76b7362b68375149654b9b2f52a0f11b9aab1fd3 | jinxin0924/LeetCode | /Edit Distance.py | 1,508 | 3.765625 | 4 | __author__ = 'Xing'
# Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2.
# (each operation is counted as 1 step.)
#
# You have the following 3 operations permitted on a word:
#
# a) Insert a character
# b) Delete a character
# c) Replace a character
class Solution(ob... |
a7dcd04461b06fae3583493ece1cdfe8ed4e5409 | passhabi/coursera-machine-learning-regression | /learnt/regression/least_square_regression.py | 1,666 | 3.75 | 4 | import numpy as np
from learnt.regression import predict_outcome
def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance):
"""
**Gradient descent Algorithm**
:param feature_matrix:
:param output:
:param initial_weights: 1×n numpy array
:param step_size:
... |
19385ebe4842470ff0d1971b2cb5c3e22f519d3f | rostonn/pythonW3 | /dictionary/2.py | 160 | 3.921875 | 4 | # Write a program to add a key to a dictionary
def add_key(d,value):
key = len(d.values())
d[key] = value
return d
d = {0:10,1:20}
print(add_key(d,5000))
|
7d75d53b4739b9e81e30adc2fe6c437ca97e9c85 | ThusharaWeerasundara/324 | /2/1/ex2.py | 1,489 | 4.1875 | 4 | from dataclasses import dataclass #to make student class
from typing import List, Dict #to use in Student class
@dataclass
class Student:
"""A student's course registration details"""
given_name: str
surname: str
registered_courses: List[str]
def load_course_registrations(filename: str) -... |
9dc211acd86883ff197f607f06c0df47d1c0c4ef | bomer/introtopython | /2helloyou.py | 180 | 4.34375 | 4 | #Lesson 2 - Here we'll be introducing Input
name=raw_input("Please enter your name:")
print "Hello " + name
num=input("Please enter a number")
print " squared is " + str(num*num)
|
e80f8d5ec846648d6906082110f46785766105d5 | yamogi/Python_Exercises | /ch03/ch03_exercises/ch03_ex03.py | 1,566 | 4.40625 | 4 | # ch03_ex03.py
#
# Modify the Guess My Number game so that the player has a limited number of
# guesses. If the player fails to guess in time, the program should display an
# appropriately chastising message.
#
import random # importing the random module
print("\t Welcome to \"Guess My Number\"!")
print("\nI'm thinki... |
49a8fa2d13d43fbab18b0d2100f934195ecc42ef | sug5806/TIL | /Python/algorithm/sort/selection_sort/prac.py | 743 | 3.859375 | 4 | # 해당 위치에 어울리는 값을 '선택'한다
# 먼저 최소값을 찾은 후 정렬된 값을 제외한 맨 왼쪽 숫자와 교환한다.
def selection_sort(arr):
length = len(arr)
# 파이썬은 range가 n-1까지이다 그러나 끝에서 2번째를 정렬하고 나면 마지막이 남는데
# 마지막 남은 하나는 정렬을 수행하지 않아도 되므로 n-1을 해준다
for i in range(length):
min_idx = i
for j in range(i + 1, length):
if arr[m... |
19515e3a029166550df4cb79352ad3bab49011a9 | ltang93/python | /python快速上手练习/7.18.2.py | 409 | 3.96875 | 4 | import re
def mystrip(words,de=''):
print(words)
if de=='':
print('1')
wordsre=re.compile(r'^\s*|\s*$')
print('your string is:'+wordsre.sub(r'', words))
else:
print('2')
wordsre=re.compile(r'^'+de+r'|'+de+r'$')
print('your string is:'+wordsre.sub(r'',words))
... |
682346f7341edbb00e2be4290aefb099a3fd9773 | 360linux/PyLearn | /day9/threading-count1000-ex1.py | 893 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-8-3 下午7:07
# @Author : Aries
# @Site :
# @File : threading-count1000-ex1.py
# @Software: PyCharm
import threading
import time
num=0
lock=threading.Lock()
class Timer(threading.Thread):
def __init__(self,count,interval):
# super(Timer,se... |
ba8fe6ccbef52c97aa3daa43c8e125069a633f19 | matteocorea/rpi-gpio | /09_7_segment_display.py | 782 | 3.53125 | 4 | #!/usr/bin/env python
import RPi.GPIO as GPIO
import time
# Configure pin numbers et al
segments = [4, 17, 22, 5, 6, 13, 19]
def display_digit(n):
digits = (126, 48, 109, 121, 51, 91, 95, 112, 127, 123)
num = digits[n]
for i in range(7):
GPIO.output(segments[6 - i], (num & (1 << i)) >> i)
def set... |
7381617877fc6312875f97452ef1f3841b0e2873 | UW-CSE442-WI20/FP-music-vibez | /data/byYearToByArtist.py | 1,715 | 3.625 | 4 | import csv
def remove_quotes(str):
'''
Removes quotes from given string str
requires: quotes are only found as the first and last characters in str
return: str without beginning and ending quotes
'''
return str[1:len(str) - 1]
def byYearToByArtist(artist, destfilename):
artist_res = []
... |
9b8ea5ce2454150451c203fa6e4d1f284f96d65a | student-work-agu-gis2021/lesson4-functions-and-modules-M094y | /temp_functions.py | 340 | 3.578125 | 4 | def fahr_to_celsius(temp_fahrenheit):
converted_temp = (temp_fahrenheit-32) / 1.8
return converted_temp
def temp_classifier(temp_celsius):
if (temp_celsius <-2):
return 0
if (temp_celsius >=-2) and (temp_celsius <2):
return 1
if (temp_celsius >=2) and (temp_celsius <15):
return 2
if (temp_celsius... |
e2ad938ed1b60655378abfc3646bcfa86576afaf | D-Lock/Tools | /split_file.py | 1,178 | 3.625 | 4 | #! /usr/bin/python3
# Splitting Algorithm for Server Side interaction
import os
import sys
def printOptions():
print ('OPTIONS')
print ('-help to print this menu')
print ('Argument format: [inputfilename] [numoutputfiles] [-o] [outputfilename]')
def operationMismatch(num):
if (num == 0):
print ("ERROR: File wa... |
0c12357f3bdcb2da965c9b55f655458f281c3f3e | samkasbawala/crackingthecodinginterview | /Chapter_001_Arrays_and_Strings/1.1_Is_Unique.py | 1,763 | 3.890625 | 4 | __author__ = 'Sam Kasbawala'
__credits__ = 'Sam Kasbawala'
import unittest
def is_unique(string: str, ds: bool = True) -> bool:
"""Function to see if inputted string has all unique characters"""
# Using set data structure, O(n) runtime
if ds:
seen = set()
for char in string:
... |
12806b0c3520361d10d094965514f40d0a510256 | taketakeyyy/atcoder | /abc/154/c.py | 295 | 3.703125 | 4 | # -*- coding:utf-8 -*-
def solve():
N = int(input())
As = list(map(int, input().split()))
dic = {}
for a in As:
if not a in dic:
dic[a] = True
continue
print("NO")
return
print("YES")
if __name__ == "__main__":
solve()
|
f33e77dc932f335e27af3d05eb1a8cd5a81745b7 | teckoo/interview_public | /coding/leetcode/220-contains-duplicate-iii/solution-AVL-tree.py | 5,113 | 3.734375 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
def __init__(self):
self.root = None
self.size = 0
def height(self, node):
if node:
return... |
91b407af4bc7d2150fe93a60b1968b7f9d218ccd | YeltsinZ/Python | /factorial.py | 186 | 4.125 | 4 | def fact(n):
f = 1
for i in range(1,n+1):
f = f * i
return f
print("Enter the number to find the factorial")
x = int(input())
result = fact(x)
print(result) |
9ee2cc9403c2c6135bfbd3c613f071d365833602 | 3chamchi/likelion-seoul-6th | /week3/03_class.py | 526 | 3.671875 | 4 | class 클래스명:
pass
class Person:
pass
class Person():
pass
class Person(object):
pass
class Person:
year = 2021
def __init__(self, name, age):
self.name = name
self.age = age
def run(self):
print(self.name, '달린다.')
def sleep(self):
print(self.name,... |
99c88549aebbb594247a09795658425e1bbec6b3 | tnakaicode/N-Body | /pointmassSim7.py | 4,337 | 3.515625 | 4 | import random as rand
import math
import numpy as np
## Class MASS framework
class Mass(object): #Mass template object
def __init__(self, i, masses, set_masses = 0):
self.numb_masses = masses
self.id = i
# SET MASS
if set_masses == 1:
if (i==0):
self.mass... |
e78f3d0f5b04ce2bda02eadfe4f8104664d4501c | Vineet2000-dotcom/Competitive-Programming | /CODECHEF/The 60 Min game/who occured once.py | 403 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 14 09:58:58 2021
@author: Vineet
"""
t=int(input())
for _ in range(t):
n=int(input())
list1=list(map(int,input().split()))
for i in list1:
if list1.count(i)==1:
if i%2==1:
print("PASS")
else:
... |
c88e8c56ce02a009be88afe4eaff3121b01e330b | Wojciech-S/python_bootcamp_28032020_remote | /03_funkcje/010_definiowanie_funkcji.py | 1,803 | 3.65625 | 4 | # def przywitanie(name="World!"):
# if name == "xxx":
# return "Nie używamy brzydkich słów!"
# return f"Hello {name}"
#
#
# print(przywitanie("Rafał"))
# przywitanie("Adam")
# przywitanie("Marcin")
# przywitanie("Paulina")
# przywitanie("Maria")
#
# przywitanie("xxx")
#
# #print(3, x)
# def incrementato... |
c27b462e08fac0aedc5ae08bd79a657abc461b57 | sjhgz/leetcode-practice | /python/107_binary_tree_level_order_traversal_ii.py | 1,370 | 3.75 | 4 | #
# @lc app=leetcode.cn id=107 lang=python
#
# [107] 二叉树的层次遍历 II
#
# 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 levelOrderBotto... |
946744455f41698515a8bc4796cddfc7e1705d96 | Augustin-Louis-Xu/python_work | /第四章/4.3 创建数值列表 动手试一试.py | 1,131 | 4.125 | 4 | #使用for循环打印数字1~20。
for value in range(1,21):
print(value)
#用for循环将创建列表的包含的1~100000打印出来,如果输出时间过长,就按ctrl+c终止。
for value in range(1,1001):
print(value)
value=[value for value in range(1,1001)]
print(value)
#计算1~1000000的和。
list=range(1,100001)
print(sum(list))
#通过指定第三个参数来打印出1~20的奇数。
values=[value for value in range(1,2... |
f1af9d8e58579da58b93017b22072e32cb2047e6 | ihaeyong/tf-example-models | /models/tf_logreg.py | 2,077 | 3.71875 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
LOCAL_FOLDER = "MNIST_data/"
IMAGE_PIXELS = 784
NUM_CLASSES = 10
LEARNING_RATE = 0.5
TRAINING_STEPS = 1000
BATCH_SIZE = 100
# PREPARING DATA
# downloading (on first run) and extracting MNIST data
data = input_data.read_data_sets(... |
bdec48b4ba0d3ec2e40547d0c236bda33f53576e | tonymontaro/Algorithmic-Problem-Solving | /Hackerrank/algorithms - practice/sorting/insertion_sort_p2.py | 881 | 3.84375 | 4 | # n = int(input().strip())
# arr = list(input().strip().split(' '))
def insertion(arr):
# arr = list(map(str, arr))
counter = len(arr) - 1
tobesorted = arr[counter]
while counter >= 0:
if counter == 0:
arr[0] = tobesorted
counter -= 1
elif int(tobesorted) >= int... |
b4d797a241f267c4dbee1148cb1fa509cb13d8a5 | jsatt/advent | /2018/d10/p1.py | 2,945 | 3.640625 | 4 | import os
import re
# INPUT_FILE = 'test_input.txt'
# ANSWER = 3
INPUT_FILE = 'input.txt'
ANSWER = 10595
# part 1 displays "JLPZFJRH"
def test_day():
return run_day() == ANSWER
def run_day():
path = os.path.join(
os.path.abspath(os.path.dirname(__file__)), INPUT_FILE)
with open(path, 'r') as f... |
8fe3cee14dcdb80e63d1bdeb30a684894fddd546 | mpt-bootcamp/python | /lab3-ex2-ans.py | 258 | 3.609375 | 4 | #! /usr/bin/env python3
import os
import shutil
import pathlib
filedir = 'data/'
print("Listing files in {}".format(filedir))
with os.scandir(filedir) as entries:
for entry in entries:
if not entry.is_dir():
print(entry.name)
|
6ee8a788e20d3df8654e0217c2d2873ff3f23d0d | amerisrudland/PocketPiano | /FindPianoCorners.py | 5,503 | 3.6875 | 4 | """
2017-02-07
This program finds the corners of the projected piano image.
It takes 2 images, manipulates and subtracts them to find
the keyboard. Then it finds the edges of the remaining image
and creates a skewed rectangle around these edges. From the
skewed rectangle the coordinates of the piano's corners can
be f... |
1c94a4993badd7e7fb71fdc04b4c5acf86d07d86 | swtwinsy/Code_Challenges | /dailyprogrammer.reddit.com/easy/E_challenge_287.py | 1,517 | 3.75 | 4 | def kaprekar_routine(num, opt=0):
"""
daily programmer challenge 287 - take a number, and return its largest digit
:param num: an integer
:param opt: which option to use
:return: varied based on option
"""
temp = list(str(num))
while len(temp) < 4:
temp.append('0')
if opt =... |
c1d27b0eeffdfdf0b792f90594bf79e5124d045a | wanglikun7342/Leetcode-Python | /leetcode_python/find_numbers_with_even_number_of_digits.py | 355 | 3.671875 | 4 | from typing import List
class Solution:
def findNumbers(self, nums: List[int]) -> int:
sum = 0
for num in nums:
if len(str(num)) % 2 == 0:
sum += 1
return sum
if __name__ == '__main__':
input_nums = [12, 345, 2, 6, 7896]
solution = Solution()
print... |
012fff481fcbd3663eb04d6de82a6556bc7aeddc | dyedefRa/python_bastan_sona_sadik_turan | /02_Python_Objeleri_Veri_Yapilari/09_strings-demos.py | 1,307 | 4.15625 | 4 | website = "http://www.sadikturan.com"
course = 'Python Kursu: Baştan Sona Python Programlama Rehberiniz (40 saat)'
# 1 'course' karakter dizisinde kaç karakter bulunmaktadır ?
print(f'Course dizisinde toplam {len(course)} karakter vardır.')
# 2 'website' içinden www karakterlerini alın
print(website[7:10])
# 3 'webs... |
0e1d9c778d3179810ba505025557a1fa9862500f | ammarahmahmood/piaic-a.i-assignments | /calculator.py | 606 | 4.3125 | 4 | print(" calculator")
addition = "+"
subtraction = "-"
multipliction = "*"
division = "/"
num_1 = float(input(""))
num_2 = float(input(""))
operator = input("kindly enter operator")
#c = "num_1" + "num2"
if operator == addition:
c = num_1+num_2
print(c)
elif operator ... |
dc2eeac637d3e3e25e8d5f4f8553f2e223ee53ec | Khanamir1/programming-exercises | /week-2/exercises5.py | 95 | 3.90625 | 4 | userinput = input("Hi there, what is your name? ")
print("Hello\n"+userinput+"\nHow are you?")
|
563694b4b66a098d1a7a5c6af738b0124c94ddec | superhman/DSC510Spring2020 | /Rossman_DSC510/Week 8 Word Dictionary.py | 1,655 | 4.03125 | 4 | # Gettysburg Address Word Dictionary
def main():
"""
Institution: Bellevue University
Course: DSC510
Assignment: 8.1
Date: 10 May 2020
Name: Alfred Rossman
Interpreter: Python 3.8
"""
# Print docstring header
print(main.__doc__)
#! python3
# Open 'gettysburg.txt' in local directory for read-o... |
2c409818f35653ffd00293658087c553404cc665 | timothyAgevi/pythonBootcamp | /wk1/password.py | 1,087 | 3.96875 | 4 | #Use Python script to generate a random password of 8 characters.
# Each time the program is run,
# a new password will be generated randomly.
# The passwords generated will be 8 characters long
# and will have to include the following characters in any order:
# 2 uppercase letters from A to Z,
# 2 lowercase lette... |
7d41b0ef7ff518befed8e8716f16e5af0b19a60d | findman/PythonCookbook | /chapter1/p1_1.py | 664 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding:utf8 -*-
p = (4, 5)
x, y = p
print("x:", x)
print("y:", y)
data = ['ACME', 50, 91.1, (2012, 12, 21)]
name, shares, price, date = data
print("name = %s, shares = %d, price = %f, date = %s" % (name, shares, price, str(date)))
name , shares, price, (year, mon, day) = data
print("name... |
575d3f7b6d5aee070ec1e0d39bec66b3d6ef2532 | oriolgarrobe/Text-classification | /helper_functions.py | 6,067 | 3.71875 | 4 | # Libraries needed
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
def preprocess_lyrics(df):
"""Function that preprocesses a dataframe before feeding it to text classification libraries"""
# Filter English song... |
3290326691063da6d8c46ab647d67ddf837fbf69 | xuchen666/DataWrangling_Python | /web scraping- download data sets locally.py | 2,407 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 26 10:36:32 2017
@author: xuchenwang
"""
'''
This file downloads data from different carrier-airport combination.
Firstly, it extracts carrier list and airport list of all carriers and airports.
Then it make requests to scraping these data set and ... |
d531d90e503f2318809a97f04dc35c8f40603aa8 | pasbahar/python-practice | /Max_sum_of_increasing_subseq.py | 1,056 | 3.96875 | 4 | '''Given an array A of N positive integers. Find the sum of maximum sum increasing subsequence of the given array.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N(the size of array). The second line of each test case contains array elements.... |
4c69d8f6b9214fe8720e9978de5b7ce732176b7f | HussainPythonista/SomeImportantProblems | /sorT/InsertionSort.py | 483 | 4.1875 | 4 | def InsertionSort(listValue):
#Pointer
for pointer in range(1,len(listValue)):
current=listValue[pointer]
sortedArray=pointer-1
while sortedArray>=0 and current<listValue[sortedArray]:
listValue[sortedArray+1]=listValue[sortedArray]
sortedArray-=1#To check the val... |
93f6f023377d4716d80d47d668839009a5648d7b | sr3688/python | /Practice/decimal_to_any_base.py | 182 | 3.6875 | 4 | num=int(input())
base=int(input())
ten=1
sum=0
while(num):
rem=num%base
sum+=rem*ten
ten*=10
num=num//base
print(sum)
|
0eeb71cc8ff4a3fd37b91ab04e66f2f761b916f2 | carlos-gutier/DS-Unit-3-Sprint-2-SQL-and-Databases | /sprint_challenge/demo_data.py | 1,224 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import sqlite3
# In[12]:
conn = sqlite3.connect('demo_data1.sqlite3')
# In[13]:
# Creating empty table `demo`
with conn:
curs = conn.cursor()
curs.execute("CREATE TABLE demo(s TEXT, x INT, y INT);")
# In[14]:
# Inserting values
with conn:
curs = ... |
f53f7c167df257cd51888c9ec979f45edff7affb | ahmedtufailtanzeem/complete_python | /src/08_functions.py | 1,360 | 4.09375 | 4 | def add(operand_1, operand_2):
return operand_1 + operand_2
result = add(10, 20)
print(result)
result = add("a", "bc")
print(result)
def odd_or_even(number):
return "even" if number % 2 == 0 else "odd"
def odd_or_even_small(number):
return number % 2 == 0
print(odd_or_even(9))
print(odd_or_even_small(101))
... |
bb152c78821bddbfd5db6b87bb859683238b5e92 | Adam21241/beeradvocate | /modules/functions.py | 1,605 | 3.578125 | 4 | import numpy as np
def is_float(x):
"""
Returns True if object is float or float convertible. Otherwise returns false
"""
try:
float(x)
return True
except ValueError:
return False
def pearson(s1, s2):
"""
Description:
Perform Pearson correlation on 2 ... |
4344734de881aa073f66ae9159d4f5a89678a295 | MkSavvy/algorithms_bank-NeuralNet0 | /my_first_NN.py | 1,148 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 08:58:48 2015
@author: Michel_home
"""
from __future__ import division
import numpy as np
# define sigmoid and derivative of sigmoid
def sigmoid(X, slope = False):
if slope:
return X*(1-X)
return 1/(1+np.exp(X))
# initialize inputs and labels (depend... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.