blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
88e8a541384d5011d840f7ed7745897a0a98b317 | prabhupavitra/NumPy-Guide-for-Data-Science | /pyFiles/NumPyCodeFiles_Basic Array Manipulation.py | 11,449 | 3.671875 | 4 | # Importing required libraries
import numpy as np
from datetime import datetime
import matplotlib.pylab as plt
# Creating 1D, 2D and 3D arrays
# One-Dimensional Array
one_dim_array = np.random.randint(12, size=7)
# Two-Dimensional Array
two_dim_array = np.array([["Cupcake","Donut"],
["Eclai... |
d338e529b9a38f19cefceb736106ce5c09b9b6f6 | sean7130/pseudo-encryption-toys | /solitaireEncryptionFinal/chiper_cli.py | 1,850 | 3.578125 | 4 | import sys
import argparse
import chiper
from generateKeyStream import generate_keystream
parser = argparse.ArgumentParser(description='Encrpyt or decrypt using a (simulated) deck of cards')
parser.add_argument('--verbose', "-v", action='store_true', help='verbose mode')
parser.add_argument('mode', choices=["e", "encr... |
d9560432ec966b017ec8790bca44002d1f4aef4c | SanjibM99/sorting | /mergesort .py | 807 | 3.859375 | 4 | def mergesort(arr):
if len(arr)>1:
mid=len(arr)//2
#print(arr[mid])
lefthalf=arr[:mid]
righthalf=arr[mid:]
#print(lefthalf,righthalf)
mergesort(lefthalf)
mergesort(righthalf)
i=j=k=0
while i<len(lefthalf) and j<len(lefthalf):
... |
122df6cd441049257b3ac6dde2c4664335d507d0 | Aashray24092000/programmingpython | /PartV_ToolsTechniques/datastructures_lib/sort.py | 970 | 3.515625 | 4 | def sort(list, field):
res = []
for x in list:
i = 0
for y in res:
if x[field] <= y[field]:
break
i += 1
res[i:i] = [x]
return res
def sort_generic(sequence, func=(lambda x,y: x <= y)):
res = sequence[:0]
for j in range(len(sequence)):... |
e5feb9d5ea514583b80c2df2c61e76158929c81f | zrjaa1/Berkeley-CS9H-Projects | /Project2B_Basic web programming/find_all.py | 583 | 4.3125 | 4 | # Function Name: find_all
# Function Description: In a string, find the position of all the substrings.
# Function Input:
# -a_str: the string's name
# -sub: sub string that we are searching for
# Function Output:
# -a list that record all the start indexs of the sub string.
import string
def find_all(a_str, sub)... |
c27f36149a3209128032cc147e3159d67d57a394 | GalyaBorislavova/SoftUni_Python_OOP_June_2021 | /3_inheritance/Lab/6_Stacks_of_strings.py | 565 | 3.75 | 4 | class Stack:
def __init__(self):
self.data = []
def push(self, element):
self.data.append(element)
def pop(self):
return self.data.pop()
def top(self):
return self.data[-1]
def is_empty(self):
if len(self.data) > 0:
return False
return ... |
c1dc89d5b76c9299942488ebdf65db36baa9a775 | Aswinraj-023/Python_CA-1 | /Assessment_1/Substitution_Cipher.py | 1,527 | 4.625 | 5 | #3) Substitution Cipher
encrypt="" # assigning encrypt variable to an empty string
decrypt="" # assigning decrypt variable to an empty string
string_1 = input("String 1 : ").upper() # getting plain text from user & converting to uppercase
string_2 = input("String 2 : ").lower() # getting encrypted text from use... |
d91e8e8fcc16d6e0bc8d407812c5c7f297404322 | zouzou6900/Python3.7 | /matrice.py | 256 | 3.59375 | 4 | import numpy as np
n = int(input("nombre de ligne : "))
m = int(input("nombre de colone : "))
a = np.arange(n*m).reshape(n,m)
i = 0
while i<n:
j=0
while j<m:
b=int(input("entre B :"))
a[i][j]= b
j+=1
i+=1
print(a)
|
7396584eacdc05f5b94255b144b4f9e0a0ad50de | heildever/leetcode | /python/easy/self-dividing-numbers.py | 659 | 3.890625 | 4 | # question can be found on leetcode.com/problems/self-dividing-numbers/
from Typing import List
class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def isSelfDividing(num):
digits = set(str(num))
dividers = 0
if "0" in digits:
... |
2c73f3b3d3c558c41425f728dc96d8615423162b | TenzinJam/pythonPractice | /freeCodeCamp1/grids_and_loop.py | 497 | 3.65625 | 4 | #grid and nested loop is similar to js as well.
# "in" is the syntax equivalent to .includes in js.
number_grid = [
[1,2,3],
[4,5,6],
[7,8,9],
[0]
]
print(number_grid[0][0])
for row in number_grid:
for column in row:
print(column)
def translate(phrase):
translated = ""
for letter in phrase:
i... |
25f1dea6646c218d213171f276cc0ceb47564371 | junjiezhou99/Python_Casa | /UF1_clase/binary.py | 346 | 4.03125 | 4 | def main():
decimal = int(input("introdueix el decimal"))
count=1
binary=0
while decimal!=0:
if decimal%2==0:
count*=10
decimal/=2
else:
binary+=count
count *= 10
decimal-=1
decimal/=2
print(binary)
if __name__... |
9bfcbb3a694d3dd883a4ce26a6542199b949e89d | vladnire/jetbrains | /rock_paper_scissors.py | 2,220 | 3.921875 | 4 | import random
def get_score():
"""Enter name, read score file
Return the score if in file or 0 if not"""
player_name = str(input("Enter your name: "))
print(f"Hello, {player_name}")
scores_list = []
with open('rating.txt', 'r') as f:
scores_list = f.read().splitlines()
for line ... |
e67ae2f1772b5aacf33a79a8a72e8f40bb774acf | smohapatra1/scripting | /python/practice/start_again/2020/12082020/generate_two_random_nums.py | 266 | 3.8125 | 4 |
#Problem 2
#Create a generator that yields "n" random numbers between a low and high number (that are inputs).
import random
random.randint(1,10)
def num(low,high,n):
for i in range(n):
yield random.randint(low,high)
for x in num(1,10,12):
print (x) |
042f568b741300491e3c8e9208c3e76baf97bef7 | li-MacBook-Pro/li | /static/Mac/play/调用/字符串公共前缀.py | 662 | 3.59375 | 4 | def subString(strs):
result=strs[0]
for i in range(1,len(strs)):
while (strs[i].startswith(result)==False):
result=result[0:len(result)-1]
if len(result)==0:
return "无公共前缀"
return result
try:
while 1:
a = input('请输入字符串,用空格隔开:')
a = a.split(... |
9a118191b74242f2dfd2683e860cb17193f2eab3 | AaronGoyzueta/Re.search-Loop | /re_search_loop.py | 581 | 3.578125 | 4 | # Function for re.search loop
import re
def main(exp, text):
cont = False
output = re.search(exp, text)
if output:
cont = True
lb = output.span()[0]
rb = output.span()[1]
print(output.span())
while cont:
new_output = re.search... |
d6c5962ba4fe9cbfd6e091524ffcf642ab5cf852 | Sujan-Kandeepan/Exercism | /exercism/python/prime-factors/prime_factors.py | 358 | 4 | 4 | def prime_factors(num):
primes = []
factor = 2
while factor <= num:
if num % factor == 0 and num == factor:
primes.append(factor)
factor += 1
elif num % factor == 0 and num != factor:
primes.append(factor)
num = num // factor
else:
... |
4b1c3e6773a01e1fb02fd4b58b15559e6d9fce22 | maybemichael/Graphs | /projects/ancestor/ancestor.py | 7,155 | 3.921875 | 4 | import collections
# Naive First Pass Iterative Solution
# def earliest_ancestor(ancestors, node):
# # we want the earliest ancestor aka the deepest ancestor so I will use a dfs search
# # loop through ancestors to create graph
# # standard dfs add starting node to stack
# # while stack isn't empty po... |
1a5a1016bf26263dc56c7b94a07d4329a553a6d1 | dishant470266/hacker_rank | /add_list_append.py | 1,171 | 4.25 | 4 | # fruits = ['banana','apple']
# fruits.append('mango')
# print(fruits)
#=======================================
#more method to add data
# fruits1 = ['banana','apple']
# fruits1.insert(1,'mango')
# print(fruits1)
#========================================
#extend_method
# fruits1 = ['banana','m... |
7e7272784e386b9912ad1c3560b5d23f84e0d568 | dorianivc/Introduccion_al_pensamiento_computacional_python | /busqueda_binaria_de_una_raiz_cuadrada.py | 465 | 3.765625 | 4 | objetivo =int(input('Escoge un numero: '))
epsilon = 0.01
bajo=0.0
alto= max(1.0, objetivo)
respuesta = (alto + bajo)/2
print(f'La raiz cuadradra de {objetivo} es: {respuesta}')
while abs(respuesta**2 -objetivo)>= epsilon:
print(f'bajo={bajo}, alto={alto}, respuesta={respuesta}')
if respuesta**2 <objetivo:
... |
e07f111905f7082b464f7c6b8fbf84ed756f5f4a | Alwayswithme/LeetCode | /Python/054-spiral-matrix.py | 889 | 4.28125 | 4 | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2015-06-17 13:57:41
# Title : 54 spiral matrix
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
# For example,
# Given the following matrix:
#
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9... |
ae96224e3deb544565a19f354a704e103094ee77 | MrZakbug/MITx-6.00.1x | /Midterm Exam/Problem 4.py | 716 | 3.84375 | 4 | def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return t... |
cee24afff7c23fee28b3ffc1c9e054c9a9662383 | AaronTho/Python_Notes | /for_loops.py | 337 | 4.125 | 4 | # for item in 'Python':
# print(item)
# for item in ['Aaron', 'John', 'Sarah']:
# print(item)
# for item in [1, 2, 3, 4]:
# print(item)
# for item in range(5, 10, 2):
# print(item)
'''
Shopping Cart price project
'''
prices = [10, 20, 30]
total = 0
for price in prices:
total += price
print(f'T... |
7ea557b614c2cfd4a0576d3c6e244ed25d7d017e | ManoVikram/The-Turtle-Crash | /car_manager.py | 880 | 3.84375 | 4 | from turtle import Turtle
import random, time
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
super(CarManager, self).__init__()
self.allCars = []
self.carSpeed = STARTING_MOVE_DISTANCE
... |
c2b233e53b3894dfe32be70223f9b2053b56478d | Mark24Code/Leetcode-200 | /53.py | 781 | 3.59375 | 4 | # 输出版
nums = [-2,1,-3,4,-1,2,1,-5,4]
max_sum = nums[0]
cur_sum = nums[0]
for i in range(1, len(nums)):
if nums[i] > cur_sum + nums[i]:
cur_sum = nums[i]
else:
cur_sum = cur_sum + nums[i]
if max_sum < cur_sum:
max_sum = cur_sum
print(max_sum)
# 类版
# class Solution(object):
# de... |
fa2be65e4cb49d6f48c1e6d46e3ab5efd3ce4782 | JTamarit/Apuntes_clase_Python | /Actividades_Evaluables/Actividad_1/Actividad_1_2.py | 192 | 3.625 | 4 | nombre = str(input("\n Introduce un nombre: "))
edad = int(input("\n Introduce edad: "))
persona= dict(name= nombre, age= edad)
print(f"\n {persona['name']} tiene {persona['age']} años. \n")
|
0d305bdb36053c73e3237b6f11f52a84b2b9e938 | luoming1224/Data-mining | /K-Means/Point.py | 545 | 3.515625 | 4 | __author__ = '25691'
from math import hypot
class Point:
def __init__(self, x, y, className = None):
self.x = x
self.y = y
self.className = className
self.distance = 0
def computeDistance(self, p):
self.distance = hypot((self.x - p.x), (self.y - p.y))
# self.dist... |
26bf856be1aad4d09387867d3dfaa20245442a20 | supreman2/project_python | /сортировка_слиянием.py | 694 | 3.890625 | 4 | def merge(a:list, b:list):
c=[0]*(len(a)+len(b))
i=k=n=0
while i<len(a) and k<len(b):
if a[i]<=b[k]:
c[n]=a[i]; i+=1; n+=1
else:
c[n]=b[k]; k+=1; n+=1
while i<len(a):
c[n]=a[i]; i+=1; n+=1
while k<len(b):
c[n]=b[k]; k+=1; n+=1
return c
def... |
9f35029fa763c311d04307468d86a490da8ec4a1 | cmontalvo251/Python | /lockbox/lockbox_combo.py | 1,055 | 4.15625 | 4 | import numpy as np
##Ok I figured it out.
#We need a function that return the possible
#combinations of a set of digits but using recursion
# for example if the possibilities are '012'
# the possible combinations are [0 + combos('12'),1 + combos('02'),2 + combos('01')]
def combos(digits):
#First, all we do is lo... |
56665532c48b2be4e69fcbba3905441963fc2114 | hieuvanvoW04/Python | /In Class/261018_2.py | 208 | 3.859375 | 4 |
#enumeate
def hour():
hours=[8,1,13,1,4,7]
counter=1
for h in hours:
print(h)
print(counter)
counter=counter+1
print(f"I've done the {counter} times")
hour() |
f705d436ca78deee31f5de097c4f40cd4fc8d2b5 | RBeltran12358/RockPaperScissorsPython | /RPS.py | 4,055 | 4.03125 | 4 | import random
# 2/3 3/5 4/5
def main():
# declaring and initializing some variables
up_to = int(input("How many points do you want to play to? "))
comp_scr = 0
while up_to < 1:
up_to = int(input("Invalid Number of Games. How many points do you want to play to? "))
player_scr = 0
com... |
e6f7c776442edeeaf6699ffcff800dfa4316f15e | ChosunOne/Python-Deep-Learning-SE | /ch02/chapter_02_001.py | 1,037 | 4.09375 | 4 | # The user can modify the values of the weight w
# as well as bias_value_1 and bias_value_2 to observe
# how this plots to different step functions
import matplotlib.pyplot as plt
import numpy
weight_value = 1000
# modify to change where the step function starts
bias_value_1 = 5000
# modify to change where the step... |
4d9d78e521b1d2b02c740f720c6d5925373ac489 | ZubritskiyAlex/Python-Tasks | /hw_9/task 9_01.py | 419 | 4.15625 | 4 | """Дан список строк. Отформатировать все строки в формате {i}-{string}, где
i это порядковый номер строки в списке. Использовать генератор списков."""
list_of_string = [
"Ihar",
"Zeka",
"wolf",
"cat",
"dog"
]
print([f"{index} : {element}" for index, element in enumerate(list_of_string)])
|
3e316a18ba430281146d9895122aeee5d40b3f56 | DagnyTagg2013/CTCI-Python | /LIST/ReverseIt.py | 4,916 | 3.5625 | 4 |
import logging
# Reversing Linked List!
class Node:
def __init__(self, value):
self.value = value
# ATTN: to RESERVED syntax hilite!
self.nextPtr = None
def __repr__(self):
if (self is not None):
status = "Value and Next Ptr: {0}, {1}".format(self.value, self.ne... |
1ebd0f2ad763852d4e7f19057b5197e56a025808 | maryoohhh/leetcodelearn | /Array/Check-if-exist.gyp | 783 | 3.96875 | 4 | # Given an array arr of integers, check if there exists two integers N and M such that N is the double of M ( i.e. N = 2 * M).
# More formally check if there exists two indices i and j such that :
# i != j
# 0 <= i, j < arr.length
# arr[i] == 2 * arr[j]
# Example 1:
# Input: arr = [10,2,5,3]
# Output: true
# Explanati... |
5d44c887b5975e4f8afdf28e125f806ca4cee3b2 | Anik2069/python_basic | /hi1.py | 270 | 4.03125 | 4 | print("Hello");
number=[1,2,3,4,56,7,8]
friend=["Anik","Shuvo","Dipu","Rasel"]
print(friend)
print(number[0])
print(friend[1:3])
friend.extend(number)
print(friend)
friend.append("Ashik")
print(friend)
friend.insert(3,"Suman")
print(friend)
print(friend.index("Suman")) |
fcf1055e6b29e5dcd2d411b1c71d0deb775cb172 | Hrishikesh-3459/leetCode | /prob_1550.py | 578 | 3.75 | 4 | class Solution:
def threeConsecutiveOdds(self, arr):
if len(arr) < 3:
return False
start = 0
stop = start + 3
q = arr[start : stop]
if self.count_odd(q):
return True
while stop < len(arr):
q.pop(0)
q.append(arr[stop]... |
747249001d522782d1042f4097c370d5989011eb | Shinrei-Boku/kreis_academy_python | /lesson07.py | 817 | 4.125 | 4 | #class 抽象クラス lesson07.py
import abc
class Person(metaclass=abc.ABCMeta):
def __init__(self,name,age):
print("create new Person")
self.__name = name
self.__age = age
def myname(self):
print("my name is {}".format(self.__name))
def myage(self):
print( "{}の{}歳です。".fo... |
09f0521a41f2ae60bb0eeebf8c200344317229da | lorenz-gorini/Python-Programs | /iss/main.py | 983 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 12:50:19 2019
@author: loreg
"""
import lib.path as path
#There's is a library to calculate the distance between two points of the ISS using the
# Haversine formula. This library is made by Bartek Gorny and is free software.
#There's also some little lib... |
cf752982ddcd8f53d3fdac41df51b669462f7b22 | luffmama/99-CapstoneProject-201920 | /src/m3_extra.py | 5,230 | 3.53125 | 4 | """
Code for sprint 3
Authors: Conner Ozatalar.
Winter term, 2018-2019.
"""
import time
# feature 1: going into deep sea
def m3_marlin_deep_sea(robot, check_box_dory_mode, dory_mode_excitement_entry):
print('Marlin deep sea activated')
robot.drive_system.go(50, 50)
while True:
if ro... |
03a99049fc957028707609f7253fdc4b3b2d83b2 | Yifei-Deng/myPython-foundational-level-practice-code | /19.py | 1,089 | 4.1875 | 4 | '''
视频中老师演示的代码
python开发基础19-math模块的使用
'''
import math #import the module
print(math.ceil(3.15)) #天花板,取大于3.15的最小的整数值
print(math.ceil(-3.15)) #天花板,取大于-3.15的最小的整数值
print(math.floor(3.15)) #地板,取小于3.15的最大的整数值
print(math.floor(-3.15)) #地板,取小于-3.15的最大的整数值
print(math.ceil(5),math.floor(5)) #如果变量是一个... |
d50a42634478c8ba579d97bb60d73e7904f49639 | 2kindsofcs/daily-algo-challenge | /2kindsofcs/191213-fair-candy-swap.py | 626 | 3.53125 | 4 | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
Asum = sum(A)
Bsum = sum(B)
A = set(A)
B = set(B)
halfDiff = (Asum - Bsum) / 2
for num in B:
target = halfDiff + num
if target in A:
return [int(t... |
180d439135cb3e781106b5f8b11d12b7e89cd452 | hiys/PYTHON | /pythonScripts/PyScripts/PyScripts4/guess2.py | 331 | 3.84375 | 4 | import random
num = random.randint(1, 10) # 随机生成一个10以内的数字
running = True
while running:
result = int(input("guess the number: "))
if result > num:
print('猜大了')
elif result < num:
print('猜小了')
else:
running = False
print('猜对了')
print(num)
|
d3e404302c3acf2bd9e7a31e35ae96028fd3fb4c | bhostetler18/TuneCoach | /TuneCoach/gui/Timer.py | 990 | 3.671875 | 4 | from datetime import datetime
import time
# Big thanks to https://stackoverflow.com/questions/60026296/how-to-make-a-pausable-timer-in-python
class Timer:
def __init__(self):
self.started = None
self.paused = None
self.is_paused = False
def start(self):
self.started = datetim... |
7b0393f46eb55417a210a7da6d3609606867ea2e | madhurijain97/Machine-Learning-Assignments | /homework1/decisiontree.py | 12,746 | 3.703125 | 4 | import sys
from math import log
import csv
import numpy as np
import os
#if all the decisions in the set belong to the same class, then this value will be returned
ifSetPure = 0
#the predictions of the test data are stored in this list too along with being written to the predctions file
testedPredictions = []
'''th... |
054c44e7efd33d04e7e7415e6133cf1a1ca96222 | GuilhermeRamous/python-exercises | /reverse_list.py | 191 | 3.96875 | 4 | def reverse_list(lista):
if len(lista) == 1:
return [lista[0]]
else:
topo = lista.pop()
return [topo] + reverse_list(lista)
print(reverse_list([1, 2, 3]))
|
71e6566da2abb705d5c2e379628539f53ef405c1 | zkydrx/pythonStudy | /study/pythonMethod/pythonAdvancdeFeatures20181108.py | 1,671 | 4.09375 | 4 | # -*- coding: UTF-8 -*-
# 匿名函数
# 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。
#
# 在Python中,对匿名函数提供了有限支持。还是以map()函数为例,计算f(x)=x2时,除了定义一个f(x)的函数外,还可以直接传入匿名函数:
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8]))) # =>[1, 4, 9, 16, 25, 36, 49, 64]
# 通过对比可以看出,匿名函数lambda x: x * x实际上就是:
def f(x):
return x * x
# 关键字la... |
2ee3665dcdd39a22cf2fa1c494323dadd61bf259 | arthurDz/algorithm-studies | /SystemDesign/multithreading and concurrency/barber_shop.py | 3,715 | 3.90625 | 4 | # A similar problem appears in Silberschatz and Galvin's OS book, and variations of this problem exist in the wild.
# A barbershop consists of a waiting room with n chairs, and a barber chair for giving haircuts. If there are no customers to be served, the barber goes to sleep. If a customer enters the barbershop and ... |
05a4a1a44e2587b466819f831b3c10d40a87510c | soutem-debug/object_orientated_programming | /object -oriented - programming/dog_tutorial.py | 605 | 3.546875 | 4 | class Dog:
def __init__(self, name, age, gender, breed):
self.name = name
self.age = age
self.gender = gender
self.breed = breed
def description(self):
print(self.name + " is" + " " + str(self.age) + "years old.")
def breeding(self):
print(self.... |
6f89570eeb1b66bcd7c02625a885f51b60ad9274 | Tavares-NT/Curso_NExT | /MóduloPython/Ex04.py | 358 | 3.9375 | 4 | '''Faça um Programa que peça as 4 notas bimestrais e mostre a média.'''
nota1 = float(input("Digite a 1ª nota: "))
nota2 = float(input("Digite a 2ª nota: "))
nota3 = float(input("Digite a 3ª nota: "))
nota4 = float(input("Digite a 4ª nota: "))
media = (nota1 + nota2 + nota3 + nota4) / 4
print(f"A média das notas info... |
fa487002afd5ccc268a737a75e71c3586f766bb2 | Shubh0794/PyCodeNotes | /3_Intro_to_List_comprehension_and_generators.py | 4,966 | 4.75 | 5 | ### Objective : Introduction to List Comprehension and Generators and Generator Expressions ###
###############################################################
############ CREATING A FUNCTION TO GENERATE LIST OF NUMS ####
###############################################################
def GetListOfNums(max):
n... |
077b4110c5fb2818335dbb72e1984610f89765f9 | igoodin/NeuronResearch | /main.py | 855 | 3.71875 | 4 | """
Author: Isaac Goodin
Date Created: 1/12/2010
Last Updated: 8/31/2010
Program to interface with the Neuron.py class and allow simple configuration and execution of the simulation.
"""
from neuron import *
file = open("neuron.txt",'w')
steps = 100000 #Total Time(Ms)
skip = 10000 #Time to Skip(Ms)... |
36b96e467d3b21f02e6d498c7239d68b07023df6 | antonyaraujo/Listas | /Lista04/Questao7.py | 290 | 4.03125 | 4 | ''' Faça uma função que, dado um número representando uma temperatura em graus Fahrenheit, retorne a
temperatura em Celsius. Obs: C=(5/9)*(F-32).'''
def conversao(fahrenheit):
return (5/9)*(fahrenheit-32)
F = float(input("Fahrenheit: "))
print("Celsius: %.1fºC" %(conversao(F)))
|
a831d531d43bf6315012dc53d4ee85456ac52d31 | tusharsadhwani/intro-to-python | /2. Data Structures/4-examples.py | 1,183 | 4.375 | 4 | # Practical examples of what we have learned so far:
# 1. generating a set of prime numbers
# upper_limit = 100
# primes = set()
# for n in range(2, upper_limit):
# primes.add(n) # assume it is a prime
# for p in primes:
# # if n is divisible by a prime (other than itself):
# if n % p == 0 a... |
e849b9a728cdd7d98e22c05158b61aa1ce8c52a4 | jtcass01/codewars | /Python/4 kyu/Range Extraction/Solution.py | 940 | 3.78125 | 4 | def solution(args):
recent = []
ranges = []
result = ""
last = args[0]
for argument in args:
if argument == last+1 or argument == last-1:
recent.insert(0,argument)
else:
if(len(recent) > 0):
ranges.append(appendRange(recent))
r... |
0d3b79b5d7739547d998f91679618eb9e0f24f1a | marusheep/python-course-practice | /course-3-string-1/3-2-concatenation.py | 673 | 4.15625 | 4 | # Concatenation "" + ""
print("tomato" + " " + "juice")
# String Exercise
# Do all of this in a .py file in Pycharm
# 1. Create a variable and assign it the string "Just do it!"
# 2. Access the "!" from the variable by index and print() it
# 3. Print the slice "do" from the variable
# 4. Get and print the slice "it!" ... |
8cb54958c6623c20044aa791ec9cddee5a75783d | gsudarshan1990/Training_Projects | /Classes/class_example138.py | 358 | 4.125 | 4 | """This is another python example"""
class Product:
def __new__(cls, *args, **kwargs):
new_product = object.__new__(cls)
print('Product __new__ is called')
return new_product
def __init__(self, name, price):
self.name = name
self.price = price
print('__init__ is... |
b34464a06002b214176c646d9c5989090b70217d | Alekceyka-1/algopro21 | /part1/LabRab/labrab-02/03.py | 137 | 3.90625 | 4 | x = int(input('Введите от 1 до 9 - '))
while x < 1 or x > 9:
x = int(input('Введите от 1 до 9 - '))
print(x)
|
1db84a813b07f1f16629059dd11bd81534243508 | feldhaus/python-samples | /hangman/hangman.py | 4,078 | 4.03125 | 4 | import random, string
WORDLIST_FILENAME = "words.txt"
def loadWords():
'''
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
returns (list): all words loaded
'''
print("Loading ... |
761fdba3ce3acbaf5aef76f7e195db382edebd58 | Rossel/Solve_250_Coding_Challenges | /chal113.py | 128 | 3.765625 | 4 | x = "The days of Python 2 are almost over. Python 3 is the king now."
if "z" in x or x.count("y") >= 2:
print("True!") |
1c9005a2f10ae16ee82c6c1164f154d34ac8b8d2 | devopshndz/curso-python-web | /Python sin Fronteras/Python/7- Gestion de archivos/2- Escribiendo en los archivos.py | 838 | 3.625 | 4 | ### escribiendo archivos
# si queremos escribir en este archivo de chancho, debemos utilizar los permisos.
# 'a'
d = open('Python/7- Gestion de archivos/chancho.txt', 'a')
d.write('\nAgregaremos una nueva linea a nuestro archivo')
# debemos colocar \n para salto de linea ya que se agg el texto al final pero no hacia... |
284d383d621e384847638eb02acfb20e410c005e | khanshoab/pythonProject1 | /concatenation+ope.py | 246 | 4.21875 | 4 | # Concatenation operator is used to join the two string.
print("khan"+"bro")
print()
str1 = "khan"
str2 = "bhaii"
str3 = str1 + str2
print(str3)
print()
str4 = "are you"
print("Hello How "+str4)
print("hello how",str4)
print("hello"+str4+"happay") |
436697395a6a1150e0e77ab0fb246a581ac1e23c | wsbresee/Playground | /Python/hello_world.py | 138 | 3.890625 | 4 | lunch = raw_input("What do you want for lunch? Pizza? ")
if lunch == "pizza":
print("Good choice!")
else:
print("that's stupid")
|
65a9e8945d0c694c07c67360696eb829628cf571 | jianhui-ben/leetcode_python | /15. 3Sum.py | 2,087 | 3.796875 | 4 |
#15. 3Sum
#Given an array nums of n integers, are there elements a, b, c in nums such
#that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
#Notice that the solution set must not contain duplicate triplets.
#Example 1:
#Input: nums = [-1,0,1,2,-1,-4]
#Output: [[-1,-1,2],[-1,0,1... |
30a23a9f2bd5629bee6ec0e152a84dba89d4309b | SteveGeyer/Firefly | /src/experiments/drive.py | 2,888 | 3.6875 | 4 | #!/usr/bin/env python3
"""Drive the quadcopter from a command line for testing.
b -- bind the quadcopter
a -- arm the quadcopter for flight
d -- disarm and stop flying
A line of one to four numbers in the range of 0.0 to 1.0 separated by
spaces. They are in the order of throttle, direction, forward/backwards,
and r... |
a21b332ae7406e1a1fdbc9311151dea6805dcf02 | rcchen0526/UVA | /uva_10006.py | 905 | 3.609375 | 4 | def mod(a, n):
N=n
ans=a if n%2 else 1
while int(n/2):
n=int(n/2)
temp=(a*a)%N
if n%2:
ans=(ans*temp)%N
a=temp
return ans
def check(a, n):
if mod(a, n)==a:
return True
else:
return False
prime=[False for _ in range(65001)]
prime[0], p... |
57c9d16ed7a19d88badc7541e5c941ccc742ee86 | zyanwei2011/Automated-Testing | /python10/class_0910_object/class_0910_3.py | 615 | 3.703125 | 4 | __author__ = 'zz'
class MathMethod:
def __init__(self,a,b):#初始化函数 通过他可以传递属性值进来
self.a=a
self.b=b
def add(self):
return self.a+self.b
def sub(self):
return self.a-self.b
def chengfa(self):
return self.a*self.b
def div(self):
return self.a/self.b
t... |
cc7eff26e3bc57e077fba51d44b86530f4ee445c | CharlyJeffrey/SemaineInfo2019 | /Activités/Tic-Tac-Toe/tic-tac-toe.py | 3,739 | 4.28125 | 4 | """
Jeu «Tic-Tac-Toe» pour la semaine Informatique tous âges.
Auteur: Fermion & Bérillium
"""
# VARIABLES GLOBALES
SYMBOLES = ["X", "O"] # Symboles possibles
JOUEUR_1 = input("Joueur 1, quel est votre nom? ") # Nom du joueur 1
JOUEUR_2 = input("Joueur 1, quel est votre nom? ") # Nom du joueur 2
JOUEURS = [JOUEUR... |
1a4b7559b45b9d1dccc1b687501b4a7f44c00ef9 | kingbj940429/Coding_Test_Solution | /beak_joon/b_3568.py | 576 | 3.53125 | 4 | ''' 3568번 iSharp '''
def remove_comma(input_data):
result_list = []
for val in input_data:
if(val.find(",") > 0):
val = val.replace(",","")
result_list.append(val)
return result_list
basic_type = ['[]', '&', '*']
if __name__ == "__main__" :
input_data = input(... |
32ab90bbe2ced17dc0fe076659dabd33d393e1fd | Mattnolan45/College-Work | /CA116-CA117 Programming 1 & 2/2017-02-07/ca117/nolanm45/league_12.py | 541 | 3.65625 | 4 | import sys
teams=sys.stdin.readlines()
largest=0
for team in teams:
team=( " ".join(team.split()[1:-8]))
if len(team)>largest :
largest=len(team)
print("{:3s} {:{}s}{:>3s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}{:>4s}".format("POS","CLUB",largest,"P","W","D","L","GF","GA","GD","PTS"))
for team in teams:
... |
a85b2eb1f984997874c8b91b24dfbcdf8fa90b48 | deo1/deo1 | /Legacy/AddressBook/Tests.py | 3,749 | 3.875 | 4 | __author__ = 'jfb_000'
from AddressBook import Book
def testbook(bookobj, firstname=None, lastname=None, phonenumber=None, emailaddress=None, street=None, city=None,
state=None, country=None):
print("----------------TEST-------------------")
# create book
print("This is " + bookobj.owner... |
acfee2ea1b9d05a5e200cd19b66a697625418f4c | Rivarrl/leetcode_python | /leetcode/algorithm_utils.py | 5,078 | 4.09375 | 4 | # -*- coding:utf-8 -*-
# 算法辅助类
import time
from typing import List
null = None
class Trie:
def __init__(self, x):
self.val = x
self.children = [None] * 26
class Employee:
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this em... |
de59bb6375281515f61085b097cba7b65b07b446 | willydavid1/python-basic | /strings.py | 399 | 3.90625 | 4 | name = 'willy'
print(name.upper())
print(name.capitalize())
print(name.strip())
print(name.lower())
print(name.replace('y', 'i'))
print(name[0])
print(len(name))
print(name[0:3]) # 'wil'
print(name[:3]) # 'wil'
print(name[3:]) # 'ly'
print(name[1:4]) # 'ill'
print(name[1:4:2]) # 'il' / access the letters two by two
p... |
925f020380e95d19eb61b20a450ea669fd6c8588 | Yellineth/Algoritmos-Python | /n_impares.py | 213 | 3.625 | 4 | #calcula cuantos numeros impares hay en un total de 100 numeros enteros
c=0
for i in range (5):
n=int(input(" ¿cual es el numero? "))
n1=n % 2
if n1<0:
c=c+1
print("Hay",c,"numeros impares") |
2ca98a7aca3fbfa90552e1fb7a4933d8f6fae22a | KTingLee/Python100D | /100D_1/Day01To07/EX6_2_Is_Scheherazade_Numbers.py | 491 | 3.8125 | 4 | # 2020/02/19 Is a Scheherazade Numbers?
#
# 對稱數又稱回文數(Scheherazade Numbers, palindromic number)
# 意即該數顛倒,仍得到相同數字。
#
# 例如 12321 顛倒仍為 12321
def is_palindromic(num):
res=0
temp=num
while temp > 0:
res = res*10 + temp%10
temp = temp // 10
if res == num:
print('%d 為對稱數' % num)
... |
2fdc32f7f246323392979ed61d134c5a788891c2 | swarnim321/ms | /dataStructures_Algorithms/k_sorted_array.py | 465 | 3.734375 | 4 | import heapq
from heapq import heappop, heappush
def sort_k_sorted_arr(list,k):
pq=list[0:k+1]
heapq.heapify(pq)
index =0
for i in range (k+1, len(list)):
list[index]=heappop(pq)
index+=1
heappush(pq,list[i])
while pq:
list[index]=heappop(pq)
ind... |
f74f98d9d5018b04534a8df239833921d97a0907 | Rudra-Patil/Programming-Exercises | /LeetCode/src/121 - Best Time to Buy and Sell Stock.py | 421 | 3.5625 | 4 | """
Topics: | Array | Dynamic Programming |
"""
class Solution:
def maxProfit(self, prices):
"""
Time: O(n)
Space: O(1)
"""
min_seen = float('inf')
max_profit = 0
for price in prices:
if price < min_seen:
min_seen = price
... |
aec68ff30245a2d399bd5644c81f88d149d7ee4a | Ch-sriram/python-advanced-concepts | /oop/polymorphism.py | 1,390 | 4.3125 | 4 | class User:
# this class doesn't have an __init__
def sign_in(self):
return 'logged in'
# we can have same method names, but in different instances
# of the same class/sub-class, they can be overridden.
# For example, attack() method is defined here, which is
# again defined in Wizard a... |
e2a575c9bd7dfc4dc0affff950ad1b8a88865076 | jairock282/pythonWorshop | /Clase6/claseObject.py | 819 | 4.3125 | 4 | ##Herencia
"""
En python todas las clases heredan por default de la clase Object, la cual,
cuenta con un alista de atributos y metodos para poder utilizar
__init__ no es un constructor, solo es un metodo que permite definir
los atributos
"""
class Gato:
def __init__(self, nombre):
self.nombre = nombre
#Meto... |
013f8fff43f21f25d0e04a6c5ba47cb07f7a7723 | flackbash/morse-code-translator | /morse.py | 5,531 | 3.546875 | 4 | import keyboard
import time
import sys
import argparse
morse = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---',
'-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-',
'..-', '...-', '.--', '-..-', '-.--', '--..', '.----', '..---',
'...--', '....-', '....... |
0ec82b8886f9adfedd2f099d3820dbe66a7f48e5 | liangg/edocteel | /src/Python/leetcode2.py | 56,114 | 3.96875 | 4 | #
# Leetcode questions on Tree, List
#
# Queestions 650 - 850
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Q-222: Count Complete Binary Tree... |
d1ae2599e0cad0363de2c45ce66cf28a8588f783 | shyamkumar2412/player | /55.py | 100 | 3.53125 | 4 | s=list(map(str,input().split(' ')))
if len(s[0])==len(s[1]):
print('yes')
else:
print('no')
|
a6a57dd3c02d981c96b9e3200134ecffd136fb7c | brennomaia/CursoEmVideoPython | /ex011.py | 303 | 3.875 | 4 | largura = float(input('Largura da Parede: '))
altura = float(input('Altura da Parede: '))
dimensao = largura*altura
tinta = dimensao/2
print('Sua parede possui a dimensão de {}x{} e sua area é de {}m²\n Para pintar está parede você precisa de {}l de tinta'.format(largura, altura, dimensao, tinta)) |
6c91ab08667064830c6f67759aae7f2726349377 | rigogsilva/sqldf | /sqldf/sqldf.py | 2,706 | 3.5625 | 4 | from pyspark import SparkContext
from pyspark import RDD
from pyspark.sql import SQLContext
from pyspark.sql import DataFrame
from sqldf import templating
import os
os.environ["SPARK_HOME"] = "/usr/local/spark/"
os.environ["PYSPARK_PYTHON"] = "/usr/local/bin/python3"
# Set spark context to be used throwout
sc = Spar... |
fbddac9a4ef48c1ca9f77c20d930ee62be908295 | BryanFriestad/ee-raspi-fun | /7seg_decoder_driver.py | 2,038 | 3.5 | 4 | import RPi.GPIO as GPIO
import time
x0_pin = 24 #blue
x1_pin = 25 #green
x2_pin = 26 #yellow
x3_pin = 27 #orange
display_state = 0 #unused currently
display_value = 0
def setup():
global display_value
#using broadcom mode for gpio numbering
GPIO.setmode(GPIO.BCM) ... |
d932ce1b9ceeb81b312fd15e6e8b82ff4dd53ca1 | ryosuzuki/hint-pilot | /data/006.py | 279 | 3.53125 | 4 | def repeated(f, n):
def h(x):
if n==0:
return x
else:
return f(repeated(h, n-1)(x))
return h
def main():
print('repeated(triple, 5)(1) should return 243')
print(repeated(triple, 5)(1))
#=> ExternalError: RangeError: Maximum call stack size exceeded
|
8ae10377b4916d732c2839c5e2df016c9ea19891 | Infosharmasahil/python-programming | /unit-6/process_nhl.py | 1,118 | 3.765625 | 4 | import json
with open('nhl.json', 'r') as nhl_file:
data = json.load(nhl_file)
print(data.keys())
#how many teams are in the nhl
team_count = len(data['teams'])
print(team_count)
'''
if team not in team_total_count.keys():
team_total_count[team_count] = []
team_total_count[team_count].appe... |
8756d07a102af02e4c6c3b38f9d2f2c102a1528f | L3ftsid3/Classes | /Big-Data/Hadoop/Intro-to-Hadoop-Udacity/Project--Week-3/ex1mapper.py | 656 | 3.515625 | 4 | #!/usr/bin/python
#Excercise 1 - The three questions that you have to answer about this data set are:
# Instead of breaking the sales down by store, instead give us a sales breakdown by product category across all of our stores.
# Format of each line is:
# date\ttime\tstore name\titem description\tcost\tmethod of pay... |
8fdaa62e4211d480c7c2a2baca58543b958edf5e | Gitosthenes/exercises | /sorting.py | 1,232 | 3.953125 | 4 | from random import randint
from random import seed
def generate_array():
test = []
for num in range(20):
seed(randint(0, 1000))
test.append(randint(0, 100))
return test
def selection_sort(my_list):
for i in range(len(my_list) - 1):
minVal = i
for j in range(i + 1, len... |
f52f06ea67bfccf67025fd704cc23492045a4da4 | aalamgeer/python_basic_tutorial | /arthmetic.py | 149 | 3.5 | 4 | print("sum of 3+2 ", 3+2)
print("product of 3*3", 3*3)
print("divide of 10/3 ",10/3)
print("modules of 10%3 ",10%3)
print("square of 10**3 ",10**3)
|
a4e02ad8dd7e7d39f1051c5dc32eeb512a4a2e34 | mkrasnitski/project-euler | /035.py | 528 | 3.625 | 4 | import math
def is_prime(n):
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def rotr(n):
n = str(n)
if len(n) == 1:
return n
return n[-1:] + n[:-1]
def rotate_prime(n):
p = [str(n)]
i = rotr(n)
while int(i) !... |
05582e0bf00c820cd0605ba50d5109a4dac6a196 | jeffzhangding/study | /letcode/字节跳动章节/数组与排序/最长连续递增序列.py | 969 | 3.5 | 4 | __author__ = 'jeff'
"""
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
"""
class Solution:
def findLengthOfLCIS(self, nums) -> int:
""""""
max_lenth = 0
current_lenth = 0
last_number = None
for i in nums:
if ... |
c4db143ae0a008a5a857be0f62517307bcebd968 | ksomemo/Competitive-programming | /atcoder/abc/053/C.py | 279 | 3.546875 | 4 | def main():
"""
1 <= x <= 10**15
どのパターンで得点が一番多いか
(5) -> 6 -> 5 > 6 -> 5 ...
"""
x = int(input())
d1, r1 = divmod(x, 11)
ans = d1 * 2 + (r1 // 6) + (r1 % 6 > 0)
print(ans)
if __name__ == '__main__':
main()
|
338f62cbdb1d96d3a46d3345b5f0cfcf3b131eaf | jao11/curso-em-video | /mundo01/aula008/des021.py | 309 | 3.65625 | 4 | # Faça um programa em python que abra e reproduza o áudio de um arquivo mp3.
import pygame
print('Gostariamos que você ouvisse essa música')
pygame.mixer.init()
pygame.mixer.music.load('des021.mp3')
pygame.mixer.music.play()
print('Por favor ouça...')
input('Para parar digite algo e de enter:')
|
53dc17b3ef84d762b4fa758818278e0e6925cd2b | M4573R/Interviewbit2 | /Arrays/PASCAL1.py | 1,611 | 3.828125 | 4 | """Given numRows, generate the first numRows of Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """
"""Analysis : 1. The first and last element in each row is 1
... |
5f7bcfb242403487dc43b90dcb8dea0a97c6d941 | ajara123/CS-1 | /task 7/7.2.py | 907 | 4.375 | 4 | #Exercise 2: Write a program to prompt for a file name,
#and then read through the file and look for lines of the form:
#X-DSPAM-Confidence:0.8475
#When you encounter a line that starts with "X-DSPAM-Confidence:" pull
#apart the line to extract the floating-point number on the line.
#Count these lines and then comput... |
6e3b9da87c2a94aec42e8b779c614ccd26ca8f3f | CleitonFurst/python_Blueedtech | /Exercicios_aula_10/Desafio_01.py | 1,645 | 4.0625 | 4 |
'''#DESAFIO:
Em uma eleição presidencial existem quatro candidatos. Os votos são informados por meio de código.
Os códigos utilizados são:
1 , 2, 3, 4 - Votos para os respectivos candidatos (você deve montar a tabela ex: 1 - Jose/ 2- João/etc)
5 - Voto Nulo
6 - Voto em Branco
Faça um programa que calcule e mostre:
... |
720efed1a77df24a21257faea7d02b7e52352eab | Karthikkk-24/ShapeAI_Python-NetworkSecurity_Project | /Algorithm#2(SHA384).py | 198 | 3.734375 | 4 | import hashlib
#Python code for SHA256 algorithm
string01 ="Cybersecurity"
SHA256algorithm = hashlib.sha384(string01.encode())
print("The hexidecimal value : ",SHA256algorithm.hexdigest()) |
56a1a960c7acdd0942f3fc3b20326415d52fcd98 | shepherdjay/reddit_challenges | /challenges/challenge364_ez.py | 607 | 3.984375 | 4 | from typing import Tuple
import random
def roll(number: int) -> int:
return random.randint(1, number)
def dice_roller(input_string: str) -> Tuple:
rolls, sides = input_string.split('d')
results = [roll(int(sides)) for _ in range(0, int(rolls))]
return sum(results), results
if __name__ == '__main__... |
397b55cf75d77cd624304e79a981332c0891c46a | pausanchezv/Estructura-de-dades-UB | /Pràctiques/Heaps i hash/Codi_i_texts/HashMapWordFinder.py | 3,484 | 3.640625 | 4 | from HashMap import *
import time
class HashMapWordFinder(object):
def __init__(self, file):
'''Mtode constructor'''
self._hashMap = HashMap()
self.appendText(file)
def appendText(self, file):
'''Llegeix el fitxer i el desglossa en lnies i paraules per lnia'''
t... |
07c9895fe98380095b2f7827b634e17aa9e30d57 | hangwudy/leetcode | /100-199/106. 从中序与后序遍历序列构造二叉树.py | 1,434 | 3.875 | 4 | from typing import List
# 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
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
n = len... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.