blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
55ef09f37beb7dffabe79a811837a8c0a042a4de | ComeOnTaBlazes/Programming-Scripting | /wk5weekday.py | 353 | 4.28125 | 4 | # James Hannon
# Create program to confirm if today is a weekday
# Import datetime
import datetime
x= datetime.datetime.now().weekday()
#test of if formula
#x = 5
#print (x)
# Weekday values in tuple list
Wkday = range (0, 5)
#x = datetime.datetime.now().weekday()
if x in Wkday:
print ("Today is a weekday")... | true |
4b79c179840e0dcebdb70592acfc383a3cae03ba | JarrodPW/cp1404practicals | /prac_01/loops.py | 825 | 4.53125 | 5 | # 3. Display all of the odd numbers between 1 and 20 with a space between each one
for i in range(1, 21, 2):
print(i, end=' ')
print()
# a) Display a count from 0 to 100 in 10s with a space between each one
for i in range(0, 101, 10):
print(i, end=' ')
print()
# b) Display a count down from 20 to 1 with a spa... | true |
5e994a2d80337153a660e00aaded081737907002 | ilante/programming_immanuela_englander | /simple_exercises/lanesexercises/py_lists_and_loops/4.addlist_from_2.py | 352 | 4.21875 | 4 | # 4. use the function addlist from point 3 to sum the numbers from point 2
x='23|64|354|-123'
y=x.split("|")
print(y)
number_list =[] # need to append int transformed stringnum
for i in y:
number_list.append(int(i))
print(number_list)
def addlist(Liste):
sum=0
for el in Liste:
sum += el
return ... | true |
3eb59906b65d759a145c8503e3be187ae8f80b5a | ilante/programming_immanuela_englander | /simple_exercises/lanesexercises/py_if_and_files/4-11_more_liststuff.py | 1,040 | 4.21875 | 4 | # 4. put the values 5,2,7,8,1,-3 in a list, in this order
li=[5,2,7,8,1,-3]
# 5. print the first and the third value in the list
print('question 5')
print(li[0], li[2])
# 6. print the double of all the values in the list
print('question 6:')
doubleli=[]
for el in li:
dob = el*2
doubleli.append(dob)
print(doub... | true |
253ee4b4fe35698ff0e94e0f4820db33167c3a08 | linkeshkanna/ProblemSolving | /EDUREKA/Course.3/Case.Study.2.Programs/target.Right.Customers.For.A.Banking.Marketing.Campaign.py | 2,297 | 4.125 | 4 | """
A Bank runs marketing campaign to offer loans to clients
Loan is offered to only clients with particular professions
List of successful campaigns (with client data) is given in attached dataset
You have to come up with program which reads the file and builds a set of unique profession list
Get input from User for ... | true |
93daf1a021a125b2d2568d299e94779795c3b7a8 | jonahnorton/reference | /recipes/function.py | 635 | 4.125 | 4 |
# create my own function and call it
# https://www.tutorialspoint.com/python/python_functions.htm
# ==================================================
# simple function call
def myfunction(x, y):
z = x + y
return z
myvalue = myfunction(3, 4)
print(myvalue)
myvalue = myfunction(5, 3)
print(myvalue)
print("... | true |
96aa3e910490ce0fb063ef1ad3faa3eb94ff8787 | matyh/MITx_6.00.1x | /Week2/Problem2.py | 1,820 | 4.53125 | 5 | # Now write a program that calculates the minimum fixed monthly payment needed
# in order pay off a credit card balance within 12 months. By a fixed monthly
# payment, we mean a single number which does not change each month, but
# instead is a constant amount that will be paid each month.
#
# In this problem, we will ... | true |
da3a76cfa02b4e807711be21ab4052bb88d8dabc | Shankhanil/CodePractice | /Project Euler/prob14.py | 1,184 | 4.15625 | 4 | """
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) c... | true |
237757575f46ccadcff1469e1b4398260299d081 | Shankhanil/CodePractice | /Project Euler/prob9.py | 512 | 4.21875 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc
"""
import math as m
if __name__ == "__main__":
N = 1000
for i in r... | true |
763b465c86db6fd897bd46f07364a9d9b8d75bb0 | MaxSpanier/Small-Projects | /Reverse_String/reverse_string.py | 947 | 4.25 | 4 | import sys
class ReverseString():
def __init__(self, string):
self.string = string
def GUI(self):
self.string = input("Please enter a string:\n")
def reverse(self, given_string):
return given_string[::-1]
def play_again(self):
choice = str(input("---------------------... | true |
7fbee4fa737684b2b92fff3f0aa74aa0130aed25 | samuelcavalcantii/Mundo3 | /ex076-ListaPreço.py | 705 | 4.125 | 4 | #Exercício Python 076: Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.
listagem = 'Lápis', 1.75,'Caderno', 15.90,'Folha A4', 40.00,'Lapiseira', 10.90, 'Estojo', 25
print(listagem)
pr... | false |
894927d48c2c671786b6ad1ee8ac1e854059feaa | MohammedBhatti/code1 | /dogpractice.py | 611 | 4.15625 | 4 | dogs = ("beagle", "collie", "healer", "pug")
dogs_characteristics = {}
list_of_characteristics = [1, 25, 'ball']
# Loop through the list and print each value out
for dog in dogs:
if dog == "healer":
print(dog)
# Create the dict object
dogs_characteristics["breed"] = dog
dogs_characteristics[... | true |
d3dc0d902f8120e90c4b85b87ef67c31b0709736 | devendra631997/python_code_practice | /graph/graph.py | 1,540 | 4.25 | 4 | # 1 2 8
# 2 3 15
# 5 6 6
# 4 2 7
# 7 5 30
# 1 5 10
# 3 5
# 2 7
# 1 6
# Add a vertex to the dictionary
def add_vertex(v):
global graph
global vertices_no
if v in graph:
print("Vertex ", v, " already exists.")
else:
vertices_no = vertices_no + 1
graph[v] = []
# Add an edge between vertex v1 and v2 w... | true |
b701b7cbcf31f704ec7d3cea7ab5a7f9092e542f | harshitksrivastava/Python3Practice | /DynamicPrograms/factorial.py | 904 | 4.34375 | 4 | # factorial using recursion without Dynamic Programming
# def fact(number):
# if number == 0:
# return 1
# else:
# return number * fact(number - 1)
# =====================================================================================================================
# factorial using recursio... | true |
9da4d5948208d4e7453bf288bfcf173c4d88beed | AM-ssfs/py_unit_five | /multiplication.py | 556 | 4.21875 | 4 | def multiplication_table(number):
"""
Ex. multiplication_table(6) returns "6 12 18 24 30 36 42 48 54 60 66 72 "
:param number: An integer
:return: A string of 12 values representing the mulitiplication table of the parameter number.
"""
table = ""
for x in range(1, 13):
table = table... | true |
887631e111b25443c7d554ebabf65b5e4cbb7e77 | eloghin/Python-courses | /PythonZTM/100 Python exercises/42.Day11-filter-map-lambda-list.py | 517 | 4.125 | 4 | # Write a program which can map() and filter() to make a list whose elements
# are square of even number in [1,2,3,4,5,6,7,8,9,10].
def map_func(l):
l = filter(lambda x: x%2==1, l)
m = map(lambda x:x*x, l)
return list(m)
print(map_func([1,2,3,4,5,6,7,8,9,10]))
******* SOL 2 *******
def even(x):
return x%2... | true |
66d361ff9b192cd686c4457bc1136c993f48e9b4 | eloghin/Python-courses | /HackerRank/interview-prep-kit-alternating-characters.py | 1,195 | 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.
https... | true |
bbb2aa394383ae52f42b842cdd19ab2d1cf46b30 | eloghin/Python-courses | /PythonZTM/100 Python exercises/22. Day08-word-frequency-calculator.py | 436 | 4.1875 | 4 | """
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
"""
string = 'New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.'
words = string.split()
word_count = {}
for word in words:
if word in word_co... | true |
cfea624a44abf9270a0c69817d417779a2d91973 | eloghin/Python-courses | /ThinkPython/12.5.CompareTuples.py | 816 | 4.25 | 4 | """
Play hangman in max 10 steps
"""
"""
Exercise 2
In this example, ties are broken by comparing words, so words with the same length appear
in reverse alphabetical order. For other applications you might want to break ties at random.
Modify this example so that words with the same length appear in random order.... | true |
a974ff163d113eebcc41271208d3610d7f00fd76 | eloghin/Python-courses | /PythonZTM/100 Python exercises/39.Day11-filter-print-tuple.py | 509 | 4.1875 | 4 |
"""
Write a program to generate and print another tuple whose values are
even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
"""
def create_tuple(t):
t2 = tuple((i for i in t if i%2==1))
print(t2)
create_tuple((1,2,3,4,5,6,7,8,9))
******* SOL 2 *******
tpl = (1,2,3,4,5,6,7,8,9,10)
tpl1 = tuple(filter(la... | true |
10166a92e26316e1182a17528bfa73e88f4364e4 | eloghin/Python-courses | /LeetCode/contains_duplicate.py | 703 | 4.1875 | 4 | # Given an array of integers that is already sorted in ascending order, find two numbers such that
# they add up to a specific target number.
# Given an array of integers, find if the array contains any duplicates.
# Your function should return true if any value appears at least twice in
# the array, and it should ... | true |
3ac0db2e66847721aad13697fad5ec3bc54353fb | eloghin/Python-courses | /HackerRank/string_Ceasar_cipher.py | 1,605 | 4.59375 | 5 | """Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c... | true |
c8a7f351613de02685ee86346e6ee5ad75f01835 | eloghin/Python-courses | /ThinkPython/12.4.SumAll.py | 443 | 4.46875 | 4 | """
Play hangman in max 10 steps
"""
"""
Exercise 1
Many of the built-in functions use variable-length argument tuples. For example, max and min can take
any number of arguments:
>>> max(1,2,3)
3
But sum does not.
>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
Write a function called sumall ... | true |
e6421c4d66bdc42d0ea5dd1c1906c0d7e7f97f43 | LucLeysen/python | /pluralsight_getting_started/loops.py | 255 | 4.15625 | 4 | student_names = ['Jeff', 'Jessica', 'Louis']
for name in student_names:
print(name)
x = 0
for index in range(10):
x += 10
print(f'The value of x is {x}')
x = 0
for index in range(5, 10, 2):
x += 10
print(f'The value of x is {x}')
| true |
ac20bc5e55fe2193c57ffc1f724ad2d9a10aadc9 | yxpku/anand-python | /chapter2/pro31-map.py | 292 | 4.1875 | 4 | # Python provides a built-in function map that applies a function to each element of a list. Provide an implementation for map using list comprehensions.
def square(num):
return num*num
print square(2)
def map(function,list):
print [function(x) for x in list]
print map(square,[1,2,3,4,5])
| true |
167d3db677427717e3002141037727da46947493 | MischaBurgess/cp1404practicals | /Prac_05/state_names.py | 1,016 | 4.125 | 4 | """
CP1404/CP5632 Practical
State names in a dictionary
File needs reformatting
Mischa Burgess
"""
# TODO: Reformat this file so the dictionary code follows PEP 8 convention
CODE_TO_NAME = {"QLD": "Queensland", "NSW": "New South Wales", "NT": "Northern Territory", "WA": "Western Australia",
"ACT": "Aus... | true |
6b33c6e9dc6d599f687331aa9934b329f91814e0 | MischaBurgess/cp1404practicals | /Prac_09/sort_files_2.py | 1,617 | 4.15625 | 4 | """sort files in FilesToSort, version 2"""
import os
import shutil
FOLDER_TO_SORT = 'FilesToSort'
def main():
os.chdir(FOLDER_TO_SORT)
files_to_sort = get_files_to_sort()
extensions = get_extensions(files_to_sort)
get_categories(extensions, files_to_sort)
def get_files_to_sort():
"""Gets a list... | true |
82a835c4a7ef3ff39ab91815f5da8d7eb0652ba9 | harofax/kth-lab | /bonus/övn-2/övn-2-krysstal.py | 1,838 | 4.46875 | 4 |
# exercise 1
def rectangle_area(height, width):
"""
:param height: height of rectangle
:param width: width of rectangle
:return: area of a rectangle with the specified width and height
"""
assert isinstance(width, int) or isinstance(width, float), "Width has to be a number!"
assert isinsta... | true |
c02807420cb24aa6153d051f927e70d79e42aa61 | pasqualc/Python-Examples | /rotatearray.py | 450 | 4.4375 | 4 | # This program will take an array and a size of rotation as input. The Output
# will be that array "rotated" by the specified amount. For example, if the Input
# is [1, 2, 3, 4, 5] and size of rotation is 2, output is [3, 4, 5, 1, 2]
while 1:
array = input("Array: ")
list = array.split()
size = int(input("... | true |
d53a41cff07f6ebbf0d2c890c6b984b5c3075dce | gladiatorlearns/DatacampExercises | /Adhoc/Packages.py | 431 | 4.125 | 4 | # Definition of radius
r = 0.43
# Import the math package
import math
# Calculate C
C = 2*math.pi*r
# Calculate A
A = math.pi*r**2
# Build printout
print("Circumference: " + str(C))
print("Area: " + str(A))
# Definition of radius
r = 192500
# Import radians function of math package
from math import radians
# T... | true |
3f66c64d2cae9031fc7b0c9e326f8c8b1f2150e8 | Dipson7/LabExercise | /Lab3/question_no_7.py | 367 | 4.34375 | 4 | '''
WAP that accepts string and calculate the number of upper case and lower case letters.
'''
def UPPERLOWER(sentence):
u = 0
l = 0
for i in sentence:
if i >= 'A' and i <= 'Z':
u += 1
elif i >= 'a' and i <= 'z':
l += 1
print(f"Uppercase: " + str(u))
print(f"L... | true |
b8e5d8bc58770e0550a59f79acd8aa5ac5881416 | Dipson7/LabExercise | /Lab3/question_no_2.py | 485 | 4.28125 | 4 | '''
WAP called fizz_buzz that takes that takes a number. If it is divisible by 3, it should return fizz.
If it is divisible by 5 return buzz. It it is divisible by both return fizzbuzz.
Otherwise it should return the same number.
'''
def div():
a = int(input("Enter any number: "))
if a/5 == a//5 and a/3 == a//3... | true |
5942e08cc117c38fbd2a4d7390f250f5d051b0bb | Barabasha/pythone_barabah_hw | /test11.py | 949 | 4.125 | 4 | #В двумерном массиве отсортировать четные столбцы по возрастанию, а нечетные - по убыванию
def random_table(table):
import random
for idx1 in range(line):
for idx2 in range(column):
table[idx1][idx2] = random.randint(1,100)
return table
def print_table(table):
for line in... | false |
a86cebe421426649f4850db1f33bde0d85a11bdf | skye92/interest_cal | /InterestCal_v.2.py | 1,455 | 4.34375 | 4 | def account_balance():# def function/ what is function name, how many params.
starting_balance = float(input("what is the starting balance? ")) # ask user for input for starting_balance
stock_cost = float(input("how much does the stock cost? "))# ask user how much the stock cost
stock_owned = starting_bal... | true |
c9d4210f3e39ee89cc3cb7816caf920e22f32513 | kalyansikdar/ctci-trees | /check_subtree.py | 1,195 | 4.1875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Algorithm:
# 1. If the structure matches with the root, return true.
# 2. Else check if it's a subtree of left subtree or right
# Note: While... | true |
1e6e5bde622e94e827a67ea13badc76d9059ee61 | LenaTsepilova/Course_python_2021 | /lesson_hm_1.py | 2,720 | 4.21875 | 4 |
"""Урок 1. Задание 2"""
# Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
# n = int(input("введите время в секундах: \n"))
# # print(1, 2, 3, sep=":")
# # print(str(n // 3600) + ":" + str(n % 3600 // 60) + ":" + str(n... | false |
c47a4043bdf87c41ac6081184473778996b750c4 | vigjo/mdst_tutorials | /tutorial1/python_exercises.py | 1,247 | 4.21875 | 4 | """
Intro to python exercises shell code
"""
from collections import Counter
def is_odd(x):
if x % 2 != 0:
return false
return true
"""
returns True if x is odd and False otherwise
"""
def reverse(s):
str = ""
for i in s:
str = i + str
return str
def is_palindrome(word):
if word == ... | true |
671b9b5777df9c755c8ee396c3cd7c21e187e7e5 | olliepotter/Python_Scripts | /Python_Scripts/Coursework_1/fibonacci.py | 1,297 | 4.78125 | 5 | """
This file contains various functions to compute a given number of fibonacci terms
"""
def fibonacci(number, next_value=1, prev_value=0):
"""
Calculates the 'nth' number in the fibonacci sequence
:param number: The 'nth' term in the fibonacci sequence to be returned
:param next_value: The next valu... | true |
66104e9f2bdb1175ad28f4ef81f1835eb449138d | FerruccioSisti/LearnPython3 | /Conditionals Examples/ex36.py | 1,668 | 4.25 | 4 | #This exercise is basically the previous one, except it is meant to be short and entirely on our own
from sys import exit
#red room option from starting room
def redRoom():
print("Everything in this room is red. You can't see any objects other than the outline of the door.")
print("Do you try and go out the do... | true |
b331aff61366b16861907d9466bd1c26e9945f66 | FerruccioSisti/LearnPython3 | /Tests/ex24.py | 1,308 | 4.4375 | 4 | #This is a longer exercise where we practice everything from the previous 23 examples
print("Lets practice everything.")
print('You\'d need to know \'bout escapes with \\ that do: ')
print('\n newlines and \t tabs')
poem = """\t the lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor com... | true |
ead6245978ad7c23674e14b472457eeafa099330 | franckess/Python-for-Everybody-Coursera- | /Python Data Structures/Scripts/Assignment_84.py | 859 | 4.5 | 4 | ## Assignment 8.4
# Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
# The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
# When the progra... | true |
df64b21d85348ac280397effe3d8cd576a73f52d | Rutujapatil369/python | /Assignment1_2.py | 621 | 4.21875 | 4 | # Write a program which contains one function named as ChkNum() which accept one parameter as number.
#If number is even then it should display “Even number” otherwise display “Odd number” on console.
#Input : 11 Output : Odd Number
#Input : 8 Output : Even Number
def ChkNum(No):
if(No%2==0):
... | true |
52753b372d177b9eb2f423cbe7270cb561f18bfe | prathimacode-hub/Python-Tutorial | /Beginner_Level/Closure + Nested Function/anotherclosureexample.py | 552 | 4.25 | 4 |
def nth_power(exponent ):
def pow_of(base):
return pow(base, exponent)
return pow_of # note that we are returning function without function
square = nth_power(2)
print(square(31))
print(square(32))
print(square(33))
print(square(34))
print(square(35))
print(square... | false |
9aa7e369bcbe68fef446bc4e64242c37df29eb0e | d2015196/PythonTutorial- | /Boolean.py | 600 | 4.15625 | 4 | favoritefood = "Hotdogs"
favoritelanguage = "Python (Yuzzz!)"
favoritecountry = "Deutschland"
stuff = []
stuff.append(favoritecountry)
stuff.append(favoritelanguage)
if favoritecountry == "Deutschland" or favoritecountry == "Mexico":
print ("You are correct ")
if favoritelanguage in stuff:
print("Cool bro")
if... | false |
38360af0cefbce3fea4b9e03931bdee92fd822aa | ZTMowrer947/python-number-guess | /guessing_game.py | 2,284 | 4.40625 | 4 | """
Python Web Development Techdegree
Project 1 - Number Guessing Game
-----------------------------------------------------------------------
This project implements a simple version of the number guessing game.
The user is prompted to guess a random number between 1 and 10, and
does so until they guess correctly. At... | true |
e249538c94d2b2c6d8a3dfece71adb4be5d187f4 | SamuelLeeuw/mypackage | /mypackage/sorting.py | 1,052 | 4.28125 | 4 | def bubble_sort(items):
'''Return array of items, sorted in ascending order'''
for passnum in range(len(items)-1,0,-1):
for i in range(passnum):
if items[i]>items[i+1]:
temp = items[i]
items[i] = items[i+1]
items[i+1] = temp
r... | true |
fd06d649f3cb966c9f5b6d0b34195f778de695bc | CAMOPKAH/BA | /LearnPython/Lesson5/task2.py | 776 | 4.25 | 4 | """
2. Создать текстовый файл (не программно), сохранить в нем несколько строк,
выполнить подсчет количества строк, количества слов в каждой строке.
"""
f_read = open ("test_words.txt", "r")
word_count = 0
line_count = 0;
for line in f_read:
line_count = line_count + 1
str = " " + line.replace("\n", "") + " ... | false |
57174e710e1cd8d871ce605f4dd7bf5d8f8a21d8 | deepakdas777/think-python-solutions | /Classes-and-functions/16.1.py | 476 | 4.375 | 4 | #Exercise 16.1. Write a function called print_time that takes a Time object and prints it in the form hour:minute:second . Hint: the format sequence '%.2d' prints an integer using at least two digits, including a leading zero if necessary.
class time:
hour=0
minut=0
second=0
def print_time(t):
print('The time ... | true |
48723d15b68caa2942c2add79890be28816fa6ea | amudwari/hangman | /game.py | 1,191 | 4.1875 | 4 | import random
def get_random_word():
small_file = open("small.txt", "r")
words = small_file.readlines()
random_word = random.choice(words)
print(random_word)
return random_word
def start_game():
print('''
You'll get 3 tries to guess the word. Lets START...''')
random_word = g... | true |
b0dfd9e4aed10b3cfc9f6931290c485e1f566482 | slubana/GuessTheNumber | /guessmynumber.py | 1,057 | 4.125 | 4 | import math
import random
import time
print("Welcome to the Guess the Number Game! \nThe goal of the game is to guess the number I am thinking!")
choice = input("Do you want to play? Enter 'No' to quit and 'Yes' to play!")
if choice=="No":
print("Ok! Have a good day!")
exit()
else:
print("You have chos... | true |
21ef5a2af4468d11bf7b1cf85f5cc861f486a912 | Krushnarajsinh/MyPrograms | /InnerClass.py | 1,237 | 4.6875 | 5 | #class inside a antother class is called as inner class
class Student:
class_name="A" #Inner class can access class variable but not instance variable of outer class
def __init__(self,no,name):
self.no=no
self.name=name
self.lap=self.Laptop("HP","i8")
def show(self):
print(s... | true |
78a7a815b07f7d0e38d74d6958e94bb35d0cbec7 | Krushnarajsinh/MyPrograms | /OneTryBlockWithManyExceptBlock.py | 1,031 | 4.28125 | 4 | #suppose i perform some operation with database and i need to open a connection to connect the detabase
#when our task is over then we must close that connection
#fa=int(input("Enter the number A:"))
a=int(input("Enter the number A:"))
b=int(input("Enter the number B:"))
try:
print("open connection")
a=int(inp... | true |
81a9ace06a898dce5d7ad77592e79ba2ae394cc5 | Krushnarajsinh/MyPrograms | /ConstructorINInheritance.py | 953 | 4.25 | 4 | class A:
def __init__(self,a):
print("This is A class Constructor","value is:",a)
def display1(self):
print("This is display1 method")
class B(A):
def __init__(self,a):
super().__init__(5)
print("This is B class Constructor","value is:",a)
def display2(self):
prin... | true |
ee198677e75c5bdac38a13c76c34c9de2ab7ad7e | Krushnarajsinh/MyPrograms | /ListAsArgumentInFunction.py | 462 | 4.21875 | 4 | def odd_even(list):
even=0
odd=0
for i in list:
if i%2==0:
even+=1
else:
odd+=1
return even,odd
list=[]
num=int(input("Howmay values you want to enter in the list:"))
i=1
while i<=num:
x=int(input("Enter the {}th value in list:".format(i)))
list.append(x)
... | true |
6e07b9cbfa479441ad03df261c47822ec6159ef4 | Krushnarajsinh/MyPrograms | /GeneratorDemo.py | 1,183 | 4.53125 | 5 | #In iterator we need to face some issues like we need to define to functions iter() and next()
#hence instead of using iterator we can use Generator
#lat's do that
def toptan():
yield 5 #yield is the keyword that make your method as generator now this is not normal method it is Generator
#yield also similar t... | true |
9b1e3c9bf8b357f38518a1c44032fc5a4780a0ca | suchismitapadhy/AlgoPractice | /zero_matrix.py | 528 | 4.125 | 4 | def zero_matrix(arr):
zero_i = set()
zero_j = set()
# find index(i,j) for zero valued elements
for i in range(len(arr)):
for j in range(len(arr[i])):
if arr[i][j]==0:
zero_i.add(i)
zero_j.add(j)
# traverse the matrix to set rows and cols to zero
... | false |
0f4b63cdb1224d2c5c86a2e75dcd9b8db925c5c9 | Edrasen/A_Algoritmos | /Divide&Conquer2_QuickSort/quickLast.py | 1,406 | 4.375 | 4 | #Practica 4
#Ramos Mesas Edgar Alain
#quicksort by pivot at last element
#By printing every iteraction with partition function we will be able to see
#how many iterations there are on the algorithm, in this case it takes only 6 iterations.
contador = 0
comparaciones = 0
def partition(arr,low,high):
... | true |
22bf6c6cd2472d712e0749844c8041f11213deec | headHUB/morTimmy | /raspberrypi/morTimmy/bluetooth_remote_control.py | 2,281 | 4.125 | 4 | #!/usr/bin/env python3
import remote_control # Controller driver and command classes
import pybluez # Bluetooth python libary
class RemoteController(ControllerDriver):
""" Remote control morTimmy the Robot using bluetooth
This class will be used to control the Raspberry Pi
using e... | true |
bad07650cf04085300eb252fccbbec7c345587f3 | impiyush83/expert-python | /decorators.py | 1,751 | 4.21875 | 4 | # DECORATORS WITH ARGUMENTS :
def trace(func):
def wrapper(*args, **kwargs):
print(f'TRACE: calling {func.__name__}() '
f'with {args}, {kwargs}')
original_result = func(*args, **kwargs)
print(f'TRACE: {func.__name__}() '
f'returned {original_result!r}')
... | true |
dedb545a4c77ff1d065cb5815b585737f6b3293a | gadepall/IIT-Hyderabad-Semester-Courses | /EE2350/Coding Assignment-1/2.1.1g.py | 1,080 | 4.15625 | 4 | # Code for Moving Average System
import numpy as np
import matplotlib.pyplot as plt
n = int(input("No.of Elements in signal: "))
x = np.ones(n)
time = np.arange(n)
for i in range(n): # Generating the input
x[i] = 0.95 ** i
def Signal_Ideal_Delay(signal,d = 2): # Function to generate ideal del... | true |
a2e5abd26ff8ebe066c20741ec54f14400942a59 | uh-bee/Balakrishnan_Story | /addSix.py | 203 | 4.40625 | 4 | """
This program will take the input of the user and return that number plus 6
in a print statement
"""
x= float(int(input('please enter a number')))
print("the number" + x + "plus 6 is:" + str((x+6)))
| true |
d5546cf9190ec318bbb90a4af97b4f46d76e5a02 | unites/code_library | /python/comparison.py | 1,757 | 4.53125 | 5 |
# Python 3 code
# check if list are equal
# using set() & difference()
# initializing list and convert into set object
x = set(['x1','rr','x3','y4'])
y = set(['x1','rr','rr','y4'])
print ("List first: " + str(x))
print ("List second: " + str(y))
# take difference of two lists
z = x.difference(y)
... | true |
c9a1ec2ce98f8d6940ec066f3354f97cb4407c7f | Yujunw/leetcode_python | /116_填充每个节点的下一个右侧节点.py | 1,217 | 4.15625 | 4 | '''
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
'''
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val ... | false |
8d27d8e9695d6316a6316194b04b792edfff183b | treelover28/Tkinter-Learning | /grid.py | 644 | 4.59375 | 5 | from tkinter import *
# create root window
root = Tk()
# define Label widget on top of the Root widget
label = Label(root, text="Hello World")
label2 = Label(root, text="My name is Khai Lai")
label3 = Label(root, text="---------------")
# instead of automating the placement using .pack()
# we can specify the position... | true |
8506fa5f0f87247548f3398f4f4d0c288e1c9780 | KseniaTrox/lesson_2 | /5.1.py | 574 | 4.28125 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.Об
# окончании ввода данных свидетельствует пустая строка.
f = open('grumbler.txt', 'w', encoding='utf-8')
while True:
s = input('введите строку:')
if s == '': break # пустая строка
f.write(s + '\n... | false |
5b834fef771547925b2e9fdf7b37a8a2c54dd4ef | AmirQadir/MITx-6.00.1x | /Week2/Prob1.py | 501 | 4.34375 | 4 |
balance = int(input("Enter the current balance:"))
annualInterestRate = float(input("Enter the annualInterestRate"))
monthlyPaymentRate = float(input("monthlyPaymentRate"))
for i in range(12):
mir = annualInterestRate / 12.0 # Monthly Interest Rate
mmp = monthlyPaymentRate * balance # Minimum Monthly Payme... | true |
90043fe44b0ade6594e0b2fad7d79bd3a14033a9 | pedrobrasileiro/Exercicios-Python-e-Django-3 | /programa1.p3.py | 626 | 4.125 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
programa1.py
Created by Pedro Brasileiro Cardoso Junior on 2010-12-28.
Copyright (c) 2010 Particular. All rights reserved.
Importa o módulo random e sorteia um número inteiro
entre 1 e 100
"""
import random
numero = random.randint(1,100)
escolha = 0
tentativas = 0
while... | false |
76f61ae21e0d1747e82e42188ed61421d2dad483 | jivid/practice | /cracking/Chapter 4 - Trees and Graphs/q4_5.py | 596 | 4.21875 | 4 | """
Implement a function to check if a binary tree is a binary search tree
"""
import sys
# Assume here that values in the tree are positive (i.e. > 0) so as to
# not worry about -1 being the base case for min and max
def is_binary_search_tree(root, max=-1, min=-1):
if root is None:
return True
if m... | true |
ad3082500a9dd68294a70036a4799d03ebf86045 | siddharth20190428/DEVSNEST-DSA | /DI015_Diameter_of_a_binary_tree.py | 741 | 4.125 | 4 | """
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them... | true |
7b425622ed0ea1745ebabc7407082b09b1cb4e2d | siddharth20190428/DEVSNEST-DSA | /DI016_Maximum_width_of_a_binary_tree.py | 1,209 | 4.125 | 4 | """
Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-n... | true |
ef367ea0d700846d6103154c1e6d92e97489c933 | thumbimigwe/nipy | /snippets/5th feb/Number based brainteasers/Digit Grouping.py | 748 | 4.34375 | 4 | #!/usr/bin/python3
# When displaying numbers it is good practice to group digits together and use the comma to separate groups of three digits. For instance 100000000 is easier to read when it is displayed as 100,000,000.
# Ask the user to enter any large number (e.g. at least 3 digits long). The program should displa... | true |
c38069122b4b78fcb3092018d9e93bdbe55223e9 | thumbimigwe/nipy | /snippets/Math Quiz/mathQuiz.py | 2,311 | 4.28125 | 4 | #!/usr/bin/python3
# ********************* PROBLEM STATEMENT *********************
# A primary school teacher wants to test her students mental arithmetic by making them complete a test with 10 questions in which they complete operations like; adding, subracting and multiplying.
# Complete the following tasks;
# 1.... | true |
7c620e8a40994c5dcf6f1a140ded402cff04b910 | GIT-Ramteja/project1 | /string2.py | 1,801 | 4.40625 | 4 | str = "Kevin"
# displaying whole string
print(str)
# displaying first character of string
print(str[0])
# displaying third character of string
print(str[2])
# displaying the last character of the string
print(str[-1])
# displaying the second last char of string
print(str[-2])
str = "Beginnersbook"
# displaying w... | true |
c612c428f14af37f07d412303b80302040f8516f | Paavni/Learn-Python | /Python project/pythonex8.py | 330 | 4.125 | 4 | #print "How are you today?"
#answer = raw_input()
#print "Enter age"
#age = raw_input()
#print "Your age is %s" %age
print "This will print in",
print "one line.",
print "One line it is!"
name = raw_input("What is your name? ")
print "Your name is: %s" %name
age = raw_input("What is your age? ")
print "Your age is... | true |
75bab9cc50495b3f50749278e02fe7e54e126c50 | timorss/python | /24addRemoveItem.py | 616 | 4.28125 | 4 | letters = ['a', 'b', 'c', 'd']
# add item in the beginning
letters.append('e')
print(letters) # ['a', 'b', 'c', 'd', 'e']
# add item in specific location
letters.insert(3, '--')
print(letters) # ['a', 'b', 'c', '--', 'd', 'e']
# remove item in the end
letters.pop()
print(letters) # ['a', 'b', 'c', '--', 'd']
# r... | true |
8010ee6122f45866fd1a3dbffac29a039ceff938 | ajpiter/CodeCombat | /Desert/SarvenSavior.py | 753 | 4.125 | 4 | """My pet gets left behind everytime :( """
# An ARRAY is a list of items.
# This array is a list of your friends' names.
friendNames = ['Joan', 'Ronan', 'Nikita', 'Augustus']
# Array indices start at 0, not 1!
friendIndex = 0
# Loop over each name in the array.
# The len() function gets the length of the list.
whi... | true |
9ba06c2ab12388b1ffe5596089dbd34c681d3c95 | AnthonyWalton1/ARBI | /Raspberry Pi/Raspberry Pi Code/Arbi GUIs/GUI Tutorials/Tutorial1.py | 350 | 4.125 | 4 | #!/usr/bin/env python
from Tkinter import *
# Start a GUI (object) from Tkinter class
root = Tk()
# Create a label (text box widget) called theLabel and set what text it shows
theLabel = Label(root, text = "Python GUI")
# Place the text box in the first available space and display it
theLabel.pack()
# Keep the G... | true |
7c92766f99e3dff17ed5426962aca10f1bac7890 | Environmental-Informatics/building-more-complex-programs-with-python-avnika16 | /amanakta_Exercise_6.5.py | 460 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Solution for Exercise 6.5
Avnika Manaktala
"""
def gcd(a,b):
#Defining GCD function
if b!=0: #Setting up recursion
return gcd(b, a%b)
else:
return a #When b=0 recursion stops
def user_gcd():
#Defining user input for GCD function
... | true |
e013ee6c78fef1df17b4f1879b49d628c0386c30 | jonathangjertsen/classmemo | /classmemo/__init__.py | 2,039 | 4.125 | 4 | """
A `Memoizer` can be used as a factory for creating objects of a certain class.
It exposes a constructor and 2 methods
* `memoizer = Memoizer(SomeClass)`
* `memoizer.get(*args, **kwargs)`
* If `memoizer` has never seen the given arguments, it creates `SomeClass(*args, **kwargs)` and returns it.
* If `memoiz... | true |
612ca7eb6e6f9e77ed0d8315e560c88ecc50840c | ferminitu/F_de_Informatica | /F. de Informática/Python avanzado/Práctico1-Parte2/Ejercicio 14.py | 661 | 4.1875 | 4 | # Creá una función que calcule la temperatura media de un día a partir de la temperatura máxima y mínima. Escribí un programa principal,
# que utilizando la función anterior, vaya pidiendo la temperatura máxima y mínima de cada día y vaya mostrando la media. El programa
# tiene que pedir el número de días que se van ... | false |
b8980a7259eb8cb5f01f156e0d053f0b74e8f758 | dwhdai/advent_of_code | /2020/day3.py | 2,826 | 4.4375 | 4 | def import_map(filepath):
"""Given a filepath, import the map object as as a nested list.
Returns:
list: a 2D nested list, representing the rows of the map
as individual list objects
"""
with open(filepath) as f:
map = f.read().splitlines()
return map
def traverse_step(s... | true |
47fb7a15721f699fdf2703ec25bea5afe020b90a | sam943/Python2.7 | /Python_301/sqlite_database_connections.py | 937 | 4.25 | 4 | import sqlite3 # default db module available with python
conn = sqlite3.connect('dem3d.db') # here is the db doesn't exist the database is created
c = conn.cursor() # cursor is a handle to execute our queries
c.execute('''CREATE TABLE users(username text,email text)''')
c.execute("INSERT INTO users VALUES ('Sam', 'me@m... | true |
8195a360629e12c4efec9d2086466e6f15e0cfe2 | josefren/numpy-scipy-exercises | /exercise-7-numpy-practice.py | 1,748 | 4.65625 | 5 | """
Start up Python (best to use Spyder) and use it to answer the following questions. Use the following imports:
import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
1 Choose a value and set the variable x to that value.
2 What is command to compute the square of x? Its cube?
3 Choose an... | true |
d6d79f72a837978a1244c929b26270b76845030f | DreamXp/cse210-student-hilo | /hilo/game/Guesser.py | 1,999 | 4.25 | 4 | import random
class Guesser:
"""The responsibility of this class of objects is to play the game - choose the card, add or subtract points from the total, guess whether the next card will be lower or higher, and determine whether the player can guess again.
Attributes:
points (number): The number o... | true |
be56e882bbb827a1e40a1d6c06333292627ab9a8 | artsalmon/Think-Python-2e---my-solutions | /07 - Exercises/7.2 - Module 2.py | 1,083 | 4.5 | 4 | """
Exercise 7.2.
The built-in function eval takes a string and evaluates it using the Python
interpreter. For example:
>>> eval('1 + 2 * 3')
7
>>> import math
>>> eval('math.sqrt(5)')
2.2360679774997898
>>> eval('type(math.pi)')
<class 'float'>
Write a function called eval_loop that iteratively prompts the user, takes... | true |
a3748d80579b19cf572f07a9dac445457895f749 | theecurlycoder/CP_PWP | /1. Python/control_flow.py | 551 | 4.25 | 4 | # if/then statements
# boolean values
likes_pizza = True
likes_cats = False
print(True)
print(False)
is_john_killer = True
is_bob_killer = False
if is_bob_killer == True:
print("Bob is the killer")
if is_john_killer == True:
print("John is the killer")
print()
#Equality Operators
print(5 == 5)
print(5 > ... | true |
7130c34b6e9b7cabc479c49e8bb118b9130b7220 | yudhapn/OCBC-H8-Python | /Session3/function.py | 2,413 | 4.1875 | 4 | # case 1
def my_function(p, l):
'''Function to calculate area of a square'''
print(p * l)
def printme(str_input):
print(str_input)
printme("I'm first call to user defined function")
printme("Again second call to do the same function")
print("\n===processing input and return it===")
def changeme(myList):
... | true |
8c54fe17d934cfeefac3baaa6852201a163cc696 | iisdd/Courses | /python_fishc/45.2.py | 1,060 | 4.125 | 4 | '''2.编写一个 Counter 类,用于实时检测对象有多少个属性
程序实现如下:
>>> c = Counter()
>>> c.x = 1
>>> c.counter
1
>>> c.y = 1
>>> c.z = 1
>>> c.counter
3
>>> del c.x
>>> c.counter
2
我的答案:
class Counter:
def __init__(self):
self.counter = 0
def __setattr__(self , name , value):
if name != 'counter':... | false |
87cf045792fbaf399c8c2285bebc1cf4fdd1696a | iisdd/Courses | /python_fishc/46.2.py | 1,201 | 4.1875 | 4 | '''2. 再来一个有趣的案例:编写描述符 MyDes,使用文件来存储属性,
属性的值会直接存储到对应的pickle(腌菜,还记得吗?)的文件中。
如果属性被删除了,文件也会同时被删除,属性的名字也会被注销
举个栗子:
>>> class Test:
x = MyDes('x')
y = MyDes('y')
>>> test = Test()
>>> test.x = 123
>>> test.y = "I love FishC.com!"
>>> test.x
123
>>> test.y
'I love FishC.com!'
产生对应的文件存... | false |
2bed38ecafd8dc1077079b023fd78cbaface8c28 | iisdd/Courses | /python_fishc/11.0.py | 386 | 4.15625 | 4 | '''0. 课堂上小甲鱼说可以利用分片完成列表的拷贝 list2 = list1[:],
那事实上可不可以直接写成 list2 = list1 更加简洁呢?
'''
# 举个例子:
list1 = [1 , 9 , 5 , 7 , 6 , 2]
list2 = list1[:]
list3 = list1
list1.sort()
print('母体列表1:' + str(list1))
print('copy列表2:' + str(list2))
print('墙头草列表3:' + str(list3))
| false |
b431fd6ddcbcb157382bcfa82b33b4b3faac088d | iisdd/Courses | /python_fishc/6.1.py | 305 | 4.125 | 4 | '''
1. 我们说过现在的 Python 可以计算很大很大的数据,但是......
真正的大数据计算可是要靠刚刚的硬件滴,不妨写一个小代码,让你的计算机为之崩溃?
'''
# 不推荐运行嗷
count = 100
for i in range(1 , 100):
count **= i
print(count)
| false |
c33e1014f0b877dbec5dc4c129c9c8d8b1934c0d | raj-andy1/mypythoncode | /samplefunction14.py | 282 | 4.15625 | 4 | """
sampleprogram14 - class 4
while loop example - type a
"""
looping = True
while looping == True:
answer = input("Type letter a")
if answer == 'a':
looping = False
else:
print ("TYPE THE LETTER A")
print ("Thanks for typing the letter A")
| true |
5bc78f4f6b0a5f48ebae15a7cc5db65e6dbdc386 | irakowski/PY4E | /03_Access Web Data/ex_12_3.py | 945 | 4.5 | 4 | """Exercise 3: Use urllib to replicate the previous exercise of
(1) retrieving the document from a URL,
(2) displaying up to 3000 characters, and
(3) counting the overall number of characters in the document.
Don’t worry about the headers for this exercise, simply show the
first 3000 characters of the document con... | true |
4ca87c9e82ed461cf2a0192c354493279d0ec224 | irakowski/PY4E | /01_Getting Started with Python/ex_3_1.py | 403 | 4.1875 | 4 | """
Exercise 1: Rewrite your pay computation to give the employee 1.5 times the hourly rate
for hours worked above 40 hours
"""
hours = float(input("Enter Hours: "))
rate = float(input("Enter Rate: "))
standart_time = 40
if hours > standart_time:
overtime_rate = rate * 1.5 * (hours - standart_time)
pay = (stan... | true |
f93df966be9f9c9c4121154d0e014840b95cc70b | irakowski/PY4E | /02_Data Structures/ex_7_1.py | 759 | 4.3125 | 4 | """Exercise 1: Write a program to read through a file and print the contents of the file
(line by line) all in upper case. Executing the program will look as follows:
python shout.py
Enter a file name: mbox-short.txt
FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008
RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJECT.... | true |
2ad39ba81a7e59fd6f49d809279ed67bfcb3f419 | Jdothager/web-caesar | /caesar.py | 1,271 | 4.25 | 4 |
def encrypt(text, rot):
""" receives a string, rotates the characters by the the integer rot and
returns the new string
"""
if type(rot) != int:
rot = int(rot)
# if text is not a string, return text
if type(text) is not str:
return text
# encrypt and return the new strin... | true |
5a25d8f5cf6f8bee0c6d43b8f591480946ed07a3 | SahRieCat/python | /02_basic_datatypes/2_strings/02_10_most_characters.py | 754 | 4.5625 | 5 | '''
Write a script that takes three strings from the user and prints them together with their length.
Example Output:
5, hello
5, world
9, greetings
CHALLENGE: Can you edit to script to print only the string with the most characters? You can look
into the topic "Conditionals" to solve this challenge.
'''... | true |
5d9540a605a97694b2b934181a11afb8c3361da6 | nkbyrne/scrap | /reusing_code/dice.py | 626 | 4.125 | 4 | #!/usr/bin/env python3
""" This will roll two dice and print out the values """
import sys
from random import randint
def rolldice():
print()
answer = input("Roll Dice? (y/n):")
if (answer == "y") or (answer == ""):
die01 = (randint(1, 6))
die02 = (randint(1, 6))
#print(("You roll... | false |
b3f95c536d87d27d1a37ec0df9e47050b2c0e0d3 | y0ssi10/leetcode | /python/symmetric_tree/solution.py | 1,338 | 4.28125 | 4 | # Problem
#
# Given a binary tree,
# check whether it is a mirror of itself (ie, symmetric around its center).
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
#
import queue
class TreeNode:
def __init__(self, x):
self.val = x
self.l... | true |
b7755ffbc6242a2098ff4a99d4623e24b7fc3d25 | y0ssi10/leetcode | /python/diameter_of_binary_tree/solution.py | 1,031 | 4.21875 | 4 | # Problem:
# Given a binary tree, you need to compute the length of the diameter of the tree.
# The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
# This path may or may not pass through the root.
#
# Note:
# The length of path between two nodes is represented b... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.