blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a9f772545af1ba2fb1e4ca48c4b8ad390d600794 | laurieskelly/lrs-bin | /euler/euler_4.py | 1,078 | 4.25 | 4 | # A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 x 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
digits = 3
def largest_palindromic_product(ndigits):
largest = 10**ndigits - 1
if is_palind... | true |
d3f0a250349a42802aa835e9683dd7fe51d3ac6e | trent-hodgins-01/ICS3U-Unit6-04-Python | /2d_average.py | 1,351 | 4.53125 | 5 | # !/user/bin/env python3
# Created by Trent Hodgins
# Created on 10/26/2021
# This is the 2D Average program
# The program asks the user how many rows and cloumns they want
# The program generates random numbers between 1-50 to fill the rows/columns
# The program then figures out and displays the average of all the nu... | true |
ea3b4a01637841a101b969124cfeb8dd08122ab4 | vallocke/zug-zug | /py_exercises/zellers_func.py | 1,340 | 4.3125 | 4 | # Name: Peter Kelt
# Date: 02-18-2013
def zellers(month, day, year):
'''zellers_func.py - Zeller's algorithm computes the day of the week on
which a given date will fall (or fell).
'''
days = {0 : 'Sunday',
1 : 'Monday',
2 : 'Tuesday',
3 : 'Wedsday',
... | false |
c838693c51ae2847566c0e635f80f05db7a215c1 | Romny468/FHICT | /Course/3.2.1.9.py | 282 | 4.21875 | 4 |
word = input("enter a word: ")
while word != 0:
if word == "chupacabra":
print("You've successfully left the loop.")
break
else:
print("Ha! You're in a loop till you find the secret word")
word = input("\ntry again, enter another word: ") | true |
02d6002df846e2f11ee5a5e7345f9df1343db18e | Romny468/FHICT | /Course/3.2.1.6.py | 394 | 4.15625 | 4 | import time
# Write a for loop that counts to five.
# Body of the loop - print the loop iteration number and the word "Mississippi".
# Body of the loop - use: time.sleep(1)
# Write a print function with the final message.
for i in range(6):
print(i, "Mississippi")
time.sleep(1)
if i == ... | true |
cf86dabe4955604b47ccc0b7e3881978291827f1 | JonathanGamaS/hackerrank-questions | /python/find_angle_mbc.py | 372 | 4.21875 | 4 | """
Point M is the midpoint of hypotenuse AC.
You are given the lengths AB and BC.
Your task is to find <MBC (angle 0°, as shown in the figure) in degrees.
"""
import math
def angle_finder():
AB = int(input())
BC = int(input())
MBC = math.degrees(math.atan(AB/BC))
answer = str(int(round(MBC)))+'°'
... | true |
d0fb9d8752231bc0728a0572e1045eb7694af8c1 | JonathanGamaS/hackerrank-questions | /python/string_formatting.py | 462 | 4.15625 | 4 | """
Given an integer, N, print the following values for each integer I from 1 to N:
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
"""
def print_formatted(number):
b = len(str(bin(number)[2:]))
for i in range(1,number+1):
print("{0}{1}{2}{3}".format(str(i).rjust(b),str(oct(i)[2:]).rjust(b... | true |
ec7ba04208c18b82e5f1b1924183b5a0c5ab2166 | ekeydar/python_kids | /lists/rand_list_ex.py | 637 | 4.125 | 4 | import random
def rand_list3():
"""
return list of 3 random items between 1 to 10 (include 1 and include 10)
"""
# write your code here
# verify that your function returns
# 3 numbers
# not all items of the list are the same always
# numbers are in 1,2,3,4,5,6,7,8,9,10
def main():
... | true |
69edca7bcdea35c28a3917d545dcbcab80e18661 | MugenZeta/PythonCoding | /BirthdayApp/Program.py | 1,260 | 4.4375 | 4 | #Birthday Program
import datetime
def printH():
User_Name = input("Hello. Welcome to the Birthday Tracker Application. Please enter your name: ")
def GetBirthDay():
#User Inputes Birthday
print()
DateY = input("Please put the year you where born [YYYY]: ")
DateM = input("Please put the year you w... | true |
40a210b5eba4a886a5056ce573276175196e98b1 | anatulea/PythonDataStructures | /src/Stacks and Queues/01_balanced_check.py | 1,475 | 4.3125 | 4 | '''
Problem Statement
Given a string of opening and closing parentheses, check whether it’s balanced. We have 3 types of parentheses: round brackets: (), square brackets: [], and curly brackets: {}. Assume that the string doesn’t contain any other character than these, no spaces words or numbers. As a reminder, balance... | true |
c07bef00e1f0ea19ca1f09e5de220f5e6ff2e3df | kuba777/sql | /cars7.py | 1,688 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Using the COUNT() function, calculate the total number of orders for each make and
# model.
# Output the car’s make and model on one line, the quantity on another line, and then
# the order count on the next line.
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connec... | true |
45f06e4bc2eb22ca904017fd6195d266643a0b21 | rprustagi/GALA-Fibonacci-Number-Programs | /chkprime.py | 395 | 4.15625 | 4 | #!/usr/bin/env python
# The programs to check if a given number is prime number.
import sys
def chkprime(param):
try:
num = int(param)
except:
return False
if num == 1:
return False
if num == 2:
return True
if num % 2 == 0:
return False
k = 3
while k * k <= num:
if num % k == 0:
... | false |
6839b8efe40a3a06f54ee81fc9a95a9ab18f189c | code613/functionalPHomework | /targilv3/t3q9.py | 1,521 | 4.15625 | 4 | #import targil3.t3q1
#from targil3 import t3q1
import targilv3.t3q1
import targilv3.t3q2 as q2
import targilv3.t3q3 as q3
import targilv3.t3q4 as q4
import targilv3.t3q5 as q5
import targilv3.t3q6 as q6
import targilv3.t3q7 as q7
import targilv3.t3q8 as q8
#dictionary menu and 1 whould be do targil3 question1
def mai... | false |
32b1cd767e5e882c04f93c41dd90af8830e3adb1 | Artexxx/Artem-python | /algorithms/Project_Euler/046 - Goldbachs other conjecture/sol1.py | 2,386 | 4.1875 | 4 | """
Кристиан Гольдбах показал, что любое нечетное составное число можно записать в виде суммы простого числа и удвоенного квадрата.
Оказалось, что данная гипотеза неверна.
9 = 7 + 2×(1)^2
15 = 7 + 2×(2)^2
21 = 3 + 2×(3)^2
25 = 7 + 2×(3)^2
27 = 19 + 2×(2)^2
33 = 31 + 2×(1)^2
Каково наименьшее нечетное составное ч... | false |
b3b0b107f3cf64ee98def0a5e6d02614eedd0dcd | Artexxx/Artem-python | /algorithms/Project_Euler/015 - Lattice Path/sol-best.py | 1,045 | 4.4375 | 4 | """
Начиная в левом верхнем углу сетки 2×2 и имея возможность двигаться только вниз или вправо,
существует ровно 6 маршрутов до правого нижнего угла сетки.
Сколько существует таких маршрутов в сетке размером gridSize?
"""
import math
def binomial(n, k):
assert 0 <= k <= n
return math.factorial(n) // (math.fa... | false |
951a0efb9e825ea81dd0ca7c7cb275a01494a422 | Artexxx/Artem-python | /algorithms/Project_Euler/018 - Maximum Path Sum I/sol1.py | 2,866 | 4.3125 | 4 | """
Начиная в вершине треугольника (см. пример ниже) и перемещаясь вниз на смежные числа, максимальная сумма до основания составляет 23.
3
7 4
2 4 6
8 5 9 3
То есть, 3 + 7 + 4 + 9 = 23
Найдите максимальную сумму пути от вершины до основания следующего треугольника:
"""
def num_to_array(triangle):
"""
Идея:... | false |
16e12a8c252bc7e83eebe5e13864b871cc9451d7 | taylorhcarroll/PythonIntro | /debug.py | 901 | 4.15625 | 4 | import random
msg = "Hello Worldf"
# practice writing if else
# if msg == "Hello World":
# print(msg)
# else:
# print("I don't know the message")
# # I made a function
# def friendlyMsg(name):
# return f'Hello, {name}! Have a great day!'
# print(friendlyMsg("james").upper())
# print(friendlyMsg("clayton"))
... | true |
df249f359269c4357e81b95506316c4481928da6 | mani67484/FunWithPython | /calculate_taxi_fare_2.py | 2,437 | 4.40625 | 4 | """
After a lengthy meeting, the company's director decided to order a taxi to take the staff home. He ordered N cars
exactly as many employees as he had. However, when taxi drivers arrived,
it turned out that each taxi driver has a different fare for
1 kilometer.The director knows the distance from work to home for ea... | true |
d8445e9f19318af7b9afc98acde565443f2e7713 | SindriTh/DataStructures | /PA2/my_linked_list.py | 2,601 | 4.21875 | 4 | class Node():
def __init__(self,data = None,next = None):
self.data = data
self.next = next # Would it not be better to call it something other than next, which is an inbuilt function?
class LinkedList:
def __init__(self):
self._head = None
self._tail = None
self._siz... | true |
c3b0de9516118a12593fdb1c33288105f5720caf | Heena3093/Python-Assignment | /Assignment 1/Assignment1_7.py | 558 | 4.25 | 4 | #7.Write a program which contains one function that accept one number from user and returns true if number is divisible by 5 otherwise return false.
#Input : 8 Output : False
#Input : 25 Output : True
def DivBy5(value):
if value % 5 == 0:
return True
else:
return False
def main()... | true |
f7cbd0159a129526f623685f9edb077d805eefd3 | Heena3093/Python-Assignment | /Assignment 3/Assignment3_4.py | 836 | 4.125 | 4 | #4.Write a program which accept N numbers from user and store it into List. Accept one another number from user and return frequency of that number from List.
#Input : Number of elements : 11
#Input Elements : 13 5 45 7 4 56 5 34 2 5 65
#Element to search : 5
#Output : 3
def DisplayCount(LIST,x):
cnt = 0
... | true |
4169416e5ec1e1bb647482465fd55ab7119a88b0 | Heena3093/Python-Assignment | /Assignment 1/Assignment1_9.py | 308 | 4.34375 | 4 | #9. Write a program which display first 10 even numbers on screen.
#Output : 2 4 6 8 10 12 14 16 18 20
def DisplayW():
print("Display First 10 even number")
i=0
while(i<20):
i=i+2
print(i)
def main():
DisplayW()
if __name__=="__main__":
main() | false |
e11d7e50b4adf445696bea2e2bbd2623c89e3af9 | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #2 Nesting, Div, and Mod/Digits of a number.py | 1,664 | 4.25 | 4 | #Author: Mohit Patel
#Date: September 16, 2014
#Purpose: To analyze positive integers and present their characteristics.
#------------------------------------------------------------------------------#
again = "Y"
while again == "y" or again == "Y":
number = int(input("Please enter a positive integer: "))
... | true |
bdb7d0ff8b7c439147fc677ac68a71ec851d2f2c | omnivaliant/High-School-Coding-Projects | /ICS3U1/Assignment #2 Nesting, Div, and Mod/Parking Garage.py | 2,142 | 4.15625 | 4 | #Author: Mohit Patel
#Date: September 16, 2014
#Purpose: To create a program that will calculate the cost of parking
# at a parking garage.
#------------------------------------------------------------------------------#
again = "Y"
while again == "Y" or again == "y":
minutes = int(input("Please enter the ... | true |
3fd8156ce49e6066d7a5ee72e892bb2f3b15ef33 | alejandroruizgtz/progAvanzada | /ejercicio34.py | 352 | 4.1875 | 4 | # Escriba un programa que lea un numero entero introduciendo pot el usuario.Su programa debe desplegar un mensaje indicando si su numero entero es par o inpar.
entero = float(int(input('Inserte un numero entero:')))
a = (entero / 2)
b = (entero % 2)
if b <= 0.0:
print('Es un numero par')
elif b >= 1:
... | false |
46e385c7eaf8fbf47187f5aca31e877c366907d7 | alejandroruizgtz/progAvanzada | /ejemplo3.py | 747 | 4.28125 | 4 | #ciclo while
#La ejcucion de esta estructura de control while es la siguiente:
#Python evalua la condicion:
#si el resultado es true, falso, se ejecuta el cuerpo del bucle
#o del ciclo. Una vez ejecutado el cuerpo del bucle, se repite
#elproceso (se evalua de nuevo la condicion y si es cierta se
#ejec... | false |
6dbd416dfcc76c593dadb4da44e5c0b4f8606061 | alejandroruizgtz/progAvanzada | /ejemplo.py | 694 | 4.125 | 4 | # El comando printp imprime un mensaje en la pantalla o en otro dispocitivo de salida. El mensaje puede ser una cadena de caracteres o cualquier objeto que sea convertible a cadena de caracteres
# El comando input permite al usuario introducir informacion utilizando el teclado. La variable donde se guarda dicha inform... | false |
cc5f99671f9f2101ff298e05a41af8c0568aefeb | alejandroruizgtz/progAvanzada | /ejercicio46.py | 519 | 4.125 | 4 | mes = input('Introduzca mes:')
dia = float(int(input('Introduzca dia:')))
if mes == 'enero' or mes =='febrero' or mes == 'marzo' or dia >= 20 or dia <=21:
print('Primavera')
elif mes == 'abril' or mes == 'mayo' or mes == 'junio' and dia >= 21 or dia <=20:
print('verano')
elif mes == 'julio' or mes =='... | false |
3a9bfeb8bf331298b613dc10f85cadd41199e5fb | 1sdc0d3r/code_practice | /leetcode/Python/backspace_compare.py | 968 | 4.15625 | 4 | # Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
# Note that after backspacing an empty text, the text will continue empty.
def backSpaceCompare(S, T):
def back(x):
newString = list()
for l in x:
if l is n... | true |
889195f0a205ab24f651a68ae067d356518c4eef | wellesleygwc/2016 | /mf/Sign-in-and-Add-user/app/db.py | 1,406 | 4.15625 | 4 | import sqlite3
database_file = "static/example.db"
def create_db():
# All your initialization code
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
# Create a table and add a record to it
cursor.execute("create table if not exists users(username text primary key not nu... | true |
b9b89f34dc087eb641cda31afde4da5022d41968 | RakeshNain/TF-IDF | /TF-IDF/task4_30750008.py | 591 | 4.1875 | 4 | """
This function is finding most suitable document for a given term(word)
"""
import pandas as pd
def choice(term, documents):
# finding IDF of given term(word)
idf = documents.get_IDF(term)
# creating a new DataFrame of the term which contain TF-IDF instead of frequencies
tf_idf_df = d... | true |
669d633b331c32363512ee50b23e414edece7277 | ElliottKasoar/algorithms | /bubblesort.py | 1,259 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 17:48:06 2020
@author: Elliott
"""
# Bubble sort algorithm
import numpy as np
import time
# Bubble sort function.
# Compares adjacent pairs of elements and swaps if first element is larger
# Repeats this (length of array - 1) times, each time ... | true |
34fbf47b698571fbe50d3fa41a948662bb64cf86 | Juliakm1997/Juliakm | /17-02_Classes/15-3-Classes2.py | 831 | 4.25 | 4 | # ----- Classes -----
# Metodo construtor
class Calculadora:
n1 = 0
n2 = 0
resultado = 0
# Criação de um método construtor, com parêmetros
def __init__(self, numero1, numero2):
self.n1 = numero1
self.n2 = numero2
# método soma utiliza as variáveis da classe n1 e n2 para realiz... | false |
ed5d38d2198adbf41ddf168c1137de333503f7ea | bwprescott/2015-Assignments-and-Projects | /c124multiplication_blakeprescott.py | 885 | 4.1875 | 4 | #!/usr/bin/python3
""" Args: 2 arrays of n bits """
def binary_multiplication(a_arr, b_arr):
print('a_arr={} b_arr={}'.format(a_arr, b_arr))
a = binary2decimal(a_arr)
print(a)
b_arr = list(reversed(b_arr))
c = [0]*len(b_arr)
pro... | false |
1d2ace87d805ecaa811e860f29f163a26c85c429 | padmacho/pythontutorial | /collections/dict/dict_demo.py | 1,585 | 4.6875 | 5 | capitals = {"india":"delhi", "america":"washington"}
print("Access values using key: ", capitals["india"])
name_age = [('dora', 5), ('mario', 10)]
d = dict(name_age)
print("Dict", d)
d = dict(a=1, b=2, c=3)
print("Dict", d)
# copying method 1
e = d.copy()
print("Copied dictionary e: ", e)
# copying meth... | true |
679d78cde339c2ab96b05a34b983f9530404d4fa | padmacho/pythontutorial | /scopes/assignment_operator.py | 311 | 4.15625 | 4 | a = 0
def fun1():
print("fun1: a=", a)
def fun2():
a = 10 # By default, the assignment statement creates variables in the local scope
print("fun2: a=", a)
def fun3():
global a # refer global variable
a = 5
print("fun3: a=", a)
fun1()
fun2()
fun1()
fun3()
fun1()
| true |
25b4cc8f5f2f989e126dc684386245f8ab25e16a | qilaidi/leetcode_problems | /leetcode/155MinStack.py | 1,488 | 4.21875 | 4 | class MinStack1:
"""
1。 直接用列表 (leetcode已提交, 这种耗时较高主要是因为没有存最小值)
2。 用链表 (leetcode已提交)
3。 用tuple列表
"""
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x: int) -> None:
if self.stack == []:
sel... | false |
e14df3b6a6de916386a171b5095f282f2a2885be | Mokarram-Mujtaba/Complete-Python-Tutorial-and-Notes | /23. Python File IO Basics.py | 755 | 4.28125 | 4 | ########### Python File IO Basics #########
# Two types of memory
# 1. Volatile Memory : Data cleared as System Shut Down
# Example : RAM
# 2. Non-Volatile Memory : Data remains saved always.
# Example : Hard Disk
# File : In Non-Volatile Memory we store Data as File
# File may be text file,binary file(Ex - Image,mp3... | true |
9892c365ccbe67416408836343251224372f854f | Mokarram-Mujtaba/Complete-Python-Tutorial-and-Notes | /15. While Loops In Python.py | 506 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# As... | true |
658bf19caa15b39086e4166c6bd43b8f026939e4 | evlevel/lab_6_starting_repo | /lab_6_starting/wordstats.py | 794 | 4.28125 | 4 | #
# wordstats.py:
#
# Starting code for Lab 6-4
#
# we'll learn more about reading from text files in HTT11...
FILENAME = 'words.txt'
fvar = open(FILENAME, 'r') # open file for reading
bigline = fvar.read() # read ENTIRE file into single string
# what happens when you print such a big line?
# try it, by unc... | true |
015b5f6887cc692ae30fdef44d1fa87e8b74ae6b | toma-ungureanu/FII-Python | /lab1/ex1.py | 1,142 | 4.3125 | 4 | class Error(Exception):
"""Exception"""
pass
class NegativeValueError(Error):
"""Raised when the input value is negative"""
pass
class FloatError(Error):
"""Raised when the input value is negative"""
pass
def find_gcd_2numbers(num1, num2):
try:
if num1 < 0 or num2 < 0:
... | true |
dc276b879b3045f27a3ae01b0984e82cf831f970 | toma-ungureanu/FII-Python | /lab5/ex5.py | 816 | 4.1875 | 4 | import os
def writePaths(dirname,filename):
file_to_write = open(filename, "w+", encoding='utf-8')
for root, dirs, files in os.walk(dirname):
path = root.split(os.sep)
file_to_write.write((len(path) - 1) * '---')
file_to_write.write(os.path.basename(root))
file_to_write.write("... | true |
f7fba7853ba6cd086384d43014fae831e5597215 | Dhruvish09/PYTHON_TUT | /Loops/function with argument.py | 1,111 | 4.5 | 4 | #Information can be passed into functions as arguments.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
#You can also send arguments with the key = value syntax.
def my_function(child3, child2, child1):
print("The youngest child is ... | true |
8af2a7bee92cdbddf41e63bc1cc143b3da929b93 | Dhruvish09/PYTHON_TUT | /Operators/Comparison Operator/ALL IN ONE.py | 273 | 4.28125 | 4 | # Examples of Comparion Operators
a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
| false |
bde78bbe09e2ba11f43555b4fce453392628e4f7 | RavikrianGoru/py_durga | /telsuko_one/py_samples/poly_method_overloading_37.py | 1,319 | 4.21875 | 4 | class Nums:
def __init__(self,m=0):
self.m=m
#def sum(self, m1,m2):
# return m1+m2
#def sum(self,m1,m2, m3):
# return m1+m2+m3
#method overloading trick
def sum(self, m1=None, m2=None, m3=None):
if m1!=None and m2!=None and m3!=None:
return m1+m2+m3
... | false |
6d260adeec1de35945ff49f6cf3507881b93e724 | RavikrianGoru/py_durga | /byte_of_python/py_flowcontrol_func_modules/10_while_else.py | 674 | 4.125 | 4 | # while-else
# input() is builtin function. we supply input as string. Once we enter something and press kbd[enter] key.
# input() function returns what we entered as string.
# then we can convert into any format what we required.
pass_mark = 45
running = True
print('Process is started')
while running:
marks = i... | true |
565570d8c4eb0e04658e96ff362e08957f516f33 | RavikrianGoru/py_durga | /byte_of_python/ds/ds_using_set.py | 907 | 4.1875 | 4 | # Sets are unordered collections of simple objects. These are used when the existence of an
# object in a collection is more important than the order or how many times it occurs.
cities = {'gnt','mas','vij'}
print('all cities set:', cities)
names = ['gnt', 'mas', 'vij', 'gnt']
print('all names list:', names)
s = set(na... | false |
3f26b2ccfc2e70402b275e09a4aa6b9a7a4a7b8a | emma-ola/calc | /codechallenge.py | 1,015 | 4.40625 | 4 | # Days in Month
# convert this function is_leap(), so that instead of printing "Leap year." or "Not leap year." it
# should return True if it is a leap year and return False if it is not a leap year.
# create a function called days_in_month() which will take a year and a month as inputs
def is_leap(year):
""" Th... | true |
545f2e6bbc59b938c2e23b1c0a4ffbda28b5f2a9 | viveksyngh/Algorithms-and-Data-Structure | /Data Structure/Queue.py | 792 | 4.21875 | 4 | class Queue :
def __init__(self) :
"""
Initialises an empty Queue
"""
self.items = []
def is_empty(self) :
"""
Returns 'True' if Queue is empty otherwise 'False'
"""
return self.items == []
def enqueue(self, item) :
"""
Inse... | true |
40cc7c6d18482056565687650ad8f77cf15208fd | AmitKulkarni23/OpenCV | /Official_OpenCV_Docs/Core_Operations/place_image_over_another_using_roi.py | 1,942 | 4.15625 | 4 | # Placing image over another image using ROI
# Use of bitwise operations and image thresholding
# API used
# cv2.threshold
# 1st arg -> gray scale image
# 2nd arg -> threshold value used to classify the images
# 3rd arg -> Value to be given if pixel value is more than threshold value
# 4th arg -> different styles of t... | true |
992c7145f29120ebfdaf21b2b503a9ebe5f05a60 | rossirm/Python | /Programming-Basics/Complex-Conditional-Statements/fruit_or_vegetable.py | 350 | 4.375 | 4 | plant = input()
result = ''
if plant == 'banana' or plant == 'apple' or plant == 'kiwi' \
or plant == 'cherry' or plant == 'lemon' or plant == 'grapes':
result = 'fruit'
elif plant == plant == 'tomato' or plant == 'cucumber' or plant == 'pepper' or plant == 'carrot':
result = 'vegetable'
else:
resu... | false |
9a7f222209e105a33d45217efb1e1f26656a4a87 | AndreasArne/python-examination | /test/python/me/kmom01/plane/plane.py | 877 | 4.5 | 4 | #!/usr/bin/evn python3
"""
Program som tar emot värden av en enhetstyp och omvandlar till motsvarande
värde av en annan.
"""
# raise ValueError("hejhejhej")
# raise StopIteration("hejhejhej")
print("Hello and welcome to the unit converter!")
hight = float(input("Enter current hight in meters over sea, and press enter... | true |
42e2363e23f1bb3ab1a1d905b7165e4c1371e456 | raymonshansen/dungeon | /python/utils.py | 1,832 | 4.1875 | 4 | """Utility functions."""
def plot_line(x1, y1, x2, y2):
"""Brensenham line drawing algorithm.
Return a list of points(tuples) along the line.
"""
dx = x2 - x1
dy = y2 - y1
if dy < 0:
dy = -dy
stepy = -1
else:
stepy = 1
if dx < 0:
dx = -dx
stepx ... | false |
ab77e72fabb93382bb3f009069465def1d6c3368 | suraj-thadarai/Learning-python-from-Scracth | /findingFactorial.py | 263 | 4.375 | 4 | #finding the factorial of a given number
def findingFactorial(num):
for i in range(1,num):
num = num*i
return num
number = int(input("Enter an Integer: "))
factorial = findingFactorial(number)
print("Factorial of a number is:",factorial)
| true |
6b1883815e71b89b42642fb84a893a599e69496e | cseshahriar/The-python-mega-course-practice-repo | /advance_python/map.py | 407 | 4.28125 | 4 | """
The map() function executes a specified function for
each item in an iterable. The item is sent to the function as a parameter.
"""
def square(n):
return n * n
my_list = [2, 3, 4, 5, 6, 7, 8, 9]
map_list = map(square, my_list)
print(map_list)
print(list(map_list))
def myfunc(a, b):
return a + b
x ... | true |
ae867fa7bd813de8cc06c1d30a7390eb8201e7fd | cseshahriar/The-python-mega-course-practice-repo | /random/random_example.py | 939 | 4.625 | 5 | # Program to generate a random number between 0 and 9
# importing the random module
import random
""" return random int in range """
print(random.randint(0, 9))
""" return random int in range"""
print(random.randrange(1, 10))
""" return random float in range """
print(random.uniform(20, 30))
"""
To pick a random e... | true |
4e75f9a6e15452f67f38d7eb43b17bc8cd8aacf9 | nikhiilll/Algorithms-using-Python | /Easy-AE/BubbleSort.py | 648 | 4.125 | 4 | def bubbleSort(array):
n = len(array)
for i in range(n):
for j in range(n - i - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
"""
TC: O(n^2) | SC: O(1)
"""
def bubbleSort2(array):
isSorted = False
counter =... | false |
414024ec189b3b448632b6743408ca1235df3b7c | Darja-p/python-fundamentals-master | /Labs/06_functions/06_02_stats.py | 455 | 4.125 | 4 | '''
Write a script that takes in a list and finds the max, min, average and sum.
'''
inp1 = input("Enter a list of numbers: ")
def MinMax(a):
listN = a.split()
listN = [float(i) for i in listN]
max_value = max(listN)
min_Value = min(listN)
avg_Value = sum(listN) / len(listN)
sum_Value = sum(li... | true |
700b4701729713ce93c836709beef9b393dd6327 | Darja-p/python-fundamentals-master | /Labs/08_file_io/08_01_words_analysis.py | 646 | 4.3125 | 4 | '''
Write a script that reads in the words from the words.txt file and finds and prints:
1. The shortest word (if there is a tie, print all)
2. The longest word (if there is a tie, print all)
3. The total number of words in the file.
'''
from itertools import count
list1 = []
with open("words.txt",'r') as fin:
... | true |
6a8ba495dd00b7a9bd3d40098780799e4bb5d03d | Darja-p/python-fundamentals-master | /Labs/07_classes_objects_methods/07_05_freeform_inheritance.py | 2,115 | 4.21875 | 4 | '''
Build on your previous freeform exercise.
Create subclasses of two of the existing classes. Create a subclass of
one of those so that the hierarchy is at least three levels.
Build these classes out like we did in the previous exercises.
If you cannot think of a way to build on your freeform exercise,
you can sta... | true |
8b84cae134528d332b0cf3e998c873697381a45e | Darja-p/python-fundamentals-master | /Labs/03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 485 | 4.1875 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list1 = list(input_dict.items())
print(list1)
def takeSecond... | true |
4d0e725efd60894619a1274d24eeb1d823966a72 | Darja-p/python-fundamentals-master | /Labs/02_basic_datatypes/02_05_convert.py | 731 | 4.5 | 4 | '''
Demonstrate how to:
1) Convert an int to a float
2) Convert a float to an int
3) Perform floor division using a float and an int.
4) Use two user inputted values to perform multiplication.
Take note of what information is lost when some conversions take place.
'''
a = 2
print (a)
a = float ... | true |
0ac789041795f5876f64b57d894d57cba7182993 | OrNaishtat/Python---Magic-Number | /TheMagicNumber.py | 2,032 | 4.1875 | 4 | ########################################################################################################################################
### NewLight - The Magic Number.
### The magic number generates a random number between 1 and 10, the user needs to guess the number.
### The user has a limited number of lives (NB... | true |
6836f4e8fada111cc10e3da114f6139277b1312f | nooknic/MyScript | /var.py | 277 | 4.25 | 4 | #Initialize a variable with an integer value.
var = 8
print(var)
#Assign a float value to the variable.
var = 3.142
print(var)
#Assign a string value to the variable.
var="Python in easy steps"
print(var)
#Assign a boolean value to the variable.
var = True
print(var)
| true |
5f26386ef1362913cba95ad2ec17ae5869fc90e3 | jagrutipyth/Restaurant | /Inheritance_polymorphism.py | 807 | 4.125 | 4 | class Restaurant:
def __init__(self,customer,money):
self.customer = customer
self.__money = money
def coupan(self):
print(f"Hello, {self.customer},please pay {self.__money} and take your coupan")
class IcecreamStand(Restaurant):
'''Using this class to show inheritence & polymorp... | true |
120762fb80c0df66a6102d87d0bac74ea94dbb4c | Ridwanullahi-code/python-list-data-type | /assignment.py | 961 | 4.25 | 4 | # base from the given list below create a python function using the following condition as specified below
# (a) create a seperated lists of string and numbers
# (b) sort the strings list in ascending order
# (c) sort the string list in descending order
# (d) sort the number list from the lowest to high
# (e) sort the ... | true |
c7a76e6560b621b5e0c8b51a17685d016f46e4d2 | lowks/levelup | /hackerrank/staircase/staircase.py | 404 | 4.21875 | 4 | #!/bin/python
import sys
def staircase(total, number):
# Complete this function
hash_number = ""
for space in range(0, total - number):
hash_number += " "
for hash in range(0, number):
hash_number = hash_number + "#"
return hash_number
if __name__ == "__main__":
n = int(raw_in... | true |
bf61a8579548ab114612df83c57576df998186fa | jacealan/eulernet | /level1/9-Special Pythagorean triplet.py | 953 | 4.21875 | 4 | #!/usr/local/bin/python3
'''
Problem 9 : Special Pythagorean triplet
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
https://projecteul... | false |
9964e05b7c8fd3ee6588d476fa2cbe240c7b921d | jacealan/eulernet | /level2/38-Pandigital multiples.py | 1,240 | 4.1875 | 4 | #!/usr/local/bin/python3
'''
Problem 38 : Pandigital multiples
Take the number 192 and multiply it by each of 1, 2, and 3:
192 × 1 = 192
192 × 2 = 384
192 × 3 = 576
By concatenating each product we get the 1 to 9 pandigital, 192384576.
We will call 192384576 the concatenated product of 192 and (1,2,3)
The same can be a... | true |
d1304b21ceb527d863c16c297877ae04b5405962 | daredtech/lambda-python-1 | /src/14_cal.py | 1,756 | 4.53125 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
... | true |
a5924b232af9c4c761d7093cce952507ba9341a8 | gopikrishnansa/weather_in_your_location | /weather app.py | 1,417 | 4.15625 | 4 | import requests
class weather:
def get(self):
try:
#gets data from openweathermap api
#converting that info to json
#accessing json files
#printing the info here
global city,api_address,mainweather,descriptio,wind,name
name = input("en... | true |
0e370f1c06a4399bf69cc0171b8d89e654c4958c | Westamus/PycharmProjects | /lesson_003/01_days_in_month.py | 1,940 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
user_input = input("Введите, пож... | false |
a7cd28c10d88473e318bf9daa1192d408d78f54a | sulleyi/CSC-120 | /Project1/card.py | 474 | 4.15625 | 4 | class card:
"""
Class for the card object
"""
def __init__(self, value, suit):
"""
initializes card object
:param self: instance of card
:param value: cards number or face value
:param suit: suit value of card (heart,diamond, club, or spade)
:return:
... | true |
c2a75a3e85541ad15cba57dbc6488e4532082b22 | shayansaha85/python_basic_loops_functions | /Factorial.py | 307 | 4.25 | 4 | # Python Program to Find the Factorial of a Number
def findFactorial(number):
if number==0:
return 1
elif number==1:
return 1
else:
return number * findFactorial(number-1)
number = int(input("Enter a number = "))
print("{0}! = {1}".format(number,findFactorial(number))) | true |
a95fb7f69f3169c125d3fa9dfc65380b2ff5efed | JubindraKc/Test_feb_19 | /question2.py | 598 | 4.125 | 4 | '''
2. Create a class Circle which has a class variable PI with value=22/7.
Make two methods getArea and getCircumference inside this Circle class.
Which when invoked returns area and circumference of each ciecle instances.
'''
class Circle:
PI = 22/7
def __init__(self,radius):
self.radius = rad... | true |
ecbdca79b8bca2250d1fc37b4449d4994c143096 | mpowers47/cs1301-intro-to-python | /Unit 3 - Control Structures/WordCount2.py | 1,981 | 4.5 | 4 | # Now let's make things a little more challenging.
#
# Last exercise, you wrote a function called word_count that
# counted the number of words in a string essentially by
# counting the spaces. However, if there were multiple spaces
# in a row, it would incorrectly add additional words. For
# example, it would ha... | true |
8f50331313f4b9b62dbcc35eeda564773bebddf3 | mpowers47/cs1301-intro-to-python | /Unit 4 - Data Structures/AfterSecond.py | 1,592 | 4.4375 | 4 | # Write a function called after_second that accepts two
# arguments: a target string to search, and string to search
# for. The function should return everything in the first
# string *after* the *second* occurrence of the search term.
# You can assume there will always be at least two
# occurrences of the searc... | true |
2b969a489710375589779588bfe13a51025b0dfc | mpowers47/cs1301-intro-to-python | /Unit 2 - Procedural Programming/GoOutToLunch.py | 1,144 | 4.46875 | 4 | hungry = True
coworkers_going = False
brought_lunch = False
# You may modify the lines of code above, but don't move them!
# When you Submit your code, we'll change these lines to
# assign different values to the variables.
# Imagine you're deciding whether or not to go out to lunch.
# You only want to go ... | true |
8b4516e193fc6281abace1fa4c3205446c57d366 | Sameer411/First_Year_Lab_Assignment | /sem 2 Programs/Assignment5/sqrt.py | 499 | 4.3125 | 4 | import math
print("We have to find squareroot of a number:\n")
number=int(input("Please enter the number:"))
if number<0:
print("Please enter valid number:")
else:
print('Squareroot of the number {0} is {1}'.format(number,math.sqrt(number)))
#OUTPUT:
#pl-ii@plii-dx2480-MT:~/Desktop/FE-D-07/ASSIGNMENT6$ python s... | true |
9ec48f6722ff8c3e5e6e21786aab2d10f045cd16 | paluch05/Python-rep | /Task17/Task17.py | 667 | 4.125 | 4 | def longest_sentence_and_most_common_word():
stream = open('artykul.txt', 'r', encoding='utf-8')
try:
content = stream.read()
n = content.split(".")
length_of_sentence = [len(i) for i in n]
from collections import Counter
count = Counter(content.lower().strip().split())
... | true |
a9d359ded1e81d98b61397d883a82e22a4682758 | luizolima/estudo-python | /08-escopo_de_variaveis.py | 1,046 | 4.59375 | 5 | """
Escopo de variáveis
Dois casos de escopo:
1 - Variáveis globais: São reconhecidas, ou seja, se escopo compreende, todo o programa.
2 - Variáveis locais: São reconhecidas apenas no blovo onde foram declaradas, ou seja, seu escopo está limitado ao bloco
onde foi declarada.
Para declarar variáveis em Python fazemos... | false |
5dbd68eb09ca61915dba0136dbd97a4bb5fbe3ad | doitharsha007/ost | /8b.py | 848 | 4.125 | 4 | from math import floor # importing 'floor' function from 'math' module
start = int(input("Enter the start of the Armstrong number range - ")) #lower limit
end = int(input("Enter the end of the Armstrong number range - ")) #upper limit
if start > end or start < 0 or end < 0:
print("Invalid range")
else:
fl... | true |
d12e0cf63a30c0065fd77ded34de601eb64c7369 | doitharsha007/ost | /9b.py | 770 | 4.125 | 4 | # 9b) : Write a program to find maximum element in the list using recursive
# functions
def maximum(numbers):
if len(numbers) == 1: #if length of list is 1
return numbers[0]
else:
max1 = numbers[0]
if max1 > numbers[1]: #if first element > second element
del n... | true |
a6ab60f863d6d342baef9849a1f9ea71a263efe8 | umeshpatil080/examples | /python/Programs/CTCI/string_reversal.py | 807 | 4.25 | 4 | #-------------------------------------------------------------------------------
# Reversing a string
#-------------------------------------------------------------------------------
class StrReversal():
def __init__(self):
pass
def reverse(self, string = ""):
if(not string):
r... | false |
207c8a802058b19c23dfa1de8d754941c84c74eb | dobrienSTJ/Daniels-Projects | /SpeedDistanceTime.py | 1,153 | 4.28125 | 4 | #A simple Program that calculates the Speed, Distance and Time!
print("This is a simple Program that calculates the Speed, Distance and Time!")
triangle=input("Please choose a number to find out: 1. Speed 2. Distance 3. Time")
if triangle == "1":
print("We will find the Speed")
distance1=(int(input("Please ... | true |
293e24949673b471c1a83d42ca74818f625dfa53 | dobrienSTJ/Daniels-Projects | /Quadratic.py | 991 | 4.25 | 4 | #A simple Program that automically adds the variable on at the start of the calculation in the same unit
def variable(x):
x = (int(x))
x = x**2
xword = (str(x))
print(xword+" is your Variable!!")
print("Now we will move onto the calculating unit") ... | true |
70578b8fa3afdc6a9394a8531ab7a29ea06617dc | aasheeshtandon/Leetcode_Problems | /102_RECURSIVE_binary_tree_level_order_traversal.py | 1,052 | 4.46875 | 4 |
# Recursive Level Order Traversal of a Binary Tree.
## Time Complexity: O(n)^2 where n is number of nodes in the binary tree
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def height(root):
if root is None:
return 0
return max(height(... | true |
11cc8880c170c7ec22010502b9606cccf3c740ac | evelinasvarovskaya/evelina | /theme10/theme10.1.py | 255 | 4.1875 | 4 | value1 = int(input("Enter A: "))
value2 = int(input("Enter B: " ))
if value1>2 and value2<=3:
print("Неравенства A > 2 и B ≤ 3 справедливы.")
else:
print("Неравества A > 2 и B ≤ 3 несправедливы.") | false |
17ce117e7470a71e2117b023b2eae966a40a5a9a | MCornejoDev/Python | /EjerciciosIFElse/Ejercicio5.py | 689 | 4.125 | 4 | #Escriba un programa que pida tres números y que escriba si son los tres iguales,
#si hay dos iguales o si son los tres distintos.
print("COMPARADOR DE TRES NÚMEROS")
n1 = float(input("Dime un número : ")); n2 = float(input("Dime otro número : ")); n3 = float(input("Dime otro número : "))
if(n1 == n2 and n1 == n3 and... | false |
482fa766ee6a9dedae61f9f62d555b124a8f67f3 | kjazleen/assignment | /assignment8.py | 1,236 | 4.21875 | 4 | #Q1 what is time tuple?
print("There is a popular time module available in python which provides function for working with time,and for converting"
" between representations ,the function (time.time()) returns the current system time in ticks since 12 am,january 1,1970(epoch)")
#"Index Attribute values... | false |
51461972405b769a39923c6255218c83f53b0a7f | proneetsharma/maze_solver | /helper.py | 1,318 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import collections
import string
import copy
def next_movement(position):
x, y = position
next_pos = [(x-1, y), (x, y-1), (x+1, y), (x, y+1)]
return next_pos
def write_to_file(file_name, all_path, maze_map):
"""Function to write o... | true |
a791f10e75505502f07622fd0d08c05994b04216 | chaseyb/python-snake-game-v2 | /Button.py | 1,582 | 4.125 | 4 | class button(object):
"""
This is a button class that makes it easy to create buttons. It includes a button initializer, and several control
functions, such as changing colour when the button is hovered.
"""
def __init__(self, colour, hoverColour, display, text, left, top, width, height, textColour... | true |
bdf38d484f83c59ac00cf2be84ae78236e1eecf1 | joe-bq/dynamicProgramming | /python/LearnPythonTheHardWay/FileSystem/Shelves/ShelvesOperation.py | 1,004 | 4.125 | 4 | '''
Created on 2012-11-16
@author: Administrator
file: ShelvesOperation.py
description: this file will demonstrate the use of the shelv object
what is shelve? shelves is something that gives you some basic persistence so you will be able to retrieve what you have shelved in last session
'''
import ... | true |
292fa24444c2d56dee834171f54e39e819495951 | k-schmidt/Learning | /Data_Structures_and_Algorithms/1_1.py | 442 | 4.25 | 4 | '''
Write a short Python function, is_multiple(n, m), that takes two integer values
and returns True if n is a multiple of m, that is, n = mi for some integer i,
and False otherwise.
'''
def is_multiple(n, m):
try:
return True if (int(n) % int(m) == 0) else False
except ValueError:
print "Numb... | true |
30dac93810bf90c35d6622ded8f249632216e5b4 | imlifeilong/MyAlgorithm | /leetcode/双指针/26. 删除有序数组中的重复项.py | 1,613 | 4.25 | 4 | """
输入:nums = [1,1,2]
输出:2, nums = [1,2,_]
解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。
输入:nums = [0,0,1,1,1,2,2,3,3,4]
输出:5, nums = [0,1,2,3,4]
解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。
思路
快慢指针 left 指向0 right 指向1
比较left 和 right 指向的值是否相等,如果相等,right向前移动
如果不相等,left移... | false |
03afc7fb75e5a49441c5a90dee8bd5fd0b336a91 | imlifeilong/MyAlgorithm | /basic/排序/排序-选择排序.py | 1,103 | 4.40625 | 4 | # _*_ coding:utf-8 _*_
'''
选择排序过程:
1、首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,
2、然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
3、以此类推,直到所有元素均排序完毕。
比较次数n(n-1)/2
时间复杂度O(n2)
'''
def select_sort(data):
length = len(data)
for i in range(length):
# 选择第一个元素为记为最小值,min_index左边是排行顺序的
min_index = i
... | false |
f2bfd56ab1e8b66be51c7646b8d797273457b5c1 | PatrickWalsh6079/Software_Security | /Brute force PIN entry/brute_force_PIN.py | 1,819 | 4.25 | 4 | """
Filename: brute_force_PIN.py
Author: Patrick Walsh
Date: 5/2/2021
Purpose: Program shows a simulation of an ATM display
screen that asks the user for their PIN. The program
is vulnerable to a brute force entry that randomly guesses
the PIN until it finds the right one. The program also
provides a mitigation... | true |
a3ac403d1c99f9eab7c7b0ae8f8f93b25621550f | Sulav13/python-experiments | /cw1/distance.py | 1,023 | 4.6875 | 5 | # A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of
# robot movement is shown as the following:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# The numbers after the direction are steps. Please write a program to compute the distanc... | true |
024a3571a0078a16507c2afd991a9d21b002e171 | swaroop325/python-programs | /4.py | 305 | 4.125 | 4 | def most_repeated_letters(word_1):
lettersCount = {}
for ch in word_1:
if ch not in lettersCount:
lettersCount[ch] = 1
else:
lettersCount[ch] += 1
return max(lettersCount, key=lettersCount.get)
str=input()
print most_repeated_letters(str)
| true |
e0f2a70c32cf95ed23f08ed72390e37d0adcaa84 | XNetLab/ProbGraphBetwn | /util.py | 548 | 4.1875 | 4 | #! /usr/bin/python
# coding = utf-8
import time
from functools import wraps
def fn_timer(function):
"""
Used to output the running time of the function
:param function: the function to test
:return:
"""
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.