blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
56df42f25fc0a3dddd57a8d70c63d7a3a4754900 | devmadhuu/Python | /assignment_01/check_substr_in_str.py | 308 | 4.34375 | 4 | ## Program to check if a Substring is Present in a Given String:
main_str = input ('Enter main string to check substring :')
sub_str = input ('Enter substring :')
if main_str.index(sub_str) > 0:
print('"{sub_str}" is present in main string - "{main_str}"'.format(sub_str = sub_str, main_str = main_str))
| false |
92d2b840f03db425aaaedf22ad57d0b291bb79e6 | devmadhuu/Python | /assignment_01/odd_in_a_range.py | 505 | 4.375 | 4 | ## Program to print Odd number within a given range.
start = input ('Enter start number of range:')
end = input ('Enter end number of range:')
if start.isdigit() and end.isdigit():
start = int(start)
end = int(end)
if end > start:
for num in range(start, end):
if num % 2 != 0:
... | true |
020278f3785bb409de5cd0afd67c4ccaf295e011 | devmadhuu/Python | /assignment_01/three_number_comparison.py | 1,464 | 4.21875 | 4 | ## Program to do number comparison
num1 = input('Enter first number :')
if num1.isdigit() or (num1.count('-') == 1 and num1.index('-') == 0) or num1.count('.') == 1:
num2 = input('Enter second number:')
if num2.isdigit() or (num2.count('-') == 1 and num2.index('-') == 0) or num2.count('.') == 1:
num3 =... | false |
66c8afbcdd793b3817993abfb904b4ec0111f666 | devmadhuu/Python | /assignment_01/factorial.py | 410 | 4.4375 | 4 | ## Python program to find the factorial of a number.
userinput = input ('Enter number to find the factorial:')
if userinput.isdigit() or userinput.find('-') >= 0:
userinput = int(userinput)
factorial = 1
for num in range (1, userinput + 1):
factorial*=num
print('Factorial of {a} is {factorial}'.... | true |
83c5184a88d030bfd7d873e728653ac1f0248245 | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio04.py | 1,195 | 4.28125 | 4 | '''
Tenemos que decidir entre 2 recetas ecológicas.
Los ingredientes para cada tipo de receta aparecen a continuación.
Ingredientes comunes: Verduras y berenjena.
Ingredientes Receta 1: Lentejas y apio.
Ingredientes Receta 2: Morrón y Cebolla..
Escribir un programa que pregunte al usuario que tipo de receta desea,
... | false |
77329d1eb28a5d3565a346a30047871d2306abc6 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio01.py | 1,484 | 4.21875 | 4 | '''
DESAFÍO 1
Nos han pedido desarrollar una aplicación móvil para reducir comportamientos inadecuados para el ambiente.
a) Te toca escribir un programa que simule el proceso de Login. Para ello el programa debe preguntar
al usuario la contraseña, y no le permita continuar hasta que la haya ingresado correctamente.
... | false |
6d030f79eb3df2a3572eaadb0757401d3a330326 | amark02/ICS4U-Classwork | /Quiz2/evaluation.py | 2,636 | 4.25 | 4 | from typing import Dict, List
def average(a: float, b: float, c:float) -> float:
"""Returns the average of 3 numbers.
Args:
a: A decimal number
b: A decimal number
c: A decimal number
Returns:
The average of the 3 numbers as a float
"""
return (a + b + c)/3
def c... | true |
5b632636066e777092b375219a7a6cd571619157 | amark02/ICS4U-Classwork | /Classes/01_store_data.py | 271 | 4.1875 | 4 |
class Person:
pass
p = Person()
p.name = "Jeff"
p.eye_color = "Blue"
p2 = Person()
print(p)
print(p.name)
print(p.eye_color)
"""
print(p2.name)
gives an error since the object has no attribute of name
since you gave the other person an attribute on the fly
""" | true |
23ee2c8360e32e0334a31da848043cf6187cd636 | cosinekitty/astronomy | /demo/python/gravity.py | 1,137 | 4.125 | 4 | #!/usr/bin/env python3
import sys
from astronomy import ObserverGravity
UsageText = r'''
USAGE:
gravity.py latitude height
Calculates the gravitational acceleration experienced
by an observer on the surface of the Earth at the specified
latitude (degrees north of the equator) and height
(met... | true |
e79076cd45b6280c2046283d9a349620af0f8d70 | joshinihal/dsa | /trees/tree_implementation_using_oop.py | 1,428 | 4.21875 | 4 | # Nodes and References Implementation of a Tree
# defining a class:
# python3 : class BinaryTree()
# older than python 3: class BinaryTree(object)
class BinaryTree():
def __init__(self,rootObj):
# root value is also called key
self.key = rootObj
self.leftChild = None
self.righ... | true |
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7 | AGriggs1/Labwork-Fall-2017 | /hello.py | 858 | 4.125 | 4 | # Intro to Programming
# Author: Anthony Griggs
# Date: 9/1/17
##################################
# dprint
# enables or disables debug printing
# Simple function used by many, many programmers, I take no credit for it WHATSOEVER
# to enable, simply set bDebugStatements to true!
##NOTE TO SELF: in Python, first letter ... | true |
f2794e3c31b085db9b10afa837d6026848ef1318 | lucasferreira94/Python-projects | /jogo_da_velha.py | 1,175 | 4.25 | 4 | '''
JOGO DA VELHA
'''
# ABAIXO ESTAO AS POSIÇÕES DA CERQUILHA
theBoard = {'top-L':'', 'top-M':'', 'top-R':'',
'mid-L':'','mid-M':'', 'mid-R':'',
'low-L':'', 'low-M':'', 'low-R':''}
print ('Choose one Space per turn')
print()
print(' top-L'+' top-M'+ ' top-R')
print()
print(' mid-L'+' mid-... | false |
a9746ae70ae68aefacd3bb071fae46e949a7e29f | YangYishe/pythonStudy | /src/day8_15/day8_2.py | 683 | 4.40625 | 4 | """
定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法。
"""
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def move(self, x, y):
self._x += x
self._y += y
def distance_between(self, other_point):
return ((self._x - other_point._x) ** 2 + (self._y - other_point._y) *... | false |
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7 | SanamKhatri/school | /teacher_delete.py | 1,234 | 4.1875 | 4 | import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the... | true |
b86433902a7cf3e9dcba2d7f254c4318656ca7f7 | heba-ali2030/number_guessing_game | /guess_game.py | 2,509 | 4.1875 | 4 | import random
# check validity of user input
# 1- check numbers
def check_validity(user_guess):
while user_guess.isdigit() == False:
user_guess = input('please enter a valid number to continue: ')
return (int(user_guess))
# 2- check string
def check_name(name):
while name.isalpha() == False:
... | true |
01a31344d5f0af270c71baa134890070081a1d5c | ColgateLeoAscenzi/COMPUTERSCIENCE101 | /LAB/Lab01_challenge.py | 898 | 4.28125 | 4 |
import time
import random
#Sets up the human like AI, and asks a random question every time
AI = random.randint(1,3)
if AI == 1:
print "Please type a number with a decimal!"
elif AI == 2:
print "Give me a decimal number please!"
elif AI == 3:
print "Please enter a decimal number!"
#defines t... | true |
bc9b0e89b907507970b187a44d0bfc3ecf2d4142 | ColgateLeoAscenzi/COMPUTERSCIENCE101 | /LAB/lab03_vowels.py | 273 | 4.21875 | 4 | #Leo Ascenzi
#sets up empty string
ohne_vowels = ""
#gets response
resp = str(raw_input("Enter a message: "))
#for loop to check if character is in a string
for char in resp:
if char not in "aeiouAEIOU":
ohne_vowels += char
print ohne_vowels
| false |
676f4845dc145feee1be508213721e26f2e55b2a | ColgateLeoAscenzi/COMPUTERSCIENCE101 | /HOMEWORK/hw3_leap.py | 2,055 | 4.15625 | 4 | # ----------------------------------------------------------
# -------- PROGRAM 3 ---------
# ----------------------------------------------------------
# ----------------------------------------------------------
# Please answer these questions after having completed this
# program
# ---... | true |
7004bc9b49acc1a75ac18e448c2256cbec808cf4 | CodyPerdew/TireDegredation | /tirescript.py | 1,350 | 4.15625 | 4 | #This is a simple depreciation calculator for use in racing simulations
#Users will note their tire % after 1 lap of testing, this lets us anticipate
#how much any given tire will degrade in one lap.
#From there the depreciation is calculated.
sst=100 #Set tire life to 100%
st=100
mt=100
ht=100
p... | true |
f0afa65944197e58bad3e76686cef9c2813ab16d | chrismlee26/chatbot | /sample.py | 2,521 | 4.34375 | 4 | # This will give you access to the random module or library.
# choice() will randomly return an element in a list.
# Read more: https://pynative.com/python-random-choice/
from random import choice
#combine functions and conditionals to get a response from the bot
def get_mood_bot_response(user_response):
#add some... | true |
5225e5adf912762cc349331c4276b978190c8bf9 | kcpedrosa/Python-exercises | /ex005.py | 222 | 4.1875 | 4 | #faça um programa que fale de sucessor e antecessor
numero = int (input('Digite um numero: '))
ant = numero - 1
suc = numero + 1
print('Urubusevando {}, seu antecessor é {} e seu sucessor é {}'.format(numero, ant, suc)) | false |
034be106f76495593e2d2acaa5683960bd3be045 | kcpedrosa/Python-exercises | /ex075.py | 565 | 4.125 | 4 | #Análise de dados em uma Tupla
numeros = (int(input('Digite o 1º numero: ')), int(input('Digite o 2º numero: ')),
int(input('Digite o 3º numero: ')), int(input('Digite o 4º numero: ')))
print(f'Você digitou os valores {numeros}')
print(f'O valor 9 foi digitado {numeros.count(9)} vez(es)')
if 3 in numeros:
... | false |
e8642c64ba0981f3719635db11e52a0823e89b68 | league-python/Level1-Module0 | /_02_strings/_a_intro_to_strings.py | 2,954 | 4.6875 | 5 | """
Below is a demo of how to use different string methods in Python
For a complete reference:
https://docs.python.org/3/library/string.html
"""
# No code needs to be written in this file. Use it as a reference for the
# following projects.
if __name__ == '__main__':
# Declaring and initializing a string variabl... | true |
f17492efff4bbe8ce87a626abfece629c0297a83 | prajjwalkumar17/DSA_Problems- | /dp/length_common_decreasing_subsequence.py | 1,918 | 4.375 | 4 | """ Python program to find the Length of Longest Decreasing Subsequence
Given an array we have to find the length of the longest decreasing subsequence that array can make.
The problem can be solved using Dynamic Programming.
"""
def length_longest_decreasing_subsequence(arr, n):
max_len = 0
dp = []
# In... | true |
8c2ae6eaa09ff199ed5dcf711ef7ad9edad03d2a | huanhuan18/test04 | /learn_python/列表练习.py | 1,081 | 4.25 | 4 | # 一个学校,有3个办公室,现在有8个老师等待工位的分配,请编写程序完成随机的分配
import random
# 定义学校和办公室
school = [[], [], []]
def create_teachers():
"""创建老师列表"""
# 定义列表保存老师
teacher_list = []
index = 1
while index <= 8:
# 创建老师的名字
teacher_name = '老师' + str(index)
# 把老师装进列表里
teacher_list.ap... | false |
9686cb889247f42481db72c01407a13fa8f03a49 | ElTioLevi/mi_primer_programa | /adivina_numero.py | 1,726 | 4.15625 | 4 | number_to_guess = int((((((((2*5)/3)*8)/2)*7)-(8*3))))
print("El objetivo del juego es adivinar un número entre 1 y 100, tienes 5 intentos")
number_user = int(input("Adivina el número: "))
if number_user == number_to_guess:
print ("Has acertado!!!")
else:
if number_to_guess < number_user:
print("Has f... | false |
97174dfe60fdb0b7415ba87061573204d41490bc | rosa637033/OOAD_project_2 | /Animal.py | 597 | 4.15625 | 4 | from interface import move
class Animal:
#Constructor
def __init__(self, name, move:move):
self.name = name
self._move = move
# any move method that is in class move
def setMove(self, move) -> move:
self._move = move
# This is where strategy pattern is implemented.
def ... | true |
fb05fad10a27e03c50ef987443726e2acd11d49a | adamchainz/workshop-concurrency-and-parallelism | /ex4_big_o.py | 777 | 4.125 | 4 | from __future__ import annotations
def add_numbers(a: int, b: int) -> int:
return a + b
# TODO: time complexity is: O(_)
def add_lists(a: list[int], b: list[int]) -> list[int]:
return a + b
# TODO: time complexity is O(_)
# where n = total length of lists a and b
def unique_items(items: list[i... | true |
12daf4f361701b49e3a14820d6bb91d337497de1 | bjskkumar/Python_coding | /test.py | 1,591 | 4.28125 | 4 | # name = "Jhon Smith"
# age = 20
# new_patient = True
#
# if new_patient:
# print("Patient name =", name)
# print("Patient Age = ", age)
#
# obtaining Input
name = input("Enter your name ")
birth_year = input (" Enter birth year")
birth_year= int(birth_year)
age = 2021 - birth_year
new_patient = True
if new_... | false |
7c4b8a424c943510052f6b15b10a06a402c06f08 | prasadnaidu1/django | /Adv python practice/QUESTIONS/10.py | 845 | 4.125 | 4 | #Question:
#Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
#Suppose the following input is supplied to the program:
#hello world and practice makes perfect and hello world again
#Then, the output s... | true |
11b760a6ae93888c812d6d2912eb794d98e9c3e0 | mohadesasharifi/codes | /pyprac/dic.py | 700 | 4.125 | 4 | """
Python dictionaries
"""
# information is stored in the list is [age, height, weight]
d = {"ahsan": [35, 5.9, 75],
"mohad": [24, 5.5, 50],
"moein": [5, 3, 20],
"ayath": [1, 1.5, 12]
}
print(d)
d["simin"] = [14, 5, 60]
d.update({"simin": [14, 5, 60]})
print(d)
age = d["mohad"][0]
print(age)
for k... | true |
b6ba17928cbcb5370f5d144e64353b9d0cd8fcbd | Mohsenabdn/projectEuler | /p004_largestPalindromeProduct.py | 792 | 4.125 | 4 | # Finding the largest palindrome number made by product of two 3-digits numbers
import numpy as np
import time as t
def is_palindrome(num):
""" Input : An integer number
Output : A bool type (True: input is palindrome, False: input is not
palindrome) """
numStr = str(num)
for i in range(len(numS... | true |
82aff3d2c7f6ad8e4de6df39d481df878a7450f7 | sree714/python | /printVowel.py | 531 | 4.25 | 4 | #4.Write a program that prints only those words that start with a vowel. (use
#standard function)
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
print("The original list is : " + str(test_list))
res = []
def fun():
vow = "aeiou"
for sub in test_list:
flag = False
... | true |
8d6df43f43f157324d5ce3012252c3c89d8ffba4 | superyaooo/LanguageLearning | /Python/Learn Python The Hard Way/gpa_calculator.py | 688 | 4.15625 | 4 | print "Hi,Yao! Let's calculate the students' GPA!"
LS_grade = float(raw_input ("What is the LS grade?")) # define variable with a string and input, no need to use "print" here.
G_grade = float(raw_input ("What is the G grade?")) # double (()) works
RW_grade = float(raw_input ("What is the RW grade?"))
F... | true |
86902979397a947dd5d85874129c8d1aab949ac6 | Vladyslav92/Python_HW | /lesson_2/3_task.py | 536 | 4.21875 | 4 | # На ввод подается строка. Нужно узнать является ли строка палиндромом.
# (Палиндром - строка которая читается одинаково с начала и с конца.)
enter_string = input('Введите строку: ').lower()
lst = []
for i in enter_string:
lst.append(i)
lst.reverse()
second_string = ''.join(lst)
if second_string == enter_string:... | false |
6cefa99cdb92c9ed5738d4a40855a78b22e23b1b | Vladyslav92/Python_HW | /lesson_8/1_task.py | 2,363 | 4.34375 | 4 | # mobile numbers
# https://www.hackerrank.com/challenges/standardize-mobile-number-using-decorators/problem
# Let's dive into decorators! You are given mobile numbers.
# Sort them in ascending order then print them in the standard format shown below:
# +91 xxxxx xxxxx
# The given mobile numbers may have +91, 91 or 0 wr... | true |
a1d76dd2a74db5557596f2f3da1fbb2bf70474d2 | chavadasagar/python | /reverse_string.py | 204 | 4.40625 | 4 | def reverse_str(string):
reverse_string = ""
for x in string:
reverse_string = x + reverse_string;
return reverse_string
string = input("Enter String :")
print(reverse_str(string))
| true |
86643c2fe7599d5b77bdcbe3e6c35aa88ba98ecc | aemperor/python_scripts | /GuessingGame.py | 2,703 | 4.25 | 4 | ## File: GuessingGame.py
# Description: This is a game that guesses a number between 1 and 100 that the user is thinking within in 7 tries or less.
# Developer Name: Alexis Emperador
# Date Created: 11/10/10
# Date Last Modified: 11/11/10
###################################
def main():
#... | true |
4978f92dab090fbf4862c4b6eca6db01150cf0b7 | aemperor/python_scripts | /CalcSqrt.py | 1,059 | 4.1875 | 4 | # File: CalcSqrt.py
# Description: This program calculates the square root of a number n and returns the square root and the difference.
# Developer Name: Alexis Emperador
# Date Created: 9/29/10
# Date Last Modified: 9/30/10
##################################
def main():
#Prompts user for a + num... | true |
a7eda8fb8d385472dc0be76be4a5397e7473f724 | petyakostova/Software-University | /Programming Basics with Python/First_Steps_in_Coding/06_Square_of_Stars.py | 237 | 4.15625 | 4 | '''Write a console program that reads a positive N integer from the console
and prints a console square of N asterisks.'''
n = int(input())
print('*' * n)
for i in range(0, n - 2):
print('*' + ' ' * (n - 2) + '*')
print('*' * n)
| true |
3f25e4489c087b731396677d6337e4ad8633e793 | petyakostova/Software-University | /Programming Basics with Python/Simple-Calculations/08-Triangle-Area.py | 317 | 4.3125 | 4 | '''
Write a program that reads from the console side and triangle height
and calculates its face.
Use the face to triangle formula: area = a * h / 2.
Round the result to 2 decimal places using
float("{0:.2f}".format (area))
'''
a = float(input())
h = float(input())
area = a * h / 2;
print("{0:.2f}".format(area))
| true |
87f5fd7703bafe4891fb042de2a7f1770c602995 | BreeAnnaV/CSE | /BreeAnna Virrueta - Guessgame.py | 771 | 4.1875 | 4 | import random
# BreeAnna Virrueta
# 1) Generate Random Number
# 2) Take an input (number) from the user
# 3) Compare input to generated number
# 4) Add "Higher" or "Lower" statements
# 5) Add 5 guesses
number = random.randint(1, 50)
# print(number)
guess = input("What is your guess? ")
# Initializing Variables
ans... | true |
6a59184a4ae0cee597a190f323850bb706c09b11 | BreeAnnaV/CSE | /BreeAnna Virrueta - Hangman.py | 730 | 4.3125 | 4 | import random
import string
"""
A general guide for Hangman
1. Make a word bank - 10 items
2. Pick a random item from the list
3. Add a guess to the list of letters guessed Hide the word (use *) (letters_guessed = [...])
4. Reveal letters already guessed
5. Create the win condition
"""
guesses_left = 10
word_bank = [... | true |
6f3f133dbbc8fc6519c54cc234da5b367ee9e80d | stark276/Backwards-Poetry | /poetry.py | 1,535 | 4.21875 | 4 | import random
poem = """
I have half my father's face
& not a measure of his flair
for the dramatic. Never once
have I prayed & had another man's wife
wail in return.
"""
list_of_lines = poem.split("\n")
# Your code should implement the lines_printed_backwards() function.
# This function takes in a list of strings... | true |
955d4bebf2c1c01ac20c697a2bba0809a4b51b46 | patilpyash/practical | /largest_updated.py | 252 | 4.125 | 4 | print("Program To Find Largest No Amont 2 Nos:")
print("*"*75)
a=int(input("Enter The First No:"))
b=int(input("Enter The Second No:"))
if a>b:
print("The Largest No Is",a)
else:
print("The Largest No Is",b)
input("Enter To Continue") | true |
9302fbf822224f10935dc423d35b283bf41b2609 | MinhTamPhan/LearnPythonTheHardWay | /Exercise/Day5.3/ex42.py | 1,371 | 4.34375 | 4 | ## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a object
class Dog(Animal):
def __init__(self, name):
## set attribul name = name
self.name = name
## Cat is-a object
class Cat(object):
def __init__(self, name):
## set name of Cat
self.name = na... | false |
b939c070c0cbdfa664cea3750a0a6805af4c6a10 | Yatin-Singla/InterviewPrep | /Leetcode/RouteBetweenNodes.py | 1,013 | 4.15625 | 4 | # Question: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
# Explanation
"""
I would like to use BFS instead of DFS as DFS might pigeonhole our search through neighbor's neighbor whereas the target
might the next neighbor
Additionally I'm not using Bi-directional ... | true |
e92e09888bff7072f27d3d24313f3d53e37fc7dc | Yatin-Singla/InterviewPrep | /Leetcode/Primes.py | 609 | 4.1875 | 4 | '''
Write a program that takes an integer argument and returns all the rpimes between 1 and that integer.
For example, if hte input is 18, you should return <2,3,5,7,11,13,17>.
'''
from math import sqrt
# Method name Sieve of Eratosthenes
def ComputePrimes(N: int) -> [int]:
# N inclusive
ProbablePrimes = [True... | true |
b9a12d0975be4ef79abf88df0b083da68113e76b | Yatin-Singla/InterviewPrep | /Leetcode/ContainsDuplicate.py | 730 | 4.125 | 4 | # Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in the array,
# and it should return false if every element is distinct.
# * Example 1:
# Input: [1,2,3,1]
# Output: true
# * Example 2:
# Input: [1,2,3,4]
# Output: false
# * ... | true |
b459e8a597c655f68401d3c8c73a68decfba186e | Yatin-Singla/InterviewPrep | /Leetcode/StringCompression.py | 1,090 | 4.4375 | 4 | '''
Implement a method to perform basic string compression using the counts of repeated characters.
For example, the string aabccccaa would become a2b1c5a3.
If the compressed string would not become smaller than the original string,
you method should return the original string. Assume the string has only uppercase an... | true |
74d654a737cd20199860c4a8703663780683cea4 | quanzt/LearnPythons | /src/guessTheNumber.py | 659 | 4.25 | 4 | import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
#Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low')
elif guess > secretNumb... | true |
0a5d7f42c11be6f4fb2f9ede8340876192080d8d | Dana-Georgescu/python_challenges | /diagonal_difference.py | 631 | 4.25 | 4 | #!/bin/python3
''' Challenge from https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=internal-search'''
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference():
... | true |
537eb97c8fa707e1aee1881d95b2bf497123fd67 | jeffsilverm/big_O_notation | /time_linear_searches.py | 2,520 | 4.25 | 4 | #! /usr/bin/env python
#
# This program times various search algorithms
# N, where N is the size of a list of strings to be sorted. The key to the corpus
# is the position of the value to be searched for in the list.
# N is passed as an argument on the command line.
import linear_search
import random
import sys
corpu... | true |
abbb02f14ecbea14004de28fc5d5daddf65bb63e | jeffsilverm/big_O_notation | /iterative_binary_search.py | 1,292 | 4.1875 | 4 | #! /usr/bin/env python
#
# This program is an implementation of an iterative binary search
#
# Algorithm from http://rosettacode.org/wiki/Binary_search#Python
def iterative_binary_search(corpus, value_sought) :
"""Search for value_sought in corpus corpus"""
# Note that because Python is a loosely typed language,... | true |
0fd4177666e9d395da20b8dfbfae9a300e53f873 | jhoneal/Python-class | /pin.py | 589 | 4.25 | 4 | """Basic Loops
1. PIN Number
Create an integer named [pin] and set it to a 4-digit number.
Welcome the user to your application and ask them to enter their pin.
If they get it wrong, print out "INCORRECT PIN. PLEASE TRY AGAIN"
Keep asking them to enter their pin until they get it right.
Finally, print "PIN ACCEPTED. ... | true |
51d409c780d13e35d3a4626a10273ef0d32e03a6 | Raivias/assimilation | /old/vector.py | 1,173 | 4.25 | 4 | class Vector:
"""
Class to use of pose, speed, and accelertation. Generally anything that has three directional components
"""
def __init__(self, a, b, c):
"""
The three parts of the set
:param a: x, i, alpha
:param b: y, j, beta
:param c: z, k, gamma
"""
... | false |
bf92d64a05ccf277b13dd50b1e21f261c5bba43c | NikitaBoers/improved-octo-sniffle | /averagewordlength.py | 356 | 4.15625 | 4 | sentence=input('Write a sentence of at least 10 words: ')
wordlist= sentence.strip().split(' ')
for i in wordlist:
print(i)
totallength= 0
for i in wordlist :
totallength =totallength+len(i)
averagelength=totallength/ len(wordlist)
combined_string= "The average length of the words in this sentence is "+str(ave... | true |
292ad196eaee7aab34dea95ac5fe622281b1a845 | LJ1234com/Pandas-Study | /06-Function_Application.py | 969 | 4.21875 | 4 | import pandas as pd
import numpy as np
'''
pipe(): Table wise Function Application
apply(): Row or Column Wise Function Application
applymap(): Element wise Function Application on DataFrame
map(): Element wise Function Application on Series
'''
############### Table-wise Function Application ####... | true |
e45c11a712bf5cd1283f1130184340c4a8280d13 | LJ1234com/Pandas-Study | /21-Timedelta.py | 642 | 4.125 | 4 | import pandas as pd
'''
-String: By passing a string literal, we can create a timedelta object.
-Integer: By passing an integer value with the unit, an argument creates a Timedelta object.
'''
print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds'))
print(pd.Timedelta(6,unit='h'))
print(pd.Timedelta(days=2)... | true |
4c4d5e88fde9f486210ef5bd1595775e0adce53c | aiworld2020/pythonprojects | /number_99.py | 1,433 | 4.125 | 4 | answer = int(input("I am a magician and I know what the answer will be: "))
while (True):
if answer < 10 or answer > 49:
print("The number chosen is not between 10 and 49")
answer = int(input("I am choosing a number from 10-49, which is: "))
continue
else:
break
factor = 99 - ... | true |
5608d39b85560dc2ea91e943d60716901f5fe88b | longroad41377/selection | /months.py | 337 | 4.4375 | 4 | monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
month = int(input("Enter month number: "))
if month > 0 and month < 13:
print("Month name: {}".format(monthnames[month-1]))
else:
print("Month number must be between 1... | true |
087a85027a5afa03407fed80ccb82e466c4f46ed | ch-bby/R-2 | /ME499/Lab_1/volumes.py | 2,231 | 4.21875 | 4 | #!\usr\bin\env python3
"""ME 499 Lab 1 Part 1-3
Samuel J. Stumbo
This script "builds" on last week's volume calculator by placing it within the context of a function"""
from math import pi
# This function calculates the volumes of a cylinder
def cylinder_volume(r, h):
if type(r) == int and type(h) == int:... | true |
d571d28325d7278964d45a25a4777cf8f121f0ce | ch-bby/R-2 | /ME499/Lab4/shapes.py | 1,430 | 4.46875 | 4 | #!/usr/bin/env python3#
# -*- coding: utf-8 -*-
"""
****************************
ME 499 Spring 2018
Lab_4 Part 1
3 May 2018
Samuel J. Stumbo
****************************
"""
from math import pi
class Circle:
"""
The circle class defines perimeter, diameter and area of a circle
... | true |
13238ec3b96e2c1297fa1548f14d19860fbe222d | GeeB01/Codigos_guppe | /objetos.py | 1,007 | 4.3125 | 4 | """
Objetos -> São instancias das classe, ou seja, após o mapeamento do objeto do mundo real para a sua
representação computacional, devemos poder criar quantos objetos forem necessarios.
Podemos pensar nos objetos/instancia de uma classe como variaveis do tipo definido na classe
"""
class Lampada:
def __init__(s... | false |
d8e32ee5aed3b8c943bbaf05545f547e2f27d464 | AnnKuz1993/Python | /lesson_02/example_03.py | 1,893 | 4.25 | 4 | # Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.
month_list = ['зима', 'весна', 'лето', 'осень']
month_dict = {1: 'зима', 2: 'весна', 3: 'лето', 4: 'осень'}
num_month = int(input("Введите... | false |
96cd937cfe7734c8fae5348b53517271e3c59321 | AnnKuz1993/Python | /lesson_03/example_01.py | 791 | 4.125 | 4 | # Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def num_division():
try:
a = int(input("Введите первое число: "))
b = int(input("Введите второе число: "))
ret... | false |
393dffa71a0fdb1a5ed69433973afd7d6c73d9ff | neelismail01/common-algorithms | /insertion-sort.py | 239 | 4.15625 | 4 | def insertionSort(array):
# Write your code here.
for i in range(1, len(array)):
temp = i
while temp > 0 and array[temp] < array[temp - 1]:
array[temp], array[temp - 1] = array[temp - 1], array[temp]
temp -= 1
return array
| true |
df11433519e87b3a52407745b274a6db005d767c | jtquisenberry/PythonExamples | /Interview_Cake/hashes/inflight_entertainment_deque.py | 1,754 | 4.15625 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/inflight-entertainment?section=hashing-and-hash-tables&course=fc1
# Use deque
# Time = O(n)
# Space = O(n)
# As with the set-based solution, using a deque ensures that the second movie is not
# the same as the current movi... | true |
fcbb62045b3d953faf05dd2b741cd060376ec237 | jtquisenberry/PythonExamples | /Jobs/maze_runner.py | 2,104 | 4.1875 | 4 | # Alternative solution at
# https://www.geeksforgeeks.org/shortest-path-in-a-binary-maze/
# Maze Runner
# 0 1 0 0 0
# 0 0 0 1 0
# 0 1 0 0 0
# 0 0 0 1 0
# 1 - is a wall
# 0 - an empty cell
# a robot - starts at (0,0)
# robot's moves: 1 step up/down/left/right
# exit at (N-1, M-1) (never 1)
# length(of the shortes... | true |
ba8395ab64f7ebb77cbfdb205d828aa552802505 | jtquisenberry/PythonExamples | /Interview_Cake/arrays/reverse_words_in_list_deque.py | 2,112 | 4.25 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1
# Solution with deque
def reverse_words(message):
if len(message) < 1:
return message
final_message = deque()
current_word = []
for i ... | true |
9adfabfbc83b97a11ee5b2f23cea5ec2eb357dd5 | jtquisenberry/PythonExamples | /Interview_Cake/sorting/merge_sorted_lists3.py | 1,941 | 4.21875 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/merge-sorted-arrays?course=fc1§ion=array-and-string-manipulation
def merge_lists(my_list, alices_list):
# Combine the sorted lists into one large sorted list
if len(my_list) == 0 and len(alices_list) == 0:
... | true |
148c6d9d37a9fd79e06e4371a30c65a5e36066b2 | jtquisenberry/PythonExamples | /Jobs/multiply_large_numbers.py | 2,748 | 4.25 | 4 | import unittest
def multiply(num1, num2):
len1 = len(num1)
len2 = len(num2)
# Simulate Multiplication Like this
# 1234
# 121
# ----
# 1234
# 2468
# 1234
#
# Notice that the product is moved one space to the left each time a digit
# of the top number is multip... | true |
b8b7d0a3067b776d6c712b2f229ef65448b9a4d9 | jtquisenberry/PythonExamples | /Interview_Cake/arrays/reverse_words_in_list_lists.py | 2,120 | 4.375 | 4 | import unittest
from collections import deque
# https://www.interviewcake.com/question/python/reverse-words?section=array-and-string-manipulation&course=fc1
# Solution with lists only
# Not in place
def reverse_words(message):
if len(message) < 1:
return
current_word = []
word_list = []
fina... | true |
1aa6ba8516a4e996c07028bc798bdb13064add85 | jaeyun95/Algorithm | /code/day05.py | 431 | 4.1875 | 4 | #(5) day05 재귀를 사용한 리스트의 합
def recursive(numbers):
print("===================")
print('receive : ',numbers)
if len(numbers)<2:
print('end!!')
return numbers.pop()
else:
pop_num = numbers.pop()
print('pop num is : ',pop_num)
print('rest list is : ',numbers)
... | false |
4b8c656ea711a2274df26c044ec6a7d7ce7b33bc | bojanuljarevic/Algorithms | /BST/bin_tree/bst.py | 1,621 | 4.15625 | 4 |
# Zadatak 1 : ručno formiranje binarnog stabla pretrage
class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.le... | true |
5f5e0b19e8b1b6d0b0142eb63621070a50227142 | steven-liu/snippets | /generate_word_variations.py | 1,109 | 4.125 | 4 | import itertools
def generate_variations(template_str, replace_with_chars):
"""Generate variations of a string with certain characters substituted.
All instances of the '*' character in the template_str parameter are
substituted by characters from the replace_with_chars string. This function
generate... | true |
cc3a1d58b9a459e87baba1db1667b8c3eafaed7a | jackjyq/COMP9021_Python | /ass01/poker_dice/hand_rank.py | 1,577 | 4.21875 | 4 | def hand_rank(roll):
""" hand_rank
Arguements: a list of roll, such as [1, 2, 3, 4, 5]
Returns: a string, such as 'Straight'
"""
number_of_a_kind = [roll.count(_) for _ in range(6)]
number_of_a_kind.sort()
if number_of_a_kind == [0, 0, 0, 0, 0, 5]:
roll_hand = 'Five of a kind'
el... | false |
8dbfcde0a480f44ea8f04d113a5214d7ddb9d290 | jgkr95/CSPP1 | /Practice/M6/p1/fizz_buzz.py | 722 | 4.46875 | 4 | '''Write a short program that prints each number from 1 to num on a new line.
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
'''
def main():
'''Read numbe... | true |
86c07784b9a2a69756a3390e8ff70b2a4af78652 | Ashishrsoni15/Python-Assignments | /Question2.py | 391 | 4.21875 | 4 | # What is the type of print function? Also write a program to find its type
# Print Funtion: The print()function prints the specified message to the screen, or other
#standard output device. The message can be a string,or any other object,the object will
#be converted into a string before written to the screen.
p... | true |
6575bbd5e4d495bc5f8b5eee9789183819761452 | Ashishrsoni15/Python-Assignments | /Question1.py | 650 | 4.375 | 4 | #Write a program to find type of input function.
value1 = input("Please enter first integer:\n")
value2 = input("Please enter second integer:\n")
v1 = int(value1)
v2 = int(value2)
choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for multiplication:\n")
choice = int(choice)
if choice... | true |
ea4c7aaefa309e8f0db99f4f43867ebd1bd52282 | Shahriar2018/Data-Structures-and-Algorithms | /Task4.py | 1,884 | 4.15625 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... | true |
05d3835f466737814bb792147e8d7b34a28d912f | qiqi06/python_test | /python/static_factory_method.py | 1,038 | 4.1875 | 4 | #-*- coding: utf-8 -*-
"""
练习简单工厂模式
"""
#建立一工厂类,要用是,再实例化它的生产水果方法,
class Factory(object):
def creatFruit(self, fruit):
if fruit == "apple":
return Apple(fruit, "red")
elif fruit == "banana":
return Banana(fruit, "yellow")
class Fruit(object):
def __init__(self, name, ... | false |
deae850e32102c9f22d108c817cfd69eebd4344f | szzhe/Python | /ActualCombat/TablePrint.py | 854 | 4.28125 | 4 | tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
# 要求输出如下:
# apples Alice dogs
# oranges Bob cats
# cherries Carol moose
# banana David goose
def printTable(data):
str_data = ''
... | false |
c6d84e1f238ac03e872eea8c8cb3566ac0913646 | Cpeters1982/DojoPython | /hello_world.py | 2,621 | 4.21875 | 4 | '''Test Document, leave me alone PyLint'''
# def add(a,b):
# x = a + b
# return x
# result = add(3, 5)
# print result
# def multiply(arr, num):
# for x in range(len(arr)):
# arr[x] *= num
# return arr
# a = [2,4,10,16]
# b = multiply(a,5)
# print b
'''
The function multiply takes two parameter... | true |
44b81e47c1cd95f7e08a8331b966cf195e8c514d | gersongroth/maratonadatascience | /Semana 01/02 - Estruturas de Decisão/11.py | 1,156 | 4.1875 | 4 | """
As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes.
Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual:
salários até R$ 280,00 (incluindo) ... | false |
e6536e8399f1ceccd7eb7d41eddcc302e3dda66b | guv-slime/python-course-examples | /section08_ex04.py | 1,015 | 4.4375 | 4 | # Exercise 4: Expanding on exercise 3, add code to figure out who
# has the most emails in the file. After all the data has been read
# and the dictionary has been created, look through the dictionary using
# a maximum loop (see chapter 5: Maximum and Minimum loops) to find out
# who has the most messages and print how... | true |
f93dd7a14ff34dae2747f7fa2db22325e9d00972 | guv-slime/python-course-examples | /section08_ex03.py | 690 | 4.125 | 4 | # Exercise 3: Write a program to read through a mail log, build a histogram
# using a dictionary to count how many messages have come from each email
# address, and print the dictionary.
# Enter file name: mbox-short.txt
# {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3,
# 'cwen@iupui.edu': 5, 'antr... | false |
f9a66f5b0e776d063d812e7a7185ff6ff3c5615f | maryamkh/MyPractices | /ReverseLinkedList.py | 2,666 | 4.3125 | 4 | '''
Reverse back a linked list
Input: A linked list
Output: Reversed linked list
In fact each node pointing to its fron node should point to it back node ===> Since we only have one direction accessibility to a link list members to reverse it I have to travers the whole list, keep the data of the nodes and then rearra... | true |
145413092625adbe30b158c21e5d27e2ffcfab50 | maryamkh/MyPractices | /Squere_Root.py | 1,838 | 4.1875 | 4 | #!/usr/bin/python
'''
Find the squere root of a number. Return floor(sqr(number)) if the numebr does not have a compelete squere root
Example: input = 11 ===========> output = 3
Function sqrtBinarySearch(self, A): has time complexity O(n), n: given input: When the number is too big it becomes combursome
... | true |
8b9f850c53a2a020b1deea52e301de0d2b6c47c3 | CodingDojoDallas/python_sep_2018 | /austin_parham/user.py | 932 | 4.15625 | 4 | class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print(self.price)
print(self.max_speed)
print(self.miles)
print('*' * 80)
def ride(self):
print("Riding...")
print("......")
print("......")
self.mi... | true |
36a4f28b97be8be2e7f6e20965bd21f554270704 | krismosk/python-debugging | /area_of_rectangle.py | 1,304 | 4.6875 | 5 | #! /usr/bin/env python3
"A script for calculating the area of a rectangle."
import sys
def area_of_rectangle(height, width = None):
"""
Returns the area of a rectangle.
Parameters
----------
height : int or float
The height of the rectangle.
width : int or float
The width o... | true |
dacaf7998b9ca3a71b6b90690ba952fb56349ab9 | Kanthus123/Python | /Design Patterns/Creational/Abstract Factory/doorfactoryAbs.py | 2,091 | 4.1875 | 4 | #A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
#Extending our door example from Simple Factory.
#Based on your needs you might get a wooden door from a wooden door shop,
#iron door from an iron shop or a PVC door from th... | true |
ab049070f8348f4af8caeb601aee062cc7a76af2 | Kanthus123/Python | /Design Patterns/Structural/Decorator/VendaDeCafe.py | 1,922 | 4.46875 | 4 | #Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class.
#Imagine you run a car service shop offering multiple services.
#Now how do you calculate the bill to be charged?
#You pick one service and dynamically keep adding to it the prices f... | true |
32c5ca8e7beb18feafd101e6e63da060c3c47647 | russellgao/algorithm | /data_structure/binaryTree/preorder/preoder_traversal_items.py | 695 | 4.15625 | 4 |
# 二叉树的中序遍历
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 迭代
def preorderTraversal(root: TreeNode) ->[int]:
result = []
if not root:
return result
queue = [root]
while queue:
root = queue.pop()
if root:
... | false |
861fab844f5dcbf86c67738354803e27a0a303e9 | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-31/python/solution_recursion.py | 950 | 4.21875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 递归
def isSymmetric(root: TreeNode) -> bool:
def check(left, right):
if not left and not right:
return True
if not left or not right:
... | true |
21f1cf35cd7b3abe9d67607712b62bfa4732e4ce | russellgao/algorithm | /dailyQuestion/2020/2020-05/05-01/python/solution.py | 944 | 4.125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def reverseList(head):
"""
递归 反转 链表
:type head: ListNode
:rtype: ListNode
"""
if not head :
return None
if not head.next :
return head
l... | false |
ecfa4146a927249cf7cb510dbf14432cd2bb84a7 | wulinlw/leetcode_cn | /剑指offer/30_包含min函数的栈.py | 1,296 | 4.125 | 4 | #!/usr/bin/python
#coding:utf-8
# // 面试题30:包含min函数的栈
# // 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min
# // 函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。
class StackWithMin:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, node):
# write code here
self.stack.append(node)
... | false |
93980a2f1b9d778ff907998b6fb722722ec28d73 | wulinlw/leetcode_cn | /递归/recursion_1_1.py | 1,304 | 4.15625 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/orignial/card/recursion-i/256/principle-of-recursion/1198/
# 反转字符串
# 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
# 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
# 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
# 示例 1:
# 输入:["h","e","l","l","o"]
# 输出:["o","l",... | false |
bacfbc3a4a068cf87954be2a53e0a6ab44ba41bc | wulinlw/leetcode_cn | /链表/linked-list_5_3.py | 2,469 | 4.125 | 4 | #!/usr/bin/python
# coding:utf-8
# https://leetcode-cn.com/explore/learn/card/linked-list/197/conclusion/764/
# 扁平化多级双向链表
# 您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。
# 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。
# 示例:
# 输入:
# 1---2---3---4---5---6--NULL
# |
# ... | false |
1926f0d51153da212fbfd132588b7547ca9b9e9d | wulinlw/leetcode_cn | /初级算法/linkedList_4.py | 1,718 | 4.25 | 4 | #!/usr/bin/python
#coding:utf-8
# https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/6/linked-list/44/
# 合并两个有序链表
# 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
# 示例:
# 输入:1->2->4, 1->3->4
# 输出:1->1->2->3->4->4
# 新建链表,对比两个链表指针,小的放新链表中,直到某条链表结束,
# 将另一条链表剩余部分接入新链表
# Definition for singly-l... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.