blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e6d8548782e9feac045b611491958e0ac948b265 | ralinc/learning-python | /narcissistic.py | 617 | 4.15625 | 4 | def is_narcissistic_number(value):
'''Check whether a given number is a narcissistic number or not.
Keyword arguments:
value -- the number to check
Returns: boolean
'''
return value == sum([int(digit)**len(str(value)) for digit in str(value)])
if __name__ == '__main__':
print(is_narcis... |
eb0954deee7f143cbe0eec9738e958c2601bf8fe | akifuji/programming_contest_challenge | /Ants.py | 302 | 3.828125 | 4 | def antsMin(L, n, x):
for i in range(n):
if x[i] > L - x[i]:
x[i] = L - x[i]
print(max(x))
def antsMax(L, n, x):
for i in range(n):
if x[i] < L - x[i]:
x[i] = L - x[i]
print(max(x))
L = 10
n = 3
x = [2, 6, 7]
antsMin(L, n, x)
antsMax(L, n, x)
|
7ce7aa8ced7b2baaf4f32ff11e97b612d4d552b7 | sanjoy-kumar/PythonMatplotlib | /Subplots.py | 2,575 | 4.4375 | 4 | # Display Multiple Plots
# With the subplot() function you can draw multiple plots in one figure:
# -------------------- Draw 2 plots: ----------------------
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1,2,1) # The layout is organize... |
48e9afe294846f2e1f19f9175afd427b6577182c | shub0/algorithm-data-structure | /python/max_product_of_len_words.py | 1,280 | 3.90625 | 4 | '''
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return ... |
1301dad7c172e1ebf8294fcb4bfb942f8d49c58a | jmcomets/EUSDAB-demo | /geometry.py | 720 | 3.71875 | 4 | import math
class Vector(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, v):
return Vector(self.x + v.x, self.y + v.y)
def __sub__(self, v):
return Vector(self.x - v.x, self.y - v.y)
def __mul__(self, coef):
return Vector(self.x*coef, self.y... |
6dece4d8f27d27552480b56e2ef93b228f8dddbb | xushuhere/LeetCode_python | /Python/264_UglyNumberII.py | 973 | 3.859375 | 4 | """
264. Ugly Number II
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and n does not exceed 1690. ... |
a38e55e055c67f73f8d1c55821ffa93f4bf8bc1a | alirezaghd/Assignment-3 | /6.py | 294 | 3.953125 | 4 | num = int(input("Enter a number: "))
sum = 0
temp = num
# num = 371
while temp > 0:
digit = temp % 10
print(digit)
sum += digit ** 3
print(sum)
temp //= 10
print(temp)
if num == sum:
print(num,"Yes")
else:
print(num,"NO") |
081d7613759271db59d5769f097821b89c5be4db | tintindas/leetcode-solutions | /Graph/Medium/684. Redundant Connection/solution.py | 738 | 3.609375 | 4 | from collections import defaultdict
from typing import List
class Solution:
def dfs(self, source, target, graph, visited):
if source not in visited:
visited.add(source)
if source == target:
return True
for nei in graph[source]:
if self.df... |
37d061ade76a863f27e0556ba4fecba331662586 | jasonusaco/Leetcode-Practice | /剑指offer/合并两个有序的链表.py | 1,526 | 3.671875 | 4 | """
方法1:转成两个list,排序,然后再并入链表
"""
class Solution:
def Merge(self, pHead1, pHead2):
if pHead1 is None and pHead2 is None:
return None
num1 = []
num2 = []
#遍历链表1,把值全部放入num1
while pHead1:
num1.append(pHead1.val)
pHead1 = pHead1.n... |
6555caf6ad1b7a13cbee8f3f5a369a1f48b0c807 | Prukutu/brandify | /brandify.py | 1,649 | 3.609375 | 4 | import matplotlib.pyplot as plt
def embed_logo(fig, img_file, loc='upper right', bbox=None):
""" Embed an image to an existing matplotlib figure object.
Input
-----
fig (obj): Matplotlib figure object
img_file (str): File to be embedded
loc (str): Location to embe... |
1745ffa312df78b989de53e4712a235a3e227800 | ChenLaiHong/pythonBase | /test/homework2/8.1.8-十进制小数转成二进制小数.py | 1,641 | 3.78125 | 4 | """
【问题描述】
编写程序,输入十进制小数(只考虑正数),把它转换为以字符串形式存储的二进制小数,输出该二进制小数字符串。
对于转换得到的二进制小数,小数点后最多保留10位。小数点后不足10位,则输出这些位,尾部不补0;小数点后超出10位,则直接舍弃超出部分。
【输入形式】
十进制浮点小数
【输出形式】
对应输入小数的二进制小数字符串。若整数部分或者小数部分为0,则输出0。比如输入0,则意味着输出0.0 。
【样例输入】
1.2
【样例输出】
1.0011001100
【样例说明】
输入为10进制小数,将该小数转化成二进制后输出。推荐采用字符串来处理生成的二进制数,特别要注意0的处理
"""
def changez(num):... |
d293f5dd3623559ba61e2e263a7ddb9a16cdcab3 | ai96yuz/python-marathon | /sprint08/task.py | 6,974 | 3.640625 | 4 | # Task 1
import unittest
class Product:
def __init__(self, name, price, count):
self.name = name
self.price = price
self.count = count
class Cart:
def __init__(self, *args):
self.data = args
def get_total_price(self):
total_price = 0
for item in self.... |
ea6d0c4637c5abd75e5e5a407cb72a4b315ea47c | wilhoite/first | /gitHook.py | 1,240 | 3.765625 | 4 | #!/usr/bin/env python
'''
Corrects / enforces curly brace rule.
AUTHOR: Frances Wilhoite frances.wilhoite@bmwna.com
'''
import sys, os
def main():
filename = raw_input('Enter a file name: ')
file = open(filename, 'r')
lines = file.readlines()
file.close()
prev_line = lines[0]
for j in range(0,... |
19baa63c5c0e4958c45b31c0bddf7f00a3f8fe6f | Chercheur232/Danylo_Rudych | /hw_2_2.py | 3,169 | 3.859375 | 4 | # -*- coding: utf8 -*-
def sum_natural_numbers(a, b):
sum_natural_num = 0
for i in range(a, b+1):
sum_natural_num += i
if a == b:
return a
return sum_natural_num
cont = 1
stop = 2
while cont is not 2:
print('Укажите начало и конец промежутка, который состоит'
... |
41cbddf5c62460673139f55640317246490730e0 | rafamatoso/python-mysql-course | /Secao3/Exercicios/l1e5_calculadora.py | 485 | 4.25 | 4 | num1 = float(input("Digite o primeiro número: "))
op = input("Digite o operador: ")
num2 = float(input("Digite o segundo número: "))
if op == "+":
result = num1 + num2
elif op == "-":
result = num1 - num2
elif op == "*":
result = num1 * num2
elif op == "/":
result = num1 / num2
elif op == "**":
... |
49ab14774b4e9c902769a68abf526d7e8dfdcdc3 | salarsen/dojoPython | /python/multiple.py | 146 | 3.578125 | 4 | a = [2,4,10,16]
def multiply(arr,multiplier):
for num in range(0,len(arr)):
arr[num] = arr[num] * multiplier
multiply(a,5)
print a
|
45fc85693d46e4591072e266c211d15cb546efec | subi-x/ded-inside | /ded.py | 261 | 3.65625 | 4 | import time
x = 1000;
print("El PrImO");
time.sleep(1);
print("БрА бРа бРаВл СтАрс")
time.sleep(1);
while x != 0:
print("1000-7=",x)
x=x-1;
time.sleep(0.1);
print("zxc дед инсайд хавыхпвахпыхх");
|
fa7e88ac771758103db6fc12fc2d2e49a73be17a | akhilsambasivan/PythonPractices | /Ex5.py | 140 | 4.03125 | 4 | x=eval(input("Enter value for x: "))
y=eval(input("Enter value for y: "))
out=x+y
print("Addition of {} and {} gives: {}".format(x, y, out)) |
6f0a5c4fb3aef7ac7251ccb597b1eab04b9f7b20 | lihongwen1/XB1929_- | /ch06/copy1.py | 315 | 3.546875 | 4 | parents= ["勤儉", "老實", "客氣"]
child=parents
daughter=parents
print("parents特點",parents)
print("child特點",child)
print("daughter特點",daughter)
child.append("毅力")
daughter.append("時尚")
print("分別新增小孩的特點後:")
print("child特點",child)
print("daughter特點",daughter)
|
e9e95e94a20c70e098fcef53e6796a3af31a02ee | Sushmitha1711/python_ws | /car.py | 982 | 3.71875 | 4 | class car:
def __init__(self,regno,no_gears):
self.regno=regno
self.no_gears=no_gears
self.is_started=False
self.c_gear=0
def start(self):
if self.is_started:
print(f"car is already started.....")
else:
print(f"car with regno :{self... |
ea8412e9c95f0f3d9296072fdfe58601c0ddde2a | mwnickerson/python-crash-course | /chapter_9/users.py | 1,111 | 4.21875 | 4 | # Users
# Chapter 9 exercise 3
# class for users with two methods
class Users:
"""a simple attempt at user system"""
def __init__(self, first, last, email, username, credit):
self.first = first
self.last = last
self.email = email
self.username = username
self.credit = cr... |
5d3e13dcee5bd1b93fa6d72efa0f5ae05e3a5e2f | anncannbann/dca | /1.py | 1,220 | 4.375 | 4 | '''
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
1 2 3
4 5 6
9 8 9
The left-to-right diagonal = 1+5+9 = 15, The ... |
0a0fae8b0a74234fbe1668e694b1c02dee4a85b5 | EthanLo01/Leetcode | /Array/189_Rotate_Array.py | 831 | 3.6875 | 4 | # original:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
new_nums = [0] * len(nums)
for i in range(len(nums)):
index =... |
18dcc289bfa57e464e1d5d4da3006ae21f829091 | yantrabuddhi/pau2motors | /src/MapperFactory.py | 3,926 | 4 | 4 | import math
class MapperBase:
"""
This is an abstract class. Methods 'map' and '__init__' are to be
implemented when writing a new Mapper class. Subclasses of MapperBase will
be used as mapping functions that take values received in messages and
return angles in radians.
"""
def map(self, val):
rais... |
9c44b84a37512f1c149157267428bab79d88e3d5 | marcjmonforte/python-crash-course | /Chapter 10 Files and Exceptions/10_3_guest.py | 459 | 4.46875 | 4 | """
10-3 Guest: Write a program that prompts the user for their name.
When they respond, write their name to a file called guest.txt.
"""
filename = 'guest.txt'
with open(filename, 'a') as file_object:
first_name = raw_input("What is your first name?\t")
last_name = raw_input("And what is your first name?\t")
prin... |
a21d81ec9f071a63f28ef22ad3b1db66e6e82d4c | vignesh-hub/leap-year-or-not | /leap_year_or_not.py | 290 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 30 23:11:13 2019
@author: vignesh
"""
print("to check the year is leap or not")
n=input("enter the year you need to check out?\n")
c=int(n)
if(c%4==0):
print("the year",c,"is leap year")
else:
print("the year",c,"is not an leap year") |
79e78627dc3f77b0bb5be2ffd4b0d8ceeb774342 | kohnakagawa/ghidra_scripts | /ghidra9.2.1_pyi/ghidra/util/datastruct/Stack.pyi | 3,588 | 3.84375 | 4 | from typing import Iterator
import java.lang
import java.util
import java.util.function
import java.util.stream
class Stack(object, java.lang.Iterable):
"""
The Stack class represents a last-in-first-out (LIFO) stack of objects.
It extends class ArrayList with five operations that allow an array list
... |
00cb3d09aae52e6a52a40ba89f942387e563c302 | aidenyan12/LPTHW | /EX48/template/ex48/lexicon.py | 537 | 3.859375 | 4 |
def scan(sentence):
words = sentence.split( )
result = []
for word in words:
get = clasify(word)
result.append(get)
return result
def clasify(word):
if word in ['north', 'south', 'east']:
return ('direction', word)
elif word in ['go', 'kill', 'eat']:
return ('verb', word)
elif word in ['the'... |
1a146889a8d9b35b0940400db4a793ae5d5fff17 | joebehymer/python-stuff | /dicts_.py | 902 | 4.5 | 4 | # represent student using dictionary
student = {
'name': 'Joe',
'age': 25,
'courses': ['Math', 'CompSci'],
1: 'intkey'
}
print(student)
# get value of one key
print (student['courses'])
print(student[1]) # keys can be ints too
# throws an error if we try to direct access a key that doesn't exist, so ... |
050ee641b566d7b0a1c95f47cb0b8f940a75e1fa | zhiyupan/Deep_Lerning | /Linear_unit | 1,385 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from perceptron import Perceptron
#定义激活函数f
f = lambda x:x
class LinearUnit(Perceptron):
pass
# test=LinearUnit(3,f)
# print(test)
def get_training_dataset():
'''
捏造5个人的收入数据
'''
# 构建训练数据
# 输入向量列表,每一项是工作年限
input_vecs = [[5],[3],[8],[1.4],[10.1]... |
5b62a6bcc69e72da40b925cc104905b8b1389399 | Kiran-24/python-assignment | /python_partA_171041001/area_of_triangle.py | 686 | 4.34375 | 4 | '''implement a python code to find the area of a triangle.'''
from math import sqrt
def area(a,b,c):
''' to find the area of triangle'''
#inequality theorem
if a+b>c and b+c>a and c+a>b:
#semi-perimeter of triangle
s = (a+b+c)/2
#Heron's formula to find area of trinagle
area_of_triangle = sqrt(s*(s... |
0ae75f820666f82aebe246760e96487ba232d38a | Kasulejoseph/Coding-Challenges-Hackathons | /AndelaHackathon/Bypass_drive_circuit.py | 1,313 | 3.734375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
from operator import itemgetter
#
# Complete the 'bypassCircuit' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY stations as parameter.
#
def bypassCircuit(stations):
# Write your co... |
c2ec564cb6a74cdef288991b0f7848b3df11a5d3 | SmeetMehta/Coding-Questions-GFG | /Arrays/EquilibriumPoint.py | 925 | 3.8125 | 4 | #User function Template for python3
class Solution:
# Complete this function
#Function to find equilibrium point in the array.
def equilibriumPoint(self,A, N):
# Your code here
if(N==1):
return(1)
else:
res=-1
sum=0
B=[]
... |
893cdea58c4242d911d2f4cdcfcdb6a469a4e366 | GIT012020/PeptidesCalculatorVol2_2.0 | /calc_add_unusual_amino.py | 2,601 | 3.921875 | 4 | import csv
from itertools import chain
class Add:
def add_unusual_amino(self, value, value1, value2):
'''Input unusual amino acid'''
Amino_Acid_Input = str(value)
Letter_abbreviation_Input = str(value1)
if Amino_Acid_Input == "" or Letter_abbreviation_Input == "":
retu... |
cb11cf134248b627a0f35a46a0ae0542648e0dad | arogovoy/leetcode | /py/search_insert_position.py | 1,072 | 4.15625 | 4 | # 35. Search Insert Position
#
# Given a sorted array of distinct integers and a target value, return the index if the target is found.
# If not, return the index where it would be if it were inserted in order.
#
# You must write an algorithm with O(log n) runtime complexity.
#
# Example 1:
# Input: nums = [1,3,5,6], t... |
8b92af7478e0ba90b0c4e7efd190223d02d93260 | wel51x/Machine_Learning_and_Spark | /Chapter_2/Ex2d.0.py | 1,668 | 3.5 | 4 | import pyspark
from pyspark.sql import SparkSession
from pyspark.sql.functions import regexp_replace
from pyspark.ml.feature import Tokenizer, StopWordsRemover, HashingTF, IDF
import pandas as pd
# Creating a SparkSession
spark = SparkSession.builder \
.master('local[*]') \
.app... |
3d12a0365dccbcda589c3f87e033c278894e6c03 | yanghaotai/leecode | /初级算法/2字符串/4有效的字母异位词.py | 983 | 3.90625 | 4 | '''
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
输入: s = "anagram", t = "nagaram"
输出: true
输入: s = "rat", t = "car"
输出: false
'''
# 方法一
# 将两个字符串切片转换成list,再排序,比较是否相等
def isAnagram(s, t):
s1 = []
t1 = []
for i in range(len(s)):
s1.append(s[i])
for j in range(len(t)):
t1.append(t[j])
s1.... |
493dbf9ce7b6c053d7b56ee89ff22f9a0b5eae0b | sasuketttiit/Hacker-Rank | /treeHeight.py | 262 | 3.828125 | 4 | def utopianTree(n):
height = 0
if n == 0:
return 1
else:
for period in range(n+1):
if period % 2 == 0:
height += 1
elif period % 2 != 0:
height = height *2
return height
|
582a7593d93205ed4472db5b1f2147e9d54a459b | Suiam/coursera-python | /n_impares.py | 118 | 3.859375 | 4 | n = int (input("Digite o valor de n: "))
i=1
k=1
while i <= n:
print (k)
k = k + 2
i = i + 1
|
8c4ee451168ba17f90bd05da922828eb0a3bd401 | ymsk-sky/atcoder | /algorithm/bit.py | 102 | 3.609375 | 4 | from itertools import product
N = 3 # ビット数
for p in product((0, 1), repeat=N):
print(p)
|
1d1da21022cf9264390a5fe41752ed8b139e6f51 | rohinrajan/AWS-Web-Application-Hadoop-Kmeans | /d3Visuals/static/quizhd/mapper.py | 1,524 | 3.75 | 4 | #!/usr/bin/env python
import sys
def getmonth_column(month):
if month == 'jan':
return 8
elif month == 'feb':
return 10
elif month == 'mar':
return 12
elif month == 'apr':
return 14
elif month == 'may':
... |
009d6db1035eb8e8d845be4e241d9537892d0f71 | James-Do9/Python-Mastering-Exercises | /exercises/13-Tens_digit/app.py | 256 | 4 | 4 | #Complete the function to return the tens digit of a given interger
def tens_digit(num):
if num > 9:
new_num = num % 100
left_num = new_num //10
return left_num
#Invoke the function with any interger.
print(tens_digit(1234)) |
3e470479a6ae804f288b950b051f1c0a34b79fc3 | Sbakken21/Discord-Bot | /pgDB.py | 967 | 3.671875 | 4 | import psycopg2
import config
"""
CONNECTION TO POSTGRESQL DATABASE
"""
# PostgreSQL DB connection
conn = psycopg2.connect(
database = config.database,
user = config.user,
password = config.password,
host = config.host,
port = config.port
)
print("Connecting to database...")
cur = conn.cursor()
... |
15f21b8795ecceebaa7bcf753aacb8f270be5855 | SVMarshall/programming-challanges | /leetcode/intersection_of_two_linked_lists.py | 1,078 | 3.78125 | 4 | # https://leetcode.com/problems/intersection-of-two-linked-lists/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head... |
25a157c305c7dcc41525d8bd44d0faa306896db8 | jdogg6ms/project_euler | /p016/p16.py | 561 | 4.09375 | 4 | #!/usr/bin/env python
# Project Euler Problem #16
"""
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?
"""
def sumPower(num):
string = str(num)
return sum(map(int,[char for char in string]))
if __name__ == "__main__":
try:
... |
7d84c38880b7a8cddce824f7f0405ac05e2bfc8e | swolecoder/competitive-programming | /projectEuler+/euler009/euler9.py | 364 | 3.65625 | 4 | #!/bin/python3
def abc(n):
product = -1
for a in range(1, n // 3 + 1):
b = (n**2 - 2 * a * n) // (2 * n - 2 * a)
c = n - b - a
if (a**2 + b **2 == c**2) and (a * b * c > product):
product = a * b * c
return product
T = int(input().strip())
for _ in range(T):
... |
8416779fee766e6ad1dbbf23bc88cdd02c7a7706 | n0execution/prometheus-python | /lab5_3.py | 635 | 4.40625 | 4 | """
function for calculating superfibonacci numbers
it is a list of whole numbers with the property that,
every n term is the sum of m previous terms
super_fibonacci(2, 1) returns 1
super_fibonacci(3, 5) returns 1
super_fibonacci(8, 2) returns 21
super_fibonacci(9, 3) returns 57
"""
def super_fibonacci(n, m) :
#chec... |
2ad1caa61549dcc94e57844433377dd865d475d1 | LaurenDevrieze/Huistaken | /NSD/Code/Code/integrators/one_step_integrator.py | 1,982 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 11:05:55 2013
@author: giovanni
"""
import scipy
class OneStepIntegrator(object):
def __init__(self,ode):
"""
Initializes a forward Euler time integration object for the system of
ODEs specified by the object ode
Input:
... |
396c9e3e0d66cf21eeeec23744239f7045167c22 | eltnas/ExerciciosPythonBrasil | /02 - EstruturaDeDecisao/08.py | 503 | 4.125 | 4 | print("Dev: Elton C. Nascimento")
print("-------------------------------------")
preco1 = float(input("Preço do primeiro produto: R$ "))
preco2 = float(input("Preço do segundo produto: R$ "))
preco3 = float(input("Preço do terceiro produto: R$ "))
if preco1 < preco2 and preco1 < preco3:
print("Compre o produ... |
a20289468355632976cf6b445d0fabcb9f58c4a5 | ailuropoda0/ComplexityNetworkProject | /code/PDnode.py | 2,058 | 3.546875 | 4 | class Node:
C, D = 1, 0
T, R, P, S = 3, 1, 0, 0
def __init__(self, state: str):
"""
node object in graph. state is C or D
"""
self.state = state
self.score = 0 # will hold value calculated based on prisoners dilemma
@classmethod
def is_cooperator_state(cls,... |
b7582297bf617b8c8522896fe2578643ab943b62 | ctb/cse491-2012-examples | /jan10/prime_generator.py | 433 | 3.890625 | 4 | #! /usr/bin/env python
def divisible(i, primes):
for p in primes:
if i % p == 0:
return True
return False
def primes():
primes = []
i = 1
while 1:
i += 1
while divisible(i, primes):
i += 1
yield i
primes.append(i)
... |
e3014e547a141c26a36982f4fdb655a8e0626719 | ssiedu/python-string | /string-12.py | 292 | 4.375 | 4 | #program to print a string that capitalizes every other letter in thr string
str1="python";
length=len(str1);
print("Original String : ",str1);
str2="";
for i in range(0,length,2):
str2+=str1[i];
if i<(length-1):
str2+=str1[i+1].upper();
print("Capitalized : ",str2);
|
0450c7fcb803ba987b504866b65e2d052ef63e48 | lyndonmenezes/madlibs | /madlibs2.py | 1,517 | 4.53125 | 5 | # Easy madlibs to use. You can choose any type of sentence you want. This is just example.
# Using formatted string to concatenate.
# Variables To take an input to use on runtime
adj = input("Adjective: ")
plural_noun = input("Plural noun: ")
plural_noun2 = input("Plural noun: ")
silly_word = input("Silly word: ")
typ... |
c2b765aea188a920a1ccfa3030c72f52ab362f31 | Cieara16/ABIST440WLUKE | /Convert Decimal to Binary.py | 626 | 4.25 | 4 | #intro display message
print('Hello!')
print('This program is constructed to convert a decimal number to binary.')
print()
def Conv_Dec2Bin(decimal):
if decimal >= 1:
Conv_Dec2Bin(decimal // 2)
print(decimal % 2, end='')
#input decimal number
dec_num = int(input('Please enter a decimal number... |
47d41fe72b05419320bebb9176efd27a45668395 | dhinesh-hub/pycode-excercise | /string_reverse_in_place.py | 302 | 4.25 | 4 | def string_reverse(text):
new_str = ""
for word in text.split():
str_len = len(word) - 1
while str_len >= 0:
new_str = new_str + word[str_len]
str_len = str_len - 1
new_str = new_str + " "
return new_str
print string_reverse("hello world")
|
7426ae59ea9886abebdb5d16fd46a2279228696c | fdgd1998/python | /modules/operaciones.py | 2,672 | 3.875 | 4 | # Librería que contiene métodos referentes a operaciones matemáticas.
# Alumno: Fran Gálvez. 2º ASIR.
# generarAleatorios -> dado un parametro, genera N numeros aleatorios entre 0 y 100 y los devuleve en una lista.
# esNegativo -> verifica si un número es negativo o no.
# ordearMayorMenor -> ordena una serie de númer... |
4d9e1f7fc53198da8f3e8011c5d4df32ce1e2266 | jdheyburn/gmspotify | /test_utils.py | 2,836 | 3.6875 | 4 | import unittest
import utils
class TestUtils(unittest.TestCase):
def test_strip_str(self):
"""
Should strip a string to remove symbols and lowercase it
"""
artist = 'Walter Bishop Jr.'
expected = 'walter bishop jr'
actual = utils.strip_str(artist)
... |
ee2dff750ad328999a23c5189e0ceb1a8e509248 | lihujun101/LeetCode | /HashTable/L3_longest-substring-without-repeating-characters.py | 856 | 3.578125 | 4 | from collections import deque
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_count = 0
count = 0
s_dict = set()
s_queue = deque()
for i in range(len(s)):
if s[i] in s_dict:
... |
f011c492f4b02681382e903564efbc049bdf4034 | alphabetz/python | /mitpython/practice/prag_recursive.py | 1,424 | 3.625 | 4 | def totalDiff(senA, senB, size):
'''
Two sensor with same size of data but a little different
find the differences
'''
# first write iterative function to solve the problem
total = []
for i in range(size):
total.append(abs(senA[i] - senB[i]))
return sum(total)
# Write dispa... |
bb1f9587b54f3ef969023dd6ffd8fa6399f5a1c1 | LarissaMidori/curso_em_video | /exercicio017.py | 536 | 4.03125 | 4 | ''' Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo. Calcule e mostre o comprimento da hipotenusa. '''
from math import hypot
co = float(input('Digite o cateto oposto: '))
ca = float(input('Digite o cateto adjacente: '))
hip1 = hypot(co, ca)
hip2 = (co ** 2 + c... |
1f6459997c81faceb95b2b4987992bf973e516f2 | hy1997/Python | /PythonDemos/FormatOut.py | 778 | 3.828125 | 4 | # 格式化输出
"""
格式符号 转换
%c 字符
%s 通过str() 字符串转换来格式化
%i 有符号十进制整数
%d 有符号十进制整数
%u 无符号十进制整数
%o 八进制整数
%x 十六进制整数(小写字母)
%X 十六进制整数(大写字母)
%e 索引符号(小写'e')
%E 索引符号(大写“E”)
%f 浮点实
%g %f和%e 的简写
%G %f和%E的简写
"""
name = "小明"
print("我的名字叫%s" % name)
student_no = 1
# 我的学号是:001
print("我的学号是:%03d" % student_no)
price = 805
weigh... |
5f0c46819efc0cedde4bf9cbd2e9f28af2a75da6 | Vladimir-Novikov/python | /lesson-7/lesson_7_task_2.py | 1,252 | 3.96875 | 4 | from abc import ABC, abstractmethod
class Suit(ABC):
@abstractmethod
def __init__(self, h):
self.suit = h
@abstractmethod
def coats(self):
pass
@abstractmethod
def suits(self):
pass
class Coat(ABC):
@abstractmethod
def __init__(self, v):
self.coat = ... |
e052f6a906341a29caf4f43468c0747807a8b040 | Jae-wan/Lotto_Project-Python- | /Lotto_Calc_1.py | 1,441 | 4 | 4 | '''
1. 번호 합 범위 필터
- rand() 번호 추출 (단, 범위는 1~45까지이되, 중복은 제거)
- 일정 번호의 범위 합을 넘어서면 재 추출 (원하는 범위까지만 추출)
* 충족 조건 3가지 *
- MAX 보다 이하인가?
- MIN 보다 이상인가?
- MIN < 값 < MAX 인가?
'''
import random
print(random.randrange(1,45))
# random.randrange(start, end, step)
# start 부터 end 까지 정수 난수 생성
... |
ab5966863e24710a3a9d257cf0d488f2505f59dd | lkaae2018/Tilfaeldighedsgenerator | /andreas.py | 221 | 3.515625 | 4 | import random
def randomizerGrp():
listen = []
while(len(listen) < 8):
rnd = random.randint(1,8)
if rnd not in listen:
listen.append(rnd)
return listen
print (randomizerGrp())
|
2fa31d65f66f83435b10451022c289aadc160716 | WangsirCode/leetcode | /Python/single-number.py | 1,191 | 3.71875 | 4 | # Given an array of integers, every element appears twice except for one. Find that single one.
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
# Time: o(n)
# Space: o(1)
class Solution(object):
def singleNumber(self, nums):
"""
... |
f65b9f2092a3f0d9ef094e1cbc6b5c331c702c4e | Zahidsqldba07/coding-exercises | /Python3/regex-boot-camp/Expert-Rating/027-Same-Letter-Patterns/same_letter.py | 391 | 3.578125 | 4 | def same_letter_pattern(txt1, txt2):
if len(txt1) != len(txt2):
return False
pairs_of_elements = list(zip(txt1, txt2))
code = {}
for pair in pairs_of_elements:
if pair[0] not in code:
code[pair[0]] = pair[1]
elif pair[0] in code:
if ... |
da26cdb057f80b1783f6328132c4ee962c56f98f | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/edc55daf5e3f4cf48fbff13a180f8cd8.py | 199 | 3.765625 | 4 | from collections import Counter
def word_count(phrase):
count = Counter(phrase.split()) #splits the phrase into elements
return count #returns element and element count
|
f060b154ed386b6203f3f85cff957b329abba5eb | pk2733/hangman | /main.py | 4,834 | 3.5 | 4 | import sys
import random
import time
def hangman_screen(tries):
stages = [ # 0
"""
--------
| |
| O
| /|\
| |
| / \
|
... |
edcf33d492bfb98fc5004ac63da72eb6c13fcf68 | F-happy/pythonTest | /Solution.py | 553 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-03-26 21:35:34
# @Author : jonnyF (fuhuixiang@jonnyf.com)
# @Link : http://jonnyf.com
class Solution:
# @return a list of lists of integers
def generate(self, numRows):
res = list()
for x in xrange(numRows):
temp =... |
9d8a67879f3795e910b0aa49bea175e41011fffe | pavdmyt/py_tricks | /tricks.py | 2,262 | 3.6875 | 4 | """
My collection of Python tricks.
"""
#######################################################################
# Control flow
## 1
x = 2
result = 'greater' if x > 3 else 'less or equal'
# same as
y = 2
if y > 3:
result = 'greater'
else:
result = 'less or equal'
assert x == y, 'Control flow #1 failed!'
##... |
6b614c3a4f4a5733e6a70b66edcfd8717f6b179e | jaewon1676/beakjoon_python | /1157.py | 746 | 3.609375 | 4 | # 백준 1157 단어 공부
# 단어에서 가장 많이 사용된 알파벳을 대문자로 출력한다.
# 단, 가장 많이 사용된 알파벳이 여러 개 존재하는 경우에는 ?를 출력한다.
words = input().upper() # 문자열 입력 받고 대문자 변환
unique_words = list(set(words)) # set함수로 중복 제거
cnt_list = []
for x in unique_words:
cnt = words.count(x) # words 변수의 문자열 개수를 cnt 변수에 저장
cnt_list.append(cnt) # count 숫자를 리스트에 ... |
54789d6c4de56bdeae67a03e20df38a4ca9417ca | nomore-ly/Job | /算法与数据结构/LeetCode/二叉树(BinaryTree)/剑指 Offer 07. 重建二叉树.py | 1,212 | 4.0625 | 4 | '''
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
'''
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
'''
思路 分治法
'''
def buildTree(self, preorder: List[int], inorder: List[int]) -> Tree... |
a21cb6c6a33dbc92cf95b1f64e388275c2ed375b | vasilcovsky/pytinypng | /pytinypng/utils.py | 2,691 | 3.8125 | 4 | import os
class Enum:
"""Used to access integer constants by string code.
>>> class Color(Enum):
... RED = 1
... YELLOW = 2
... GREEN = 3
...
>>> Color.from_value("RED")
1
"""
@classmethod
def from_value(cls, value):
if value in cls.__dict__:
... |
534e6f2634036662ffc138fa33c91031dae09ba6 | thallesgomes/Curso-de-Python | /Exercícios/Exercício 061.py | 1,179 | 3.515625 | 4 | print('\n\033[1;7;30m {:=^150} \033[m\n\n'.format(' | EXERCÍCIO PYTHON 061 - PROGRESSÃO ARITMÉTICA (v2.0) | '))
# ========================================================================================================================= #
'''print('Gerador de PA')
print('-=' * 10)
primeiro = int(input('Primeiro termo: '... |
dbf3077015d9709fbe44e088e8a58bc2157fab80 | SousaPedro11/pythonProjects | /exercicio_simpples/lembra_tarefa_2000/lista_tarefas.py | 964 | 3.578125 | 4 | """
Programinha para criar uma lista de tarefas contendo no minimo 4 operações
add - adicionar tarefa
listar - listar tarefa
desf - desfazer a última tarefa
ref - refazer a última tarefa
Feito por Lívio Lopes
"""
import os
import functions
try:
os.mkdir('guarda_tarefas')
except:
pass # O diretório já existe
while... |
a6987bc7291be4a1f62239be0bd9562e7400412e | ywpark/Python3 | /STEP3/Calendar.py | 1,060 | 3.765625 | 4 | import datetime, calendar
#calendar.prmonth(2017,7)
def printCalendar(year, month):
"달력 그리기"
# index[0] : ( 0 ~ 6 , Mon ~ Sun ), index[1] : lastDays
totalDays = calendar.monthrange(userSearchYear, userSearchMonth)
currentColPos = totalDays[0] + 1 if totalDays[0] != 6 else 0
for cDaysText in custD... |
52ed6a73709e5bb8b76a6ef26f43f271b63c336b | AlphaFlagship/themetamorphosis | /Python Learning/sandwich.py | 559 | 3.75 | 4 | sand_orders = ['plain', 'cheese','pastarami','veg' ,'italian','roasted','plain','pastarami','cheese','pastarami','pastarami']
finished = []
while sand_orders:
current = sand_orders.pop()
if current == 'pastarami':
print("no pasta")
while 'pastarami' in sand_orders:
sand_orders.remove... |
ff9378a05d68c137c37cc36fa0f331b82935afc8 | ZhizhouTian/python | /2_file_open.py | 563 | 3.71875 | 4 | #!/usr/bin/python
import os
def readfile(filp):
try:
i=0
for line in filp:
print "%d\t"%i +line ,
i+=1
#print filp.fileno()
filp.close()
except IOError, e:
print 'file open error:', e
return 0
def main():
filename=raw_input("input a filename: ")
print filename
try:
if os.path.exists(file... |
9c35b949e3a7865bf6da3b887d3365933007fb37 | Thang1102/PYTHON-ZERO-TO-HERO | /Basic/Chapter2/08Conditionals.py | 525 | 3.90625 | 4 | #dieu kien
x = 15
y = 50
#if statement
if x > y:
print ('X: ' , x)
print ('Y: ' , y)
print('X lon hon Y') #Truong hop chua nhieu dong trong if
print('OK')
#if-else statement
if x > y :
print ('X: ' , x)
print ('Y: ' , y)
print ("X lon hon Y")
else:
print ('X: ' , x)
print ('Y: ' , y)
print ... |
6beed6fa23f4f2155208fbc170776154bee62c7d | jarthurj/ThinkPython | /14-4.py | 646 | 3.6875 | 4 | import os
def walk(dirname):
"""
dirname: top of directory that is being searched
"""
try:
dir_list = os.listdir(dirname)
except:
return []
files_and_dirs = []
# print(dirname)
for thing in dir_list:
print(thing)
if os.path.isfile(os.path.join(dirname, thing)):
files_and_dirs.append(thing)
else:
... |
67b786d9661e586443cd1ae654c9e28331037656 | sas342/hackerRank | /greedy/ChiefHopper.py | 731 | 3.5 | 4 | '''
https://www.hackerrank.com/challenges/chief-hopper
'''
def findMinimumEnergy(n, H):
k = 0
botEnergy = -1
start = -1
while botEnergy < 0:
start += 1
botEnergy = start
for k in xrange(n):
#find bot energy after leap to next building
if H[k] > botEn... |
df163bc00d65ec9fd5cc178970b286b9304479c8 | rutuja1302/PythonPrograms | /CountVowels/vowels.py | 492 | 4.15625 | 4 | #count vowels in a string
#good news for you is the python already has a function call count() in strings
#so we are just going to implement that
#read a string
st = input("Enter a string: ")
#lower case all the characters as the function is case sensitive
st = st.lower()
#count all the vowels and add them
countVow... |
8ab873bf51713d9e9b6bfc8c66898dc0de1fd36b | ROCKET19/Python-Beginner | /largest_num_in_a_list.py | 200 | 4.25 | 4 | numbers = [1, 2, 3, 5, 78, 34]
largest_num = numbers[0]
for count in numbers:
if count > largest_num:
largest_num = count
print(f"The Largest number in the list is {largest_num}")
|
398f6283c1465d180b201b66f9a55aa86b83ca44 | PKD667/self-game | /rock,paper,scissor.py | 1,150 | 3.53125 | 4 | import random
play = []
def player(number) :
global play
words = ("Rock", "Paper", "scissor")
word = random.choice(words)
correct = word
play.append(word)
def verifier(play) :
win = None
if play[0]== "Rock" :
if play[1] == "Rock" :
win = None
if pla... |
280a3a545328e872839de115f3c9260521d27b55 | emirju/myapps | /Requests_in_Python/POST_Requests.py | 642 | 3.65625 | 4 | ### HTTP POST requests in Python ###
import requests
url = 'https://enhktdry5i2hc.x.pipedream.net' # check here : https://requestbin.com/r/enhktdry5i2hc/1p1FnFa3mrtdnx5UpwwPwGo1RTG
r = requests.post(url)
#-------------------------------------------------------------------
payload = { # here in PAYLOAD is a ... |
ae1dd4019558aca06f42fd0b7ded75619036f473 | FrankCasanova/Python | /Funciones/293.py | 368 | 4.15625 | 4 | # implements a python procedure susch that, given an integer,
# its figures in reverse order. for exaple, if the procedure
# receives the number 324, it will display 4, 2 and 3
# (on different lines)
def reverse(n):
reverse = int(str(n)[::-1])
return reverse
def display(n):
show = str(reverse(n))
... |
465a8ddfb5d1d6a2855af9dd3dff2363fbf3676a | KingEnoch/Python-Projects | /gibberishGame.py | 4,278 | 4.21875 | 4 | #######################################################################################
# Program Description: Program that converts a word input by a user into gibberish and displays the gibberish word.
# Author: Thamsanqa Sibanda & Enoch Oppong
# Date: 07/10/2019
# Compiler: PyCharm Python 3.x
##################... |
b1953d55ee890bc17026b4466a30ad271572fadd | agupta7/COMP6700 | /softwareprocess/test/AltitudeTest.py | 3,371 | 3.65625 | 4 | import unittest
import softwareprocess.angles.Altitude as Alt
class AltitudeTest(unittest.TestCase):
def setUp(self):
self.altitudeTooLowStr = 'The altitude specified is too low! It must be greater than 0 degrees and 0.0 minutes'
self.altitudeTooHighStr = 'The altitude specified is too high! It ... |
bad9f2f1a1c3c9fff6220a3efddf0742b40e9951 | Sudo-Milin/Coursera_Crash_Course_on_Python | /Module_3/Graded_Assesment_Q03.py | 1,377 | 4.25 | 4 | ### Complete the function digits(n) that returns how many digits the number has.
# For example: 25 has 2 digits and 144 has 3 digits.
# Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
def digits(n):
# A 'count' variable is initialized, which keeps t... |
6ffe5d90248beeed6b08fa8c767eb8531690a73f | alejandrozorita/Python-Pensamiento-computacional | /clonacion.py | 127 | 3.515625 | 4 | a = [1, 2, 3]
b = a
print(a)
print(b)
print(id(a), id(b))
c = list(a)
print(c)
print(id(c))
d = a[::]
print (d)
print(id(d))
|
2c418c7ce4940830b8239bc85a8c3a30aa2dd1c2 | AniketKul/kafka-fraud-detector | /producer/transactions.py | 662 | 3.625 | 4 | from string import ascii_letters, digits
from random import choices, randint
account_chars: str = digits + ascii_letters
"""Return a random account number which consists of 15 characters"""
def create_random_account_id():
return ''.join(choices(account_chars, k=15))
"""Return a random amount between 1.00 and 500... |
44644d6b183f40ee9b274338800110715996fd75 | Elaine-gona/integration-project | /ElaineGon_Main.py | 6,955 | 4.3125 | 4 | # Elaine Gonzalez
# This_integration_project_will_showcase_all_that_I_have_learned_in_this_Spring_semester_of_COP1500
# The_main_sources_I_used_were_W3schools, Think Python 2e and HackerRank.
# I was_aided_by_Professor_Vanselow_and_Rachel_Matthews_"."
def main():
your_name = input("enter your name ")
... |
92785a4e79a79ae0092d99e25b50c0135e605a14 | Tribruin/AdventOfCode | /2015/Day14.py | 2,248 | 3.515625 | 4 | # inputFile = "/Users/rblount/OneDrive/AdventOfCode/2015/Day14-Input-Test.txt"
inputFile = "Day14-Input.txt"
totalTime = 2503
def readFile(fileName):
reindeers = list()
f = open(fileName, "r")
for line in f.readlines():
lineSplit = line.rstrip().split()
name = lineSplit[0]
speed = ... |
5aaf36d65f2c7c1dbb09cf57c4219b92bf214e2e | dawoodalo/python | /functions_task.py | 611 | 4.15625 | 4 | def check_birthdate(y,m,d):
import datetime
date_object = datetime.date.today()
past_check = date_object > check_birthdate
return past_check
def calculate_age(y,m,d):
from datetime import date
calc_year = date.today().y - y
calc_month = date.today().m - m
calc_day = date.today().d - d
print("You are %s year(s... |
577e22fdc65752dbecafb49b2d6392c2bc378b8e | sandeepkumar8713/pythonapps | /23_thirdFolder/36_bomb_enemy.py | 2,543 | 4 | 4 | # https://massivealgorithms.blogspot.com/2016/06/leetcode-361-bomb-enemy.html
# https://leetcode.com/problems/bomb-enemy/
# Question : Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0'
# (the number zero), return. the maximum enemies you can kill using one bomb.
# The bomb kills all the enemies... |
f843fcdda5bf9226d44c828edfa25d3ff9a2a702 | SiriusCraft/SiriusPlanet.Alpha | /py3_leetcode_practice/SorroundedRegion.py | 459 | 3.625 | 4 | class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
board_heigh = len(board)
board_width = len(board[0])
if __name__ == '__main__':
# test case:
board_test ... |
235a3c98408dfe655976ac28091cf22b97c96154 | busliksuslik/OverComplicatedCalc | /Overcomplicatedcalc.py | 4,044 | 3.703125 | 4 | def numberBefore(string, sym):
indexSym = string.find(sym)
numArray = []
i = 1
while True:
if indexSym - i >= 0:
if (string[indexSym - i].isdigit or string[indexSym - i] == "."):
numArray.append(string[indexSym - i])
i += 1
else:
... |
487dc936d9fe3fece6369a705bdbbbf4f8732ba6 | TairanHu/Learn-Python-The-Hard-Way | /ex20.py | 810 | 3.84375 | 4 | # -- coding: utf-8 --
# python ex20.py test.txt
#
# test.txt:
# To all the people out there.
# I say I don't like my hair.
# I need to shave it off.
from sys import argv
script, input_file = argv
def print_all(f):
print (f.read())
def rewind(f):
f.seek(0) #重新定位在文件的第0位及开始位置
def print_a_line(line_count, f):
... |
80cf00318a89f9d5c4dc7a6275e6279ff1b8896e | Hemant1-6/python-practice | /chapter 1 & 2/start.py | 952 | 4.0625 | 4 | # movies = ['"The holy grail"', 1975, '"The life of Brain"', 1979, '"The Meaning of Life"', 1983]
# print(movies)
# print(len(movies))
# movies.pop();
# print(len(movies))
# movies.insert(1,"The Marvel Avengers")
# print(movies)
# movies.extend("Black Hawk Dawn")
# print(len(movies))
# for x in movies: print(x)
# prin... |
50ac234f9b900ad7c822f73e93ab85ea18f94dce | thorn3r/sudokuSolver | /array2d.py | 470 | 3.53125 | 4 | class Array2d:
#constructor
def __init__(self, height, width):
self.rows = [None] * width
i = 0
while i < len(self.rows):
self.column = [None] * height
self.rows[i] = self.column
i += 1
def get(self, x, y):
return self.rows[x][y]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.