blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
067dc51bc622e4e7514fc72c0b8b4626db950da5 | amitp29/Python-Assignments | /Python Assignments/Assignment 3/question12.py | 1,237 | 4.34375 | 4 | '''
Read 10 numbers from user and find the average of all.
a) Use comparison operator to check how many numbers are less than average and print them
b) Check how many numbers are more than average.
c) How many are equal to average.
'''
num_list = []
sum_of_num = 0
for i in range(10):
while True:
try:
... | true |
45bcaf8e7ddb54e50dc916ee8ae1604345c27072 | amitp29/Python-Assignments | /Python Assignments/Assignment 3/question20.py | 835 | 4.34375 | 4 | '''
Write a program to generate Fibonacci series of numbers.
Starting numbers are 0 and 1, new number in the series is generated by adding previous two numbers in the series.
Example : 0, 1, 1, 2, 3, 5, 8,13,21,.....
a) Number of elements printed in the series should be N numbers, Where N is any +ve integer.
... | true |
874f3d5621af8a3cd128bd2d06e30cfe6bb3f0c5 | amitp29/Python-Assignments | /Python Assignments/Assignment 3/question7.py | 430 | 4.21875 | 4 | '''
Create a list with at least 10 elements in it :-
print all elements
perform slicing
perform repetition with * operator
Perform concatenation wiht other list.
'''
#perform repetition with * operator
list1 = [1]*7
list2 = [4,5,6]
#Perform concatenation with other list
list3 = list1+list2... | true |
7545be7a5decce69dd33717fc7a77ca5848e6a3d | amitp29/Python-Assignments | /Python Assignments/Assignment 2/question3.py | 942 | 4.15625 | 4 | '''
4. Given a list of strings, return a list with the strings in sorted order, except
group all the strings that begin with 'x' first.
e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'].
Hint: this can be done by m... | true |
1dca7820586525dcd22cebeb2d851eb1d2bf8c42 | SJasonHumphrey/DigitalCrafts | /Python/Homework004/word_histogram.py | 958 | 4.3125 | 4 | # 2. Word Summary
# Write a word_histogram program that asks the user for a sentence as its input, and prints a dictionary containing
# the tally of how many times each word in the alphabet was used in the text.
wordDict = {}
sentence = input('Please enter a sentence: ')
def wordHistogram(sentence):
for word in s... | true |
615c76f289b017a1c7a9b8a9f956a594f17ab727 | LucianoBartomioli/-EDU-IRESM_AEDI_2020 | /clase_7_clases_busqueda/clases.py | 1,042 | 4.21875 | 4 | class Empleado:
def __init__(self, nombre, apellido, dni, legajo, puesto, salario_por_hora, cantidad_hs_trabajadas):
self.nombre = input("Ingrese el nombre")
self.apellido = input("Ingrese el apellido")
self.dni = input("Ingrese el DNI")
self.legajo = input("Ingrese el N° de legajo")... | false |
f37f41087fd970146217e4b32a16f0d3af7d9b5e | naolwakoya/python | /factorial.py | 685 | 4.125 | 4 | import math
x = int(input("Please Enter a Number: "))
#recursion
def factorial (x):
if x < 2:
return 1
else:
return (x * factorial(x-1))
#iteration
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
def factorial(p):
if p ==... | true |
05bf4280a7750cf207609ae63ed15f1cee96843f | jkfer/Codewars | /logical_calculator.py | 1,602 | 4.40625 | 4 | """
Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50.
Links referring to logical operations: AND, OR and XOR.
You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequenti... | true |
b3a0608ad6899ac13e9798ecf4e66c597f688bd1 | jkfer/Codewars | /valid_paranthesis.py | 1,071 | 4.3125 | 4 | """
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => t... | true |
ad16030fe65ac0005b1d07d56957fb66737f5d72 | yvlian/algorithm | /python/继承.py | 1,460 | 4.40625 | 4 | '''
继承的优点:提升代码的复用程度,避免重复操作。
继承的特点:
1、 同时支持单继承与多继承,当只有一个父类时为单继承,当存在多个父类时为多继承。
2、子类会继承父类所有的属性和方法,子类也可以覆盖父类同名的变量和方法。
3、在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。有别于C#
4、在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数
5、Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。
(先在本类中查找调用的方法,找不到才去基类中找)。
... | false |
da88cd5960d8aeb8fd8a0717714cf88dcd5b707a | Mario97popov/Python-Advanced | /Tuples and Sets excercise/Battle_of_Names.py | 858 | 4.125 | 4 | n = int(input())
even__numbers_set = set()
odd_numbers_set = set()
for current_iteration_count in range(1, n+1):
name = input()
current_sum = sum([ord(el) for el in name]) // current_iteration_count
if current_sum % 2 == 0:
even__numbers_set.add(current_sum)
else:
odd_numbers_se... | false |
f6d7508e322f3248106378483dd377e9ee7ac9e8 | YaserMarey/algos_catalog | /dynamic_programming/count_factors_sets.py | 1,410 | 4.15625 | 4 | # Given a number 'n'
# Count how many possible ways there are to express 'n' as the sum of 1, 3, or 4.
# Notice that {1,2} and {2,1} are two methods and not counted as one
# Pattern Fibonacci Number
def CFS(Number):
dp = [0 for _ in range(Number + 1)]
dp[0] = 1 # if number = 0 then there is only set ... | true |
5871c7a813bddf1480a681d08b2ee5d1d76c52d7 | YaserMarey/algos_catalog | /dynamic_programming/count_of_possible_way_to_climb_stairs.py | 1,035 | 4.1875 | 4 | # Given a stair with ‘n’ steps, implement a method to count how many
# possible ways are there to reach the top of the staircase,
# given that, at every step you can either take 1 step, 2 steps, or 3 steps.
# Fib Pattern
def CS(S):
T = [0 for i in range(S + 1)]
T[0] = 1
T[1] = 1
T[2] = 2
... | true |
5d671a339e350f8a3c039ed153667496f6f5850c | burnbrigther/py_practice | /ex15_2.py | 687 | 4.46875 | 4 | # imports the argv feature from the sys package
from sys import argv
# Takes input values from argv and squishes them together (these are the two command line items)
# then unpacks two arguments sent to argv and assigns them to script and filename
script, filename = argv
# Takes the value from the command line argumen... | true |
f65244692ce1cdcb5357529ee11fb9bb344f4ae9 | saranya258/python | /3.py | 250 | 4.1875 | 4 | char=input()
if char.isalpha():
if(char=='A'or char=='E'or char=='I'or char=='O'or char=='U'or char=='a'or char=='e'or char=='i'or char=='o'or char=='u'):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
| false |
978a2fdf4c8dd6ec10b53d88591c18b452ec29ca | OluchiC/PythonLab1 | /Lab1.py | 925 | 4.21875 | 4 | sentence = 'I can’t wait to get to School_Name! Love the idea of meeting new Noun and making new Noun! I know that when Number years pass, I will be Age and I will have a degree in Profession. I hope to make my family proud! Am I done with this MadLib Yet?: Boolean.'
school_name = input('What\'s the school name?')
mee... | true |
9bf71c7546e14fcade018ff905880acd633547e9 | rainakdy1009/Prog11 | /dragon games.py | 2,525 | 4.21875 | 4 | import random
import time
def displayIntro(): #Explain the situation
print('''You are in a land full of dragons. In front of you,
you see two caves. In one cave, the dragon is friendly
and will share his treasure with you. The other dragon
is greedy and hungry, and will eat you on sight.''')
print()
... | true |
ce503a9b5367381fa3774fc0187a506ea0fa3dd6 | rainakdy1009/Prog11 | /Mad libs Dayoung.py | 1,528 | 4.1875 | 4 | noun1 = input("Enter a noun: ")
noun2 = input("Enter a noun: ")
adjective1 = input("Enter an adjective: ")
verb1 = input("Enter a verb: ")
plural_noun1 = input("Enter an plural noun: ")
plural_noun2 = input("Enter an plural noun: ")
number1 = input("Enter a number: ")
adjective2 = input("Enter an adjective: ")
... | false |
342ca3b9f92f9adf562bf6fd4b5278305e466255 | jessegtz7/Python-Learning-Files | /Strings.py | 1,018 | 4.15625 | 4 | name = 'Ivan'
age = 29
#**Concateante**
'''
print('His name is ' + name + ' and he is ' + age) -- this will result as a "TypeError: can only concatenate str (not "int") to str"
age mus be cast in to a str
'''
print('His name is ' + name + ' and he is ' + str(age))
#**String format**
#1.- Arguments by position.
print... | true |
76ab13972c5734bc324efb8b53482705ae990746 | irtefa/bst | /simple_bst.py | 1,142 | 4.1875 | 4 | from abstract_bst import AbstractBst
class SimpleBst(AbstractBst):
# A simple compare method for integers
# @given_val: The value we are inserting or looking for
# @current_val: Value at the current node in our traversal
# returns an integer where
# -1: given_val is less than current_val
# 1: given_val is grea... | true |
c1ad1d4d22f1edfe5bd439118e7c79fc67d7567d | romanticair/python | /basis/Boston-University-Files/AllAnswer/Assignment_9_Answer/a3_task1.py | 2,967 | 4.125 | 4 | # Descriptive Statistice
# Mission 1.
def mean(values):
# Take as a parameter a list of numbers, calculates4
# and returns the mean of those values
sumValues = 0
for value in values:
sumValues += value
return sumValues / len(values)
# Mission 2.
def variance(values):
# Take as a parame... | true |
5bba7d2cf4162e8cb4be68b0eec0c2c698843073 | ivenabc/algorithm_examples | /basic/queue.py | 808 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Queue
# 先进先出队列(FIFO)
class Queue(object):
def __init__(self):
self.__list = []
# 添加一个元素
def en_queue(self, item):
self.__list.append(item)
# 删除最近添加的元素
def de_queue(self):
self.__list.pop()
def is_empty(self):
... | false |
dff8367263ee46866a30dd2fcb8e241d07968d21 | chsclarke/Python-Algorithms-and-Data-Structures | /coding_challenge_review/array_practice.py | 885 | 4.28125 | 4 |
def mergeSorted(arr1, arr2):
#code to merge two sorted arrays
sortedArr = [None] * (len(arr1) + len(arr2))
i = 0
j = 0
k = 0
#iterate through both list and insert the lower of the two
while(i < len(arr1) and j < len(arr2)):
# <= allows function to support duplicate values
i... | true |
589ff4948bafda92c5f6007c693dd42b4ec5853c | Abel237/automate-boring-stuffs | /automate_boring_stuffs/automate.py | 1,384 | 4.15625 | 4 | # This program says hello and asks for my name.
# print('Hello, world!')
# print('What is your name?') # ask for their name
# myName = input()
# print('It is good to meet you, ' + myName)
# print('The length of your name is:')
# print(len(myName))
# print('What is your age?') # ask for their age
# myAge... | true |
db31469c2a0a7810db6d65c47229d489188687db | evgeniikotliarov/python_example | /method_user_add.py | 1,161 | 4.21875 | 4 | # pizza = ['pipperoni', 'chilli', 'mozarella']
# print(pizza)
# for piz in pizza:
# print(piz + " I like it")
#
# for pis in pizza:
# print("Do you like " + pis.title() + ".\n")
# print("Bla bla bla")
#
# for value in range(1,21):
# print(value)
#
# for value in range(1,9):
# print(value)
#
# numbers = ... | false |
d8326d7dd0f2ea05957104c482bacf2776968aff | optionalg/HackerRank-8 | /time_conversion.py | 987 | 4.125 | 4 | '''
Source: https://www.hackerrank.com/challenges/time-conversion
Sample input:
07:05:45PM
Sample output:
19:05:45
'''
#!/bin/python
import sys
def timeConversion(s):
meridian = s[-2]
time = [int(i) for i in s[:-2].split(':')] # Converting each time unit to integer and obtaining
# each unit by split... | true |
9bc2d5011ccdacbf7e172ab4c0245c8b5f437f3f | harrowschool/intro-to-python | /lesson3/task2.py | 620 | 4.3125 | 4 | # Task 2a
# Add comments to the code to explain:
# What will be output when the code is run?
# In what circumstances would the other output message be produced
num1 = 42
if num1 == 42:
print("You have discovered the meaning of life!")
else:
print("Sorry, you have failed to discover the meaning of life!")
... | true |
a0c0c94d964d43a60a5473386310f66e3f2a7e5c | TokyGhoul/Coursera | /Week2/HW8.py | 538 | 4.21875 | 4 | '''
Шоколадка имеет вид прямоугольника, разделенного на n×m долек.
Шоколадку можно один раз разломить по прямой на две части.
Определите, можно ли таким образом отломить от шоколадки
ровно k долек.
'''
num1 = int(input())
num2 = int(input())
num3 = int(input())
if (num3 <= num1 * num2) and \
(num3 % num1 == 0 ... | false |
cbea431354921c463d0c4ebf4f923361203ba3b3 | TokyGhoul/Coursera | /Week2/HW14.py | 536 | 4.40625 | 4 | '''
Даны три целых числа. Определите, сколько среди них совпадающих.
Программа должна вывести одно из чисел: 3
(если все совпадают), 2 (если два совпадает) или 0 (если все числа различны).
'''
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 or num2 == num3 or num1 == num3:
if num1 == nu... | false |
fcd89523ec988e761b4cc22611dd69548b449951 | gitghought/python1 | /day3/mendswith.py | 382 | 4.125 | 4 |
mstr = "u can u up, no can no 13 B"
#查看实现准备好的字符串是否以‘B’字符结尾
#该函数的返回值是布尔值
mbool = mstr.endswith("B")
print(mbool)
#查看实现准备好的字符串是否以‘B’字符结尾
#该方法指定了查找的范围,3-末尾
#该函数的返回值是布尔值
mbool = mstr.endswith("B", 3, mstr.__len__())
print(mbool)
| false |
9c6a978c2595de1301aef97991389bb02cb9855f | skipdev/python-work | /assignment-work/jedi.py | 554 | 4.15625 | 4 | def jedi():
#Display the message "Have you fear in your heart?"
print("Have you fear in your heart?")
#Read in the user’s string.
response = input(str())
#The program will then decide if the user can be a Jedi or not, based on their response.
if response.lower() == "yes":
print("Fear is the path t... | true |
b76cdc2e8a3bf58989bd280c7f3d82810c67f153 | skipdev/python-work | /assignment-work/jumanji.py | 543 | 4.28125 | 4 | number = 0
#Display the message "How many zones must I cross?"
print("How many zones must I cross?")
#Read in the user’s whole number.
number = int(input())
#Display the message "Crossing zones...".
print("Crossing zones...")
#Display all the numbers from the user's whole number to 1 in the form "…crossed zone [num... | true |
072bac7e650722c717a17abfa2bc288fde93e0f2 | skipdev/python-work | /work/repeating-work.py | 219 | 4.25 | 4 | #Get the user's name
name = str(input("Please enter your name: "))
#Find the number of characters in the name (x)
x = len(name)
#Use that number to print the name x amount of times
for count in range(x):
print(name) | true |
04a15af1fcb1ffccb529a4321c499c5bd1b88d04 | skipdev/python-work | /work/odd-even.py | 238 | 4.375 | 4 | #Asking for a whole number
number = (int(input("Please enter a whole number: ")))
#Is the number even or odd?
evenorodd = number % 2
#Display a message
if evenorodd == 0:
print("The number is even")
else:
print("The number is odd")
| true |
f2b76267a6fcd9f60e5c1c4745a8362ed3c9bd27 | MrT3313/Algo-Prep | /random/three_largest_numbers/✅ three_largest_numbers.py | 1,413 | 4.34375 | 4 | # - ! - RUNTIME ANALYSIS - ! - #
## Time Complexity: O(n)
## Space Complexity: O(1)
# - ! - START CODE - ! - #
# - 1 - # Define Main Function
def FIND_three_largest_numbers(array):
# 1.1: Create data structure to hold final array
finalResult = [None, None, None]
# 1.2: Loop through each item in the chec... | true |
3c84466bc01a6b2a5ddbd595fbb6dcb107b40e74 | MrT3313/Algo-Prep | /⭐️ Favorites ⭐️/Sort/⭐️ bubbleSort/✅ bubbleSort.py | 590 | 4.21875 | 4 |
def bubbleSort(array):
isSorted = False
counter = 0 # @ each iteration you know the last num is in correct position
while not isSorted:
isSorted = True
# -1 : is to prevent checking w/ out of bounds
# counter : makes a shorter array each iteration
for i in range(len(array)... | true |
71dc3f9110ad21660a526284e6b58b8834729e7a | ashNOLOGY/pytek | /Chapter_3/ash_ch3_coinFlipGame.py | 799 | 4.25 | 4 | '''
NCC
Chapter 3
The Coin Flip Game
Project: PyTek
Code by: ashNOLOGY
'''
import math
import random
#Name of the Game
print("\nThe Coin Flip Game"
"\n------------------\n")
#Set up the Heads & Tails as 0
h = 0
t = 0
#ask user how many flips should it do
howMany = int(input("How many fli... | true |
a494320f224a78e13f565b69e7aebd406709c979 | RanabhatMilan/SimplePythonProjects | /GussingNum/guessing.py | 880 | 4.25 | 4 | # This is a simple guessing game.
# At first we import a inbuilt library to use a function to generate some random numbers
import random
def guess_num(total):
number = random.randint(1, 10)
num = int(input("Guess a number between 1 to 10: "))
while num != number:
if num > number:
num = ... | true |
f8a581b6c8a2f6c71e332e0e749dc8ce9988159d | mfleming1290/My-written-code | /Python/testing.py | 2,404 | 4.25 | 4 | # first_name = "Zen"
# last_name = "Coder"
# print "My name is {} {}".format(first_name, last_name)
# name = "Zen"
# age = 15
# print "My name is " + name + age
# name = "Zen"
# print "My name is", name, "i am ", 24
# hw = "hello %s" % 'world'
# print hw
# my_string = 'hello world'
# print my_string.capitalize()
#
... | false |
cf64c6a26c86f5af34c39f617763757d4ab270ed | bushki/python-tutorial | /tuples_sets.py | 1,801 | 4.53125 | 5 | # tuple - collection, unchangeable, allows dupes
'''
When to use tuples vs list?
Apart from tuples being immutable there is also a semantic distinction that should guide their usage.
Tuples are heterogeneous data structures (i.e., their entries have different meanings),
while lists are homogeneous sequences. Tuples... | true |
350b1239f1f389a5181a11f3b9fa1c3ed74fa6e6 | victor-erazo/ciclo_python | /Mision-TIC-GRUPO-09-master(16-06-21)/semana 3/ejercicio5.py | 1,813 | 4.1875 | 4 | '''
for x in range(0,10):
print('Valor de x : ', x)
'''
'''
for j in range(0,10,2):
print('La iteracion j : '+ str(j))
'''
'''
for k in range(10,0,-1):
print('La iteracion decremental k es : ' + str(k))
'''
'''
oracion = 'Mary entiende muy bien python'
frases = oracion.split()
print('la oracion analizar ... | false |
ce183d2eae5e4e129a0145de41efada56256241d | JessicaCoelho21/ASI | /ASI_FP_5/ASI_FP_05_ex4.py | 654 | 4.28125 | 4 | # Semana 5, exercício 4
import re
# Verificar se a inicial de todos os nomes se encontra em letra maiúscula
# e as seguintes em letra minúscula
def upperCaseName(name):
# Início da linha (^) com letra maíuscula seguido de letras minúsculas
# Seguido do espaço (/s), depois novamente letra maíuscula seguido de... | false |
757c5b54164ebe279401ef9cb63e920715352258 | xatrarana/python-learning | /PYTHON programming/3.dictonary in python/dict problemss.py | 269 | 4.15625 | 4 | ## i have to get the sentance as input form the user and cout the user input..
#sentence -> input,key->word, value->length of the word
sent=input("Enter the sentence")
words=sent.split(" ")
count_words={words:len(words) for words in words}
print(count_words)
| true |
635385f3da34913511846c5f0010347b260aa5fa | houckao/grade-calculator-python | /grades_calculator.py | 1,598 | 4.15625 | 4 | """
This is a library of functions designed to be useful in a
variety of different types of grade calculations.
"""
# import support for type hinting the functions
from typing import List, Dict
def average(grades: List[float]) -> float:
"""Calculates the average of an array of grades, rounded to 2 decimal places
... | true |
c4e289b3c851d27b251685e6ecce708b590c519e | qihong007/leetcode | /2020_04_16.py | 2,169 | 4.125 | 4 | '''
一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),返回总的分钟数。
注意:本题相对原题稍作改动
示例 1:
输入: [1,2,3,1]
输出: 4
解释: 选择 1 号预约和 3 号预约,总时长 = 1 + 3 = 4。
示例 2:
输入: [2,7,9,3,1]
输出: 12
解释: 选择 1 号预约、 3 号预约和 5 号预约,总时长 = 2 + 9 + 1 = 12。
示例 3:
输入: [2,1,4,5,3,1,1,3]
输出: 12
解释: 选择 1 ... | false |
7bda8a77649f5832e637e38a7f7564cc0b2fd4d1 | qihong007/leetcode | /2020_03_04.py | 1,138 | 4.3125 | 4 | '''
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only u... | true |
3761089895083f5fb8111f5b8db218c81fa86d71 | khushalj/GOOGLE-HASH-CODE-2021 | /pizza.py | 2,318 | 4.1875 | 4 | #!/usr/bin/python3
#Function that prints the solution to send to the judge
def imprimirsolucion(deliveries):
# We print number of shipments
print (len (deliveries))
for between in deliveries:
#We print each shipment generating a string and finally printing it
#First, we put the... | true |
9a20562783968cda53b51396d3a55fc0072ff9d0 | pouya-mhb/My-Py-projects | /OOP Practice/prac1.py | 1,658 | 4.15625 | 4 | # A class for dog informations
dogsName = []
dogsBreed = []
dogsColor = []
dogsSize = []
dogsInformation = [dogsName, dogsBreed,
dogsColor, dogsSize]
#Create the class
class Dog ():
#methods
# init method for intialization and attributes in ()
def __init__(self, dogBreed, name, dog... | true |
272ecae5432fdc867ed406d728418733938d6525 | pouya-mhb/My-Py-projects | /PublicProjects/1/tamrin5.py | 432 | 4.25 | 4 | number = int(input("please enter a number : "))
number = 5
k = 2 * number - 2
for i in range(0, number):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = number - 2
for i in range(number, -1, -1):
for j in range(k, 0, -... | false |
d779c188dbd38b81d162f126fe2f502e2dd671d6 | adityagrg/Intern | /ques2.py | 234 | 4.3125 | 4 | #program to calculate the no. of words in a file
filename = input("Enter file name : ")
f = open(filename, "r")
noofwords = 0
for line in f:
words = line.split()
noofwords += len(words)
f.close()
print(noofwords) | true |
343677c250f436b5095c72985eadd30da635da00 | Young-Thunder/RANDOMPYTHONCODES | /if.py | 206 | 4.1875 | 4 | #!/usr/bin/python
car = raw_input("Which car do you have")
print "You have a " + car
if car == "BMW":
print "Its is the best"
elif car =="AUDI":
print "It is a good car"
else:
print "UNKNOWN CAR "
| true |
e535d1c452c734ab747fda28d116d4b5fe2f9325 | gia-bartlett/python_practice | /practice_exercises/odd_or_even.py | 431 | 4.375 | 4 |
number = int(input("Please enter a number: ")) # input for number
if number % 2 == 0: # if the number divided by 2 has no remainder
print(f"The number {number} is even!") # then it is even
else:
print(f"The number {number} is odd!") # otherwise, it is odd
''' SOLUTION:
num = input("Enter a number: ")
mo... | true |
626d8988b97db70d28e03e7e884120410120021a | igor91m/homework_1 | /task_1.py | 438 | 4.1875 | 4 | # Создаем простые переменные
name = input("Введите своё имя: ")
print(f"Hello, {name}")
price = 100
quantity = 50
total_cost = price * quantity
print(f"Цена: {price} , Количество: {quantity}")
print(f"Общая стоймость: {total_cost}")
a = int(input(f"Введите цену: "))
b = int(input(f"Количество: "))
print(f"Общая стойм... | false |
03d0df2365d10490641e078569b2164c81009fa2 | malthunayan/python | /functions_task.py | 2,165 | 4.21875 | 4 | print("Hello and welcome to the Python Birthday Calculator!\n")
def check_birthdate(d,m,y):
from datetime import date
if y>date.today().year:
return False
elif y==date.today().year:
if m>date.today().month:
return False
elif m==date.today().month:
if d>date.today().day:
return False
elif d<0:
... | false |
8596578006399b3095b2a572e3f08aa0789031ba | JavaPhish/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 340 | 4.28125 | 4 | #!/usr/bin/python3
""" Adds 2 integers """
def add_integer(a, b=98):
""" Adds A + B and returns """
if (type(a) is not int and type(a) is not float):
raise TypeError("a must be an integer")
if (type(b) is not int and type(b) is not float):
raise TypeError("b must be an integer")
retur... | true |
a6b0b97119142fff91d2b99dc01c945d5409c799 | JavaPhish/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 873 | 4.125 | 4 | #!/usr/bin/python3
""" AAAAAAHHHHH """
class Square:
""" Square: a class. """
def __init__(self, size=0):
""" Init - init method """
if type(size) is not int:
raise TypeError("size must be an integer")
if size < 0:
raise ValueError("size must be >= 0")
... | true |
649b70c784a4bebd56897ba1f7b89fc98277a6e8 | OlayinkaAtobiloye/Data-Structures | /Data Structures With OOP/linkedlist.py | 2,391 | 4.3125 | 4 | class Node:
def __init__(self, value, next_=None):
self.value = value
self.next = next_
class LinkedList:
"""A linked list is a linear data structure. It consists of nodes. Each Node has a value and a pointer
to a neighbouring node(i.e it links to it's neighbor) hence the name linked list.... | true |
59c9e4ce10bbfcff84f1d0b23d2938ea98e67783 | motleytech/crackCoding | /RecursionAndDyn/tripleStep.py | 568 | 4.1875 | 4 | '''Count ways to get to nth step, given child can
take 1, 2 or 3 steps at a time'''
# let f(n) be the ways to get to step n, then
# f(n) = f(n-1) + f(n-2) + f(n-3)
def tripleStep(n):
'return number of ways to get to nth step'
if 1 <= n <= 3:
return n
a, b, c = 1, 2, 3
n = n-3
while n > 0:... | true |
0eaabc6474396fc098c038667a838bf486705375 | motleytech/crackCoding | /arraysAndStrings/uniqueCharacters.py | 1,703 | 4.21875 | 4 | '''
determine if a string has all unique characters
1. Solve it.
2. Solve it without using extra storage.
Key idea: Using a dictionary (hashmap / associative array), we simply iterate
over the characters, inserting each new one into the dictionary (or set).
Before inserting a character, we check if it already exists... | true |
e7d7975306ff4dc19aace83acc35a0b95172a3e0 | motleytech/crackCoding | /arraysAndStrings/isStringRotated.py | 788 | 4.125 | 4 | '''
Given 2 strings s1 and s2, and a method isSubstring, write a
method to detect if s1 is a rotation of s2
The key ideas are...
1. len(s1) == len(s2)
2. s1 is a substring of s2 + s2
If the above 2 conditions are met, then s2 is a rotation of s1
'''
def isSubstring(s1, s2):
'''
Returns True if s1 is a subst... | true |
6a6a06d047a95ed76a60ed9f2392016f6d379ccf | motleytech/crackCoding | /arraysAndStrings/urlify.py | 1,506 | 4.34375 | 4 | '''
Replace all spaces in a string with '%20'
We can do this easily in python with the string method 'replace', for example
to urlify the string myurl, its enough to call myurl.replace(' ', '%20')
Its that simple.
To make the task a little more difficult (to be more in line with what
the question expects), we will c... | true |
edf168e27bffaa08a8f44733f3b55a524ff3052f | ZswiftyZ/Nested_Control_Structures | /Nested Control Structures.py | 1,064 | 4.25 | 4 | """
Programmer: Trenton Weller
Date: 10.15.19
Program: This program will nest a for loop inside of another for loop
"""
for i in range(3):
print("Outer for loop: " + str(i))
for l in range(2):
print(" innner for loop: " +str(l))
"""
Programmer: Trenton Weller
Date: 10.22.19
Program: Aver... | true |
fe6259b11728d674f4e31caef1a1d284bc2b225a | Harshhg/python_data_structures | /Arrays/alternating_characters.py | 634 | 4.125 | 4 | '''
You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching
adjacent characters. To do this, you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
For example, given the ... | true |
368a07b7981351a62e8090e04924e62e0a03bafa | Harshhg/python_data_structures | /Graph/py code/implementing_graph.py | 1,481 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Implementing Graph using Adjacency List
from IPython.display import Image
Image("graph.png")
# In[6]:
# Initializing a class that will create a Adjacency Node.
class AdjNode:
def __init__(self,data):
self.vertex = data
self.next = None
# In[1... | true |
6d9e626308c9d866e15c071a6b0e74a3f38eeda5 | NiklasAlexsander/IN3110 | /assignment3/wc.py | 2,168 | 4.40625 | 4 | #!/usr/bin/env python
import sys
def main():
"""Main function to count number of lines, words, and characters, for all
the given arguments 'filenames' given.
A for-loop goes through the array of arguments given to wc.py when run from
from the terminal. Inside the loop each argument will be 'open' for... | true |
5d86b8b02a006566aefd819c9249151916514c82 | TECHNOCRATSROBOTICS/ROBOCON_2018 | /Computer Science/Mayankita Sisodia/ll.py | 1,564 | 4.53125 | 5 | # TO INSERT A NEW NODE AT THE BEGINNING OF A LINKED LIST
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data to the node.
self.next = None # In... | true |
dca26a9e0cc1952bd168baae5621036c8ac19e8d | TECHNOCRATSROBOTICS/ROBOCON_2018 | /Computer Science/Mayankita Sisodia/tree.py | 1,955 | 4.28125 | 4 | class Node:
def __init__(self, val): #constructor called when an object of class Node is created
self.left = None #initialising the left and right child node as null
self.right = None
self.data = val ... | true |
818f452713e6fce3908f59df610f6a9e4dd073b9 | mo2274/CS50 | /pset7/houses/import.py | 1,508 | 4.375 | 4 | from sys import argv, exit
import cs50
import csv
# check if the number of arguments is correct
if len(argv) != 2:
print("wrong argument number")
exit(1)
# create database
db = cs50.SQL("sqlite:///students.db")
# open the input file
with open(argv[1], "r") as characters:
# Create Reader
reader_csv ... | true |
d56d83109a66b60b73160c4a45d770d01ef76274 | Stuff7/stuff7 | /stuff7/utils/collections/collections.py | 1,021 | 4.1875 | 4 | class SafeDict(dict):
""" For any missing key it will return {key}
Useful for the str.format_map function when
working with arbitrary string and you don't
know if all the values will be present. """
def __missing__(self, key):
return f"{{{key}}}"
class PluralDict(dict):
""" Parses keys with the form "k... | true |
5fdd9607564a70b74cbab892584f6c9f6a83d532 | vinaud/Exercicios-Python | /Recursividade/elefantes.py | 1,044 | 4.15625 | 4 | """
Implemente a função incomodam(n) que devolve uma string contendo "incomodam "
(a palavra seguida de um espaço) n vezes. Se n não for um inteiro estritamente positivo,
a função deve devolver uma string vazia. Essa função deve ser implementada utilizando recursão.
Utilizando a função acima, implemente a função ele... | false |
ebba3c73c933c9b32ba3b2e1a59600e1bfb84d3e | aaazezeze1/BMI-Python | /bmi.py | 544 | 4.34375 | 4 | print("BMI Calculator\n")
name = input("Enter your name: ")
weight = float(input("Enter your weight (kg): "))
height = float(input("Enter your height (mtr): "))
bmi = weight / (height * height)
if bmi <= 18.5:
print('\nYour BMI is', bmi, 'which means you are underweight')
elif 18.5 < bmi < 25:
p... | false |
68b0ed0774592899b32fc7838d54d9d361a05ff8 | gevuong/Developer-Projects | /python/number_game.py | 1,407 | 4.21875 | 4 | import random
def game():
# generate a random number between 1 and 10
secret_num = random.randint(1, 10) # includes 1 and 10 as possibilities
guess_count = 3
while guess_count > 0:
resp = input('Guess a number between 1 and 10: ')
try:
# have player guess a number
... | true |
8f8cb15ef494edb05050d9eb8e82047c89dd1ad1 | chandrikakurla/inorder-traversal-using-stack-in-python | /bt_inorder traversal using stack.py | 1,018 | 4.28125 | 4 | #class to create nodes of a tree
class Node:
def __init__(self,data):
self.left=None
self.data=data
self.right=None
#function to inorder traversal of a tree
def print_Inorder(root):
#initialising stack
stack=[]
currentnode=root
while True:
#reach leftmost... | true |
1398699207d99c1fd94e7ed1e72fc3ec0cb661de | cvk1988/biosystems-analytics-2020 | /assignments/01_strings/vpos.py | 1,425 | 4.375 | 4 | #!/usr/bin/env python3
"""
Author : cory
Date : 2020-02-03
Purpose: Find the vowel in a string
"""
import argparse
import os
import sys
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casb... | true |
d5ff9d18c1fdf3e489080b6925293d5626adae93 | sideroff/python-exercises | /01_basic/exercise_024.py | 363 | 4.25 | 4 | def is_vowel(char: str):
vowels = ('a', 'e', 'i', 'o', 'u')
if len(string_input) > 1:
print("More than 1 character received. Choosing the first char as default.")
char = string_input[:1]
print("Your char is a vowel" if char in vowels else "Your char is not a vowel")
string_input = input(... | true |
58a9abb0dae2450fd180b6e00ae41748647b9176 | sideroff/python-exercises | /various/class_properties.py | 634 | 4.15625 | 4 | # using property decorator is a different way to say the same thing
# as the property function
class Person:
def __init__(self, name: str):
self.__name = name
def setname(self, name):
self.__name = name
def getname(self):
return self.__name
name = property(getname, setname)
... | true |
e6f65dfc64711b4e19a0c2d0391197a050402ac1 | judyhuang209/001Data-Science | /hw2/euclideanDistance.py | 606 | 4.375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 14:00:49 2019
Ref: https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/
@author: 105502506
"""
import math
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(length):
distanc... | false |
bd11a5ebbf2cdb102526ec1f39866c801e04ff54 | ladamsperez/python_excercises | /Py_Gitbook.py | 2,123 | 4.75 | 5 | # # Integer refers to an integer number.For example:
# # my_inte= 3
# # Float refers to a decimal number, such as:
# # my_flo= 3.2
# # You can use the commands float()and int() to change from onte type to another:
# float(8)
# int(9.5)
# fifth_letter = "MONTY" [4]
# print (fifth_letter)
# #This code breaks because Py... | true |
8c650f2e69061c4d164e8028b41009512e47d715 | ladamsperez/python_excercises | /task6_9.py | 636 | 4.125 | 4 | # Write a python function that takes a list of names and returns a new list
# with all the names that start with "Z" removed.
# test your function on this list:
# test_list = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara']
test_list = ['Zans', 'Dan', 'Grace', 'Zelda', 'L.E.', 'Zeke', 'Mara']
def noznames... | true |
49e49eb50b5beca72b1e6261390d99b1d45922a5 | Vuyanzi/Python | /app.py | 307 | 4.125 | 4 |
name = input ('What is your name? ')
print ('Hi '+ name)
colour = input ('What is your favourite colour ' + name + '')
print (name + ' likes ' + colour)
year_of_birth = input (name + ' Please enter your year of birth ' )
age = 2019 - int(year_of_birth)
g = 'Your current age is '
v = age
print (g + str(v)) | false |
7816945813febe2936ba26f6177c1bbfae2e4724 | lisachen0112/Coffee-machine | /coffee_machine.py | 2,499 | 4.34375 | 4 | water = 400
milk = 540
coffee_beans = 120
cups = 9
money = 550
espresso = {"water": 250, "milk": 0, "coffee_beans": 16, "money": 4}
latte = {"water": 350, "milk": 75, "coffee_beans": 20, "money": 7}
cappuccino = {"water": 200, "milk": 100, "coffee_beans": 12, "money":6}
def home():
print(f"""The coffee machine ha... | false |
b3facc57e8f25fe47cbd1b12d94d98403d490c9a | GabrielCernei/codewars | /kyu6/Duplicate_Encoder.py | 596 | 4.15625 | 4 | # https://www.codewars.com/kata/duplicate-encoder/train/python
'''
The goal of this exercise is to convert a string to a new string where each character in the new
string is "(" if that character appears only once in the original string, or ")" if that character
appears more than once in the original string. Ignore ... | true |
2811c2f7ad8732f43ab8498fb10ba05d8e6ad1e6 | GabrielCernei/codewars | /kyu6/Opposite_Array.py | 342 | 4.15625 | 4 | # https://www.codewars.com/kata/opposite-array/train/python
'''
Given an array of numbers, create a function called oppositeArray that returns an array
of numbers that are the additive inverse (opposite or negative) of the original. If the
original array is empty, return it.
'''
def opposite_list(numbers):
return... | true |
61e909280a67b37ae7f53ace4915e2ef3b51ba67 | GabrielCernei/codewars | /kyu6/To_Weird_Case.py | 859 | 4.5625 | 5 | # https://www.codewars.com/kata/weird-string-case/train/python
'''
Note: The instructions are not very clear on this one, and I
wasted a lot of time just trying to figure out what was expected.
The goal is to alternate the case on *EACH WORD* of the string,
with the first letter being uppercase. You will not pass al... | true |
0e26c6bb0da2b0e5546e86aa6b2cb6ba09b27ccf | enajeeb/python3-practice | /PythonClass/answer_files/exercises/sorting.py | 711 | 4.1875 | 4 | # coding: utf-8
'''
TODO:
1. Create a function called sort_by_filename() that takes a path and returns the filename.
- Hint: You can use the string's split() function to split the path on the '/' character.
2. Use sorted() to print a sorted copy of the list, using sort_by_filename as the sorting function.
'''
p... | true |
c09cdf2e94f9060f285d01e110dc2fc48f2db496 | enajeeb/python3-practice | /PythonClass/class_files/exercises/lists.py | 688 | 4.34375 | 4 | # coding: utf-8
'''
Lists
Lists have an order to their items, and are changeable (mutable).
Documentation:
https://docs.python.org/2/tutorial/introduction.html#lists
'''
# Square brackets create an empty list.
animals = []
# The append() function adds an item to the end of the list.
animals.append('cat')
animals... | true |
cffa20e72d74c07324bac4fdd490bac5218dae9a | enajeeb/python3-practice | /PythonClass/class_files/exercises/functions.py | 552 | 4.40625 | 4 | # coding: utf-8
''' Useful functions for the Python classs. '''
'''
TODO:
1. Create a function called words().
2. The function should take a text argument,
and use the string's split() function to return a list of the words found in the text.
The syntax for defining a function is:
def func_name(arg... | true |
dd18b7dbf8cf814f889a497c4565dcb3b1d12719 | drnodev/CSEPC110 | /meal_price_calculator.py | 1,349 | 4.15625 | 4 | """
File:meal_price_calculator.py
Author: NO
Purspose: Compute the price of a meal as follows by asking for the price of child and adult meals,
the number of each, and then the sales tax rate. Use these values to determine the total price of the meal.
Then, ask for the payment amount and compute the amount of chan... | true |
a90c6a4910e4c959057a6662dfb76c08fa123931 | LucasHenriqueAbreu/introducaoprogramaca | /exercicios.py | 777 | 4.15625 | 4 | # Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre:
# A) Quantas vezes apareceu o valor 9.
# B) Em que posição foi digitado o primeiro valor 3.
# C) Quais foram os números pares.
valores = (
int(input('Informe um número: ')),
int(input('Informe um número: ... | false |
844344450154b2caacee4af1a0530e14781b9ace | sayan19967/Python_workspace | /Python Application programming practice/Context Managers.py | 2,410 | 4.59375 | 5 | #A Context Manager allows a programmer to perform required activities,
#automatically, while entering or exiting a Context.
#For example, opening a file, doing few file operations,
#and closing the file is manged using Context Manager as shown below.
##with open('a.txt', 'r') as fp:
##
## content = fp.read... | true |
baef544efc97fab5a7ce87d4a9ccff5fae67b5f8 | DeepthiTabithaBennet/Py_Conversions_Temperature | /Celsius_to_Farenheit.py | 397 | 4.28125 | 4 | #TASK :
#Convert the given temperature to Farenheit
#(Celsius * 9/5) + 32 = Farenheit
#INPUT FORMAT :
#Temperature in Celsius
#OUTPUT FORMAT :
#Temperature in Farenheit
#__________________________________________________________________________________#
Celsius = float(input())
x = Celsius * 9.0
y = x / 5.0... | false |
81eccca3e13efaf255a41a92b5f7ee203a6aca41 | Elzwawi/Core_Concepts | /Objects.py | 2,689 | 4.4375 | 4 | # A class to order custom made jeans
# Programming with objects enables attributes and methods to be implemented
# automatically. The user only needs to know that methods exist to use them
# User can focus on completing tasks rather than operation details
# Difference between functions and objects: Objects contain stat... | true |
af30645406d953795958b806cf529f1ce97150c2 | ZSerhii/Beetroot.Academy | /Homeworks/HW6.py | 2,918 | 4.1875 | 4 | print('Task 1.\n')
print('''Make a program that generates a list that has all squared values of integers
from 1 to 100, i.e., like this: [1, 4, 9, 16, 25, 36, ..., 10000]
''')
print('Result 1:\n')
vResultList = []
for i in range(1, 101):
vResultList.append(i * i)
print('Squared values list of integers from 1 to... | true |
4cc9d559c7a44cd2f500a60548fc6b98294828f0 | erictseng89/CS50_2021 | /week6/scores.py | 769 | 4.125 | 4 | scores = [72, 73, 33]
""" print("Average: " + (sum(scores) / len(scores))) """
# The "len" will return the number of values in a given list.
# The above will return the error:
# TypeError: can only concatenate str (not "float") to str
# This is because python does not like to concatenate a float value to a string.
... | true |
72548593092cdbc2ddb64d76951d71d4a89b93e3 | mzdesa/me100 | /hw1/guessNum.py | 599 | 4.21875 | 4 | #write a python program that asks a user to guess an integer between 1 and 15!
import random
random_num = random.randint(1,15) #generates a random int between 0 and 15
guess = None #generate an empty variable
count = 0
while guess != random_num:
count+=1
guess = int(input('Take a guess: '))
if guess == rand... | true |
e7011a00db9e29abb6e8ad19259dfcacc1423525 | abrolon87/Python-Crash-Course | /useInput.py | 1,219 | 4.28125 | 4 | message = input("Tell me something, and I will repeat it back to you: ")
print (message)
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
#prompt += "\nWhat is your age? " this do... | true |
1957711865e1570ed423c327f288ce8a12d2fe50 | jacquelinefedyk/team3 | /examples_unittest/area_square.py | 284 | 4.21875 | 4 | def area_squa(l):
"""Calculates the area of a square with given side length l.
:Input: Side length of the square l (float, >=0)
:Returns: Area of the square A (float)."""
if l < 0:
raise ValueError("The side length must be >= 0.")
A = l**2
return A
| true |
a957e7f81f52bc56d9af1cd63a284f2e597c6f9d | JohnAsare/functionHomework | /upLow.py | 766 | 4.15625 | 4 | # John Asare
# Jun 19 2020
""" Write a Python function that accepts a string and calculates the number of upper case letters and
lower case letters.
Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'
Expected Output :
No. of Upper case characters : 4
No. of Lower case Characters : 33 """
def up_low(... | true |
f5306409b6be76bdc3ce5789daafcca973fdb971 | kelvinng213/PythonDailyChallenge | /Day09Challenge.py | 311 | 4.1875 | 4 | #Given a string, add or subtract numbers and return the answer.
#Example:
#Input: 1plus2plus3minus4
#Output: 2
#Input: 2minus6plus4plus7
#Output: 7
def evaltoexpression(s):
s = s.replace('plus','+')
s = s.replace('minus','-')
return eval(s)
print(evaltoexpression('1plus2plus3minus4')) | true |
e082eb4ff18f0f3a19576a5e3e346227ba98ebf8 | kelvinng213/PythonDailyChallenge | /Day02Challenge.py | 894 | 4.53125 | 5 | # Create a function that estimates the weight loss of a person using a certain weight loss program
# with their gender, current weight and how many weeks they plan to do the program as input.
# If the person follows the weight loss program, men can lose 1.5% of their body weight per week while
# women can lose 1.2% o... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.