blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3c47d535501c877aae1e7c115534d309f9cfac32 | indexcardpills/python-labs | /15_generators/15_01_generators.py | 237 | 4.3125 | 4 | '''
Demonstrate how to create a generator object. Print the object to the console to see what you get.
Then iterate over the generator object and print out each item.
'''
daniel = (x+'f' for x in "hello")
for x in daniel:
print(x)
| true |
eb2128c3f33e18a27de998a58e00a0c1056d28d3 | indexcardpills/python-labs | /04_conditionals_loops/04_07_search.py | 575 | 4.15625 | 4 | '''
Receive a number between 0 and 1,000,000,000 from the user.
Use while loop to find the number - when the number is found exit the loop and print the number to the console.
'''
while True:
number = int(input("Enter a number between 0 and 1,000,000,000: "))
x = 7
if number < x:
print("no, higher... | true |
a4508650196850cea3aecd960dd0e9a06c98cbe3 | indexcardpills/python-labs | /10_testing/10_01_unittest.py | 690 | 4.34375 | 4 | '''
Demonstrate your knowledge of unittest by first creating a function with input parameters and a return value.
Once you have a function, write at least two tests for the function that use various assertions. The
test should pass.
Also include a test that does not pass.
'''
import unittest
def multiply(x, y):
... | true |
2ca18b8597a9d80d73fd7d1da52f7691664b5bf4 | indexcardpills/python-labs | /04_conditionals_loops/04_05_sum.py | 791 | 4.3125 | 4 | '''
Take two numbers from the user, one representing the start and one the end of a sequence.
Using a loop, sum all numbers from the first number through to the second number.
For example, if a user enters 1 and 100, the sequence would be all integer numbers from 1 to 100.
The output of your calculation should therefo... | true |
0ef559fbb64de7780dda09df151d2e4482bc1410 | tonynguyen99/python-stuff | /guess number game/main.py | 945 | 4.25 | 4 | import random
def guess(n):
random_number = random.randint(1, n)
guess = 0
while guess != random_number:
guess = int(input(f'Guess a number between 1 and {n}: '))
if guess > random_number:
print('Too high!')
elif guess < random_number:
print('Too low!')
... | true |
b51af61c9960b18b8829708f6a0d3a8f18a5fd2f | sathvikg/if-else-statement-game | /GameWithBasics.py | 1,463 | 4.1875 | 4 | print("Welcome to your Game")
name = input("What is your name? ")
print("hi ",name)
age = int(input("What is your age? "))
#print(age)
#print(name,"you are good to go. As you are",age,"years old")
health = 10
print("you are starting with ",health,"health")
if age > 18:
print("you can continue the game.")
... | true |
f642a041bcda31d628b16181016fae4cbb9c128d | nikonoff16/Simple_Number | /simple.py | 1,576 | 4.15625 | 4 | #Создаем переменную
quest_number = int(input("Введите число "))
# концепция проекта такая: если число простое, то при делению по модулю всегда будет остаток. Если посчитать эти остатки
# и сравнить их с самим числом за вычетом двух из него, то можно понять, простое оно или нет.
cycle_th = quest_number - 1
counter... | false |
d3246fddc314795c42ec10a19be60f2c0e026675 | GaborVarga/Exercises_in_Python | /46_exercises/8.py | 1,124 | 4.34375 | 4 | #!/usr/bin/env python
#######################
# Author: Gabor Varga #
#######################
# Exercise description :
# Define a function is_palindrome() that recognizes palindromes
# (i.e. words that look the same written backwards).
# For example, is_palindrome("radar") should return True.
#
# http://www.ling.gu... | true |
e7e4117d2f583ceedce8c4cdba546523d9532ac8 | UCdrdlee/ScientificComputing_HW0 | /fibonacci.py | 2,824 | 4.5 | 4 | """
fibonacci
functions to compute fibonacci numbers
Complete problems 2 and 3 in this file.
"""
import time # to compute runtimes
from tqdm import tqdm # progress bar
# Question 2
def fibonacci_recursive(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return fibonacci_recursiv... | true |
837b4fe80020202ed9b37e0ac5dc0f868ec0aa8f | Yagomfh/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 713 | 4.34375 | 4 | #!/usr/bin/python3
"""Module that that adds 2 integers.
Raises:
TypeError: if a or b are not int or floats
"""
def add_integer(a, b=98):
"""Function that adds 2 integers
Args:
a (int/float): first digit
b (int/float): second digit
Returns:
Int sum of both digits
"""
... | true |
c0a7efc9d8720a168c1677b413d2a86f8a494fe6 | kadahlin/GraphAlgorithms | /disjoint_set.py | 1,877 | 4.15625 | 4 | #Kyle Dahlin
#A disjoint set data structure. Support finding the set of a value, testing if
#values are of hte same set, merging sets, and how may sets are in the entire
#structure.
class Disjoint:
def __init__(self, value):
self.sets = []
self.create_set(value)
def create_set(self, value):... | true |
fb8318baba89169105e27fdc76b00e80888fb222 | Mone12/tictactoe-python | /.vscode/tictactoe.py | 1,176 | 4.1875 | 4 | import random
## Need to establish which player goes first through randomization
player = input("Please enter your name:")
cpu = "CPU"
p_order = [player,cpu]
if player:
random.shuffle(p_order)
if p_order[0] == player:
print(f"{player} you are Player 1. You go first!")
print(f"{cpu} is Playe... | true |
7182d6fa3958283a46dfdb5b9f4b6c5eea17055d | kontai/python | /面向對象/運算符重載/classMethod.py | 970 | 4.25 | 4 | # Copyright (c) 2019.
# classMethod.py
#
class FirstClass:
def setdata(self, value):
self.data = value
def display(self):
print(self.data)
class SecondClass(FirstClass):
def display(self):
print("Current data is %s" % self.data)
class ThirdClass(SecondClass):
def __init__... | false |
d867547f67b3c2697fffaabdccd39b4571ee473c | smukh93/Python_MITx | /iter_pow.py | 606 | 4.125 | 4 | def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
prod = 1
if exp == 0:
return 1
else:
for x in range(exp):
prod *=base
return prod
def recurPower(base, exp):
'''
base: ... | true |
a3a152ffc0a8fb2fe28def7b018ef54f4a65506d | gourav287/Codes | /Codechef-and-Hackerrank/NoOfStepsToReachAGivenNumber.py | 1,304 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Question Link:
https://practice.geeksforgeeks.org/problems/minimum-number-of-steps-to-reach-a-given-number5234/1
Given an infinite number line. You start at 0 and can go either to the left or to the right.
The condition is that in the ith move, youmust take i steps.
Given a destinati... | true |
089e2881ecc68c06e9fd9fe958d4ccd1414d55d0 | gourav287/Codes | /BinaryTree/TreeCreation/CreateTreeByInorderAndPreorder.py | 2,259 | 4.28125 | 4 | """
Implementation of a python program to create a binary tree
when the inOrder and PreOrder traversals of the tree are given.
"""
# Class to create a tree node
class Node:
def __init__(self, data):
# Contains data and link for both child nodes
self.data = data
self.left = None
... | true |
263b8fdfdc3989979ec92e72110fd79be8ead6fd | gourav287/Codes | /Codechef-and-Hackerrank/Binary_to_decimal_recursive.py | 740 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
Write a recursive code to convert binary string into decimal number
"""
# The working function
def bin2deci(binary, i = 0):
# Calculate length of the string
n = len(binary)
# If string has been traversed entirely, just return
if i == n - 1:
return ... | true |
ed43aa7eacb8f54d80102e3b05a2147451b636a8 | januarytw/Python_auto | /class_0605/0605作业.py | 1,702 | 4.15625 | 4 | # 1:创建一个名为 Restaurant 的类,其方法 init ()设置两个属性: restaurant_name 和 cooking_type。
# 创建一个名为 describe_restaurant()的方法和一个名为 open_restaurant()的方法,其中前者打印前述两项信息,
# 而后者打印一条消息, 指出餐馆正在营业。 根据这个类创建一个名为 restaurant 的实例,分别打印其两个属性,再调用前述两个方法。
class Restaurant():
def __init__(self,restaurant_name,cooking_type):
self.restaurant_n... | false |
a056d2b012f5d2d3c8b0cb46cd26e5a960550970 | HANZ64/Codewars | /Python/8-kyu/07. Return Negative/index.py | 1,405 | 4.15625 | 4 | '''
Title:
Return Negative
Kata Link:
https://www.codewars.com/kata/return-negative
Instructions:
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Example:
make_negative(1); # return -1
make_negative(-5); # return... | true |
a93e2fab8fe0972396945484bf75634184a2bf70 | albihasani94/PH526x | /week3/word_stats.py | 645 | 4.1875 | 4 | from week3.counting_words import count_words
from week3.read_book import read_book
def word_stats(word_counts):
"""Return number of unique words and their frequencies"""
num_unique = len(word_counts)
counts = word_counts.values()
return (num_unique, counts)
text = read_book("./resources/English/shak... | true |
be8849979ce06c3cfa24cae9fb933e6673de5a3d | af94080/dailybyte | /next_greater.py | 1,066 | 4.21875 | 4 | """
This question is asked by Amazon. Given two arrays of numbers, where the first array is a subset of the second array, return an array containing all the next greater elements for each element in the first array, in the second array. If there is no greater element for any element, output -1 for that number.
Ex: Giv... | true |
3941ff68870c3b573885de1fb512c97953d29dcf | pjm8707/Python_Beginning | /py_basic_datatypes.py | 2,077 | 4.28125 | 4 | import sys
print("\npython data types -Numeric")
#create a variable with integer value
a=100
print("The type of variable having value", a, "is", type(a))
print("The maximum interger value", sys.maxsize)
print("The minimum interger value", -sys.maxsize-1)
#create a variable with float value
b=10.2345
prin... | true |
1f9bd3a166434e6f800e9f01938fd3bf615c5ec9 | inesjoly/toucan-data-sdk | /toucan_data_sdk/utils/postprocess/rename.py | 976 | 4.25 | 4 | def rename(df, values=None, columns=None, locale=None):
"""
Replaces data values and column names according to locale
Args:
df (pd.DataFrame): DataFrame to transform
values (dict):
- key (str): term to be replaced
- value (dict):
- key: locale
... | true |
6bee3da547307daf0e4245423a159b4196dcd025 | Vishal0442/Python-Excercises | /Guess_the_number.py | 480 | 4.21875 | 4 | #User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct,
#on successful guess, user will get a "Well guessed!" message, and the program will exit
import random
while True:
a = random.randint(1,9)
b = int(input("Guess a number : "))
i... | true |
3ecfd62848650e4bfe40cb5907d31eb9398e18c5 | nikhil-jayswal/6.001 | /psets/ps1b.py | 1,002 | 4.21875 | 4 | # Problem Set 1b
# Nikhil Jayswal
#
# Computing sum of logarithms of all primes from 2 to n
#
from math import * #import math to compute logarithms
n = int(raw_input('Enter a number (greater than 2): '))
start = 3 #the second prime; don't need this can do candidate = 3
log_sum = log(2) #sum of logarithms of primes, fi... | true |
b6ccbbb9ab29a1cbe46ef64731dad597b94c337b | GaneshGoel/Basic-Python-programs | /Grades.py | 555 | 4.125 | 4 | #To print grades
x=int(input("Enter the marks of the student:"))
if(x<=100 or x>=0):
if(x>90 and x<=100):
print("O")
elif(x>80 and x<=90):
print("A+")
elif(x>70 and x<=80):
print("A")
elif(x>60 and x<=70):
print("B+")
e... | true |
ee5f0793f86f7396d38234c1ac621a387fa768f2 | kt00781/Grammarcite | /AddingWords.py | 826 | 4.1875 | 4 | from spellchecker import SpellChecker
spell = SpellChecker()
print("To exit, hit return without input!")
while True:
word = input("Input the word that you would like to add to the system: ")
if word == '':
break
word = word.lower()
if word in spell:
print ("Word ({}) already in Dictionar... | true |
d03bc8035c16bdef2486f27e59d3e430b178790c | Leofariasrj25/simple-programming-problems | /elementary/python/sum_multiples(ex5).py | 258 | 4.34375 | 4 | print("We're going to print the sum of multiples of 3 and 5 for a provided n")
n = int(input("Inform n: "))
sum = 0
# range is 0 based so we add 1 to include n
for i in range(3, n + 1):
if i % 3 == 0 or i % 5 == 0:
sum += i
print(sum)
| true |
3042b228dba1572138e2216bcef1f3dac8f0368b | CTTruong/9-19Assignments | /Palindrome.py | 455 | 4.1875 | 4 | def process_text(text):
text = text.lower()
forbidden = ("!", "@", "#")
for i in forbidden:
text = text.replace(i, "")
return text
def reverse(text):
return text[::-1]
def is_palindrome(text):
new = process_text(text)
return process_text(text) == reverse(process_text(text))
someth... | true |
d0c094920da68f24db3d489cab6c1f2e37a17787 | yeshwanthmoota/Python_Basics | /lambda_and_map_filter/map_filter.py | 1,148 | 4.3125 | 4 | nums=[1,2,3,4,5,6,7,8,9]
def double(n):
return n*2
my_list=map(double,nums)
print(my_list)
def even1(n):
return n%2==0
def even2(n):
if(n%2==0):
return n
my_list=map(even2,nums) #This doesn't return a list it returns-
#-address of the genrators of the operation performed.
print(my_list)
my_list=... | true |
4abe4684d196821bdc39592e31e3b94d21f8e22b | yeshwanthmoota/Python_Basics | /comprehensions/zip_function.py | 433 | 4.125 | 4 | names=["Bruce","Clark","Peter","Logan","Wade"]
heroes=["Batman","Superman","Spiderman","Wolverine","Deadpool"]
# Now to use the zip function
Identity_list=list(zip(names,heroes))
print(Identity_list)
Identity_tuple=tuple(zip(names,heroes))
print(Identity_tuple)
Identity_dict=dict(zip(names,heroes)) # This is importan... | true |
866832f1f7e1429b4462491be12a4891f10934f7 | rivergillis/mit-6.00.1x | /midterm/flatten.py | 614 | 4.34375 | 4 | def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
[[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5]
'''
if aList == []:
return []
print(aList)
for index,elem in enumerate(aList):
prin... | true |
d5dae53d28dc9f6964c7adf0f83a5a5359309792 | Gaurav-dawadi/Python-Assignment | /Function/question19.py | 226 | 4.25 | 4 | """Write a Python program to create Fibonacci series upto n using Lambda."""
fib = lambda n: n if n<=1 else fib(n-1)+fib(n-2)
# print(fib(10))
print("The Fibonacci Series is :")
for i in range(10):
print(fib(i))
| false |
6406ba8d6fa1df233b6bd4ed010c5061bab39066 | Gaurav-dawadi/Python-Assignment | /Data Types/question21.py | 909 | 4.28125 | 4 | """Write a Python program to get a list, sorted in increasing order by the last
element in each tuple from a given list of non-empty tuples."""
def getListOfTuples():
takeList = []
num = int(input("Enter number of tuples you want in list: "))
for i in range(num):
takeTuples = ()
for j ... | true |
79a49b8caf4291c0c762e81a851212cc509e6c6a | Joyce-O/Register | /treehouse_python_basics.py/masterticket.py | 1,514 | 4.125 | 4 | TICKET_PRICE = 10
tickets_remaining = 100
#Run tickets untill its sold out
while tickets_remaining >= 1:
# Output how many tickets are remaining using the tickets remaining variable
print("There are {} tickets remaining.".format(tickets_remaining))
# Gather the user's name and assign it to a new variable
... | true |
d5498151efd9677fe5247d12c6b4956822937f60 | erin-weeks/hello_world | /8_person.py | 777 | 4.46875 | 4 | #Building more complicated data structures
'''This exercise takes various parts of a name and then returns a dicionary.'''
def build_person(first_name, last_name, age = ''):
'''Return a dictionary of information about a person'''
person = {'first': first_name, 'last': last_name}
'''Because age is optiona... | true |
a2c94ca0ccf5569edfd3637bfeabc22c4ca84940 | Nelapati01/321810305034-list | /l1.py | 231 | 4.28125 | 4 | st=[]
num=int(input("how many numbers:"))
for n in range (num):
numbers=int(input("Enter the Number:"))
st.append(numbers)
print("Maximum elements in the list:",max(st),"\nMinimum element in the list is :",min(st))
| true |
adfaf200179e8e696cc6f1d74ae475a0beab43c5 | slovoshop/LightIT_test_task | /convert_roman_to_arabic.py | 1,303 | 4.34375 | 4 | # -*- coding: utf-8 -*-
""" Program in Python 3.6.4
Calculating the numeric value of a Roman numeral.
Here is an example of calculating:
roman CXLIV
values [100, 10, 50, 1, 5]
values[:-1] [100, 10, 50, 1]
values[1:] [10, 50, 1, 5]
zip ... | false |
e049d49db2e69afaa2795331bdd9500cb0ebc2de | MilesBell/PythonI | /practicep1.py | 1,916 | 4.15625 | 4 | chapter="Introduction to PythonII"
print("original chapter name:")
print(chapter)
print("\nIn uppercase:")
print(chapter.upper())
print("\nIn 'swapcase':")
print(chapter.swapcase())
print("\nIn title format:")
print(chapter.title())
print("\nIn 'strip' format:")
print(chapter.strip())
print("\n\nPress the enter key to ... | true |
2f32e330a2d5ce49f9687db2f826f1baeaef1089 | wkdghdwns199/Python_basic_and_study | /chap_4/22_dic_tion_ary.py | 352 | 4.15625 | 4 | dictionary={
"key1":"ant",
"key2":"bee",
"key3":"cake"
}
print("#딕셔너리의 items() 함수")
print("items():",dictionary.items())
print()
for key,element in dictionary.items():
print("dictionary[{}]= {}".format(key,element))
a_list=["1","2","3"]
b_list=["a","b","c"]
for i in range(len(a_list)):
print(a_... | false |
3410fdab20dd9e10e148c29a69b40ef8e10bc160 | HaythemBH2003/Object-Oriented-Programming | /OOP tut/Chapter4.py | 1,478 | 4.125 | 4 | ######## INTERACTION BETWEEN CLASSES ########
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def get_grade(self):
return self.grade
def get_name(self):
return self.name
class Course:
d... | true |
9d9e6c968ceabf5bceaeeeb848face6ddf0b24f1 | emberenot/pythoncourse | /lab1(py)/lab1_10.py | 526 | 4.28125 | 4 | #Напишите скрипт, позволяющий определить надежность вводимого пользователем пароля. Это задание является творческим: алгоритм
#определения надежности разработайте самостоятельно.
password = input("Введите пароль: ")
if len(password)>8 and not password.isdigit():
print("Пароль надёжный")
else:
print("Плохой ... | false |
59e52bd9931ca75082f8d2504722e8b2bc2c976a | alitsiya/InterviewPrepPreWork | /strings_arrays/maxSubArray.py | 670 | 4.21875 | 4 | # Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
# For example:
# Given the array [-2,1,-3,4,-1,2,1,-5,4],
# the contiguous subarray [4,-1,2,1] has the largest sum = 6.
# For this problem, return the maximum sum.
def maxSubArray(A):
if len(A) == 0:
retur... | true |
dea9250a810a2f87be8ee0f6bbf720dfa963d144 | nmoore32/coursera-fundamentals-of-computing-work | /2 Principles of Computing/Week 4/dice_analysis.py | 1,893 | 4.21875 | 4 | """
Program to analyze expected value of simple dice game.
You pay $10 to play.
Roll three dice.
You win $200 if you roll triples, get your $10 back if doubles, and lose the $10 otherwise
"""
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcom... | true |
bff961baa068c0a52ce669edd31222aa2b45e928 | xxw1122/Leetcode-python-xxw | /283 Move Zeroes.py | 835 | 4.15625 | 4 | """
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimi... | true |
c0a4b16a1d9a2d072892909a4a50def04dc9cb68 | masterzht/note | /other/python/code/2_list.py | 709 | 4.3125 | 4 | # this is the code of list
word=['a','b','c','d','e','f','g']
a=word[2]
print " a is : " +a
b=word[1:3]
print b # index 1 and 2 elements of word.
c=word[:2]
print c # index 0 and 1 elements of word.
d=word[0:]
print "d is "
print d # All elements of word.
e=word[:2]+word[2:]
print "e is :"
print e # All elements of w... | false |
72c69bbe24970624694106bf99d404fc77b21743 | SerioSticks/AprendiendoPython | /Aleatorio.py | 1,101 | 4.1875 | 4 | #Creador Jorge Alberto Flores Sánchez
#Matricula: 1622167 Grupo: 22
#Fecha de Creación : 18/09/2019
#En python existen muchas librerias para facilitar la programación,
#a estas se les denomina modulos (module).
#Para usar un modulo debe importarse y para esto se utiliza la,
#instrucción import
import random
... | false |
7fb3ca8717ca50c532ef518d2569aa39c43afef8 | gitjit/ehack | /py/emp.py | 993 | 4.25 | 4 | # This is a sample to demonstrate Python OOP features
class Employee(object):
raise_amount = 1.04 # class variable
num_emps = 0
def __init__(self, first, last, pay):
self._first = first
self._last = last
self._pay = pay
self._email = first + '.' + last + '@company.com'
... | false |
602a2952d43b2c43eab807be4a629af2a6fc4849 | feladie/info-206 | /hw3/BST.py | 2,481 | 4.46875 | 4 | #---------------------------------------------------------
# Anna Cho
# anna.cho@ischool.berkeley.edu
# Homework #3
# September 20, 2016
# BST.py
# BST
# ---------------------------------------------------------
class Node:
#Constructor Node() creates node
def __init__(self,word):
self.word = word
... | true |
9ce73959107cd05593c971af07ac82530e9b6a35 | chilango-o/python_learning | /seconds_calculator.py | 739 | 4.34375 | 4 | def calcSec():
""" A function that calculates a given number of seconds (user_seconds)
and outputs that value in Hour-minute-second format
"""
user_seconds = int(input('cuantos segundos? '))
hours = user_seconds // 3600 #integer division between the given seconds and the number of seconds in 1 hour ... | true |
21026c68e2fb2a211d72eaf48ab67edc023ffe32 | MulengaKangwa/PythonCoreAdvanced_CS-ControlStatements | /53GradingApplication.py | 790 | 4.15625 | 4 |
m=int(input("Enter your maths score (as an integer):"))
if m >=59:
p = int(input("Enter your physics score(as an integer):"))
if p >= 59:
c = int(input("Enter your chemistry score(as an integer):"))
if c >= 59:
if (p + m + c) / 3 <= 59:
print("You secured a C grade"... | true |
3b0e84aa74c12e1a1771755e73d37993d27e1ba6 | push-95/Project-Euler | /p001.py | 279 | 4.375 | 4 | # Problem 1 - Multiples of 3 and 5
# Pushyami Shandilya
# http://github.com/push-95
def calc_sum(N):
'''
Function to find the sum of all the multiples of 3 or 5 below a number N.
'''
return sum(i for i in range(N) if (i%3==0 or i%5==0))
if __name__ == '__main__':
print calc_sum(1000) | false |
8d8e09d5241dcf6a3055e72355029a84967aa0af | ellisgeek/linux1 | /chapter7/scripts/month.py | 332 | 4.34375 | 4 | #!/usr/bin/env python
#define the months of the year
months = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
print "Traditional order:"
for month in months:
print month
print "\n\nAlphabetical order:"
for month in sorted(months):
... | true |
eec1de729ffc2a62859746605198505a3f8a994a | tamjidimtiaz/CodeWars | /<8 Kyu> Logical calculator.py | 1,216 | 4.34375 | 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 sequen... | true |
80ce0b6a98ffad061eeb45a97c81851afe42a216 | Venkatesh123-dev/100-Days-of-code | /Day_06_2.py | 1,860 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 13 19:28:24 2020
@author: venky
There are two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location and moves at a rate of meters per jump. The second kangaroo st... | true |
2fc9577d7073827d48449eb4c3988998e55da166 | DizzyMelo/python-tutorial | /numbers.py | 288 | 4.25 | 4 | # There are three numeric types in python
# int, float and complex
import random
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(complex(x))
print(int(y))
print(type(z))
# the last number is not included, then, numbers from 1 to 9 will show up
print(random.randrange(1, 10))
| true |
115e1cc9db1fc292b214b1f31ff5b23b62dbd684 | DizzyMelo/python-tutorial | /ifelse.py | 1,263 | 4.375 | 4 | # Python Conditions and If statements
# Python supports the usual logical conditions from mathematics:
# Equals: a == b
# Not Equals: a != b
# Less than: a < b
# Less than or equal to: a <= b
# Greater than: a > b
# Greater than or equal to: a >= b
# These conditions can be used in several ways, most commonly in "if s... | true |
6869f7ccbbe5124779270653201b7bfeb5b12ba5 | DizzyMelo/python-tutorial | /trycatch.py | 1,830 | 4.375 | 4 | # The try block lets you test a block of code for errors.
# The except block lets you handle the error.
# The finally block lets you execute code, regardless of the result of the try- and except blocks.
# Exception Handling
# When an error occurs, or exception as we call it, Python will normally stop and generate an... | true |
abbeac5ff24ee0715d8f0e788244239d4740de5a | danieldiniz1/blue | /aula 15 21.05/exercicio 1.py | 323 | 4.15625 | 4 | numeros = []
for nm in range(5):
numero = int(input(f"Digite o {nm+1}º número: "))
for chave, valor in enumerate(numeros):
if numero < valor:
numeros.insert(chave, numero)
break
else:
numeros.append(numero)
print("Lista: ", numeros)
for nmrs in numeros:
print(nmrs... | false |
79dd6ddfe911e50f068d60014f5713afd3572345 | danieldiniz1/blue | /aula 14.05/aula 14.05.py | 515 | 4.125 | 4 | # exercício de while
opc = 1
while opc == 1:
numero = float(input("digite um numero: "))
print()
if (numero == 0):
print(f'o numero digitado é: {numero}')
print()
elif (numero > 0):
print(f'o numero {numero:.2f} é positivo')
print()
else:
print(f'o numero {... | false |
0798b0374d82ddc94292b856402b782474d8c891 | chaithanyasubramanyam/pythonfiles | /linkedlist.py | 992 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insert(self,previous_node... | false |
16ad2f811290b82e99ad541713ca0b48adc99f87 | gauravlahoti80/Project-97-Number-Guessing-Game | /guessing Game/main.py | 1,899 | 4.21875 | 4 | #importing modules
import random
import pyttsx3
#welcome screen
input_speak = pyttsx3.init()
input_speak.say("Enter your name: ")
input_speak.runAndWait()
#taking name input from the user
user_name = input("Enter your name: ")
#showing hello to the user
input_speak.say(f"Hello,{user_name}")
input_speak... | true |
bf5e398738221308a2c5fa8462c32ff1d8de1cbb | emmanuelaboah/Data-Structures-and-Algorithms | /Solved Problems/Data structures/Recursion/String-Permutations.py | 1,790 | 4.125 | 4 | # Problem Statement
# Given an input string, return all permutations of the string in an array.
# Example 1:
# string = 'ab'
# output = ['ab', 'ba']
# Example 2:
# string = 'abc'
# output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']
# Note - Strings are Immutable
# Recursive Solution
"""
Param - input string
Return... | true |
2eff58b50c69128a2999948651acc3cb11701e98 | emmanuelaboah/Data-Structures-and-Algorithms | /Solved Problems/Data structures/Recursion/Reverse _string_input.py | 1,389 | 4.53125 | 5 |
def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
# (Recursion) Termination condition / Base condition
if ... | true |
f10c03cbd6d9a175258290a51135d1ab0609281b | ParthRoot/Basic-Python-Programms | /list Python program to print even numbers in a list.py | 444 | 4.15625 | 4 | # Programme by parth.py
# Python program to print even numbers in a list
def even(lst):
for i in lst:
if i % 2 == 0:
print(i, end=" ")
def odd(lst):
for i in lst:
if i % 2 != 0:
print(i, end=" ")
print("Even Number is-:")
even([1,2,3,4,5,6,7,8,9])
print("\no... | false |
0424290f9aa1009976c74c19bfc41f65da59146e | ParthRoot/Basic-Python-Programms | /Fectorial.py | 285 | 4.1875 | 4 | num=int(input("enter the num"))
factorial=1
if num < 0:
print("sorry factorial doesnot exit negative num")
elif num == 0:
print("factorial always start 1")
else:
for i in range(1,num+1):
factorial = factorial * i
print("the factorial of",num,factorial) | true |
bb328aa070b6889b12d9dac1b3508801da268fd6 | daniel-laurival-comp19/slider-game-1o-bimestre | /getStartingBoard.py | 574 | 4.25 | 4 | def getStartingBoard():
''' Return a board data structure with tiles in the solved state. For example, if BOARDWIDTH and BOARDHEIGHT are both 3, this function returns [[1, 4, 7], [2, 5, 8], [3, 6, BLANK]]''' counter = 1 board = []
for x in range(BOARDWIDTH):
column = []
for y in ... | true |
d3911c904e2e9cae6da70563f707270a07aae8f6 | jnegro/knockout | /knockout_steps/knockout_step3.py | 2,339 | 4.46875 | 4 | #!/usr/bin/python
# STEP 3 - Code the 'main' function to play the game
# In this step we replace the 'main' function with code that runs the game
from __future__ import print_function
# We need to import the 'random' Python library in order to generate random numbers
import random
class Boxer(object):
"""
... | true |
0ae1e723b9a16cd4c9a5bad9d756158888ccfe27 | SabiqulHassan13/python3-programiz-try | /NumberIsOddOrEven.py | 290 | 4.46875 | 4 | # python program to check a number is even or odd
#take input a number to check from the user
num = float(input("Enter a number: "))
# checking a number is odd or even
if num % 2 == 0:
print("{} is even number".format(num))
elif num % 2 == 1:
print("{} is odd number".format(num)) | true |
886979bbd25e5a15e02eef4cad6519d56f710c6c | SabiqulHassan13/python3-programiz-try | /FindFactorsOfANumber.py | 251 | 4.4375 | 4 | # python program to find the factors of a number
# take input a number
num = int(input("Enter a positive integer: "))
# print the factors
print("The factors of {} are: ".format(num))
for i in range(1, num + 1):
if num % i == 0:
print(i)
| true |
56353728f6e3f62a021e580e8e73cb4231c5e41a | Sohan11Sarkar/Basic-Calculator.github.io- | /main.py | 1,011 | 4.1875 | 4 | print('*********** WELCOME TO MY CALCULATOR ************')
while True:
print()
print("Please select the operation you want to perform : \n\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exit\n")
option = int(input("Enter pption here -> "))
if option==1:
no1=int(input("Enter First Number -> "))... | false |
ed5cd23e31fcabc16b3ec9a5822e666bfa66b667 | utolee90/Python3_Jupyter | /workspace2/10-collection/exam1_.py | 730 | 4.1875 | 4 | # 문자열 여러개 한꺼번에 저장
str_list = ['국어', '영어', '수학', '사회', '한국사']
print(str_list)
# 인덱싱 : 데이터 1개 처리
print(str_list[0])
print(str_list[3])
# 슬라이싱 : 데이터 여러개 처리
print(str_list[1:4])
print(str_list[:4])
print(str_list[1:])
print(str_list[:])
print(str_list[::2])
print(str_list[::-1])
print('-' * 30)
# 정수 저장
num_list = [1, 2, ... | false |
a59bc8107619ffaa5468ee7d5df1e9cf6cc3ebee | utolee90/Python3_Jupyter | /workspace2/06-operator/exam6.py | 646 | 4.25 | 4 | '''
논리 연산자 : 수학의 집합 기호를 명령어로 만들어 놓은 것
=> boolean 연산
<진리표>
x y x and y x or y not x
true true true true false
true false false true false
false true false true true
false false ... | false |
55d460794565caf77b2f5c357a550f86049a7c9e | gawalivaibhav/Vg-python | /08-usefull datastructures/07-sets.py | 370 | 4.15625 | 4 | #Sets :- collection of uniqu elements
#Union "|" #intersection "^" #diffrence "-"
my_set = set(['one','two','three','one'])
#print(my_set)
my_set1 = set(['two','three','four'])
a = my_set - my_set1
print(a <= my_set) #subset
my_set1.add('five')
print(my_set1)
#print(my_set|my_set1) #Union
#print(my_set ^ my_set1) ... | false |
2a14971a28aee88ed93ee3aefb06dc1ec2fc0151 | rickyqiao/data-structure-sample | /binary_tree.py | 1,401 | 4.125 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.parent = None
self.data = data
self.height = 0
class BinaryTree:
def __init__(self):
self.root = None
def __str__(self, node = 0, depth = 0, direction_label = ""):
"The tr... | true |
9670dc0c87a0205c248e98154aa92186b48addba | arinmsn/My-Lab | /Books/PythonCrashCourse/Ch8/8-6_CityNames.py | 720 | 4.53125 | 5 | # Write a function called city_country() that takes in the name
# of a city and its country. The function should return a string formatted like this:
# "Santiago, Chile"
# Call your function with at least three city-country pairs, and print the value
# that’s returned.
def city_country(city, country):
message = ci... | true |
de0f6049fdf79eddf97e30129d1c449999dc4cab | slayer96/codewars_tasks | /pattern_craft_decorator.py | 1,691 | 4.5 | 4 | """
The Decorator Design Pattern can be used, for example, in the StarCraft game to manage upgrades.
The pattern consists in "incrementing" your base class with extra functionality.
A decorator will receive an instance of the base class and use it to create a new instance with the new things you want "added on it".
... | true |
5a31b5a75acc5bba977ad3117973e674063ffcc8 | joseph-guidry/dot | /mywork/ch5_ex/ex7.py | 636 | 4.125 | 4 | #! /usr/bin/env python3
def update_value(dictionary, num):
"""Take a dictionary and number to add values. Returns an updated
dictionary"""
for key in dictionary:
dictionary[key] += num #with no return
dict_value = {"cats":0, "dogs":0}
#get input and convert to int
number = int(input("What va... | true |
5380d9d84232b3c71cac9aa3e622a86d34dd1939 | dayna-j/Python | /codingbat/not_string.py | 238 | 4.375 | 4 | # Given a string, return a new string where "not " has been added
# to the front. However, if the string already begins with "not", return the string unchanged.
def not_string(str):
if str[0:3]=='not':
return str
return 'not '+str
| true |
aa5611dd17a02c0642afabcb5d37e5816079631d | deepakgd/python-exercises | /class7.py | 719 | 4.1875 | 4 | # multiple inheritance init call analysis
class A:
def __init__(self):
print("init of A")
def feature1(self):
print("Feature 1-A")
def featurea(self):
print("Feature A")
class B:
def __init__(self):
print("init of B")
def feature1(self):
print("Fea... | true |
f0c63a412162c445546ebdb2b5f12239f85e2212 | pxblx/programacionPython | /practica03/E01Cuadrado.py | 925 | 4.15625 | 4 | """
Ejercicio 1 de clases
Implementa en Python las clases GatoSimple, Cubo y Cuadrado vistas en el libro "Aprende Java con Ejercicios" y sus
respectivos programas de prueba.
"""
class Cuadrado:
def __init__(self, lado):
self.__lado = lado
def __str__(self):
resultado = ""
c = 0
... | false |
db71200cb44b9a230d57338187a30ad8045b7912 | pxblx/programacionPython | /practica05/E10HashMap.py | 1,025 | 4.1875 | 4 | """
Ejercicio 10 de POO4
Crea un mini-diccionario español-inglés que contenga, al menos, 20 palabras
(con su correspondiente traducción). Utiliza un objeto de la clase HashMap para
almacenar las parejas de palabras. El programa pedirá una palabra en español
y dará la correspondiente traducción en inglés.
"""
dicciona... | false |
6d51a33cce5ed2c713c298e7a0ae483a3c8ebedf | pxblx/programacionPython | /practica01/repetitivas/E05Repetitivas.py | 1,166 | 4.25 | 4 | """
Ejercicio 5 de repetitivas
Escribe un programa que pida el limite inferior y superior de un intervalo. Si el limite inferior es mayor que el
superior lo tiene que volver a pedir. A continuacion se van introduciendo numeros hasta que introduzcamos el 0. Cuando
termine el programa dara las siguientes informaciones:
... | false |
3cf82f53cf591934fb01755beabf9904c3c1ffdf | Aobie/Project-Euler | /Euler9.py | 1,170 | 4.1875 | 4 | #Euler 9
#Pythagorean triplet is a set of 3 natural numbers which can define a right triangle
#a ** 2 + b ** 2 = c ** 2, where a < b < c
import math
import time
def find_product():
# since a, b, and c are natural numbers and a < b < c
# the smallest set possible is a = 1, b = 2, c = 3
# this also means that... | false |
f87730c01046eddf792665e051463ff59fde7aa0 | LilMelt/Python-Codes | /Rock_Paper_Scissors.py | 1,880 | 4.1875 | 4 | import random
def opponent():
choice = random.choice(["rock", "paper", "scissors"])
print("Your opponent chose " + choice)
return choice
def main():
game = True
score = 0
opponent_score = 0
while game:
# input user move
user_move = input("Type \"rock\", \"paper\" or \"sci... | true |
0a749ccfccd2d7b18168455fca9c7701f26177fd | Pankhuriumich/EECS-182-System-folder | /Homeworks/HW5/printmovie.py | 994 | 4.25 | 4 | '''TASK: Fill in the code to generate the HTML-formatted string
from the fields of a movie. See the README.txt for the
format
'''
def print_movie_in_html(movieid, movie_title, moviedate, movieurl):
'''STUB code. Needs to change so that the return value
contains HTML tags, as explained in README.txt.'''
resul... | true |
30e6b14d953e87fb0f37066e53f5222755743ddb | Pankhuriumich/EECS-182-System-folder | /Lecture_Code/Recursion/stone_to_dust_simulation/stonetodust.py | 797 | 4.21875 | 4 | def turn_stone_into_dust(stone):
if (isdust(stone)):
print "We got a dust piece! Nothing more to do on the piece!";
return;
else:
(piece1, piece2) = strike_hammer(stone);
turn_stone_into_dust(piece1);
turn_stone_into_dust(piece2);
def isdust(stone):
# Stones of size 1 or ... | true |
92d1c7f8015d4d552bb11fa8c818f81840d49646 | lavenderLatte/89926_py | /homework/helperfunctions.py | 536 | 4.34375 | 4 | """
Create a python module helperfunctions.py with the following functions.
add - returns the sum of two numbers
diff - returns the difference between two numbers
product - returns the product of two numbers
greatest - returns the greatest of two numbers.
Import this module in your python program and use the functions ... | true |
54bc71f87b9de5e9956881744c63d1501c24ddd4 | saragregory/hear-me-code | /pbj_while.py | 1,801 | 4.28125 | 4 | # Difficulty level: Beginner
# Goal #1: Write a new version of the PB&J program that uses a while loop. Print "Making sandwich #" and the number of the sandwich until you are out of bread, peanut butter, or jelly.
# Example:
# bread = 4
# peanut_butter = 3
# jelly = 10
# Output:
# Making sandwich #1
# Making sandwi... | true |
a9d2ac3204cf92eb968c39fcc51ba887805b9645 | coolguy-kr/questions | /py-multiple_inheritance.py | 826 | 4.4375 | 4 | # The following code is an example. The tree structure of class inheritance relationships is displayed as a list on the console.
class X:
pass
class Y:
pass
class Z:
pass
class A(X, Y):
pass
class B(Y, Z):
pass
class M(B, A, Z):
pass
print(M.mro())
# So, It displays a result as a list.
... | true |
87bf49b4a94a28bd4ae46e00b09ef44e3ddfa977 | the-brainiac/twoc-problems | /day6/program_14.py | 699 | 4.15625 | 4 | #to solve this question i used geeksforgeeks{in anticlockwise} as a reference
# https://www.geeksforgeeks.org/inplace-rotate-square-matrix-by-90-degrees/
#
N = 4
def rotateMatrix(mat):
for x in range(0, int(N / 2)):
for y in range(x, N-x-1):
temp = mat[N-1-y][x]
mat[N-1-y][x]=mat[N-1-x][N-1-y]
... | false |
8d37ab6a0ee58ee4f45551e06ac99603c239f64b | suboqi/-python | /ex3.py | 794 | 4.53125 | 5 | #现在数一数我的鸡
print("I will now count my chickens:")
#hens有30只鸡,打印出来
print("Hens",25+30/6)
#roosters有97只鸡,打印出来
print("Roosters",100-25*3%4)
#现在数一数我的蛋
print("Now i will count the eggs:")
#一共有以下几只蛋,并打印出来
num1=print(3+2+1-5+4%2-1/4+6)
#这是一个判断
print("Is it true that 3 + 2 <5 - 7?")
#判断真假
print(3+2<5-7)
#这是一个判断
print("What is 3... | false |
511f378d45e5474c7a7eb679a78a14af4bac5cbf | asikurr/Python-learning-And-Problem-Solving | /3.Chapter three/elseif_stste.py | 350 | 4.125 | 4 | age = input("Input Your Age : ")
age = int(age)
if 0<age<=3:
print("Ticket is free for you. ")
elif 3<age<=10:
print("Ticket price is 150 tk.")
elif 10<age<=20:
print("Ticket price is 250 tk.")
elif 20<age<=150:
print("Ticket Price is 350 tk.")
elif age == 0 or 0>age or age>150:
print("Sorry... Yo... | true |
1ba6cdf92840fef7f2deef408520de98826d61e9 | asikurr/Python-learning-And-Problem-Solving | /8.Chapter eight SET/set.py | 499 | 4.28125 | 4 | # Set is unordered collection of unique data item
# why we user set method
# Because it contain unique data
#but we cannot user 'list' and 'dictionary' in set
# what is we do by set functon
# list data unique and tuple data unique
s = {1,2,3}
# print(s)
list1 = [6,3,4,5,4,3,5,4,4,3,3,4,6,8]
l = list(set(list1)) # Re... | true |
34585338db8d706740fe31e9c42ba2dd934580e6 | asikurr/Python-learning-And-Problem-Solving | /2.Chapter two/exercise3.py | 517 | 4.21875 | 4 | #String case insensetive
name , char = input("Enter a Name and a character separate by coma : ").split(",")
print(f"the length of your name : {len(name)}")
print(f"Number of Character in your name case sensetive: {name.count(char)}")#case sensetive
print(f"Number of Character in your name case insensetive: {name.lower... | false |
832e49a939e333b9d95193acd6aae656167855df | asikurr/Python-learning-And-Problem-Solving | /6.Chapter six/about_tuple.py | 667 | 4.34375 | 4 | #looping in tuple
#tuple in one element
# tuploe without paranthesis
# tuple unpacking
# list inside tuple
# some function that you can use tuple
mix = (2,1,4,1,4,5,6,32)
# i = 0
# while i<len(mix):
# print(mix[i])
# i+=1
# for i in mix:
# print(i)
#Single element with tuple
n = (1,)
s = ('asikur',)
# p... | false |
6e632c820c3eda237542b2035be429ead1069019 | asikurr/Python-learning-And-Problem-Solving | /8.Chapter eight SET/more_set.py | 343 | 4.125 | 4 | # more about set method
# Union and Intersection methode
s = {'a','b','v', 'd'}
# if 'as' in s:
# print('Present')
# else:
# print('Not present')
# for i in s:
# print(i)
# Union operation
s1 = {1,2,3,3,4}
s2 = s | s1
# print(s2)
#Intersection
s3 = {1,2,3,4,5,6,7,8,9}
s4 = {1,2,3,45,6,7,8,9,10,11,12}
... | false |
674fb6ebc81e0fca4a75301afcd0ec17922d5051 | chamzheng/python-cookbook | /c01_data_structures_algorithms/p09_find_commonalities_in_dicts.py | 1,943 | 4.1875 | 4 | # -*- coding:utf-8 -*-
# 问题
# 怎样在两个字典中寻寻找相同点(比如相同的键、相同的值等等)?
# 解决方案
# 考虑下面两个字典:
a = {
'x': 1,
'y': 2,
'z': 3
}
b = {
'w': 10,
'x': 11,
'y': 2
}
# 为了寻找两个字典的相同点,可以简单的在两字典的 keys() 或者 items() 方法返回结果上执行集合操作。比如:
# Find keys in common
print(a.keys() & b.keys()) # {'y', 'x'}
# Find keys in a that a... | false |
edb125836089b25155cd4c46222393d502e7881e | wangmengyu/pythontutorial27 | /ch04/unchangeable.py | 625 | 4.125 | 4 | # -*- coding: utf-8 -*
# 参数默认值
i = 5
def my_fun(num=i):
"""默认值只被赋值一次,传递了不可变的对象"""
print num
i = 6
my_fun()
def append_list(a, l=[]):
"""默认值只被赋值一次,传递了可变的对象"""
l.append(a)
return l
print append_list(1)
print append_list(2)
print append_list(3)
def append_list_2(a, l=None):
"""将传递的可变的对象换成NOne,函数内... | false |
e433f895bb2fc8d0cf6607b9e5801bd8f61f57c4 | erikaosgue/python_challenges | /easy_challenges/7-write_a_function.py | 349 | 4.1875 | 4 | #!/usr/bin/python3
def is_leap(year):
leap = False
# leap year have to be divided by 4 and not by 100, or
# leap year have to be divided by 400
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
leap = True
return leap
if __name__ == "__main__":
year = int(inpu... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.