blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
697e60d969dbd76294777f36eeb39c469f164800 | knitinjaideep/Python | /fileRecursion.py | 503 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 3 09:13:25 2019
@author: nitinkotcherlakota
"""
def threeNumberSum(array, targetSum):
final_array = []
for i in range(len(array)-2):
a = array[i]
for j in range(i+1,len(array)-1):
b = array[j]
for k in (i+2,len(array)):
c = array[k... |
06ca7f1662023ecb7bd2e5eedef72bac1128683d | chablis8/ECON611_HW5_GrpProject | /hw5.py | 375 | 4.15625 | 4 |
# use recursion to find factorial
def find_factori(x):
try:
if x == 1 :
return 1
elif x<1 or not (isinstance(x, int)):
return 'no flaot & negatives'
else:
return x*find_factori(x-1)
except Exception:
return ('invali... |
558a3748b51b3624d46493f8e9c13340069cfb7d | fionnmcguire1/LanguageLearning | /PythonTraining/Python27/PalendromicSubstrings_medium.py | 1,669 | 4.1875 | 4 | '''
Author: Fionn Mcguire
Date: 25-11-2017
Description: Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
'''
'''
Requirements:
Traverse through s... |
261e4d8a6eaa4ecdbed16093110be47c5dc0fed1 | praveengadiyaram369/geeksforgeeks_submissions | /geeksforgeeks_SumOfDigitsNumber.py | 143 | 3.625 | 4 | # _Sum of Digits of a Number
def sumOfDigits(n):
if n > 0:
return ((n % 10) + sumOfDigits(int(n/10)))
else:
return 0
|
b5087a93226c431ec34de00bc02957c4aa6f23dc | daniloaugusto0212/EstudoPython | /python_dankicode/listas/strings_range.py | 94 | 3.6875 | 4 | # 0123456
nome = "chicago"
print(nome[1]) #letra h
for x in nome:
print(x, end='') |
647450b99c9a43248f7af8599c8d8420b0a74c15 | htmathl/exerciciosPython | /python_types.py | 284 | 3.609375 | 4 | str = input('digite algo: ')
print('Alpha: ', str.isalpha())
print('Alfanum: ', str.isalnum())
print('Numeric: ', str.isnumeric())
print('Uppercase: ', str.isupper())
print('Lowercase: ', str.islower())
print('Capitalize: ', str.istitle())
print('Only with spaces: ', str.isspace())
|
b80198383d69433f99adbef91c44495cf4831087 | rohangiriraj/classic-problems-in-cs | /nth_fib.py | 687 | 4.40625 | 4 | # Program to find the Nth Fibonacci number.
# Example: If n=5 then the fibonacci number is 5.
# This program is done using loops, recursive solution seems needlessly complicated.
def nthfib(n):
if n == 0:
print(f"The {n}th Fibonacci number is 0")
elif n == 1:
print(f"The {n}st Fibonacci number... |
097aba00cac3e135fe3fd9b469773d89bf79390a | syurskyi/Algorithms_and_Data_Structure | /Linked List Data Structure using Python/exercise/Section 5 Singly Linked List/SLL-Easy.py | 1,228 | 4.21875 | 4 | # # Print the middle node of a Singly Linked List
#
# c_ Node
# ___ - data
# ? ?
# next _ N..
#
# c_ LinkedList
# ___ -
# head _ N..
#
# ___ insertEnd newNode
# __ h.. __ N..
# h.. _ ?
# r_
# lastNode _ h..
# w__ ?.ne.. __ no. N..
# ... |
ed43992b3b349fff219c2d92381820877dcdc8b2 | PrestonSo4/PythonChallenges | /Triangle Trig/triangleFunctions.py | 2,222 | 4.21875 | 4 | #https://www.101computing.net/triangle-geometry-functions/
from math import sqrt
def getPerimeter(a,b,c):
perimeter = a+b+c
print("The perimeter of a triangle with sidelengths: " + str(a) + ", "+ str(b) + ", "+ str(c) + ", will have a perimeter of:", perimeter)
def getArea(b, h):
area = b*h/2
print("The... |
32e0c1fbdfe0e257e70dd7e932dea5ca38ab4f31 | gberger/euler | /27.py | 1,076 | 3.9375 | 4 | A = range(-1000,1001)
B = range(-1000,1001)
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
... |
fab7be18661fc5a820021fd84d2e3f5d466dc73a | KodianKodes/holbertonschool-sysadmin_devops | /0x17-api/0-gather_data_from_an_API.py | 964 | 3.703125 | 4 | #!/usr/bin/python3
"""
Write a script that hits a REST api that has data on employees and tasks
and filters the data based on an argument passed to the script.
The argument is the employee ID, and the output should display the employee
name and the tasks the employee completed.
"""
import requests
import sys
if __name... |
e9fcca5aa9af972c5d5a618bca330feedfdbcc43 | Sildinho/aprendaPython3DoJeitoCerto | /apy3JeitoCerto_Exerc_33.py | 407 | 4.1875 | 4 | # -- coding utf-8 --
""" Exercício 33 - loops while - pag: 119 - livro aprenda python 3 do jeito certo by zed shaw - https://learnpythonthehardway.org/"""
i = 0
numbers = []
while i < 6:
print(f"\nNo inicio: {i}")
numbers.append(i)
i = i + 1
print("O numero agora: ", numbers)
print(f"é ... |
2874ee80f58097ce6e3fc19c040210d8837855b8 | diocelinas561/programacion-python | /programas 1 diocelina/ejercicio 2 dioce.py | 331 | 3.625 | 4 | #Diocelina Sierra martinez
#22/11/16
#ejercicio 2
interes=input("ingresar el saldo al final del ano:")
pirmer=interes*.4
segundo=interes*.8
tercero=interes*.12
1resultado=interes+primer
2resultado=interes+segundo
3resultado=interes+tercero
print "saldo 1 al final", 1resultado
print "saldo 2 al final", 2resultado
print ... |
97d2432ae3d9310f09e7f6ebe838f9ec58e3c927 | yatish0492/PythonTutorial | /36_1_Duck_Typing.py | 631 | 4.03125 | 4 | '''
Duck Typing
-----------
We can pass/assign any class obj to a variable as we don't specify the type of variable any class object can be
assigned to it.
'''
class StartCar:
def start(self, someCar): # We are passing 'Cruze' and 'Ritz' class objects to same parameter 'someCar'
print("Startin... |
5a5d27d8b8b826d15fc5cf2349c2ef02c53cfae6 | wouterPardon/AI | /CodeAdvent/Day2/PartTwoMain.py | 793 | 3.515625 | 4 | #!/usr/bin/env python
inputFile = open('./input.txt')
words = []
def main():
for word in inputFile.readlines():
words.append(word.strip())
check(words)
def check(word_list):
done = False
for word in word_list:
for _word in word_list:
count = 0
all_same_chars... |
a4f58e013e1e776102968b840d51e4b9a553f83a | marciof2/PYTHON- | /desafio42.py | 532 | 4.15625 | 4 | n= int(input('Primeira Medida: '))
n2= int(input('Segunda Medida: '))
n3= int(input('Terceira Medida: '))
print('\n')
if n < n2 + n3 and n2 < n3 + n and n3< n + n2:
print('É um TRIANGULO !!')
if n==n2==n3:
print('Classificado como EQUILÁTERO.')
elif n != n2 and n!= n3 and n2!=n3:
pr... |
a7b0e055c133a9ac884a1ecf929d35604f95cd09 | AHecky3/Chapter_7 | /Solutions/challenge2.py | 4,077 | 4.40625 | 4 | """
2. Improve the Trivia Challenge game so that it maintains a highscores list in a file.
The program should record the player’s name and score if the player makes the list.
Store the high scores using a pickled object.
"""
#Challenge 2
#Andrew Hecky
#12/9/2014
import sys, pickle
def open_file(file_name, mode)... |
bdec24f78ba76f08d4075a9ea6df9948d42aab53 | vikas0694/python_programs | /dictionaries in python/dic0.py | 499 | 3.53125 | 4 | # # dictionaries
# #
# # how to add data
#
# data
user_info = {
'name' : 'vikas' ,
'age' : '23',
'movie' : ['lagaan, coco'],
'song' : ['chalti ka naam gadi, music, gana'],
}
# add and delete data
#
# how to add data
user_info['fav_songs'] = ['song1', 'song2']
print(user_info)
#
# pop method
po... |
fce26a6371424e5802189a55edf529256f99772a | terralogic-QA/Python-Selenium | /sangeetha-k/commonInLists.py | 588 | 3.96875 | 4 | found = 0
# first list
size = int(input('Enter total number of elements in list 1: '))
list1 = []
for j in range(0, size):
num = int(input('Enter element of position {} '.format(j+1)))
list1.append(num)
# second list
size1 = int(input('Enter total number of elements in list 2: '))
list2 = []
for j in range(0, s... |
5abc764836fa97b5b4ad689900ed02086ab818ca | lacra-oloeriu/learn-python | /ex7.py | 779 | 4.25 | 4 | print("Mary had a littlr lamb. ")#This is a comment
print("Its fleece was write as{}." . format('snow'))#that is a comment whit format that is means ...
print("and everywhere that Mary went.")#that is a comment
print(" ." * 10 ) # what'd that do ?#that's do 10points
end1 = "C"#this is a variablle
end2 ="h"#variable
en... |
9de1f0d31f265accfc3835a311a160dc849e2344 | huangy10/LearningTensorFlow | /example6.py | 2,352 | 3.671875 | 4 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# This tutorial is about add_layer
layer_count = 1
def add_layer(inputs, in_size, out_size, activation_function=None):
global layer_count
with tf.name_scope("layer%s" % layer_count):
with tf.name_scope("weights"):
... |
2ff313726f1719bcdcd28b3ab1129079ce7b4e72 | ryojikaji/school | /NJPOII/Collections/kolekcja.py | 2,389 | 3.828125 | 4 | # zadanie 3: Stwórz kolekcję książek zawierającą takie pola jak tytuł, gatunek, autor, isbn. Napisz trzy funkcje, (i) zapisującą kolekcję, (ii) odczytującą kolekcję, (iii) obliczająca statystykę wg. gatunku i autora.
# File :: "books.txt"
# Funkcja odczytująca kolekcje z pliku || użycie readBooks()
def readBooks():
... |
7f17e64984e107f69b3ef35e9f83ed1381307e53 | RuningBird/pythonL | /day01/wordgame2.py | 355 | 3.78125 | 4 | import random as rd
print("-------------------")
guess = 0
rdnum = rd.randint(1, 10)
while guess != rdnum:
temp = input("心中数字:")
guess = int(temp)
if guess == rdnum:
print("right")
guess = rdnum
else:
if guess > rdnum:
print("big")
else:
print("li... |
3a8fafb60e6c85e58c1f078f659b937263d1fe33 | dalq/python-cookbook | /cookbook/two/20OperationOnByteString.py | 412 | 3.578125 | 4 | # 在字节串上执行文本操作
# 几乎所有能再文本字符串上执行的操作同样也可以在字节串就上进行
data = b'Hello World'
print(data)
print(data[0:5])
d = bytearray(b'Hello World')
print(d)
print(d[0:5])
# 区别
a1 = 'Hello World'
print(a1[0])
a2 = b'Hello World'
print(a2[0])
#如果想对字节串做格式化操作,应该先转为普通的文本字符串然后再做编码
|
c49186e2b549c43849d0af572a522fca482a9593 | Nitindrdarker/datastructures-with-python | /stack.py | 1,230 | 4 | 4 | class node():
def __init__(self,d):
self.data = d
self.next = None
class Stack():
def __init__(self):
self.head = None
def push_stack(self,d):
new_node = node(d)
if(self.head == None):
self.head = new_node
else:
last = self.head
... |
4138d1ae5975bf963934ad6937b1c6aee61597e0 | nueadkie/cs362-hw4 | /test_full_name.py | 593 | 3.59375 | 4 | import unittest
import full_name
class Tester(unittest.TestCase):
# Test for a case of a mix between integers/floats/complex numbers.
def test_name(self):
result = full_name.generate("Chris", "Miraflor")
self.assertEqual(result, "Chris Miraflor")
# Test for a case with non-string inputs.
def test_nu... |
df0f515e92e8861dbeb77b8c59f965558494eb3c | evaseemefly/CasablancaPython_Pro | /myPy.py | 432 | 3.9375 | 4 | a = "123"
print(a)
# 有序集合
mylist = ['联系人1','联系人2','联系人3']
print(mylist)
len(mylist)
# 取出末尾的元素
a = mylist.pop()
print(a)
# 元组-tuple
mytuple=('测试1','测试2','测试3')
print(mytuple[0])
L=[
['Apple','Google','Microsoft'],
['Java','Python','Ruby','Php'],
['drno','Casablanca']
]
# 打印Apple
print(L[0][0])
# 打印Python
... |
96f39aa2f1d58f4bde0b22ca5bb5f439abf2736f | imoren2x/biblab | /Python/02_Ejercicios/01_Basic/ProgrFun_3_generador.py | 1,240 | 4.5625 | 5 | #!/usr/bin/python
# -*- coding: latin-1 -*-
"""
Las expresiones generadoras funcionan de forma muy similar a la
comprensión de listas.
Su sintaxis es igual pero usan parentesis en lugar de corchetes.
Lo que devuelven son una funcion generadora.
El generador se puede utilizar en cualquier lugar donde se n... |
334823b7d3e9045a58f2b73d07b9ee2c9850ac77 | aditiav/python-projects | /Guess-Number.py | 1,466 | 3.875 | 4 | import random
randnum = random.randint(1,100)
inputnum=input('Guess your number between 0 and 100 : ')
num=int(inputnum)
print(randnum)
myguess=[0]
len(myguess)
while num !=randnum:
if num < 1 or num >100:
print ('\nNumber out of bounds')
inputnum=input('Guess the number between 0 and ... |
b02ae3dabdee904b6c4e614cb52cf1101399bb51 | aasgreen/Quantum-Hall-Effect | /Code/ocupBose.py | 20,610 | 3.5625 | 4 | import sys
import os
from numpy import *
import math
'''Program: Temp_Plot
This is a new program that I will be using to test my code. It will calculate the hall conductivity, for
the case of bosons for the case of finite temperature. The major change to this program, is that instead of interating over temperature.
'... |
1af3dfa853e350728b8ff2fef69cbb30f807d030 | haldous2/coding-practice | /ctci_16.22_langtons_ant.py | 7,403 | 4.59375 | 5 | """
An ant is sitting on an infinite grid of white and black squares.
It initially faces right.
At each step, it does the following:
(1) At a white square,
flip the color of the square,
turn 90 degrees right (clockwise), and move forward one unit.
(2) At a black square,
flip the color of the s... |
08e2bc98a31900c697b6d5f537d9dc610b2a5651 | miamirobin/2015Fall_ComputerProgramming | /hw6/hw6.py | 4,750 | 3.65625 | 4 | import math
from visual import *
# Data in units according to the International System of Units
G = 6.67 * math.pow(10,-11)
# Mass of the Earth
ME = 5.974 * math.pow(10,24)
# Mass of the Mars
MM = 6.418 * math.pow(10,23)
# Mass of the Sun
MS = 1.989 * math.pow(10,30)
MH = 2.2 * math.pow(10,14)
# Radius E... |
21edc0e6fb3cd7f4f8639d7d415483babfc841f0 | ishaansharma/ProblemSolving_Python | /7. Most booked hotel room.py | 1,369 | 3.921875 | 4 | """Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z].
You are given a sequence of rooms, where + suggests room is booked, - room is freed. You have to find which room is booked maximum number of times.
You may assume that the list describe a correct sequence of bookings in chronological order;
... |
9ac9c0a2eef880a5499130deec9ec07b98db123f | kishorebolt03/learn-python-the-hard-way | /ITVAC/problem_solving/printDIAMOND.py | 362 | 3.5625 | 4 | n=int(input())
a=input()
for i in range(n):
for j in range(1,n+i+1):
if j<n-i:
print(end=' ')
else:
print(a,end="")
print()
k=1
f=1
for i in range(1,n):
for j in range(1,k+i):
print(end=' ')
k+1
while f<=(2*(n-i)-1):
print(a,end... |
a84fa834437df9559724e565e85437842c7afb1c | hofernandes/python3-mundo-1 | /ex023.py | 419 | 4 | 4 | # Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
# num=str(input('Digite um número: '))
# print(f'Unidade: {num[3]}\nDezena: {num[2]}\nCentena: {num[1]}\nMilhar: {num[0]}')
num2=int(input('Digite um número: '))
print(f'Unidade: {((num2%1000)%100)%10}')
print(f'Dezena: {(... |
62c1c0466403de99a24551d8ef64c40398133e8b | wchen02/python-leetcode | /Questions/33-SearchInRotatedSortedArray.py | 1,345 | 3.703125 | 4 | from typing import List
# See details here https://wenshengchen.com/2020/01/10/33-search-in-rotated-sorted-array.html
class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums: return -1
lo = 0
hi = len(nums) - 1
while lo <= hi:
mid = lo... |
cbd904e06bb7b1912a25f541ac0ce210a7983f78 | boknowswiki/mytraning | /lintcode/python/0262_heir_tree.py | 1,254 | 3.796875 | 4 | #!/usr/bin/python -t
# dfs and multiple tree.
class MyTreeNode:
"""
@param val: the node's val
@return: a MyTreeNode object
"""
def __init__(self, val):
# write your code here
self.val = val
self.children = []
self.parent = None
self.is_deleted = False
... |
f6ec1195df42651f56bb184fa71d1aaf911582ec | gyx2110/algorithm-book | /mycode-python/step-2/day06/Problem380_RandomizedSet.py | 1,632 | 3.875 | 4 | # class RandomizedSet(object):
# def __init__(self):
# self.element = set()
# self.map = {}
# self.size = 0
# def insert(self, val):
# if val in self.map:
# return False
# self.map[val] = self.size
# self.element.add(val)
# self.size+=1
# ... |
4b4621e03046e60fbc3e587fc6864a9008e397f4 | omakasekim/python_algorithm | /04_프로그래머스/lev2_전화번호목록.py | 733 | 3.671875 | 4 | # my solution
def solution(phone_book):
if len(phone_book) == 1:
return False
for i, num1 in enumerate(phone_book):
for num2 in phone_book[i+1:]:
if num1 == num2 or num1 == num2[:len(num1)] or num2 == num1[:len(num2)]:
return False
return True
# Status: Accepted
#... |
1cb040ca20e149a390562fe8e23554ef150d6550 | GloriaWing/wncg | /输出指定范围内的素数.py | 240 | 3.578125 | 4 | min = int(input("min:"))
max = int(input("max:"))
sushu = []
for i in range(min,max+1):
fg = 0
for j in range(2,i):
if (i % j) == 0:
fg = 1
break
if (fg == 0):
sushu.append(i)
print(sushu)
|
8546bbfe99f5ca39bc0a3879c2773e62ed6e4ef3 | taiannlai/Pythonlearn | /CH4/CH4_L6.py | 117 | 3.96875 | 4 | x = 3.305
y = input("請輸入房屋坪數:")
z = float(x) * float(y)
print("房屋總平方公尺為:%2.1f" % z) |
bffbdba4ee075bd10d61c3d4427882faf8cabf62 | wooseong-dev/python | /algorithm/module/reverse.py | 600 | 3.71875 | 4 | #mutable(변환가능자료형) 원소를 역순 정렬
from typing import Any, MutableSequence
def reverse_arr(a: MutableSequence) -> None:
#mutable 시퀀스 a의 원소 역순 정렬
n = len(a)
for i in range(n//2):
a[i],a[n-i-1]=a[n-i-1],a[i]
if __name__ == '__main__':
nx = int(input('원소의 개수를 입력하시오 >> '))
x = [None]*nx #원소수... |
307c596ae9f62366859eca2ff690937423cf4610 | tburette/leetcode | /problems/11ContainerWithMostWater.py | 4,253 | 3.640625 | 4 | import unittest
from typing import List, Dict, Tuple
# Bruteforce-ish solution : start at the leftmost and rightmost edges,
# check all the potentials solutions with smaller width
# (left more to the right and/or right more to the left)
# skip a 'smaller' solution if height of the new left/right is not higher.
# Coul... |
90eabf22a8feae6871b0f318d6b896b78446d90f | CodeAlpha7/WebDevCode | /Google-Work-Sample/python/src/video_player.py | 8,580 | 3.875 | 4 | """A video player class."""
from .video_library import VideoLibrary
import random
playlist_name_list = []
class VideoPlayer:
"""A class used to represent a Video Player."""
def __init__(self):
self._video_library = VideoLibrary()
self.prev = ""
self.flag = 0
... |
48c3b2ec26afc16de8a847faa1e4da33d6098383 | jacobwin/MH8811-G1901740C | /02/02-2.py | 121 | 4.0625 | 4 | C = float (input('Enter the temperature in degree celsius: '))
F = C*1.8+32
print ('The temperature in Fahrenheit is', F) |
df991bac479dacac6d2d16020255bcf4c7a0b0d7 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Collections/program-2.py | 1,357 | 4.15625 | 4 | #!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Finds the most common elements and their counts of a specified #
# ... |
0ff010ce691aedb4c6f79d3d7c59ba6628ac57a5 | scottmaccarone2/Udacity-Intro-Programming-Projects | /order_breakfast.py | 16,048 | 4.40625 | 4 | # The first program to write is a breakfast bot that allows us to place a breakfast order (based on only two items). Before launching into code, there are some crucial pieces of the program we need to build:
# 1. Get input and use it to determine what happens next
# 2. Handle bad input without crashing
# 3. Be flexible... |
60bf5cb1dbba62c4f151da25daac9e8826aa5cc2 | AurelioLMF/PersonalProject | /ex059.py | 1,274 | 4.21875 | 4 | '''Crie um programa que leia dois valores e mostre um menu como apresentado abaixo. Seu programa deverá realizar a
operação solicitada em cada caso:
[ 1 ] somar
[ 2 ] multiplicador
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa'''
from time import sleep
n1 = int(input('Primeiro valor: '))
n2 = int(in... |
f410976a9a5dbe250c22d29422c10be8e3b9681c | GosiaZalecka/kalendarz | /kalendarz2.py | 1,603 | 3.953125 | 4 | import calendar
#podanie roku
print("Czy to rok przestępny?")
year = input("podaj rok: ")
#sprawdzenie czy to rok przestępny
czy_przestępny = calendar.isleap(int(year))
if czy_przestępny == True:
print("Tak, rok " + year + " to rok przestępny")
else:
print("Nie, rok " + year + " to nie rok przestępny")
print... |
1d011bf2e03deb98ac9f58f49121a20f47ae374e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2845/61048/315118.py | 308 | 3.640625 | 4 | def arr22():
n=int(input())
set=[]
for i in range(n):
set.append([int(x) for x in input().split(' ')])
set.sort(key=lambda x:x[0])
tmp=set.copy()
tmp.sort(key=lambda x:x[1])
if(tmp==set):
print("Poor Alex")
else:
print("Happy Alex")
return
arr22() |
1b31aaa5c52a5a76374c178a642c804ec09d27c1 | ClaudioCarvalhoo/you-can-accomplish-anything-with-just-enough-determination-and-a-little-bit-of-luck | /problems/LC1457.py | 926 | 3.765625 | 4 | # O(n)
# n = numberOfNodes(root)
# 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 pseudoPalindromicPaths(self, root: TreeNode) -> int:
return self.explo... |
1d3b6431db645dd16742f3f88d0ccff41c02564c | MAPLE-Robot-Subgoaling/IPT | /data/HW4/hw4_157.py | 441 | 4.125 | 4 | def main():
heightList = []
height = int(input("Please enter the starting height of the hailstone: "))
while height !=1:
heightList.append(height)
if height/2 == float:
ans= height * 3 + 1
print("Hail is currently at heaight", ans)
if height/2 == int:
... |
fa9975296c033d22eb76f35a9e560fd5890af6ed | abahmer/music-classification | /spotify.py | 2,466 | 3.546875 | 4 | import requests
import base64
class Connection:
"""
Class' object instantiates a connection with spotify. When the connection is alive, queries are made with the query_get
method.
"""
def __init__(self, client_id=None, secret=None):
if client_id is None:
client_id = open("./ig... |
46e404b392aacaaa835e568279e5dcb9c00c50ea | YongKhyeShern/DPL5211Tri2110 | /Lab 2.4.py | 644 | 3.640625 | 4 | #Student ID: 1201201010
#Student Name: Yong Khye Shern
BC=1.5 #constant value, the value doesn't change, name in Capital letters
GC=5.6
print("Invoice for Fruits Purchase")
print("---------------------------------")
bananas=int (input("\nEnter the quantity (comb) of bananas bought: "))
grapes=int (input(... |
edbf1ee31fc6a69f9ae6b6d7d97f342d3671b64c | MHM18/hm18 | /hmpro/zhangxiyang/list/list5.py | 247 | 3.546875 | 4 | a = [66.25,333,333,1,1234.5]
print(a.count(333),a.count(66.25),a.count('x'))
a.insert(2,-1)#插入
a.append(333)
print(a)
a.index(333)#索引
a.remove(333)#删掉第一个333
print(a)
a.reverse#倒序排
print(a)
a.sort()#从小到大排
print(a)
|
c4d734b5a307ffbb1ec79bea3780ae93a61d3ea4 | ADWright18/Learning | /LeetCode/Hash Table/Problems/groupAnagrams.py | 957 | 4.15625 | 4 | """
Problem Description: Given an array of strings, group anagrams together
Example:
Input:
["eat", "tea", "tan", "ate", "nat", "bat"]
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Solution:
1. Initialize a dictionary to store {sorted_char : [list of anagrams]} pairs
2. Iterate through the list... |
931e20a0ed557a8b904b4ae0580a58e6aaf0c969 | bgoonz/UsefulResourceRepo2.0 | /GIT-USERS/amitness/leetcode/387-first-unique-char.py | 335 | 3.609375 | 4 | # https://leetcode.com/problems/first-unique-character-in-a-string
def firstUniqChar(s):
"""
:type s: str
:rtype: int
"""
h = {}
for i, c in enumerate(s):
if c in h:
h[c] = -1
else:
h[c] = i
for c in s:
if h[c] != -1:
return h[c]... |
ae218ec695c553a345c567313238246d1a4db5c5 | BrunaNayara/ppca | /eda/lista1/13.py | 226 | 4.0625 | 4 | n = int(input())
c = int(input())
while(c != n):
if c < n:
print("O número correto é maior.")
elif c > n:
print("O número correto é menor.")
c = int(input())
print("Parabéns! Você acertou.")
|
d80f6c7bfdf80c7cbbd5bf3e6651250afc2bdd6c | shichao-an/ctci | /chapter5/question5.5.py | 660 | 3.84375 | 4 | from __future__ import print_function
def num_bit_swap(a, b):
count = 0
c = a ^ b # Bits that are different are 1s
while c != 0:
count += c & 1 # `count` increments upon a different bit
c >>= 1 # Right shift `c` by one bit so that LSB can be got
return count
def num_bit_swap2(a, b... |
fb26320a5614ef723fee554c71a58289690a3de4 | ptrgags/affine-font-indeed | /font.py | 1,975 | 3.515625 | 4 | from future.utils import iteritems
import numpy
import yaml
class Font(object):
"""
a Font holds the geometry for every letter and the corresponding
strokes.
"""
def __init__(self, fname='font.yaml'):
"""
Initialize the font from a YAML file
"""
self.font_data = sel... |
5d0e99f7e604778d72531f5a4b5655b0efc958d9 | sahilsehgal81/python3 | /listcopy.py | 388 | 3.890625 | 4 | #!/usr/bin/python
def list_copy(lst):
result = []
for list in lst:
result += [list]
return result
def main():
a = [10, 20, 30, 40]
b = list_copy(a)
print("a = ", a, " b = ", b)
print("Is", a, "equals to ", b, "?", sep="", end=" ")
print(a == b)
print("Is", a, "an alias of", b, "?", sep="", end=" ")
pri... |
2145f92973e4c5d7bd6afca1a5ab10c332c9ea83 | DSmathers/Blackjack.py | /Blackjack.py | 6,303 | 3.734375 | 4 | import random
print('****************************************')
print("* Welcome to Daniel's Casino game v1.0 *")
print('* started on 11/18/2020 using Python *')
print ('****************************************')
print ('')
def new_deck():
'''creates a new 52 card deck
'''
deck = []... |
718c1106eccb9afffbb8d52346526116b177ba68 | imiu/studydocs | /books/pyalg/ch2.py | 2,274 | 3.875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
... |
42b25c5a0b5d332c6ae9d329784439cbe8a4a4a8 | JonesCD/LPtHW | /ex15.py | 685 | 4.25 | 4 | # initiate argv module from sys library?
from sys import argv
# run the script and incorporate the filename in the python run command
script, filename = argv
# define string txt and fill it with file
txt = open(filename)
# show back name of file from python run command
# show contents of txt file with .read modifier... |
40734cdc4ddcbff931b8a85867f834cc01101c40 | holothuria/python_study | /基礎編/数値/モジュール/数値01_四則演算.py | 219 | 3.765625 | 4 |
test_integer = 100
print(test_integer + 10) # 加算(足し算)
print(test_integer - 10) # 減算(引き算)
print(test_integer * 10) # 乗算(掛け算)
print(test_integer / 10) # 除算(割り算)
|
b3f1ed249fe8a901bf48e65e40c536248bd2dd8c | priyancbr/PythonProjects | /StringIndexing.py | 462 | 4.375 | 4 | MyString = 'abcdefghij'
print(MyString)
print(MyString[-1])
print(f"Last letter is {MyString[-1]}")
print("Printing below using the other format method")
print("Last letter is {}".format(MyString[-1]))
print("First three characters {}".format(MyString[:3]))
print("Four characters from 'b' are {}".format(MyString[1:5]))... |
dc35049acbe82cf3fd10545fd8795745c08f817c | b2utyyomi/Network_data_acquisition | /use_14.py | 236 | 3.53125 | 4 | from product import Product
prod1 = Product('carrot', 1.25, 10)
print(prod1)
print('Buying 4 carrots...')
prod1.buy_Product(4)
print(prod1)
print('Changing the price to $1.50...')
#prod1.price = 1.50
prod1.set_price(1.50)
print(prod1)
|
8aff91fb29b51a83d870777445eedcc80d735f86 | a-ruzin/python-base | /lesson_3/_2_try_except.py | 283 | 3.953125 | 4 | """
Исключения
"""
i = int(input('целое'))
b = 3
a = 'Отрицательное' if i < 0 else 'не отрицательное'
if i < 0:
a = 'Отрицательное'
elif i > 0:
a = 'Положительное'
else:
a = 'равно 0'
print(a)
|
3243979dd198f446d2ddb4bd6c99666580128f48 | YunzeZhao/EnglishSubtitlesForSubs2srs | /srtIntoSubs2srs.py | 4,284 | 3.5 | 4 | #!python3
# -*- coding:utf8 -*-
# Author: Rundeepin
# Contact: alicecui.ac@gmail.com
from typing import List
from tkinter import filedialog
import os
import re
import ntpath
# 选择时间轴和字幕正文
def select_subtitle(raw_data):
data = []
for line in raw_data:
data.append(line.strip())
subtitle = []
ind... |
ee362623c03cf0ba897c311c0c013c9bbeca9117 | peiyong-addwater/2018SM2 | /2018SM2Y1/COMP90038/assessments/Assignment1/problem2.py | 1,691 | 4.03125 | 4 | # Python3 program to count
# occurrences of an element
# if x is present in arr[] then
# returns the count of occurrences
# of x, otherwise returns -1.
def count(arr, x, n):
# get the index of first
# occurrence of x
i = first(arr, 0, n-1, x, n)
# If x doesn't exist in
# arr[] then return... |
e0563a42905f029f9c5214e921a9147d2c4cdc7c | thu4nvd/ATBS-python | /book scripts/tablePrinter.py | 1,017 | 4.09375 | 4 | # tableData = [['apples', 'oranges', 'cherries', 'banana'],
# ['Alice', 'Bob', 'Carol', 'David'],
# ['dogs', 'cats', 'moose', 'goose']]
# Your printTable() function would print the following:
# apples Alice dogs
# oranges
# Bob cats
# cherries Carol moose
# banana David goose
def tprint(tableData):
# Tim so lon nh... |
bf8eaf08b4bb5b65ea2fc70a4be673af8cf427d0 | niluferbozkus/Odevler_EsraCakir | /dörtislemhesap.py | 760 | 3.90625 | 4 | islem = [ "+" , "-" , "*" , "/"]
count= 1
islemsayisi=int(input("Kaç işlem yapmak istiyorsunuz?: "))
while count <= islemsayisi:
sayi1 = int(input("İşlem yaapmak istediğiniz ilk sayıyı girin: "))
sayi2 = int(input("İşlem yaapmak istediğiniz ikinci sayıyı girin: "))
op = input("Yapmak istediğiniz işlem... |
45d1116212e96e64cc261aa1c5941bd687f9d56e | lannyMa/s3 | /面向对象/08with-enter-exit.py | 3,046 | 3.96875 | 4 | #!/usr/bin/env python
# coding=utf-8
# 追踪信息+异常类+异常值
# raise AttributeError("hello world")
class Open:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
print("触发: __enter__")
def __exit__(self, exc_type, exc_val, exc_tb):
print("触发: __exit__")
# with ... |
d47a63d434018aa774834e56b7270be73253661e | panditdandgule/DataScience | /NLP/Projects/BirthdayApp.py | 1,094 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 09:10:41 2019
@author: pandit
#Birthday Reminder Application
"""
import time
#os module is used to notify user
#using default "Ubuntu" Notification bar
import os
#Birthday file is the one in which the actual birthdays
#and dates are present. Thi... |
ada0e1719a920175a7c216eaa31a4b580b3eea0d | AlexisFil/Solved_Problems_With_Python | /datetime_lib_testscript.py | 840 | 4.5 | 4 | """
A simple code demonstrating the use of datetime library
for calendar dates manipulation
"""
from datetime import datetime,timedelta
#Current date
currentDate = datetime.now()
print("Today the date is \n> {}\n".format(currentDate))
#Print date in past/future
aWeek = timedelta(days=7)
aWeekAgo = (currentDate - aW... |
706244d6701350d109509dfa3820ecd48c008330 | 821-N/holbertonschool-higher_level_programming | /0x05-python-exceptions/4-list_division.py | 459 | 3.890625 | 4 | #!/usr/bin/python3
def list_division(list_1, list_2, list_length):
result = [0] * list_length
try:
for i in range(0, list_length):
try:
result[i] = list_1[i] / list_2[i]
except ZeroDivisionError:
print("division by 0")
except (TypeError... |
4f605451cff9a4d6c2cb619c6937a3c246ace2db | SagarKulk539/APS_Lib_2020 | /Codeforces/threePairs_656_A.py | 995 | 3.6875 | 4 | '''
APS-2020
Problem Description, Input, Output : https://codeforces.com/contest/1385/problem/A
Code by : Sagar Kulkarni
'''
for _ in range(int(input())):
x,y,z=map(int,input().split())
if x==y and x==z and y==z:
print("YES")
print(x,y,z)
else:
if x==y:
a=x
b... |
961430ff650850b757dceefe38f98213312e814a | SaretMagnoslove/Python_OOP_Tutorial-Corey_Schafer | /Python OOP Tutorial 5 Special (MagicDunder) Methods/Python OOP Tutorial 1 Classes and Instances/oop.py | 410 | 3.8125 | 4 | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@compony.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('first', 'employee', 5000)
emp_2 =... |
6dae8ea26026027d2169131e9bcfe3c8d57cc286 | zolxl/python | /python/m1.2EchoName.py | 319 | 3.828125 | 4 | name = input("请输入姓名:") #输入姓名
print("{}同学,学好python,前途无量!".format(name)) #输出整个字符
print("{}大侠,学好python,大展拳脚!".format(name[0])) #输出第0个字符
print("{}哥哥,学好python,人见人爱!".format(name[1:])) #输出第一个字符以后
|
822e171340e2eae615cb1b768205109236cca25b | byungjur96/Algorithm | /2822.py | 270 | 3.5625 | 4 | score = []
questions = []
final = 0
for i in range(8):
score.append((i+1, int(input())))
score.sort(key=lambda a: a[1])
for i in range(3,8):
questions.append(str(score[i][0]))
final += score[i][1]
questions.sort()
print(final)
print(" ".join(questions))
|
968cb730d2ed3829230059558b3ea358df6e1109 | fllsouto/py14 | /cap6/funcao-kwargs.py | 829 | 3.71875 | 4 | def teste_kwargs(**kwargs):
for key, value in kwargs.items():
print('{0} = {1}'.format(key, value))
print('-'*10)
# Passando apenas uma chave
teste_kwargs(nome='fellipe')
# Passando mais de uma chave
teste_kwargs(nome='fellipe', idade=28)
dados = {"nome" : 'fellipe', "idade" : 28}
# TypeError: teste_kwargs(... |
4a486a8942d7558a434af3a1292042db2f873c9d | RodoDenDr0n/UCU_labs | /Lab 5/caesar.py | 1,385 | 3.953125 | 4 | """CAESAR ENCODE"""
def caesar_encode(message, key):
"""
>>> caesar_encode("hello", 1)
ifmmp
"""
message = message.lower()
message = list(message)
if key >= 26:
key = key % 26
for i in range(len(message)):
if message[i] == " ":
continue
if ord(messag... |
2968da6f10153ca7b4049ac5a71e23ef027bc6e3 | sweetysweets/makeSimple | /Dinic/Dinic.py | 1,626 | 3.546875 | 4 | #!/usr/bin/python
# c.durr - 2009 - max flow by Dinic in time O(n^2 m)
from queue import Queue
def dinic(graph, cap, s,t):
""" Find maximum flow from s to t.
returns value and matrix of flow.
graph is list of adjacency lists, G[u]=neighbors of u
cap is the capacity matrix
"""
assert s!=t
... |
3b05bc5abc9adb1dc12c559e60f3945bfcd6c509 | MercyFlesh/associative_rules | /associative_rules/rules.py | 5,471 | 4.125 | 4 | """
Module for finding associative rules
"""
import itertools as it
def _get_keys_combinations(sequence):
"""Get pairs of item
Сreates unique combinations for rules
from the passed sequence
Args:
sequence (tuple): sequence to get pairs of combinations
Returns:
... |
18db26889c87feda77e465990681a3d825e0a3b7 | jedi-the-code-warrior/python-applications | /geodesic_distance_between_two_addresses.py | 1,381 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 13:47:46 2019
@author: Anjani K Shiwakoti
Synopsis: Given starting address and destination address, calculate the geodesic
distance between the two locations. A geodesic line is the shortest path between
two points on a curved surface, like the Earth.
... |
6e51f874011fc0c980fd507ff6b7c820201942ce | dibery/UVa | /vol111/11108.py | 746 | 3.515625 | 4 | import sys
def test(S, p, q, r, s, t):
S = S.replace('p', p).replace('q', q).replace('r', r).replace('s', s).replace('t', t)[::-1]
stack = []
for i in S:
if i in 'TF':
stack.append(i)
elif i == 'N':
stack[-1] = 'T' if stack[-1] == 'F' else 'F'
else:
a, b = stack.pop(), stack.pop()
if i == 'K':
... |
3db9359bc0c38db69fc44918960ad0a5461d8826 | thomas-liao/leetcode_lintcode | /Python/leetcode_python/92_reverse_linked_list_ii-medium.py | 2,068 | 3.578125 | 4 | # solution 1, mine, not exactly one pass...
# class Solution:
# def reverseBetween(self, head, m: int, n: int):
# if not head or not head.next or m == n:
# return head
# dummy = ListNode(0)
# dummy.next = head
# runner1 = dummy
# counter = 0
# assert m <... |
7a0164a2b62eb121d3b6bcca547da09e9ad6259d | yooshinK/Python_Study | /Algorithm_py_Input_Num_Find_Max_Num.py | 704 | 4.09375 | 4 | import math
#-------------------------------------
def find_max_num_for(array_values):
n = len(array_values)
s = array_values[0]
max_idx = 0
for i in range(1, n):
if s <= array_values[i]:
s = array_values[i]
max_idx = i
print("Max Id is " + max_idx.__str__()... |
c7cc156d5a91f5afb2600045e9d6527c77c74e70 | LiangZZZ123/algorithm_python | /1/18_graph.py | 2,429 | 3.65625 | 4 | from collections import deque
GRAPH = {
'A': ['B', 'F'],
'B': ['C', 'I', 'G'],
'C': ['B', 'I', 'D'],
'D': ['C', 'I', 'G', 'H', 'E'],
'E': ['D', 'H', 'F'],
'F': ['A', 'G', 'E'],
'G': ['B', 'F', 'H', 'D'],
'H': ['G', 'D', 'E'],
'I': ['B', 'C', 'D'],
}
# FIFO
class Queue(object):
... |
3a85d51ba6071903a05633a03478d118d18bccd4 | mpellittieri/hear-me-code | /pbjloop.py | 460 | 4.09375 | 4 | bread = input("How many slices of bread do you have?")
peanutbutter = input("How much peanut butter do you have?")
jelly = input ("How much jelly do you have?")
sandwich = 1
while bread >= 2 and peanutbutter >=1 and jelly >=1:
print "I'm making sandwich #{0}".format(sandwich)
bread = bread - 2
peanutbutter = pean... |
1895f3c5fd2ab17e9c4b3ac935800adb2af55d8d | samuelreboucas07/Challenges-Project-Euller | /problem-2.py | 719 | 3.703125 | 4 | # Even Fibonacci numbers
limit_upper = 4000000
number_fibonacci = 1
sequence_fibonacci = [1]
sum_even_fibonacci = 0
while (number_fibonacci < limit_upper):
if(len(sequence_fibonacci) == 1):
number_fibonacci = sequence_fibonacci[0] + 1
else:
size_sequence = len(sequence_fibonacci)
numb... |
dc70644bd22c7623f9191d448f02b4dfa372348e | tykennedy13/python-work | /week_1_todo/bath_math_todo.py | 1,116 | 3.9375 | 4 | """
Lets do a basic math problem
"""
# TODO: perform all of the following mathematical operations and print the results in between
# TODO: set a constant tax rate of 20%
# TODO: ask a user what their revenue was for the quarter
# TODO: deduct the tax rate from the revenue and print the profit as well as the tax amo... |
79b055568de551296bfa426b04183f501db6b63f | Rubyroobinibu/pythonpractice | /python 15.09.19/abstraction.py | 448 | 3.609375 | 4 | class Mobile:
def __init__(self):
# self.__maxPrice=897
self.maxPrice=897
mob=Mobile()
print(mob.maxPrice)
class Mobile:
def __init__(self):
self.__maxPrice=897
def getPrice(self):
print(self.__maxPrice)
def setPrice(self,price):
... |
14c18561c0795efb27dbc0e09b49a7fbe709c375 | TyrannousHail03/PythonProjects | /Physics_VADT Calculator/vadtformulas.py | 1,637 | 4.09375 | 4 | import math
class vadtformulas:
def __init__(self):
self.vinit = None
self.vfinal = None
self.time = None
self.distance = None
self.acceleration = None
def ift_distance(self):
self.vinit = int(input("\n What is the Initial Velocity? "))
self.vfinal = int(i... |
8372ecd3e78c88144ab306e05a537e9d7e4b15e9 | mkonate/python-fun | /string-fun.py | 280 | 4.21875 | 4 | message = 'This is a basic string in single quotes'
message_2 = "This is another basic string; this time, in double quotes"
print(message)
print(message_2)
print('The lenght of the string "{}" is {}.'.format(message, len(message)))
print('All Caps: {}'.format(message.upper()))
|
6c2c2ec42521d23dffed9b0f3bea1908a5ee6230 | chelseahouston/Year-100 | /main.py | 592 | 3.984375 | 4 | def form():
name = input("What is your name? ")
age = input("What is your age? ")
try:
age = int(age)
except ValueError:
print("Incorrect value. Please enter a number. Restarting...")
form()
difference = 100 - age
year100 = 2020 + difference
print("Hello, " + name + ".")
print(f"You will tur... |
23591873e5a1f7dcec0d2640dd504384716e5e35 | neverlish/Learned | /data/ebs-ai-basic/3/5/02.py | 503 | 3.703125 | 4 | import numpy as np
import pandas as pd
df_train = pd.read_csv('fashion-mnist_train.csv')
df_test = pd.read_csv('fashion-mnist_test.csv')
# step1 각 데이터 프레임의 값을 배열에 저장하기
data_train = np.array(df_train, dtype=np.float32)
x_train = data_train[:, 1:]
y_train = data_train[:, 0]
data_test = np.array(df_test, dtype=np.floa... |
ad5944b9daf89b13c3f151f6a37109fc83bee824 | geomsb/KalHomework | /Homework 3/3_4.py | 1,177 | 3.90625 | 4 | import turtle
turtle.pensize (5)
def drawChessboard(startx, endx, starty, endy):
turtle.penup ()
turtle.goto (startx,starty)
turtle.pendown ()
for row in range (0,8):
for column in range (0,8):
if row % 2 == 0:
if column % 2 >0:
turtle.color("... |
74cda87619ad120f32f4c43a6e2e95060835acec | jwayneroth/mpd-touch | /pygameui/label.py | 7,289 | 3.625 | 4 | import re
import view
CENTER = 0
LEFT = 1
RIGHT = 2
TOP = 3
BOTTOM = 4
WORD_WRAP = 0
CLIP = 1
class Label(view.View):
"""Multi-line, word-wrappable, uneditable text view.
Attributes:
halign
CENTER, LEFT, or RIGHT. Horizontal alignment of
text.
valign
... |
c9bbad78c99bcd525962805cec6bb22cce86f12f | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day04/exercise04.py | 698 | 3.921875 | 4 | """
根据成绩判断等级,如果录入空字符串,程序退出
如果录入成绩错误达到3次,则退出程序并显示成绩输入错误
"""
count = 0
while count < 3:
str_score = input("请输入一个成绩:")
if str(str_score) == "":
break
score = int(str_score)
if 90 <= score <= 100:
print("优秀")
elif 80 <= score < 90:
print("良好")
elif 70 <= score < 80:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.