blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6bd8e9904b1fc9a1573512dd73214bbf37f68ce0 | pravinherester/LearnPython | /functions/calculator/Calculator6.py | 1,147 | 4.15625 | 4 | def add(n1,n2):
return n1+n2
def subtract(n1,n2):
return n1-n2
def multiply(n1,n2):
return n1*n2
def divide(n1,n2):
return n1/n2
from art import logo
from replit import clear
operations={
"+":add,
"-":subtract,
"*":multiply,
"/":divide,
}
def calculator():
print (logo)
num1= float (input("Enter ... | true |
fe4aaa884307c5b8b358e25b2bb2aa8dca01d1eb | PrabhatRoshan/Daily_Practice_Python | /Daily_practice_codes/if-elif-else/user_input.py | 594 | 4.21875 | 4 | # Write a python program to check the user input abbreviation.If the user enters "lol",
# print "laughing out loud".If the user enters "rofl", print "rolling on the floor laughing".
# If the user enters "lmk", print "let me know".If the user enters "smh", print "shaking my head".
user_ip=input("Enter the user inp... | true |
41dade8692d9fbc19de8226e9abe366225058ddb | ionblast25/css-225-homework | /problem_4.py | 470 | 4.46875 | 4 | #Justine Rosado
#10/31/20
#this program is supports to iterates the integers from 1 to 50
def divisible_by_3(n):
if n%3 == 0 or n%6 == 0:
print("divisible by 3")
if n%5 == 0 or n%20 == 0:
print("divisible by 5")
elif n%3 == 0 and n%5 == 0:
... | false |
73a1084037267aa353163c663ce2c6ccf22b6d1b | Bamblehorse/Learn-Python-The-Hard-Way | /ex3.py | 979 | 4.3125 | 4 | #Simple print " "
print "I will now count my chickens:"
#print "string then comma", integer
print "Hens", 25 + 30 / 6
#bidmas. Brackets, indices div, mult,
#add, sub. PEMDAS. Mult first.
#so div first 30 / 6 = 5
#then 25 + 5 = 30, simples
print "Roosters", 100 - 25 * 3.0 % 4.0
#3 % 4 = 3?, 3 * 25 = 75, 100 -... | true |
af6dde0e1aaddafe38cab5a891fd6895207d2b7b | kent10636/Learn_Python | /set.py | 1,755 | 4.28125 | 4 | # set和dict类似,是一组key的集合,但不存储value
s = set([1, 2, 3])
print(s) # 显示的{1, 2, 3}只表示set内部有1、2、3这3个元素,显示的顺序也不表示set是有序的
print()
# 重复元素在set中自动被过滤
s = set([1, 1, 2, 2, 3, 3])
print(s)
print()
# 通过add(key)方法添加元素到set中,可以重复添加,但不会有效果
s.add(4)
print(s)
s.add(4)
print(s)
print()
# 通过remove(key)方法删除元素
s.remove(4)
print(s)
print()
... | false |
ccbd0b742eb6ccaf7095dcb23c79e3a9ab190048 | kent10636/Learn_Python | /args.py | 2,720 | 4.28125 | 4 | # 必选参数在前,默认参数在后
# 函数有多个参数时,变化大的参数放前面,变化小的参数放后面
def power(x, n=2): # 可以把第二个参数n的默认值设定为2
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(5))
print(power(5,3))
print()
def enroll(name, gender, age=6, city='Beijing'): # 把年龄和城市设为默认参数
print('name:', name)
print('gender:', gender)
print('age:', age)
p... | false |
3cba62c7a9bd0ef2b0a3ee2544f0296461590d11 | Vindhesh/demopygit | /calc.py | 1,111 | 4.125 | 4 |
class Calculator:
def __init__(self):
pass
def calculate(self):
answer = 0
memory = list()
while True:
input1, operator, input2 = input("Enter your first number, operator and second number with space: ").split()
input1 = float(input1)
in... | true |
817849b00859f665a1ba1830469f7d29cbc177e4 | chenfangstudy/data_analysis | /chapter_2/01-任务程序/code/任务2.2 认识NumPy矩阵与通用函数.py | 2,932 | 4.15625 | 4 | # -*- coding: utf-8 -*-
###############################################################################
####################### 正文代码 #######################
###############################################################################
# 代码 2-30
import numpy as np #导入NumPy库
matr1 = np... | false |
74df44cb43c3fc886f1c684aab78a5864cdc6893 | SamirDjaafer/Python-Basics | /Excercises/Excercise_106.py | 868 | 4.34375 | 4 | age = input('How old are you? ')
driver_license = input('Do you have a drivers license? Yes / No ')
if driver_license == 'Yes' or driver_license == 'yes':
driver_license = True
else:
driver_license = False
# - You can vote and drive
if int(age) >= 18 and driver_license == True:
print('Nice, you can vote ... | true |
ecf1eaf7b05d97214568ab6fc69c31a41f74fd4f | ssiddam0/Python | /Lab7/lab7-13_Sowjanya.py | 1,176 | 4.28125 | 4 | # program - lab7-13_sowjanya.py 26 April 2019
'''
This program simulates a Magic 8 Ball game, which is a fortune-telling toy
that displays a random response to a yes or no question. It performs the
following actions:
1) Reads the 12 responses from the file named 8_ball_responses.txt
2) Prompts the user to ask... | true |
d0c72888e33db08b24f9c9e0b6e089665561fc9b | JackStruthers/CP1404_Practicals | /CP1404_Practicals/week_02/average_age.py | 410 | 4.15625 | 4 | age = int(input("Please enter the age of a person (use a negative if there are no more people): "))
collective_age = 0
people = 0
while age >= 0:
people += 1
collective_age += age
age = int(input("Please enter the age of a person (use a negative if there are no more people): "))
if people == 0:
print(... | true |
b8aed7db2cc46f37e0bda243edfa6fc00c9d8e7f | JackStruthers/CP1404_Practicals | /CP1404_Practicals/week_01/Lecture 1 act 2.py | 260 | 4.15625 | 4 | def main():
user_age = int(input("Please enter your age: "))
while user_age < 0:
user_age = int(input("You must be older than 0: "))
if user_age < 18:
print("You are a child")
else:
print("You are an adult")
main()
| false |
1cf789a5c355229d5426c3d334e30367eeb5e00c | sanxofon/basicnlp3 | /tiposvars.py | 2,892 | 4.375 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Tipos de variables y constantes
"""
# Números
# Enteros -n, ...,-1, 0, 1,..., n
entero = 5
# Si tengo una cadena u otra cosa y quiero convertirla a entero
cadena = "5"
entero = int(cadena)
# Comprobar si una variable es un entero
if isinstance(cadena, int):
print(cad... | false |
7fe329824f1077f9f49f8b6595bbfbd9abe1cb75 | rahulraghu94/daily-coding-problems | /13.py | 670 | 4.125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given an integer k and a string s, find the length of the longest substring
that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct
characters is "b... | true |
02aae668f0f2be658aefa800ad3e22eac941a801 | makoalex/Python_course | /Regular expressions/functions_RE.py | 1,084 | 4.34375 | 4 | import re
# making a function that extracts a phone number and all phone numbers in a given sequence
def extract_phone(input):
phone_regex = re.compile(r'\b\d{3} \d{4}-?\d{3}\b')
match = phone_regex.search(input)
if match:
return match.group()
return None
def extract_all_phone(input):
p... | true |
92d0d3047686d2b0f01898d074e5b585df4e1052 | makoalex/Python_course | /Iterator.py | 2,040 | 4.375 | 4 | # the for loop runs ITER in the background making the object an iterator after which it calls next
# on every single item making the object an iterable
def my_loop(iterable):
iterator = iter(iterable)
while True:
try:
it = next(iterator)
print(it)
except StopIteration:
... | true |
77164c1cfa58f37069bc368e79ab0268c12d5645 | WeikangChen/algorithm | /data_struct/tree/trie0b.py | 1,807 | 4.15625 | 4 | class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.value = None
self.children = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word ... | true |
146a08687142b1a7ed5a341541616d637b308056 | rolandoquiroz/hackerrank_coderbyte_leetcode | /list2.py | 1,260 | 4.375 | 4 | #!/usr/bin/python3
"""
Find Intersection
Have the function FindIntersection(strArr)
read the array of strings stored in strArr
which will contain 2 elements: the first element
will represent a list of comma-separated numbers
sorted in ascending order, the second element will
represent a second list of comma-separated n... | true |
01fab7efbe9448f98e97707caac64405ad3a190b | j-python-programming/python-programming | /src/06-area.py | 511 | 4.15625 | 4 | # Python によるプログラミング:第 6 章
# 例題 6.5 Polymorphism
# --------------------------
# プログラム名: 06-area.py
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
class Circle:
def __init__(self, radius):
self.radius = radi... | false |
c55b2e80288a101ebbc61a3847ca4386b7814f09 | diegoro1/Tutorials | /python/guess_list.py | 1,539 | 4.25 | 4 | #----------------------------------------------------------------------------------------------------------
# Short List Exesise
#----------------------------------------------------------------------------------------------------------
guests = ['Joe','Jan','June','Julian',... | false |
1f40b96cdc1c945a813c755336b73bb576ac93c7 | ValynseeleAlexis/PythonScripts | /Pong/pong1.py | 2,821 | 4.15625 | 4 | # Valynseele Alexis
# From Learn Python by building Full Course - FreeCodeCamp.org
# 14/01/2020
import turtle
window = turtle.Screen()
window.title("Pong")
window.bgcolor("black")
window.setup(width = 800, height = 600)
window.tracer(0)
# Paddle A
paddleA = turtle.Turtle()
paddleA.speed(0)
paddleA.shape("square")
p... | false |
96b85d55696fb32aaad2a79314b88880a0363da8 | MaxKrivulin/Home_Work | /HW_1/HW_1_1.py | 786 | 4.3125 | 4 | #1. Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
number = int(input("Введите целое число: "))
print("Ваше число равно ", number)
number_1 = int(input("Введите еще одно целое число: "))
print("Ваше второ... | false |
8985c182f0d906b520962503eae94659bb7c6553 | dongrerohan421/python3_tutorials | /09_if_else.py | 522 | 4.15625 | 4 | '''
This program shows use of If-Else conditional statement.
1. Your condition doesn't starts with indentations or tab.
2. statment inside the condition starts with indentation or tab.
3. Once condition satisfied, next statement must starts with new line with no indentation or no tab.
'''
n = int(input("Number: "))
... | true |
baf9a7f27bbb8bb66f3565d3b3be2daf9651d090 | dongrerohan421/python3_tutorials | /06_strings.py | 686 | 4.34375 | 4 | '''
This program explains Pytho's string
'''
# Escape character usefule to jump over any character.
# Use double back slash to print back slash in your output.
a = 'I am \\single quoted string. Don\'t'
b = "I am \\double quoted string. Don\"t"
c = """I am \\triple quoted string. Don\'t"""
print (a)
print (b)
print (... | true |
b837247ea4c25e581303bc36092eebafd4f0b0e6 | Gowtham-P-M/Coding-with-python | /task5.py | 990 | 4.1875 | 4 | #1)Write a program to create a list of n integer values
def add(k):
l=int(input("What position do you want to add the item "))
m=int(input("What is the item value "))
k.insert(l,m)
print("The new list is ",k)
def dele(k):
f=int(input("What is the item you want to delete "))
for i in k:
... | false |
675c80d6f783c90bcec8fc34cb91ddff2ebdfe61 | nmounikachowdhary/mounikan28 | /firstassignment.py | 2,373 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Python Program - Calculate Circumference of Circle
print("Enter 'x' for exit.");
rad = input("Enter radius of circle: ");
if rad == 'x':
exit();
else:
radius = float(rad);
circumference = 2*3.14*radius;
print("\nCircumference of Circle =",circumferenc... | true |
7859e5d4e892f162c23a96dc1a7480f556f28fef | Josglynn/Public | /List Less Than Ten.py | 1,487 | 4.75 | 5 | # Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# Write a program that prints out all the elements of the list that are less than 13.
list_num = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
filtered_1 = [item for item in list_num if item < 13] # Comprehensions style
print(filt... | true |
0bfc7cae00049db8f2bee365c4d85001c0a92e62 | michaelschuff/Python | /DailyCodingChallenge/201.py | 499 | 4.21875 | 4 | #You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
# 1
# 2 3
#1 5 1
#We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending wit... | true |
25cb09b0c2f6330633749615ec5264f7a8f3245d | jabedkhanjb/Hackerrank | /30-Days-of-Code/Day 26:_Nested Logic.py | 2,276 | 4.25 | 4 | """
Objective
Today's challenge puts your understanding of nested conditional statements to the test. You already have the knowledge to complete this challenge, but check out the Tutorial tab for a video on testing.
Task
Your local library needs your help! Given the expected and actual return dates for a library book,... | true |
3ca41732ad78e387b0d4eb6af55b65cbd08d19be | jabedkhanjb/Hackerrank | /Python/String/Text_Wrap.py | 570 | 4.15625 | 4 | '''
Task
You are given a string and width .
Your task is to wrap the string into a paragraph of width .
Input Format
The first line contains a string, .
The second line contains the width, .
Output Format
Print the text wrapped paragraph.
Sample Input
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output
ABCD
EFGH
IJKL
IMN... | true |
63d0bdef7cc2dab2c6bbc15a51f3e5061485d23f | jabedkhanjb/Hackerrank | /30-Days-of-Code/Day16:_Exceptions.py | 1,756 | 4.53125 | 5 | """
Objective
Today, we're getting started with Exceptions by learning how to parse an integer from a string and print a custom error message. Check out the Tutorial tab for learning materials and an instructional video!
Task
Read a string, , and print its integer value; if cannot be converted to an integer, print Ba... | true |
3515dd6d4de9cea5f774213bc7c4bef6af4d97e5 | jabedkhanjb/Hackerrank | /Python/String/Capatilize.py | 1,250 | 4.40625 | 4 | """
You are asked to ensure that the first and last names of people begin with a capital letter in their passports.
For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name... | true |
c91d3ef1c333c85daf6cfca9de9962d25675b640 | jabedkhanjb/Hackerrank | /10_Days_of_Statistics/Day0/Mean_Median_Mode.py | 2,255 | 4.375 | 4 | """
Objective
In this challenge, we practice calculating the mean, median, and mode. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an array, , of integers, calculate and print the respective mean, median, and mode on separate lines. If your array contains more than one modal... | true |
f651b61ddacc18b64492fe337fbc3fbf0653f86a | yoginee15/Python | /venv/Conditions.py | 332 | 4.3125 | 4 | x = int(input("Enter number"))
r = x%2
if r==0:
print("You entered even number")
else:
print("You entered odd number")
if x>0:
print("You entered positive number")
elif x<0 :
print("You entered negative number")
elif x==0:
print("You entered zero")
else :
print("Please enter number. You entered... | true |
85da073031a62446c1e48e915337b04f76a268ba | numeoriginal/multithread_marketplace | /consumer.py | 2,118 | 4.25 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
import time
from threading import Thread
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
Thread.__in... | true |
620ab9fd31bc864245668f9445ad4801e96d9603 | PHILLIPEBLOOD/pythonquestions | /string/quests2.py | 411 | 4.15625 | 4 | '''Nome ao contrário em maiúsculas. Faça um programa que permita ao usuário
digitar o seu nome e em seguida mostre o nome do usuário de trás para frente
utilizando somente letras maiúsculas. Dica: lembre−se que ao informar o nome o
usuário pode digitar letras maiúsculas ou minúsculas. '''
nome = input("Nome: ").upper()... | false |
111310ed7fc2bff2464a4622ba4b0ba969be21dc | PHILLIPEBLOOD/pythonquestions | /sequencial/quest16.py | 542 | 4.15625 | 4 | '''Faça um programa para uma loja de tintas.
O programa deverá pedir o tamanho em metros quadrados da área a ser pintada.
Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados
e que a tinta é vendida em latas de 18 litros,
que custam R$ 80,00.
Informe ao usuário a quantidades de latas de tinta... | false |
7eae123f77a6d3ddee18ec46551920ca2fb5ee8d | PHILLIPEBLOOD/pythonquestions | /funcoes/questf1.py | 348 | 4.15625 | 4 | '''Faça um programa para imprimir:
1
2 2
3 3 3
.....
n n n n n n ... n
para um n informado pelo usuário.
Use uma função que receba um valor n inteiro e imprima até a n-ésima linha. '''
def imprimir(n):
cont = 0
while cont < n:
print(n, end=", ")
n = int(input("Di... | false |
1a8ea3a5f1983a0f5ef66f35685f27b52e5af392 | PHILLIPEBLOOD/pythonquestions | /decisao/questd25.py | 991 | 4.3125 | 4 | '''Faça um programa que faça 5 perguntas para uma pessoa sobre um crime.
As perguntas são:
"Telefonou para a vítima?"
"Esteve no local do crime?"
"Mora perto da vítima?"
"Devia para a vítima?"
"Já trabalhou com a vítima?" O programa deve no final emitir uma classificação
sobre a participação da pessoa no crime. Se a pe... | false |
863ca5da1caa5585a0661baf3f7268f5090ab874 | PHILLIPEBLOOD/pythonquestions | /string/quests1.py | 936 | 4.28125 | 4 | '''Tamanho de strings. Faça um programa que leia 2 strings e informe o conteúdo
delas seguido do seu comprimento. Informe também se as duas strings possuem o
mesmo comprimento e são iguais ou diferentes no conteúdo.
Compara duas strings
String 1: Brasil Hexa 2006
String 2: Brasil! Hexa 2006!
Tamanho de "Brasil Hexa 200... | false |
c7d134cfabb926abfa32c50ee6e89de88ea987b6 | PHILLIPEBLOOD/pythonquestions | /repeticao/questr8.py | 236 | 4.21875 | 4 | '''Faça um programa que leia 5 números e informe a soma e a média dos números.
'''
soma = 0
for n in range(1, 6):
numero = int(input("Numero: "))
soma += numero
media = soma / 5
print("Soma: ", soma)
print("Media: ", media)
| false |
e27300a48afbd15702297b8ec6d2a5b33d493b10 | PHILLIPEBLOOD/pythonquestions | /string/quests5.py | 225 | 4.3125 | 4 | '''Nome na vertical em escada invertida. Altere o programa anterior de modo
que a escada seja invertida.
FULANO
FULAN
FULA
FUL
FU
F '''
nome = input("Nome: ")
i = len(nome)
a = 1
while a <= i:
print(nome[0:i])
i -= 1
| false |
bfc1b1dbc57b1f755badff44a4fee261a2d9247a | EladAssia/InterviewBit | /Binary Search/Square_Root_of_Integer.py | 990 | 4.15625 | 4 | # Implement int sqrt(int x).
# Compute and return the square root of x.
# If x is not a perfect square, return floor(sqrt(x))
# Example :
# Input : 11
# Output : 3
##########################################################################################################################################
class Solut... | true |
141a8525869b6a6f2747b61228f70224ae2fcc63 | EladAssia/InterviewBit | /Two Pointers Problems/Merge_Two_Sorted_Lists_II.py | 1,452 | 4.125 | 4 | # Given two sorted integer arrays A and B, merge B into A as one sorted array.
# Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code.
# TIP: C users, please malloc the result into a new array and return the result.
# If the number of elements initialized in A and ... | true |
38bd841245ca882be8cbade1bc9648aee3ea9073 | EladAssia/InterviewBit | /Hashing/Anagrams.py | 1,774 | 4.125 | 4 | # Given an array of strings, return all groups of strings that are anagrams. Represent a group by a list of integers representing the
# index in the original list. Look at the sample case for clarification.
# Anagram : a word, phrase, or name formed by rearranging the letters of another, such as 'spar', formed from '... | true |
c7cc0ced10bcf0bf1bb0e4da0cd97fc978ac9dd6 | zk18051/ORS-PA-18-Homework05 | /task6.py | 718 | 4.375 | 4 | """
=================== TASK 6 ====================
* Name: Typewriter
*
* Write a script that will take file name as user
* input. Then the script should take file content
* as user input as well until user hits `Enter`.
* At the end, the script should store the content
* into the file with given name. If the file... | true |
f285ba64dd8d68b96db0f7430fe2cf8a9bb111d3 | fatpat314/SPD1.4 | /Homework2/leet_code.py | 2,473 | 4.15625 | 4 | # Q1
"""Given an array of integers, return indices of the two numbers
such that they add up to a specific target"""
# restate question
'''So we have an array of ints. we want to return the position of the index
of two numbers that add to our target number'''
# clearifying questions
'''None'''
# assumptions
'''No neg... | true |
54f4b9f4d9b00e05ccf0e06ae96051cea6873fae | Chewie23/fluffy-adventure | /CodingTestForOpenGov/SortListAndOutputElement.py | 913 | 4.25 | 4 | from random import randrange
from heapq import nlargest
def organize_and_pull_K_biggest_num(num_of_elem, Kth):
if Kth <= 0 or Kth > num_of_elem:
print("That number is out of range!")
exit(0)
num_list = []
for n in range(num_of_elem):
num_list.append(randrange(-100, 100))
pr... | true |
2eea86811100bc9b0d3641ce9b31f58c503fa58d | Tweek43110/PyPractice | /Loops.py | 1,679 | 4.1875 | 4 | # There are two type of loops available FOR and WHILE
# FOR examples
simpleTest = [1,2,3,4]
for number in simpleTest:
print(number)
# another useful example
for i in range(12, 20):
print(i)
for evenNumbers in range(0,20,2):
print(evenNumbers)
# WHILE examples
x = 0
while x < 5:
print(x)
x += 1
#... | true |
5c535cf88790186b556a71dacc4eb4b6482ea4db | OliveiraFabioPereirade/introducao_python | /aula11.py | 1,450 | 4.125 | 4 | # lista de exceções nativas do python
# https://docs.python.org/3/library/exceptions.html
lista = [10, 1]
try:
arquivo = open('teste.txt', 'r')
texto = arquivo.read()
divisao = 10/0 # força erro: divisão por zero
# numero = lista[3] # força erro: excedeu número de elementos da lista
# x = a # força... | false |
46d626b6ae270bca958857b813b6baea359b8804 | hongkailiu/test-all | /trunk/test-python/script/my_exception.py | 922 | 4.1875 | 4 | #!/usr/bin/python
def kelvin_to_fahrenheit(temperature):
"""test exception"""
assert (temperature >= 0), "Colder than absolute zero!"
return ((temperature - 273) * 1.8) + 32
print kelvin_to_fahrenheit(273)
print int(kelvin_to_fahrenheit(505.78))
# will raise an exception
# print kelvin_to_fahrenheit(-5)... | true |
8813818cf837609e9c75a9ae8ddfd1954246ba7f | RizwanRumi/python_Learning | /OOP/constructor_callingmethod.py | 999 | 4.21875 | 4 | class eval_equations:
# single constructor to call other methods
def __init__(self, *inp):
# when 2 arguments are passed
if len(inp) == 2:
self.ans = self.eq2(inp)
# when 3 arguments are passed
elif len(inp) == 3:
self.ans = self.eq1(inp)
... | false |
382861d6c759a0954249f94c18732f562183bebf | jahick/pythonSamples | /convert.py | 901 | 4.1875 | 4 | # Put your code here
decimal = int(input("Enter an integer: "));
base = int(input("Enter a base number to convert to. (2, 8, 10, 16): "));
def decimalToRep(decimal,base):
if base == 10:
return decimal;
elif base == 2:
return str(bin(decimal)[2:]);
elif base == 8:
return oct(decimal)... | true |
aacf2efce41b7894a1e69ab400e9efdffcb16758 | goosen78/simple-data-structures-algorithms-python | /bubble_sort.py | 912 | 4.4375 | 4 | #!/usr/bin/env python3
"""
Bubble Sort Script
"""
def bubble_sort(L):
"""
Sorts a list in increasing order. Because of lists are mutable
this function does not have to return something.
This algorithm uses bubble sort.
@param L: a list (in general unsorted)
"""
for i in... | true |
81c3ccbe5b8b5a1464a2244761a38c18f60e265d | imrajashish/python-prog | /heap&queu.py | 789 | 4.4375 | 4 | #Write a Python program to find the three largest integers from a given list of numbers using Heap queue algorithm
import heapq
h = [12,34,56,786,56,45,3,453]
print("Three largest number in list: ")
print(heapq.nlargest(3,h))
#Write a Python program to find the three smallest integers from a given list of numbers usin... | true |
3d7582f3f5e45f2d1819763c4e96a3b4c5e26bb8 | imrajashish/python-prog | /list2.py | 550 | 4.625 | 5 | #Write a Python program to extract the nth element from a given list of tuples.
def extract_nth_element(test_list, n):
result = [x[n] for x in test_list]
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print ("Original list:")
p... | true |
95bd03109ce74e6f3207be3dfa2f7ff15cd26840 | imrajashish/python-prog | /lambda2.py | 2,376 | 4.34375 | 4 | #Write a Python program to sort a list of dictionaries using Lambda.
models = [{'make':'Nokia', 'model':216, 'color':'Black'}, {'make':'Mi Max', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}]
print("\n originals dict in model:")
print(models)
sorted_models = sorted(models,key = lambda x:x... | true |
c0ef45938c2daadcd8095d36ef7037c502ad0fc1 | imrajashish/python-prog | /lambda3.py | 2,251 | 4.28125 | 4 | #Write a Python program to find intersection of two given arrays using Lambda
num1 = [1,2,3,4,5,6,7,8,7]
num2 = [3,4,5,6,6,8,8,9,8,7]
print("\n original arrays:")
print(num1)
print(num2)
result = list(filter(lambda x: x in num1,num2))
print("\n Intersection of the said array: ",result)
#Write a Python program to rearr... | true |
d1f0d16d6f96eeec6981e70ead1cf21d33762dd3 | brianchun16/PythonPractices | /Lecture04/practice1_while.py | 238 | 4.15625 | 4 | x = int(input('Enter an integer: '))
x = abs(x)
ans = 0
while ans**3 < x:
ans = ans+1
if ans**3 == x:
print('X is a perfect cube')
print('The X value is: ', ans)
else:
print('X is not a perfect cube')
print('The X value is:', ans)
| true |
ff0b42c3fd172deb291c9e510b3f1cff9ef61497 | nikhilgurram97/CS490PythonFall2017 | /Lab Assignment 1/gameboard.py | 611 | 4.25 | 4 | hinp=int(input("Enter Height of Board : "))
winp=int(input("Enter Width of Board : ")) #For taking input height and input width respectively
def board_draw(height,width): #Initializing a drawing function
for j in range(0,height): #In this loop, the reverse shaped '... | true |
1a4d6a0fc3ae833fa1bb09a2130c9d11eab3417a | plammens/python-introduction | /Fundamentals I/Elements of Python syntax/Statements expressions/main.py | 1,011 | 4.40625 | 4 | # ----- examples of statements (each separated by a blank line): -----
import math # import statement
my_variable = 42 # assignment statement
del my_variable # del statement
if __name__ == '__main__': # if statement
print('executing as script') #
else: #
... | true |
a2b0fd51ade7db2efafb76fab1291b73ccf516af | rduvalwa5/Examples | /PythonExamples/src/PyString.py | 2,687 | 4.21875 | 4 | '''
Created on Mar 24, 2015
@author: rduvalwa2
https://docs.python.org/3/library/string.html?highlight=string#module-string
https://docs.python.org/3/library/stdtypes.html#string-methods
This is how to reverse a string
http://stackoverflow.com/questions/18686860/reverse-a-string-in-python-without-using-reversed-or-1
'... | true |
d570c49f66084ad88db859791decfc6b6e296911 | Shashwat15/GitHackeve | /project1.py | 657 | 4.25 | 4 | def fib(number_for_fibonacci):
# Add code here
return #Fibonacci number
def is_prime(number_to_check):
n=0
while n<=b/2:
if b/n==0:
print ("not prime")
elif b/n!=0:
print ("prime")
n=n+1
return #boolean value
def reverse_strin... | false |
65059eda46952316221245f7b021616acb7b7c87 | Exubient/UTCS | /Python/Assignment 4/assignment4.py | 2,830 | 4.15625 | 4 | """
Assignment 4: Metaprogramming
The idea of this assignment is to get you used to some of the dynamic
and functional features of Python and how they can be used to perform
useful metaprogramming tasks to make other development tasks easier.
"""
#Hyun Joong Kim
#hk23356
import functools
import logging
... | true |
537fc9c10ae830cd564ae892235719b048178bb3 | johncmk/cloud9 | /rec_pointer.py | 726 | 4.3125 | 4 | '''
Updating the el in the li while
traversing in recursion can effect the
changes of original value of the li in running time because
its updating the value via address.
Updating the value that is pass by value
through recursion would not change the orginal value
beause it copies the value before it goes into the
nex... | true |
2b4c15c744d01b2a58a72f47a4b9bcca85336c2c | johncmk/cloud9 | /qsort_CLRS.py | 792 | 4.125 | 4 | '''This function takes last element as pivot,
places the pivot element at its correct position in sorted array,
and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right of pivot'''
def partition(arr,low,high):
i = (low-1)
pivot = arr[high]
''''''
for j in... | true |
fe0846d78614934ff88ecbe3a04dc09e9b77e9b4 | johncmk/cloud9 | /Perm_Comb.py | 1,351 | 4.3125 | 4 | '''Factorial function means to multiply
a series of descending natural number 3! = 3 x 2 x 1
Note: it is generally agreed that 0! = 1.
It may seem funny that the multiplying no numbers
together gets us 1, but it helps simplify a lot
of equation.'''
'''non-tail recursion;
waste more memory when n is big integer
... | true |
97dc89fba3c044b3da16e5fcf6468ecd45d33efb | timvan/reddit-daily-programming-challenges | /multiplication_table.py | 569 | 4.21875 | 4 | # Multiplication Table
# Request two numbers and create the multiplication table of those numbers
def start():
print ("Welcome to multiplication table emulator!")
print ("Choose two numbers to create a multiplication table!")
while True:
N1 = raw_input("Number 1:")
try:
N1 += 1
except TypeError:
... | true |
59dd3f87c0c58dc421fcf023143edc716299389c | darloboyko/py_courses | /codewars/kata_7/NegativeConnotation_04.py | 1,214 | 4.46875 | 4 | #You will be given a string with sets of characters, (i.e. words), seperated by between one and
# three spaces (inclusive).
#Looking at the first letter of each word (case insensitive-"A" and "a" should be treated the same),
# you need to determine whether it falls into the positive/first half of the alphabet ("a"-"m... | true |
46b238bee670488bed3f121c59febe2abce590c3 | darloboyko/py_courses | /codewars/kata_8/task_01.py | 1,169 | 4.28125 | 4 | '''David wants to travel, but he doesn't like long routes. He wants to decide where he will go, can you tell him
the shortest routes to all the cities?
Clarifications:
David can go from a city to another crossing more cities
Cities will be represented with numbers
David's city is always the number 0
If there isn't any... | true |
609d502011f4d6dbb5bac47aaa2f8c93a7a7819f | darloboyko/py_courses | /codewars/kata_7/comfortableWords_04.py | 1,348 | 4.1875 | 4 | #A comfortable word is a word which you can type always alternating the hand you type with
#(assuming you type using a QWERTY keyboard and use fingers as shown in the image below).
#That being said, create a function which receives a word and returns true/True if it's a
# comfortable word and false/False otherwise.
#... | true |
213e764cb9f5daa61e1a52034de135ad1c131b99 | darloboyko/py_courses | /homeworks/home_work_4/PrintNumberInWord.py | 649 | 4.1875 | 4 | #Написать программу с названием “PrintNumberInWord”,
# которая напечатает “ONE”, “TWO”, …, “NINE”,
# “OTHER” если переменная “number” типа int будет 1, 2, 3, 4, … 9, или любой другой.
number = int(input("number: "))
if number == 1:
print("ONE")
elif number == 2:
print("TWO")
elif number == 3:
print("THREE")
eli... | false |
5e4348ef368e6c84323177ab213768049cb940fe | darloboyko/py_courses | /homeworks/home_work_6/SumOfTwoColumns.py | 663 | 4.1875 | 4 | #5. Написать программу, которая считает сумму двух колонок. Если одна из колонок имеет больший размер
# - вывести, какая колонка больше. Если колонки одинаковы, вывести результат так:
# | row_1 | row_2 | sum |
# | 2 | 5 | 7 |
row_1 = [1, 2, 5, 6, 54]
row_2 = [11, 5, 5, 7, 3]
if len(row_1) == len(row_2):
for i i... | false |
8733c8cf2c440511396a3f70075dbcbb9a2aab73 | darloboyko/py_courses | /homeworks/home_work_3/task_04.py | 567 | 4.125 | 4 | #Посчитать площадь треугольника по формуле Герман:
#S = sqrt(p * (p-a) * (p-b) * (p-c))
#Где p = (a + b+ c) / 2 - полупериметр треугольника
#Сделать 3 варианта возведения в степень
import math
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
p = (a + b + c) / 2
S = ((p * (... | false |
b8a5f2c3249336321cce13fc43cce156f4f37283 | darloboyko/py_courses | /homeworks/home_work_2/part_1/temperature.py | 765 | 4.34375 | 4 | # Написать программу, которая умеет переводить температуру из C в из Фаренгетов и Кельвинов Например:
# дана температура в Цельсиях 25 С
# Фаренгейт: 45.9F - считается по формуле (C + 32) * 5/9
# Кельвины: 298.16K - считается по формуле C + 273.16
print("Temperature converter")
temperature_сelsius = int(input("Enter ... | false |
f6ce75e92016710e60e625e80adfb0911d7b44ec | darloboyko/py_courses | /codewars/kata_7/niceArray_03.py | 575 | 4.21875 | 4 | #A Nice array is defined to be an array where for every value n in the array, there is also an
# element n-1 or n+1 in the array.
#example:
#[2,10,9,3] is Nice array because
#2=3-1
#10=9+1
#3=2+1
#9=10-1
#Write a function named isNice/IsNice that returns true if its array argument is a Nice array, else false.
# You s... | true |
771ca2a109d51e3aa667106e3b44c071a1cb86f3 | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_13.py | 2,667 | 4.90625 | 5 | """
Exercise 13: Parameters, Unpacking, Variables
In this exercise we will cover one more input method you can use to pass
variables to a script (script being another name for you .py files). You
know how you type python lesson_03.py to run the lesson_03.py file? Well
the lesson_13.py part of the comman... | true |
308bdfde1b97e5dc0f719c1c620d257479c55464 | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_18.py | 2,333 | 4.75 | 5 | """
Exercise 18: Name, Variables, Code, Functions
Functions do three things:
1. They name pieces of code the way variables name strings and
numbers.
2. They take arguments the way your scripts take argv.
3. Using 1 and 2 they let you make your own "mini-scripts" or
"tiny comm... | true |
14626d6e41bbc14f2569725273aa3aad5210d8cf | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_20.py | 1,703 | 4.46875 | 4 | """
Exercise 20: Functions and Files
"""
from sys import argv
# get the input file name from terminal
[script, input_file] = argv
def print_all(f):
# output a whole file
print f.read()
def rewind(f):
# jump to the beginning of a file
f.seek(0)
def print_a_line(line_count, f):
# output a line... | true |
46f2a1f6ce47d9f80f71ef4250d3b3389068f2ca | SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way | /lesson_23.py | 2,091 | 4.46875 | 4 | """
*****
Exercise 23: Read Some Code
You should have spent the last week getting your list of symbols straight
and locked in your mind. Now you get to apply this to another week of
reading code on the internet. This exercise will be daunting at first.
I'm going to throw you in the deep end for a few da... | true |
230bba3cff67045255bc24d2d6b6702a42d0fb75 | tmcook23/NICAR-2016 | /intro-to-python/part2/2_files.py | 739 | 4.15625 | 4 | # Import modules
import csv
# Write a function that accepts one file name as an argument.
# The function should print each row from a csv file as well as each row's length and its type.
def output_rows_from(file_name):
# Open the csv
csv_file = open(file_name, 'rb')
# Create the object that represents the data i... | true |
59665fb98044dc3610126dd3b08b1cc43ce0b8d7 | tmcook23/NICAR-2016 | /intro-to-python/part1/1_workingwintegers.py | 1,402 | 4.375 | 4 |
#INTEGERS
#In programming, an integer is a whole number. You can do all sorts of math on integers,
#just like you'd do with a calculator or in Excel or a database manager.
2+2
5*5
# In the command line Python interpreter, these results will always show up.
# But if you run an entire Python (.py) program, however ... | true |
51a776bb343bb4b917107e5f6009760141ed134b | akjha013/Python-Rep | /test7.py | 791 | 4.21875 | 4 | #LOOP PRACTICE EXAMPLE PYTHON
command = ""
hasStarted = False
hasStopped = True
while True:
command = input('>').lower()
if command == 'start' and hasStarted is False:
print('Car has started')
hasStopped = False
hasStarted = True
elif command == 'start' and hasStarted is True:
... | true |
3aa6555c1783ec5428bed334fdb94f429bc0b087 | Girum-Haile/PythonStudy | /DecisionMaking.py | 806 | 4.125 | 4 | # if statement -It is used to decide whether a certain statement or block of statements will be executed or not.
# simple if statement
age = int(input("Enter your age: ")) # we use input() to get input from a user
if age <= 30:
print("accepted")
# nested if statement
name = input("enter name")
sex = input("enter... | true |
a7d1334d4cdcb8b8273111a495eb2d3bf0badc9d | Girum-Haile/PythonStudy | /OOP-Class.py | 1,290 | 4.28125 | 4 | # class - creates user defined data structure.
# class is like a blue print of an object
# class creation
class New:
pass
class Dogs:
type = "Doberman" # class attributes
atr = "mamal"
def method(self):
print("Dog breed:", self.type)
print("Dog atr:", self.atr)
Dog1 = Dogs() # o... | true |
d8a274f82384cce62ec81666552b1c45484cf035 | aduanfei123456/algorithm | /back_track/array_sum_combinations.py | 827 | 4.25 | 4 | """
WAP to take one element from each of the array add it to the target sum. Print all those three-element combinations.
/*
A = [1, 2, 3, 3]
B = [2, 3, 3, 4]
C = [1, 2, 2, 2]
target = 7
*/
Result:
[[1, 2, 4], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 3, 3], [1, 4, 2], [2, 2, 3], [2, 2, 3], [2, 3, 2], [2, 3, 2], [3, 2, 2], [... | true |
8cab6c1c7f300b82ba739fc47993357228e2601b | yiyinghsieh/python-algorithms-data-structures | /cw_odd_or_even.py | 1,081 | 4.46875 | 4 | """Codewars: Odd or Even?
7 kyu
URL: https://www.codewars.com/kata/5949481f86420f59480000e7/train/python
Task:
Given a list of numbers, determine whether the sum of its elements is odd
or even.
Give your answer as a string matching "odd" or "even".
If the input array is empty consider it as: [0] (array with a zero).... | true |
fdeebbb4cdf146cb9f1456617c4ab9e0b240917d | raviss091/assignment | /CS102 Assignment Q-03.py | 1,251 | 4.25 | 4 | # CS102 Assignment-03, Python Program for Post order and Depth first level search.
# 19BCS091, RAVI SHANKAR SHARMA
class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left) ... | true |
ed8f1be00e133ac5283ff5c2db68d744937a5886 | JHolderguru/OPP | /dog_class.py | 2,203 | 4.40625 | 4 | # Abstract and create the class dog
#
from animal import *
# from cat_class import *
class Dog(Animal):
# this is a special method
# it comes defined either was but we can re-write it
# this methods stands for initialize class object AKA the constructor
# in other languages
# Allows us to set... | true |
c0d965379441722987627ba1e8eb0aa5930fd5e6 | nvovk/python | /Recursion/D - Точная степень двойки/index.py | 461 | 4.125 | 4 | """
Дано натуральное число N. Выведите слово YES, если число N является точной степенью двойки,
или слово NO в противном случае. Операцией возведения в степень пользоваться нельзя!
"""
def test(n):
if n == 2:
return 'Yes'
elif n % 2 == 1:
return 'No'
else:
test(n // 2)
print(test(2... | false |
6d97c798e03fddff1356794f5297341525c6bd3a | jtplace1/School_Projects | /Python/Mile-2-km/Mile-2-Km.py | 1,248 | 4.3125 | 4 | # Program Name: Test 2 p2.py
# Course: IT1113/Section w01
# Student Name: Jabari Smith
# Assignment Number: Test 2 Due Date: 10/25/20
def main():
#enter the choice
for x in range(0,15):
choice = int(input("1. Miles to Kilometers \n2. Kilometers to Miles \nEnter 1 or 2: "))
if ch... | false |
eda80049c2742dd09afdfc8c103418a3ce33f200 | Chruffman/Personal-Projects | /binary_search.py | 1,398 | 4.28125 | 4 |
# Recursive function that uses the binary search algorithm to find a given value in a list in O(logn) time
# Does not require a sorted list, sorting is performed within
def binary_search(arr, val):
# if the list is empty or there is only one element and it is not the value we are looking for
if len(arr) == ... | true |
e4ced192f6fab6fddf6101649759fee018ae522a | saadmgit/python-practice-tasks | /task8.py | 958 | 4.4375 | 4 |
# TASK 8: Take integers input from user as a comma separated
make_list = []
odd_list = []
input_nums = str(input("Enter numbers in comma ',' separated : ")) # Taking input as a comma separated
input_list = input_nums.split(",") # Making string a list
for i in input_list: ... | true |
5b3821a5bd436027a0672d2755fdcffdbd8257d7 | AthulKrishna14310/Learn_Python | /dictionary.py | 1,049 | 4.3125 | 4 | #Initialise
_dictionary={
"Name":"Game of Thrones",
"Actor":"Peter Dinglage",
"Actress":"Emilia Clarke",
"Director":"George Lucas",
"Year":2011,
"Episodes":73,
"Season":8,
}
#Print Element
print(_dictionary["Season"])
_year=_dictionary["Year"]
print(_year)
#Changing value
_dictionary["Year... | true |
012d5ac14fd9bf17f1c7ef924a24a4d83cf6e278 | jaimecabrera911/PythonBasico | /02 Operadores y expresiones/Ejercicio1.py | 558 | 4.15625 | 4 | # Ejercicio 1
# # Realiza un programa que lea 2 números por teclado y determine los siguientes aspectos (es suficiene con mostrar True o False):
# #
# # Si los dos números son iguales
# # Si los dos números son diferentes
# # Si el primero es mayor que el segundo
# # Si el segundo es mayor o igual que el primero
a = i... | false |
c5b812e1751f4dfdc560e58bfb4aa24a73bb92e3 | prasen7/python-examples | /time_sleep.py | 393 | 4.1875 | 4 | import time
# Write a for loop that counts to five.
for i in range(1,6):
print(i,"Mississippi")
# Body of the loop - print the loop iteration number and the word "Mississippi".
time.sleep(1)
# suspend the execution of each next print() function inside the for loop for 1 second
# Write a prin... | true |
3344d7f063149be56690a4065d2f5e69b2d4b379 | prasen7/python-examples | /pyhton_read.py | 1,840 | 4.3125 | 4 | # python reading materials
#1. decorator:
# a decorator is a design pattern in python that allows a user to add new
# functionality to an existing object without modifying its structure.
from time import time
def timer(func):
def f(*args, **kwargs):
before=time()
rv=func(*args, **kwargs)
... | true |
c809a4e3c916ac15635078c03d4cd71f13e0e7ea | prasen7/python-examples | /listslice.py | 1,007 | 4.375 | 4 | # Lists (and many other complex Python entities) are stored in different ways than ordinary (scalar) variables.
# 1. the name of an ordinary variable is the name of its content.
# 2. the name of a list is the name of a memory location where the list is stored.
# The assignment: list2 = list1 copies the name of t... | true |
99c8dff869acb2bf89280f747bb371a3d5824e81 | Johanna-Mehlape/TDD-Factorial | /TDD Factorial/factorial.py | 705 | 4.375 | 4 | #factorial.py
"""python code to find a Factorial of a number"""
def factorial(n):
"""factorial function"""
try: #to try the input and see if it is an integer
n = int(n) #if it is an integer, it will print out its factorial
except:#if it is not an integer, except will return an message
p... | true |
c0bb38dc8e38eac9c7f1d1bad6a3ba60f217fbbd | steve1998/scripts | /palindromechecker.py | 1,010 | 4.1875 | 4 | # checks if a word is a palindrome
# palindrome function
def palindrome(str):
reversedWord = str[::-1]
# comparison of each word
if str.lower() != reversedWord.lower():
return False
return True
def main():
filename = input("Enter list of words to check for palindrome: ")
counter ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.