blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
09eeafe1cd1b4def9d15c30dff18024ed280ccbd | ketasaka/Python_study | /08.コレクション/8_3.py | 232 | 3.515625 | 4 | x = []
y = []
for i in range(10):
a = int(input("{}件目:整数値を入力 =".format(i + 1)))
if a % 2 == 0:
x += [a]
else :
y += [a]
print("偶数値リスト=",x)
print("奇数値リスト",y) |
b3b873bed6927d840166d613b1c9ad80987d5c6e | SantQC90/4to_Semestre_M_N | /Inversa_de_Matriz.py | 1,329 | 4 | 4 | # Determinar la matriz inversa de dimension 2 x 2
import sys
import numpy as np
#Pedimos datos al usuario para formar la matriz 2 x 2
x1=int(input("Digite el valor de a1,1 ->"))
y1=int(input("Digite el valor de a1,2 ->"))
x2=int(input("Digite el valor de a2,1 ->"))
y2=int(input("Digite el valor de a2,2 ->"))
#Se for... |
9b876479eef1cafb01a3003a1751c780a47db0f4 | fslaurafs/Projetos-Python | /Curso em Vídeo/exercicios/Ex028 - Jogo da Adivinhação v1/ex28.py | 568 | 3.8125 | 4 | # JOGO DA ADIVINHAÇÃO
from random import randint
from time import sleep
print("-=-" * 24)
print("Vou pensar em um número entre 0 a 5. Tente descobrir qual é o número...")
print("-=-" * 24)
n = randint(0, 5) # número escolhido pelo computador
r = int(input("Em que número estou pensando? ")) # número escolhi... |
40f150c9ddf651f84ce79a87f4c7d687bee11163 | GrigorevEv/Hello-World | /Algorithms and data structures (Python)/Q. Dictionaries and Sets in Python and Asymptotics of Standard Operations/D. Task 1 - set.py | 237 | 3.953125 | 4 | # Вывести на экран все элементы множества A, которых нет в множестве B.
A = set('bqlpzlkwehrlulsdhfliuywemrlkjhsdlfjhlzxcovt')
B = set('zmxcvnboaiyerjhbziuxdytvasenbriutsdvinjhgik')
print(A, B, sep='\n')
for x in A:
if x in B:
print(x, end=' ')
|
753f618258f4032cdebccbc171500b5e5be5d5f5 | Lucas130/leet | /offer32-levelOrder.py | 2,200 | 3.671875 | 4 | """
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder1(self, root: TreeNode) -> list[int]:
if not root:
return []
... |
ee8c5ea9c074430b682b393aa9051b73e2bf7a2f | yakuza8/peniot | /src/protocols/MQTT/mqtt_protocol.py | 2,762 | 3.546875 | 4 | from Entity.protocol import Protocol
import unittest
class MQTT(Protocol):
def __init__(self):
mqtt_definition = "MQTT is an application layer internet of things (IoT) protocol. " \
"It is mainly a messaging protocol. At the center of MQTT, there exists a central broker " \
... |
eea068c413e7aa3b947620f0eae89d88c864ba32 | uma-c/CodingProblemSolving | /BinarySearch/find_min_in_rotated_sorted_array_dups.py | 1,654 | 4.0625 | 4 | '''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
This is a follow... |
6a7eebd1b0d6bc706067abad2f23c8e38f0caeb2 | dhaipuleanurag/CourseWork | /BigData/hw2_solution/task2-b/reduce.py | 423 | 3.6875 | 4 | #!/usr/bin/python
import sys
sum = 0
#input comes from STDIN (stream data that goes to the program)
for count in sys.stdin:
try:
count = int(count)
except ValueError:
continue
sum += count
print sum
... |
76dc7a45a350448d641a0da523c9b08883eb6e77 | JoshTheBlack/Project-Euler-Solutions | /001.py | 521 | 4.25 | 4 | #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
from comm import timed
@timed
def driver(max=1000, *args):
'''Function to add up all multiples of *args less than max.'''
a... |
5eb86e32a178a1cbc36fb61f5e21b6d86f4c55d8 | xuzjun/SolutionsForProjectEuler | /p43.py | 2,351 | 3.71875 | 4 | # -*- coding: utf-8 -*-
if __name__ == '__main__':
s = 0
for one in range(1, 10):
for two in range(10):
if two == one:
continue
for three in range(10):
if three == two or three == one:
continue
for four in range(10):
if four == three or four == two \
or four == o... |
859029c4e341503c957a3bb64d997929e6ce2698 | goutham2027/project_euler | /50_consecutive_prime_sum.py | 1,941 | 4.03125 | 4 | ## problem-50 ##
## Consecutive prime sum ##
'''
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contain... |
c5eae9b5d9561d707ae072691f2a5befc2aa3322 | mavrovski/PythonPrograming | /Programming Basics - Python/06Drawing Figures with Loops/06RhombusOfStars.py | 325 | 3.875 | 4 | n = int(input())
# top side
for row in range(1,n+1):
print(" "*(n-row),end='')
print("*",end='')
print(" *"*(row-1), end='')
print()
# bottom side
for row in range(n-1,0,-1):
for col in range(n-row,0,-1):
print(" ", end='')
for col in range(1,row+1):
print("* ", end='')
pr... |
ce6c54f2f5fc5af39012632a1fb5752194af8791 | sciolizer/octopress | /source/downloads/code/yield-lambda/game.py | 1,735 | 3.515625 | 4 | import random
rgen = random.Random()
class RandomNumberGame(object):
def __init__(self, interface):
self.interface = interface
def __iter__(self):
name = yield lambda: self.interface.prompt_string(
"Greetings. What is your name? ")
yield lambda: self.interface.display(... |
ab112deabf33360979e86f15533f3c1c0448f5a6 | WSUCS665/WSU_ALDB | /main.py | 513 | 3.9375 | 4 | """
Tutorial: https://repl.it/talk/learn/How-to-create-an-SQLite3-database-in-Python-3/15755
"""
from modules.pysqllite import PySQLLite
from pprint import pprint
while True:
# Connect to a database
my_db = PySQLLite("database/WSU_AL.db")
statement = input("Please enter a statement: ")
my_db.execute(... |
31625ea2902758e0b7840d7986ec1f55f7c98cd2 | Stanwar/Udacity | /Linear_Algebra/vector.py | 4,042 | 3.65625 | 4 | import math
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = coordinates
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be ... |
2b2695f9758bf04fa0725b41b3ded63310291ee7 | svworld01/group-coding | /day0018/2_same_tree.py | 1,147 | 3.71875 | 4 | # created by KUMAR SHANU
# 2. Same Tree
# https://leetcode.com/problems/same-tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# Solution 1
class Solution:
def __ini... |
e11183cca5c09cfb6a407432be4fa765cd4af14d | maggiejjgreene/Python-Project | /m1c3.py | 2,108 | 3.609375 | 4 | # Import numpy as np
import numpy as np
# Lists
prices = [170.12, 93.29, 55.28, 145.30, 171.81, 59.50, 100.50]
earnings = [9.2, 5.31, 2.41, 5.91, 15.42, 2.51, 6.79]
# NumPy arrays
prices_array = np.array(prices)
earnings_array = np.array(earnings)
# Print the arrays
print(prices_array)
print(earnings_array)
# Creat... |
4ab88054c4b68188b8757bb8ffc90fc0f8b18537 | max180643/Pre-Programming-61 | /Onsite/Week-1/Friday/[Extra] Cola.py | 524 | 3.875 | 4 | """[Extra] Cola"""
import math as m
def main():
"""Main Function"""
can1 = convert(float(input()), float(input()))
can2 = convert(float(input()), float(input()))
can3 = convert(float(input()), float(input()))
can4 = convert(float(input()), float(input()))
can5 = convert(float(input()), f... |
b029d4cdef06248a90cf9ab639985a90fc45bccf | dastagg/bitesofpy | /104/pipe.py | 288 | 3.53125 | 4 | message = """Hello world!
We hope that you are learning a lot of Python.
Have fun with our Bites of Py.
Keep calm and code in Python!
Become a PyBites ninja!"""
def split_in_columns(message=message):
spl_msg = message.split("\n")
join_msg = "|".join(spl_msg)
return join_msg
|
eac7958f287482cbef1df6b3409c99599579fb97 | lindsaymarkward/CP1404-2016-2 | /exceptions.py | 466 | 4.25 | 4 |
# age = int(input("Age: "))
# while age < 0:
# print("Invalid age")
# age = int(input("Age: "))
#
# print("You are {} years old".format(age))
valid_age = False
while not valid_age:
try:
age = int(input("Age: "))
if age < 0:
print("Invalid age - must be non-negative")
e... |
f48de8701f99c2d29afe9c8db7a04bb3dce41549 | ulgoon/fcwps-pre | /sources/day2/list_tuple.py | 435 | 3.59375 | 4 | lang = []
lang.append("python")
lang.append("java")
lang.append("golang")
lang.append("julia")
lang.append("golang")
lang.insert(1, "c")
lang.remove("golang")
java = lang.pop(2)
# =========================
# sorting
# =========================
numbers = [2, 1, 4, 3]
print(numbers)
# numbers.sort()
# numbers.rever... |
bcb7fb6ac23daf0e432d0cd620c556974cc03980 | gregorydillon/dsi-coursework | /statistics/power-individual/individual.py | 6,173 | 3.640625 | 4 | import numpy as np
import pandas as pd
from scipy.stats import norm
import matplotlib.pylab as pl
# pl.ion()
# coke_data = np.loadtxt('data/coke_weights.txt')
coke_data = np.loadtxt('data/coke_weights_1000.txt')
def part_1():
"""
My null hyp: Coke bottle, on average, do in fact weigh null_mean ounces.
A... |
a81faf15241b1142605a0562c73b49fd736ea240 | Jacklli/Algorithm | /sort/bubblesort.py | 307 | 3.84375 | 4 | def bubble_sort(l):
for i in range(len(l),0,-1):
for j in range(len(l)-1):
if l[j] > l[j+1]:
tmp = l[j]
l[j] = l[j+1]
l[j+1] = tmp
print("result: " + str(l))
l = [2,5,8,1,878,22,125]
bubble_sort(l)
print("bubble_sort success!!!")
|
46968b5e3c6b5e976c7610dceae4f1033294c6a4 | 15cs026priyanka/kannangeetha123 | /5.py | 181 | 4.34375 | 4 | num = int(input('How many numbers: '))
total_sum = 0
for n in range(num):
numbers = float(input('Enter number : '))
total_sum += numbers
print("display the numbers")
|
635857eedd042d4cb4af8467d62cc380d5d46e23 | Ccccarson/study_python | /basic/slice.py | 666 | 3.65625 | 4 | # slice 切片
l=list(range(100))
print(l)
print(l[0:10])
print(l[-10:])
# l[0:10] 表示从索引 0 开始取,知道索引 10 为止,但不包括索引 10
# 如果第一个索引事 0 ,还可以省略
# 甚至什么都不写,只写 [:] 就可以原样复制一个list或者tuple
# 字符串‘xxx’也可以看成是一种list,每个元素就是一个字符。
# 因此,字符串也可以用切片操作,只是操作结果认识字符串
print('ABCDEFG'[:3])
def trim(l):
if l[:1]==' ':
return trim(l[1:len(l... |
6a8e426336d0ca73fdc226a4a1e2be7be1302ff8 | shouliang/Development | /Python/PyDS/sort/logn/test_quick.py | 616 | 3.96875 | 4 | def quickSort(nums):
if not nums:
return []
helper(nums, 0, len(nums) - 1)
def helper(nums, low, high):
if low >= high:
return
pivot = partition(nums, low, high)
helper(nums, low, pivot - 1)
helper(nums, pivot+1, high)
def partition(nums, low, high):
pivotValue = nums[hig... |
2d03324632f0700718be880632fa19254f7912ff | HPaulowicz/algorithmic-toolbox | /week1_programming_challenges/1_sum_of_two_digits/APlusB.py | 441 | 3.703125 | 4 | # Uses python3
# There are two ways of running this program:
# 1. Run
# python3 APlusB.py
# then enter two numbers and press ctrl-d/ctrl-z
# 2. Save two numbers to a file -- say, dataset.txt.
# Then run
# python3 APlusB.py < dataset.txt
import sys
def apb(a, b):
return a + b
if __name__ == '__main__':
... |
b462a4596f2de99dfb08afc70c56591c41ca82ea | Rishicr73/30-Days-python-project-challenge | /Day16/Numberconverstion.py | 1,620 | 4.25 | 4 | #Simple number convertion in python
def decimal_binary(num):
num = int(num)
if num >= 1:
decimal_binary(num//2)
print(num%2 , end ='') #Using recursion ,you can also use in-built function "bin"
def binary_decimal(num):
num = int(num)
decimal , i , n = 0 , 0 , 0
while num != 0:
... |
4932654ad3b9d9c917aa6f6a6389be8d0f35ac1d | dhengkt/CourseProjects | /Python/340/InClassCode/casino.py | 1,236 | 4.0625 | 4 | # In class practice on 04/08/2019
SUITS = ("spade", "club", "heart", "diamond")
NUM_CARDS_IN_SUIT = 13
class Card:
def __init__(self, value = 1, suit = None):
if value < 1 or value > NUM_CARDS_IN_SUIT:
self.__value = 1
else:
self.__value = value
if suit not in SUIT... |
b608aa6b509f05a7bf8a09df0b03f6a98907588e | fukkyy/python-algorithm | /stack.py | 716 | 4.09375 | 4 | #! /usr/local/bin/python
# -*- coding:utf-8 -*-
class stack:
def __init__(self,data=[]):
self.data=data
def stack_empty(self):
if len(self.data)==0:
return True
else:
return False
def push(self,x):
self.data.append(x)
def pop(self):
... |
3ede2bef06333b01fb7f06ec18bbd987bc5e1e54 | RafelQC/practicaPython | /OOP/coche.py | 1,450 | 3.78125 | 4 | class coche():
def __init__(self): #CONSTRUCTOR definimos los estados iniciales de los objetos creados, más adelante pueden ser modificados
self.__largoChasis=250
self.__anchoChasis=120
self.__ruedas=4 #con las "__" no se pueden modificar estas variables desde fuera del objeto (ENCAPSULADO)
self.__enmarcha=F... |
eb8944e2c093535fe0bd250e0c3a92a58265c993 | LKHUUU/SZU_Learning_Resource | /计算机与软件学院/Python程序设计/实验/实验7/problem5.py | 723 | 3.5625 | 4 | class China:
def __init__(self, given, family):
self.given = given
self.family = family
def __str__(self):
return self.given + ' ' + self.family + '\n' + self.get_description()
def get_description(self):
return 'From China'
def execute(self):
print(self.f... |
16663dc0456afa53af7cc91ca7ff1bd550da993e | DANUSHRAJ/Skillrack-Daily-Challenge-And-Daily-Test | /Shuffling Cards.py | 1,547 | 3.90625 | 4 | Shuffling Cards
The program must accept two integers N and T as the input. The
integer N represents the number of cards in a deck, which are
numbered from 1 to N (the value of N is always even). A boy shuffles
the cards T times based on the following conditions.
- The boy divides the deck of cards into two equal h... |
4f85b80abafc90a8fe7d9eb76ca9a7950ab2c554 | mustafayb/py-snippets | /sysStdin.py | 375 | 4.03125 | 4 | #!/usr/bin/python3
import sys
if sys.stdin.isatty(): # the isatty method checks if input is from a terminal
print('Interactively reading data')
print('Press ^D (ctrl-d) to end input')
data = sys.stdin.readlines() # list of lines of text
data.reverse() # reverse the order of the lines
for line in data:
pri... |
18972de4ad31d5db5ac5c9d20c2781e67691e2a4 | Mells/Preprocess03 | /O3_extract_sentences_from_corpus/O3_3_calculate_learner_score.py | 6,815 | 3.625 | 4 | import ast
from lxml import etree as et
import csv
lemma_chap_book_pos_dict = {}
# ------------------------------------- LEARNER COMPREHENSION POINTS -------------------------------------
# Compute how much of the sentence is comprehensive to the learner
def contains_learned_words(m_sentence, m_chapter, m_book):
... |
9becd0367157a3f94f08510b83666c4e3ac281c9 | krisKKKb/tura | /auto.py | 476 | 4 | 4 | name = str(input("Mis on sinu nimi?: "))
x = name.capitalize()
print("Tere " + x)
location = str(input("Mis on sinu elukoht?: "))
y = location.capitalize()
if location == "Saaremaa" or location == "saaremaa":
print(y + " on lahe koht")
age = int(input("Kui vana sa oled: "))
if age>18:
print("Sa või... |
f80bf5d11317162d2d26bda944819e3be7a30821 | timmy61109/Introduction-to-Programming-Using-Python | /examples/PassTwoDimensionalList.py | 716 | 4.5 | 4 | def getMatrix():
matrix = [] # Create an empty list
numberOfRows = eval(input("Enter the number of rows: "))
numberOfColumns = eval(input("Enter the number of columns: "))
for row in range(numberOfRows):
matrix.append([]) # Add an empty new row
for column in range(numberOfColumns):
... |
787922e522480b12c7fbc63ea55c1c51b6b2212f | quirogaluistomas/PythonTest | /ExpresionesRegularesII.py | 774 | 3.890625 | 4 | import re
lista_nombres = ["Ana Gomez", "María Martín",
"Sandra López", "Santiago Martín",
"niños", "niñas"]
for elemento in lista_nombres:
if re.findall("^Sandra", elemento): #^Busca en los elementos que comienzan con lo que sigue al simbolo
print(elemento)
for element... |
0a965c37151d3140b1298c467e28faa9ea076460 | MohamadRezaSafari/MatPlotLib | /scatter.py | 223 | 3.59375 | 4 | import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8]
y = [2,4,3,2,5,3,4,2]
plt.scatter(x, y, label = 'test', color = 'red', s=100, marker='*')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sample')
plt.show()
|
e90a1e986d7f3e544a4ce07ca5666f16fb7f0b91 | jonathan-sarmento/angry-cats-projeto | /relogio.py | 486 | 3.6875 | 4 | class Relogio:
def __init__(self):
self.horas = 7
self.minutos = 0
def __str__(self): # Pesquisar significado dessa função especifica.
return f"{self.horas:02d}:{self.minutos:02d}"
def Tempogasto(self, minutos):
self.minutos += minutos
while(self.minutos >= 60):... |
1d32e222b09b8123e10de9ee8a8f47944c906200 | jrzingel/general-programs | /memory/learn-spelling.py | 7,958 | 3.75 | 4 | #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
# Code taken and adapted from memory.py
import random
import os
import time
import sys
# Constants
DEFAULT_SPLITTER = ' '
MY_DIR = os.path.realpath(os.path.dirname(__file__))
DICTIONARIES_DIR = os.path.join(MY_DIR, 'dictionaries')
COMMAND = 'python3 ' + ... |
df296e58317c7df9c623fa651295f4b4fd936558 | maxwbuckley/AnalyticsResearchProgrammingAssignment | /location_planning.py | 5,707 | 3.84375 | 4 | #! /usr/bin/python
"""This script is for the UCD MSc. Business Analytics, specifically the
Analytics Research modules programming assignment. It opens a database
connection and reads the data out of it into relevant data structures. It
then checks the distance between all possible pairs of Plant and Port,
r... |
c9b1eb1bfb664a22b8e06b4561ef12eef75e8c2b | Pheewuh/Blackjack | /Blackjack.py | 1,804 | 3.65625 | 4 | import random
class Deck():
def __init__(self):
self.Suits=['Hearts','Spades','Diamonds','Clubs']
self.Ranks={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'Jack':10,'Queen':10,'King':10,'Ace':10}
self.Cards=[]
self.Myhand=0
self.PChand=0
for i in self.Suit... |
4b7291774f08ecc09e9617482f84c4e12fc13da2 | forzen-fish/python-notes | /5.函数/随机函数.py | 248 | 3.828125 | 4 | """
随机函数
导入随机函数: import random
random.random():返回0与1之间的随机浮点数N
random.uniform(a,b):返回ab之间的随机浮点数,ab可以位置不同
random.reanint(a,b):整数随机
其他的应该也用不到
""" |
7e287ae491500e1568104e84be028ee0c4a7b7ab | sswest/leetcode | /19_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.py | 934 | 3.703125 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def list_to_node(nums: list) -> ListNode:
"""从列表构建链表"""
dummy = ListNode()
node = dummy
for n in nums:
node.next = ListNode(n)
node = node.next
return dummy.next
def node_to_... |
3a2b76f9846c9f9f54313135db1fa6dcbff1c537 | jasapluscom/PYTHON | /JASAPLUS.COM TRAINING MATERIALS/trik/argument_sample.py | 352 | 4.25 | 4 | #!/usr/bin/env python3
'''
sample argument processing demo
for python3 course at jasaplus.com
'''
import sys
print("\n\tType of sys.argv : " , type(sys.argv))
print("\n\tLength of sys.argv : ", len(sys.argv))
print("\n\tPrinting each argument :")
i = 0
for x in sys.argv:
print("\n\tsys.argv[" + str(i).strip() + "]... |
2eab387d27f14bbbaf05a9315c78c7fc9412fbea | petre061/Machine-Learning-Course | /Manipulating DataFrames/Dropping rows and columns.py | 1,647 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 7 11:20:00 2020
@author: acer
"""
#Drop rows based on if there are duplicate rows
#Confine our search for duplicates on certain columns
#Drop distinct columns or rows, and using it in a loop
import pandas as pd
import numpy as np #Nan
#data = {"Part 1":[... |
420a26345362e2e74f783b8281c6a2ffdc124bf2 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/codeabbey/_Python_Problem_Solving-master/BMI_Calculator.py | 567 | 3.53125 | 4 | ___ BMI_calculator
num_of_people = i..(input
result # list
___ i __ r..(0, num_of_people
weight,height i.. ).s..
BMI i.. ?/(f__(height)**2)
__ BMI < 18.5:
result.a..('under')
____ BMI >_ 18.5 a.. BMI < 25.0:
result.a..('normal')
... |
e35189f0d9969dc8ca56c64f5c9989ba2cba3371 | jlant/web-development | /lesson-02/play/play.py | 2,772 | 3.5 | 4 | import webapp2
import cgi
form = """
<form method="post">
What is your birthday?
<br>
<label>
Month
<input type="text" name="month" value={month}>
</label>
<label>
Day
<input type="text" name="day" value={day}>
</label>
<label>
Year
<input ... |
fbc488bac510e5d3ac316b7bbf2bd434f5ee433d | abdulrafaykhan/Bus-Booking-Bot | /modules/populate_json_file.py | 2,699 | 3.53125 | 4 | ##########################################
##########################################
## ##
## This file populates the some.json ##
## files which contains the credentials ##
## such as username, password, the API ##
## endpoints. This will half be auto- ##
## -matic and half ... |
bacd148d2b50c1041b2aa84e93466580ff982021 | dundunmao/lint_leet | /mycode/lintcode/Binary Search/non_586_sqrtx-ii.py | 315 | 3.75 | 4 | # coding:utf-8
# Implement double sqrt(double x) and x >= 0.
#
# Compute and return the square root of x.
#
# 注意事项
#
# You do not care about the accuracy of the result, we will help you to output results.
#
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# Given n = 2 return 1.41421356 |
980152f0843f010aeba4396ddd85dec17731e3c3 | tattudc/pythonestudos | /introdução à programação com Python/aumento salárial.py | 456 | 3.921875 | 4 | #Aumento de salário
#Programa que mostra o salário atual e multiplica pelo seu aumento
salario = float(input("Digite seu salário atual "))
aumento = float(input("Digite quanto vai ser seu aumento "))
calcaumento = salario + ((salario * aumento)/100)
print("-"*20)
print("Seu salário é de R${}".format(salario))
print("O ... |
5364b2080569eb7931336dbb7a64b330cfaaf813 | timManas/Practice | /Python/project/src/Lists/FindCommonCharacters/FindCommonCharacters.py | 2,849 | 3.765625 | 4 | class Solution(object):
def commonChars(self, inputArr):
# Step1 - Set the output Variable
output = []
commonCharDict = {} # This is the main Dictionary to keep track of all common letters
# Step2 - Traverse all words in input Arrat
for word in inputArr:
... |
b95fa63287cde54c84882cc927fb874206817305 | jobaamos/gap-year-club-code | /AMOS37.py | 183 | 4.25 | 4 | #python program to sum up the factorial of a number
num=int(input('enter a number'))
fac=1
fac_sum=0
for i in range(1, num+1):
fac=fac*i
fac_sum+=fac*1
print(fac_sum)
|
213542d5f9dba8ea6cf008646415b87873c3ce2e | yuansiang/cpy5python | /practical02/q04_determine_leap_year.py | 297 | 4.03125 | 4 | #filename: q04_determine_leap_year.py
#author: Yuan Siang
#created: 3/2/13
#modified: -
#description: Determine leap year
#Practical 02 Q4
#main
#prompt for year
yr = int(input("Enter year: "))
#check if yr is divisible by 4
if (yr%4==0):
#print results
print("Leap")
else:
print("Non-Leap")
|
b7347a7361dc7a9d3dbe98ed1f068c70be714ef2 | mahatmadanu/hackerrank | /Problem Solving/Implementation/Angry Professor.py | 287 | 3.609375 | 4 | def angryProfessor(k, a):
# Complete this function
sizeOfA = len(a)
i = 0
inClass = 0
cancelOrNo = "YES"
while i < sizeOfA:
if a[i] <= 0:
inClass += 1
i += 1
if inClass >= k:
cancelOrNo = "NO"
return cancelOrNo |
6efd409ca83e552fba37f5fa51ce815f6c969be2 | prasadbylapudi/PythonProgramming | /python tricks/Else with a for loop.py | 125 | 3.859375 | 4 | a = [1, 2, 3]
for x in a:
if x > 2:
break
print("Number: ", x)
else:
print("I did not break out")
|
14d2493b3d0cfc05e66991b3d425b3686d5721ab | richardvecsey/python-basics | /045-upper.py | 376 | 4.4375 | 4 | """
Return uppercase version of a string
------------------------------------
Input: (string) any string
Output: (string) uppercase version of input string
"""
original_string = 'This is an "A" letter.'
modified_string = original_string.upper()
print(' original string: {}\nuppercase versio... |
492748ff27615f3507c82fa264f8ee195ac7e4e3 | Souji9533/Mycode | /python/whielloop1.py | 275 | 3.578125 | 4 | #i=10
#i= i%2
#while i<20:
# while i<=12:
# print("finally soujanya is in good position")
#for i in range(1,50):
#if i<50:
#i=i*i
#print(i)
#if i>=50:
#break
#i=50
for i in range (1,50):
if i%3!=0 and i%5 !=0 :
print(i) |
7eb46b27ca7c67e20d86294dfda6f2d1b123b20e | flkt-crnpio/algorithms-exercises | /bubble-sort.py | 256 | 4.03125 | 4 | #
def bubbleSort(arr):
for i in range(len(arr)):
for j in range(0, len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
arr = [5,1,4,2,8]
ordered = bubbleSort(arr)
print(ordered)
|
9a117fdc0d6f71706e877743891aab9751be94cd | Mahedi522/Python_basic | /29_Way_of_create_array.py | 607 | 3.625 | 4 | from numpy import *
# 6 Way
# array()
arr = array([1, 2, 3, 4, 5])
print(arr)
print(arr.dtype)
# linspace() # devide into how many parts #gap between 2 element is fixed
arr1 = linspace(0, 16, 3) # By default part is 50
print(arr1)
# arange() # skip steps
arr2 = arange(1, 16, 2) # steps skip steps
print(ar... |
7c597bf7d89af35b7155aba116a19f9dbca3103f | LanzAdreanYap/Python_Solution_Problem_5_YAP-MERCADO | /YAP-MERCADO_Problem_5_Python.py | 1,670 | 4.15625 | 4 | import matplotlib.pyplot as p
from math import *
# Enter a user-input equation for x(n)
X = input("Enter an equation for x(n): ")
# create a function that will evaluate x(n), which is the user input X, for every n called
def x(n):
return eval(X)
# Create a function that will evaluate y(n) with conditions... |
8efa19c66be284a3912e42f02ccdc99650040573 | dairycode/Python-language | /05_高级数据类型/hm_08_格式化字符串.py | 282 | 3.546875 | 4 | info_tuple = ("小明", 21, 1.85)
# 格式化字符串后面的'()'本质上就是元祖
# print("%s 年龄是 %d 身高是 %.2f" % ("小明", 18, 1.75))
print("%s 年龄是 %d 身高是 %.2f" % info_tuple)
info_str = "%s 年龄是 %d 身高是 %.2f" % info_tuple
print(info_str) |
01c87e490de1a0df49f82e23efd07e1e503d4599 | smartinsert/CodingProblem | /interview_bit_amazon/dynamic_programming/longest_increasing_subsequence.py | 2,243 | 4.25 | 4 | """
Given a number sequence, find the length of its Longest Increasing Subsequence (LIS).
In an increasing subsequence, all the elements are in increasing order (from lowest to highest).
"""
def longest_increasing_subsequence(arr):
if len(arr) == 0:
return 0
return longest_increasing_subsequence_util(... |
caa069b297917754c5b76484dec1df3de655e2b4 | Dinosurr/nackademinlabb | /funcs/1.3.1.py | 238 | 3.9375 | 4 | uInput = int(input("insert number"))
if uInput <= 5:
for item in range(0, uInput):
num = str(uInput)
num = num * uInput
print(num)
elif uInput > 5:
num = str(uInput)
num = num * uInput
print(num)
|
005c0748f8fb4c155a702618e949610cb28c1d3c | mflix21/BasicCode | /all_kinds_of_loop.py | 8,078 | 4.5 | 4 | """
Loop:
There are two kinds of loops used in python (i) while loops (ii) for loops
(i) while loops: we are going to show (a) only while loops, (b) while loops with break, (c) while loops with continue
(a). example of only while loops:
01. print 1 to 10 using only while loops
i = 1
while i <= 10:
# print(i)
... |
b447f6804b1aaf41f103aa9b75afd2814c207163 | Jethet/Practice-more | /small-projects/inverseRandNum.py | 720 | 4.21875 | 4 | import random
# instead of the computer generating a random number, the user is giving the number
def computer_guess(x):
low = 1
high = x
feedback = ""
while feedback != "c":
# you cannot have low and high be the same:
if low != high:
guess = random.randint(low, high)
... |
70d8a528a99c1599b955146f76a6c9db09b9f3e8 | TarunVenkataRamesh-0515/19A91A0515_IICSEA_IVSEM_PYTHONLAB_1_TO_3 | /distance.py | 368 | 4.125 | 4 | """
Implement a python script to compute
distance between two points taking inp from the user (Pythagorean Theorem)
"""
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance ... |
1cbc86a14319f79455710d65a7054599530fd3da | everythingProgrammer/Python | /Project1_calculator.py | 2,275 | 3.796875 | 4 | import tkinter as tk
mainWindow = tk.Tk()
mainWindow.title("Sample Window")
First_Label = tk.Label(mainWindow, text= "Parameter1 ",pady = (10))
First_Label.pack()
para1 = tk.Entry(mainWindow)
para1.pack()
Second_Label = tk.Label(mainWindow, text= "Parameter2 ", pady = (10))
Second_Label.pack()
para2 = tk.Entry(mainWi... |
881c9d6504da6932952ceb43887c8158cdf88490 | griever255/CompSci_Python_6.0001 | /Lec4/finger_exercises.py | 1,522 | 3.796875 | 4 | # ## Write a function isIn that:
# # Accepts two strings as inputs
# # Returns True if either string occurs anywhere in the other,
# # otherwise returns False
# def isIn(str_a, str_b):
# """
# Compares two strings.
# Returns True if either string is in the other, False otherwise
# """
# if str_a in... |
12a477dcf9cb21802012375af1f77fef3c03e131 | toki888/MyTutorial | /Begining_Python/Chapter8_Exception/Chapter8_exception.py | 401 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def mydiv (x,y):
try:
return x/y
except (ZeroDivisionError) as e:
print ( "The second number can't be zero!" )
print ( e )
return None
x=4;y=0
#print ( mydiv(x,y) )
try:
4/10
except (ZeroDivisionError) as e:
print ( e )
class... |
8bb4cb58faf57cd647fd1c5ad7c5aa66070f936c | fwk1010/python-learn | /stringType.py | 720 | 4.46875 | 4 | #!/usr/bin/env python3
'''
This file is to learn about string type more detail.
'''
# Get length
s1 = "hello,world"
print(len(s1))
# Get substring
print(s1[0])
print(s1[0:2])
# format
print("hi,I love %s" % ("python!"))
''' some helpful string operate functions '''
# upper and lower
s2 = "hi,HI"
print(s2.upper())
... |
2bf5d12c930bf619f3986873492fe2dd945d9765 | manishjain79/regular_expression | /13_regex_Non_Capturing_Group.py | 2,965 | 3.984375 | 4 | import re
string = '1234 9876'
match = re.findall('((\d)+)', string)
# print(match)
# output is: [('1234', '4'), ('9876', '6')]
# It printed out bigger group of first match and then final occurrence of smaller group. And same for second match.
#
# You do not get confuse. Remember that findall() method would have captur... |
cc8d746374ba0e0013ace4411abee19212f0e89c | Hamng/hamnguyen-sources | /python/validate_floating_point.py | 1,449 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 10:42:27 2019
@author: Ham
HackerRanch Challenge: Detect Floating Point Number
Task
You are given a string N.
Your task is to verify that N is a floating point number.
In this task, a valid float number must satisfy
all of the following requirements:
... |
79747c7021455fccd25b76a98e00d2189f9e1b9e | bjmcminn/udacity | /lastfm1.py | 1,164 | 3.734375 | 4 | import json
import requests
def api_get_request(url):
# In this exercise, you want to call the last.fm API to get a list of the
# top artists in Spain.
#
# Once you've done this, return the name of the number 1 top artist in Spain.
topartist = "joe"
data = requests.get(url).text
data = jso... |
7a182c2595cf434babe490f8af0d7823b8902ca8 | besteffects/Python_tutorials | /week3_bool_examples..py | 1,024 | 3.515625 | 4 | Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 3<4
True
>>> 3>5
False
>>> 8>3
True
>>> 3.5 >3.4
True
>>> 7==7
True
>>> 7==7.0
True
>>> x=7
>>> y=8
>>> x==y
False
>>> x==7
True
>>> 3!=4
True
>>> grade=80
... |
d300183790983f33a33900e1a33df353b69c1e8a | dangconnie/python101 | /dictionary_exercises.py | 3,694 | 4.6875 | 5 | # # Exercise 1
# # Given the following dictionary, representing a mapping from names to phone numbers:
# phonebook_dict = {
# 'Alice': '703-493-1834',
# 'Bob': '857-384-1234',
# 'Elizabeth': '484-584-2923'
# }
# # Write code to do the following:
# # Print Elizabeth's phone number.
# print phonebook_dict["Eliza... |
a9ef0dc620afcedc689ad38d9ad5d1231507d539 | vaibhavvarunkar/DSA | /singlyLinkedList.py | 3,317 | 4.125 | 4 | # Node class for creatring node
class Node:
def __init__(self, data):
self.data = data
self.ref = None
# Insert operatoins
# at the beginning
# at the end
# between nodes after and before certain node
# class for creating a linked list
class LinkedList:
def __init__(self):
self.hea... |
ea998096c616c95acf19df4cbdbae5edd93d568a | soumyarooproy/leetcode_solutions | /code/python/median-of-two-sorted-arrays.py | 1,816 | 3.5 | 4 | class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
# Ensure that nums1 is NOT the longer of the two arrays
if len(nums1) > len(nums2):
nums1, nums2 = nums2, n... |
b4605a1a6a51e1bb58882bf0d134c44f5a667d5e | linkjavier/holbertonschool-machine_learning | /math/0x03-probability/binomial.py | 2,670 | 4.1875 | 4 | #!/usr/bin/env python3
""" Initialize Binomial """
class Binomial:
"""Class Binomial that represents a binomial distribution"""
def __init__(self, data=None, n=1, p=0.5):
"""Class constructor"""
if data is not None:
n, p = self.calculate_n_p(data)
self.n = n
self.... |
065154b875ef6839a2ce3f82684acdb9fd91eb11 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Basic - Part-II/program-35.py | 908 | 4.0625 | 4 | #!/usr/bin/env python3
#################################################################################
# #
# Program purpose: Finds the solution to simultaneous equation. #
# Program Author : Happi Yvan <ivensteinpok... |
b5c54ea639d4c04af8a8cf193c8a79532f0a722b | Yingglish/python_Learning | /基础/文件和异常/write_message.py | 303 | 3.59375 | 4 | with open('programming.txt','w') as file_object:
file_object.write("I love programming")
print(file_object.writable())
# 文件不存在,自动创建 ,文件存在将清空原文件内容进行写入,若要在源文件的内容下继续写入,将mode参数改为`a`,eg: open('fileName', 'a' )
|
d66a3d74150be882f1b94d66f266be63a5e7bbf8 | nmkmms/word_generator | /word_generator.py | 2,645 | 4.0625 | 4 | """Word generator using Markov chain algorithm."""
import sys
import random
from string import ascii_lowercase as letters
from collections import defaultdict
# -------------------------------------------------------
# USER INPUT:
# dictionary file to compare:
DICT_FILE = 'dictionary.txt'
# number of words to generate... |
ea838b14e4889a28e02da5dd5707f9bc56a35017 | bordils/crateGTFS | /main.py | 4,254 | 3.5625 | 4 | '''
First crate and auxiliary functions are called.
Then the client connection is set.
Next, tables are created in the DB.
After that, data to be uploaded is parsed into a tuple containing:
a string with the name of the database
a list of lists containing each line a list of elements
Auxiliar parse operations ... |
b5bd354b0819087929074886d4d19559157b210b | deesaw/PythonD-04 | /Exception Handling/53_raiseExcept.py | 380 | 3.75 | 4 | #Custom class
class Custom_error(BaseException):
pass
try:
print("hello")
raise Custom_error
print("world")
except Custom_error:
print("found it not stopping now")
print("im outside")
try:
a = int(input("Enter a positive integer value: "))
if a <= 0:
raise ValueError("This is not a... |
fee3f954c067fb6e31c1902bbad12b6e03e55cf6 | AlexanderIvanofff/Python-Fundamentals | /regular expressions/mirror_words.py | 611 | 3.875 | 4 | import re
pattern = r"(#|@)([a-zA-z]{3,})\1{2}([a-zA-Z]{3,})\1"
string = input()
matches = re.finditer(pattern, string)
full_mach = []
mirrors = []
for mach in matches:
full_mach.append(mach[0])
if mach.group(2) == mach.group(3)[::-1]:
full_maching = mach.group(2) + ' ' + '<=>' + ' ' + mach.group(3... |
7fe257db30600e33ccd1b6c1ba489766d080803c | chrisjdavie/project_euler_python | /maximum_path_sum.py | 956 | 3.5 | 4 | from collections import defaultdict
def memoi_twod(orig_func):
def replace(array, i, j):
if not hasattr(replace, "memoi_array") or replace.base_array is not array:
replace.memoi_array = defaultdict(lambda: defaultdict(lambda: None))
replace.base_array = array
... |
bc901ba2f17759cf0e9de9bbc36e544cd19b37e3 | unsortedtosorted/elgoog | /medium/string/countSubstrings.py | 882 | 3.875 | 4 | """
647. Palindromic Substrings
1. Given a string find the number of palindromic substrings.
2. If string is length of N, then there are 2*N-1 centre
3. for each centre check if left == right , if yes, its a palindrome
4. the left and right will follow this pattern:
00
01
11
12
22
23
...
... |
f9761cc288a13785a20b602f2477bc22213fe464 | lucky1506/PyProject | /item6_katie.py | 1,191 | 4.21875 | 4 |
def print_all(file_to_print):
""" Print entire file row-by-row. User chooses to display 20 records at a time or print the entire file."""
with open(file_to_print) as student_records:
student_records.readline() # skip header of txt file
print('_'*60)
print('')
header = 'STUDENT ... |
5e8edb81dbef44910e43a4d0c9d027a81fa22f55 | joetomjob/PythonProjects | /src/Sem1/drawAntennaPart2.py | 1,234 | 3.578125 | 4 | import turtle as t
def drawleft(len):
t.fd(len)
t.left(90)
def drawright(len):
t.fd(len)
t.right(90)
def penupdown(n):
if n > 1:
t.up()
else:
t.down()
def drawAntennaP2(order,size):
t.speed(0)
print(order)
if order == 0:
return
else:
drawAntenn... |
557550a1df24a439ac1cdb898afaf43d1d5bbdb9 | yash399/CS-Homework | /Practical_Assignment#4.py | 2,019 | 3.890625 | 4 | '''# QUESTION 1
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
spl_char = ['~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '... |
c5682bd6eca8441f7686e87ef1f8fad5d5926bd8 | wsvoboda/digitalcrafts-03-2021 | /week1/day4/functions.py | 2,458 | 4.21875 | 4 | # print(1 + 3) #shows 4 on terminal
# def used to define a function
# need a name, parentheses, and a colon :
# you need a return statement in the body of the function (indented)
# def add(number1, number2):
# return print(number1 + number2) #can put print here or write it when function is called
# def addAgain... |
ca31839fc6abe8083f68387acbccf4f67814245d | tatiana-ediger/ds4400-code | /homework1/lr-closed-form.py | 1,526 | 3.984375 | 4 | import numpy as np
import matplotlib.pyplot as plt
# The given training data for this model.
training = [(0.1, 0.15), (0.5, 0.4), (0.9, 0.85), (1.5, 1.62), (-0.2, -0.17), (-0.5, -0.42)]
# Finds and returns the value of theta using the closed form solution when given training data.
# The closed form solution is: (((X... |
c59125f159e007f8b2cb5b946aa29ffd828030c0 | VladimirGl/junction2016 | /device/rpi/button.py | 911 | 3.5 | 4 | import RPi.GPIO as GPIO
import time
import threading
class Button(threading.Thread):
def __init__(self, pin, c1, callbackReleased):
threading.Thread.__init__(self)
self.name = "buzzModule"
self.pin = pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
self.state = GPIO.input... |
f979c07d9a4c8deccc1935aa49176f859053ee08 | lleon95/nsc-image-converter | /nsc/img/tiff2png.py | 1,626 | 3.546875 | 4 | #!/usr/bin/env python3
"""
.. module:: tiff2png
:synopsis: Converts from TIFF in 12 bits to PNG
.. moduleauthor:: Luis G. Leon Vega <luis@luisleon.me>
"""
import argparse
import cv2 as cv
import numpy as np
def name_change(input_path):
splitted_name = input_path.split('.tif')
output_name = ''
if len(... |
269d7b75c34ea7a94d34429ad45a706669cabe9b | rahulagarwal86/ShareAnalysis | /share_analysis.py | 1,614 | 3.859375 | 4 | import csv
import os
from collections import OrderedDict
import unittest
#Function to find max share price for each company with year and month details
def get_share_data(file_path=None):
if not file_path:
file_path = raw_input("\nEnter your file path: ")
#File Validation Check
#1. Check i... |
bd488c3585dbf1e3dfd83170624920ba2164ba65 | PrakarshBhardwaj/Automate-The-Boring-Stuff | /APIs/iptracker.py | 570 | 3.53125 | 4 | import json , sys , pprint
import requests
if len(sys.argv) < 2:
print("Usage: python ipstack.py <ip address>")
sys.exit()
url = "http://api.ipstack.com/{}?access_key=your_key".format(sys.argv[1])
response = requests.get(url)
response.raise_for_status()
ipdata = json.loads(response.text)
try:
... |
85bf6b5b23714db1f11545b50524a057ba27c07f | audreyandoy/Python2CampWarm-Up | /main.py | 634 | 4.5625 | 5 | # 1) create a variable called x and assign its value to 10.
# x = 10
# 2) Print out that variable to the compile
# print(x)
# 3) Create a variable that asks for user's name via input
# name = input("What is your name?")
# print(name)
# 4) Have a user enter a number, if the number is greater than 10, print "the number ... |
ef09b0574fa017b654890f6d5d36935dab1e8627 | robertvandeneynde/parascolaire-students | /2 Noah/ex3.py | 178 | 3.734375 | 4 | a=2
b=6
c=1
if a<b<c:
print(a)
if a<c<b:
print(a)
if b<a<c:
print(a)
if b<c<a:
print(b)
if c<a<b:
print(c)
if c<b<a:
print(c)
|
b7db5df6f4a3fb1d2db0fc89f9f5e5d76570dc96 | lsl12345/python-lsl | /day-1.py | 5,105 | 3.984375 | 4 | # 练习
# --------------------------------------------------------------------------
# a = float(input('请输入'))
# b = float(input('请输入另一个'))
# print('%.2f - %.2f =%.2f'%(a,b,a-b))
# F = float(input('输入华氏度'))
# C = (F-32)/1.8
# print('%.2f 摄氏度'%C)
# year = int (input ('请输入一个年份:>>'))
# if(year % 4 == 0 a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.