blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
12e5e732c419b74b89317f85d2a55fc440f93dde | kvguarin/Recursion-Examples | /lab8.py | 1,854 | 4.375 | 4 | def main():
#1test recursive printing
n = input("Enter a number: ")
rprint(int(n))
#2test recursive multiplication
x = input("Enter a number: ")
y = input("Enter a number: ")
print(rmultiplication(int(x), int(y)))
#3test out recursive lines
n = input("Enter a number: ")
rline... | false |
f9eb94c80dc1c3ecb13f02972c98c3f9f7a98adb | acode-pixel/YT_Tutorials | /Python/Password Generator/passwordgen.py | 938 | 4.4375 | 4 | import random
import string
import pyperclip # pip install pyperclip
# Alphabet, letters will be picked out of this randomly
alphabet = string.ascii_letters + string.digits + string.digits + string.punctuation
# Output password
password = ""
# Desired password length
password_length = 0
# Try to parse password ... | true |
0843641cd5ea25605cacc906a8ab988d83e20afb | kaiqinhuang/Python_hw | /lab8.py | 1,348 | 4.40625 | 4 | """
lab8.py
Name: Kaiqin Huang
Date: 1/17/2017
A module of functions count_merge(), count_as(), and split_evens().
"""
def count_merge(set1, set2):
'''Merges two sets and returns the length of the new set
Args:
set1 and set2: Two sets
Returns:
len: The l... | true |
08f51d0480b9941cb45193217932ed301858120e | broepke/GTx | /part_2/3.4.3_leap_year.py | 1,529 | 4.6875 | 5 | # A year is considered a leap year if it abides by the
# following rules:
#
# - Every 4th year IS a leap year, EXCEPT...
# - Every 100th year is NOT a leap year, EXCEPT...
# - Every 400th year IS a leap year.
#
# This starts at year 0. For example:
#
# - 1993 is not a leap year because it is not a multiple of 4.
# ... | true |
d230225cc9bbc3dbc9f78411744aae6a13d87b14 | broepke/GTx | /part_1/2.2.5_printing_variable_labels.py | 1,444 | 5.03125 | 5 | my_int1 = 1
my_int2 = 5
my_int3 = 9
# You may modify the lines of code above, but don't move them!
# When you Submit your code, we'll change these lines to
# assign different values to the variables.
#
# The code above creates three variables: my_int1, my_int2,
# and my_int3. Each will always be an integer
#
# Now, ad... | true |
c85f996ea4ff3b1e73c3a6b4714613206ef35cbe | broepke/GTx | /part_3/4.5.9_word_length.py | 2,263 | 4.21875 | 4 | # Recall last exercise that you wrote a function, word_lengths,
# which took in a string and returned a dictionary where each
# word of the string was mapped to an integer value of how
# long it was.
#
# This time, write a new function called length_words so that
# the returned dictionary maps an integer, the length of... | true |
37051b0a6dba88f6aab62a6a1d08e897ca8b71f1 | broepke/GTx | /final_problem_set/2_moon_moon.py | 2,828 | 4.625 | 5 | # A common meme on social media is the name generator. These
# are usually images where they map letters, months, days,
# etc. to parts of fictional names, and then based on your
# own name, birthday, etc., you determine your own.
#
# For example, here's one such image for "What's your
# superhero name?": https://i.img... | true |
1f76b2f5c2026de6f80747b54d5514580d7a02ab | broepke/GTx | /part_2/3.4.12_vowels_and_consonants.py | 1,615 | 4.40625 | 4 | # In this problem, your goal is to write a function that can
# either count all the vowels in a string or all the consonants
# in a string.
#
# Call this function count_letters. It should have two
# parameters: the string in which to search, and a boolean
# called find_consonants. If find_consonants is True, then the
#... | true |
f4d20669a86ca333aab2533c2009c25f9648ae00 | broepke/GTx | /part_2/3.4.8_bood_pressure.py | 1,425 | 4.21875 | 4 | # Consult this blood pressures chart: http://bit.ly/2CloACs
#
# Write a function called check_blood_pressure that takes two
# parameters: a systolic blood pressure and a diastolic blood
# pressure, in that order. Your function should return "Low",
# "Ideal", "Pre-high", or "High" -- whichever corresponds to
# the given... | true |
075ecb060a7f0b6d9cd8fa05d7da73768e32f604 | broepke/GTx | /part_2/3.4.6_ideal_gas_law_2.py | 1,539 | 4.1875 | 4 | # Last problem, we wrote a function that calculated pressure
# given number of moles, temperature, and volume. We told you
# to assume a value of 0.082057 for R. This value means that
# pressure must be given in atm, or atmospheres, one of the
# common units of measurement for pressure.
#
# atm is the most common unit ... | true |
2cfa42ff4415d16c64e6472d5e77a3e44a2b128f | broepke/GTx | /part_1/2.4.3_tip_tax_calculator.py | 1,426 | 4.28125 | 4 | meal_cost = 10.00
tax_rate = 0.08
tip_rate = 0.20
# You may modify the lines of code above, but don't move them!
# When you Submit your code, we'll change these lines to
# assign different values to the variables.
# When eating at a restaurant in the United States, it's
# customary to have two percentage-based surcha... | true |
695f060a489383010787ba21a5b912dfd98ab83e | broepke/GTx | /part_4/5.2.6_binary.py | 2,311 | 4.53125 | 5 | # Recall in Worked Example 5.2.5 that we showed you the code
# for two versions of binary_search: one using recursion, one
# using loops. For this problem, use the recursive one.
#
# In this problem, we want to implement a new version of
# binary_search, called binary_search_year. binary_search_year
# will take in two ... | true |
81362c17cae57d883a967c67f3f9139a59e26b9a | anthonyz98/Python-Challenges | /Chapter 9 - Challenge 9-14.py | 539 | 4.125 | 4 | from random import randint # This is what helps me to create a random generator
class Die:
def roll_die(self, number_of_sides):
for number in range(10):
random_number = randint(1, number_of_sides)
if number < 10:
print("The first few choices were: " + str(random_... | true |
f48fff4737b10860529bd8f50efc880819793896 | jn7163/pyinaction | /lesson10/reporting_scores_final.py | 2,522 | 4.25 | 4 | '''
分数处理程序最终版
文本格式如下
学号,姓名,语文,数学,英语
1,王小明,100,88,90
2,李思思,90,70,85
3,刘畅,88,78,92
'''
class ClassRoom:
def __init__(self, name):
self.name = name
self.students = []
self.lessons = []
def __str__(self):
return '班级: {}'.format(self.name)
def add_student(... | false |
0f5c6af7067abf2be115a148e4943a419029b725 | snwalchemist/Python-Exercises | /Strings.py | 2,991 | 4.25 | 4 | long_string = '''
WOW
O O
---
|||
'''
print(long_string)
first_name = 'Seth'
last_name = 'Hahn'
# string concatenation (only works with strings, can't mix)
full_name = first_name + ' ' + last_name
print(full_name)
#TYPE CONVERSION
#str is a built in function
#coverting integer to string and checking type
print(type(... | true |
c85a823c75350ae4e867cdf035fa786d108e6ae7 | alephist/edabit-coding-challenges | /python/odd_or_even_string.py | 233 | 4.21875 | 4 | """
Is the String Odd or Even?
Given a string, return True if its length is even or False if the length is odd.
https://edabit.com/challenge/YEwPHzQ5XJCafCQmE
"""
def odd_or_even(word: str) -> True:
return len(word) % 2 == 0
| true |
7214521f443d6bc968cc44a96693a14ef9570085 | alephist/edabit-coding-challenges | /python/give_me_even_numbers.py | 387 | 4.15625 | 4 | """
Give Me the Even Numbers
Create a function that takes two parameters (start, stop), and returns the sum of all even numbers in the range.
Notes
Remember that the start and stop values are inclusive.
https://edabit.com/challenge/b4fsyhyiRptsBzhcm
"""
def sum_even_nums_in_range(start: int, stop: int) -> int:
... | true |
b2b884acb6b2556429015f0aeb153895a9242681 | alephist/edabit-coding-challenges | /python/sweetest_ice_cream.py | 1,047 | 4.25 | 4 | """
The Sweetest Ice Cream
Create a function which takes a list of objects from the class IceCream and returns the sweetness value of the sweetest icecream.
Each sprinkle has a sweetness value of 1
Check below for the sweetness values of the different flavors.
Flavors Sweetness Value
Plain 0
Vanilla 5
ChocolateChip ... | true |
4e10af8ac9c4715985095b319e82135c0d25f4ba | alephist/edabit-coding-challenges | /python/name_classes.py | 936 | 4.34375 | 4 | """
Name Classes
Write a class called Name and create the following attributes given a first name and last name (as fname and lname):
An attribute called fullname which returns the first and last names.
A attribute called initials which returns the first letters of the first and last name. Put a . between the two lett... | true |
1ef5f82d753596c3bab615f1a8e03b7c3a6cef95 | alephist/edabit-coding-challenges | /python/longest_word.py | 400 | 4.28125 | 4 | """
Longest Word
Write a function that finds the longest word in a sentence. If two or more words are found, return the first longest word. Characters such as apostophe, comma, period (and the like) count as part of the word (e.g. O'Connor is 8 characters long).
https://edabit.com/challenge/Aw2QK8vHY7Xk8Keto
"""
de... | true |
f9a0aaf41836d4b08beccc61fa560cc8a908daa4 | alephist/edabit-coding-challenges | /python/factorize_number.py | 291 | 4.1875 | 4 | """
Factorize a Number
Create a function that takes a number as its argument and returns a list of all its factors.
https://edabit.com/challenge/dSbdxuapwsRQQPuC6
"""
from typing import List
def factorize(num: int) -> List[int]:
return [x for x in range(1, num + 1) if num % x == 0]
| true |
2b3dfc742dbb00d5a3e1371026f1ed677cf70494 | alephist/edabit-coding-challenges | /python/summing_squares.py | 270 | 4.15625 | 4 | """
Summing the Squares
Create a function that takes a number n and returns the sum of all square numbers up to and including n.
https://edabit.com/challenge/aqDGJxTYCx7XWyPKc
"""
def squares_sum(n: int) -> int:
return sum([num ** 2 for num in range(1, n + 1)])
| true |
4427e2e6710c395ef38c7b7c255346c2e7b1b2ca | bgescami/CIS-2348 | /Homework 2/Zylabs7.25.py | 2,970 | 4.28125 | 4 | # Brandon Escamilla PSID: 1823960
#
# Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line.
# The coin types are dollars, quarters, dimes, nickels, and pennies. Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies... | true |
138d341c3b3cab8f6cc5a21f379137c42032d202 | xiaoahang/teresa | /python_exercise_solutions/lab3/soln_lab3_sec1.py | 943 | 4.1875 | 4 |
###########################
# Factorial
def factorial(n):
fact = 1
while n > 1:
fact = fact * n
n = n - 1
return fact
###########################
# Guessing Game
from random import randint # import statements should really be at top of file
def guess(attempts,numrange):
number = ran... | true |
9c38f0a0fd982e5cfbe1c52313c58d1dcbfbc527 | uzzal408/learning_python | /basic/list.py | 978 | 4.21875 | 4 | #asigning list
list1 = ['apple','banana','orange','mango','blackberry']
print(type(list1))
print(list1)
#get length of a list
print(len(list1))
#create a list using list constructor
list2 = list(('Juice','ice-cream',True,'43'))
#accessing list
print(list2[0])
#negetive indexing
print(list2[-1])
#Range of index
pr... | true |
0fe6b610f1ca3c349a9eea94e9c52b6d2bf10b41 | uzzal408/learning_python | /basic/lambda.py | 435 | 4.34375 | 4 | #A lambda function is a small anonymous function.
#A lambda function can take any number of arguments, but can only have one expression
x = lambda a:a*10
print(x(5))
#Multiply argument a with argument b and return the result
y = lambda a,b,c:a+b+c
print(y(10,15,5))
#Example of lambda inside function
def my_func(n):... | true |
aa242b4c078deaa804e459013c657d3672988272 | AlexBarbash0118/02_Area_Perim_Calc | /03_perim_area_calculator.py | 875 | 4.4375 | 4 | # functions go here
# checks if input is a number more than zero
def num_check(question):
valid = False
while not valid:
error = "Please enter a number that is more than zero"
try:
response = float(input(question))
if response > 0:
retu... | true |
781712626c80e2ee3cfe2663c511ba45eed66b23 | DmitrievaOlga/Python_lab | /Task_1.py | 581 | 4.1875 | 4 | number = int(input('Введите число '))
border_number = int(input('Введите пограничное число '))
if number < border_number:
print('Ваше число меньше пограничного')
elif number > border_number:
if number/border_number > 3:
print('Ваше число больше пограничного более, чем в три раза')
else:
... | false |
a6bb292e99bf1955a2592bc00fa4b11e31238725 | Lindaxu88/lab1-python | /main.py | 551 | 4.40625 | 4 | #Author: Yeman Xu ybx5148@psu.edu
#Collaborator: Shiao Zhuang sqz5328@psu.edu
#Collaborator: Zhihong Jiang zbj5088@psu.edu
temperature = input ("Enter temperature: ")
Ftemperature = float(temperature)
unit = input("Enter unit in F/f or C/c: ")
if unit == "c" or unit == "C":
print(str(temperature) + "°" + " in Celsiu... | false |
051cd729f80322625ba31db19e952ae904e15d68 | kodfactory/AdvayaGameDev | /LambdaFunction.py | 624 | 4.1875 | 4 |
# def sum(a,b):
# c = (a*2) + (b*2)
# return c
# sum(5,10)
# Lambda function: inline function or 1 liner function
# 3 -> 3**3
# def square(a):
# return a**2
# print(square(5))
# Syntax: lambda a : a**2
# x = lambda a : a**2
# print(x(10))
# Filter: What is filter in python?
# for i in listA:
# ... | false |
4e79db4cdeca3aec368c6d54c48b205af84fad0e | kodfactory/AdvayaGameDev | /SetExample.py | 1,343 | 4.21875 | 4 | # listB = [1,2,3]
# tupleA = (1,2,3,4,5)
# setA = {'test', 1, 2, 3, 4}
# Set? : It is used to remove duplicate values from collection and it's and unordered collection
# setA = {1,2,3,4,5,6,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,6,6,6,6,7,7,7}
# listA = [1,2,2,2,2,2,2,3,3,3,3,3,3,4,5,6,7,8,8,8]
# li... | true |
020edcdb427275c281acb7bbbcc1246424a3997f | ChristopherSClosser/python-data-structures | /src/stack.py | 1,007 | 4.125 | 4 | """Implementation of a stack."""
from linked_list import LinkedList
class Stack(object):
"""Class for a stack."""
def __init__(self, iterable=None):
"""Function to create an instance of a stack."""
self.length = 0
self._stack = LinkedList()
self.top = None
if isinstan... | true |
d037f7008e387b29a4ed7eb9a45c773340b286cc | pshappyyou/CodingDojang | /SalesbyMatch.py | 1,405 | 4.15625 | 4 | # There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
# Example
# There is one pair of color and one of color . There are three odd socks left, one of each color. The number of ... | true |
78901929ac5489a5c87506dd1e9a0289d0e7cdf8 | pshappyyou/CodingDojang | /LeetCode/ConvertNumbertoList.py | 249 | 4.1875 | 4 | num = -2019
# printing number
print ("The original number is " + str(num))
# using list comprehension
# to convert number to list of integers
res = [int(x) for x in str(num)]
# printing result
print ("The list from number is " + str(res)) | true |
e7e6f6f920cac9d89420df579892dc4e96cfa8ef | 4ug-aug/hangman | /game | 2,205 | 4.3125 | 4 | #! /usr/bin/env python3
#! python3
# a program to pick a random word and letting the player guess the word, uses a dictionary to replace 0'es in the word to print
import random
from nltk.corpus import words
word_list = words.words()
# Get desired level, assign variables to levels and assign a variable to the dictiona... | true |
7519d41fb031a20c15612d4a57c9dc9d1fa43697 | Anknoit/PyProjects | /OOPS PYTHON/OOPS_python.py | 2,128 | 4.3125 | 4 | #What is OOPS - Coding of objects that are used in your project numerous times so we code it one time by creating class and use it in different parts of project
class Employee: #Class is a template that contains info that You can use in different context without making it everytime
#These are class variables
... | true |
9ffb92983051919884f5953a1f593b6ce7ac033c | Code141421425/pyPractise | /16_格式时间输出.py | 2,062 | 4.28125 | 4 | #https://www.runoob.com/python/python-exercise-example16.html
#输出指定格式的日期。
##分析
#以前写过:
#就是以一个python相关的时间模块,提取当时具体的年,月,日,时,分,秒进行
#然后就可以随意输出了
#程序规模:随便写
import datetime
year = datetime.datetime.now().year
month = datetime.datetime.now().month
day = datetime.datetime.now().day
hour =datetime.datetime.now().hour
minute =d... | false |
a4c287127286484047e854a7342cd8f79eae0a19 | Code141421425/pyPractise | /24_求数列前20项和.py | 2,630 | 4.28125 | 4 | #https://www.runoob.com/python/python-exercise-example24.html
#有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
#
#分析:
# 总述:看到这题第一个反应,就是分子分母分别存在一个数组里求前n项和,
# 然后在通过一个合成函数将这两个数组合并起来,求和
# 不过问题是合并的时候,肯定是除完之后,用一个小数相加,这样势必会对精准度造成影响。如果求前n项和的最大公约数分母,又会非常复杂1
# 不过想想也可以看看有没有分数相关的函数库支撑一下
# 查了一下,有个fractio... | false |
6d11be7b10ff8034ebe0edd99273c64104d9412f | amisha1garg/Arrays_In_Python | /BinaryArraySorting.py | 1,188 | 4.28125 | 4 | # Given a binary array A[] of size N. The task is to arrange the array in increasing order.
#
# Note: The binary array contains only 0 and 1.
#
# Example 1:
#
# Input:
# N = 5
# A[] = {1,0,1,1,0}
# Output: 0 0 1 1 1
# User function Template for python3
'''
arr: List of integers denoting the input array
... | true |
a8cf5626cfd591b015537d963deb9dd08e5657eb | sanpadhy/GITSOURCE | /src/Datastructure/BinaryTree/DC247/solution.py | 841 | 4.1875 | 4 | # Given a binary tree, determine whether or not it is height-balanced. A height-balanced binary tree can
# be defined as one in which the heights of the two subtrees of any node never differ by more than one.
class node:
def __init__(self, key):
self.left = None
self.right = None
def heightofTr... | true |
1478c759eba3c8ab035955abfd78e2c05f9fe706 | bgenchel/practice | /HackerRank/MachineLearning/CorrelationAndRegressionLinesQuickRecap2.py | 1,414 | 4.4375 | 4 | """
Here are the test scores of 10 students in physics and history:
Physics Scores 15 12 8 8 7 7 7 6 5 3
History Scores 10 25 17 11 13 17 20 13 9 15
Compute the slope of the line of regression obtained while treating Physics as the independent variable. Compute the answer correct to three d... | true |
07983f3a2a0469f5aebbc056e1bd5dd7cf1f3d37 | ivanwakeup/algorithms | /algorithms/prep/ctci/8.2_robot_in_grid.py | 2,076 | 4.46875 | 4 | '''
Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can only move in two directions, right and down, but certain cells are "off limits" such that
the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to
the bottom... | true |
c9686fbbd56e64d04af916d2669aeaed445ef8b3 | ivanwakeup/algorithms | /algorithms/binary_search/find_num_rotations.py | 1,189 | 4.1875 | 4 | '''
given a rotated sorted array, find the number of times the array is rotated!
ex:
arr = [8,9,10,2,5,6] ans = rotated 3 times
arr = [2,5,6,8,9,10] ans = rotated 0 times
intuition:
if the array is sorted (but rotated some number of times), we will have 1 element that is less than both of its neighbors!
using this ... | true |
2cca77c1ac6730329cafbb23a02499ad0b02c48e | ivanwakeup/algorithms | /algorithms/data_structures/ivn_Queue.py | 1,087 | 4.3125 | 4 | class LinkedListQueue:
class Node:
def __init__(self, val):
self.val = val
self.next = None
def __init__(self):
self.head = None
self.cur = None
#you need the self.cur pointer (aka the "tail" pointer)
def enqueue(self, value):
if not self.head:
... | true |
b7bdee4bc45c3d4ec6e0d9a122f2b3f888669ecb | ivanwakeup/algorithms | /algorithms/prep/ctci/str_unique_chars.py | 498 | 4.125 | 4 | '''
want to use bit masking to determine if i've already seen a character before
my bit arrays_and_strings will be 26 bits long and represent whether i've seen the current character already
'''
def str_unique_chars(s):
bit_vector = 0
for char in s:
char_bit = ord(char) - ord('a')
mask = (1 << ch... | true |
35dd3ef835c6e0256b80dc62e69f02505749e604 | ivanwakeup/algorithms | /algorithms/greedy_and_backtracking/letter_tile_possibilites.py | 1,292 | 4.15625 | 4 | '''
You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make.
Example 1:
Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".
Example 2:
Input: "AAABBC"
Outpu... | true |
d6a029452757778866d432e9e3db3f08e20e3235 | ivanwakeup/algorithms | /algorithms/prep/microsoft/lexicographically_smallest_Str.py | 612 | 4.125 | 4 | '''
Lexicographically smallest string formed by removing at most one character.
Example 1:
Input: "abczd"
Output: "abcd"
"ddbfa" => "dbfa"
"abcd" => "abc"
"dcba" => "cba"
"dbca" => "bca"
approach:
just remove the first character that we find that appears later in the alphabet than the char after it.
'''
def lexic... | true |
0c45d4bec9078117031e2983bd1322d3ccea2405 | uyiekpen/python-assignment | /range.py | 538 | 4.40625 | 4 | #write a program that print the highest number from this range [2,8,0,6,16,14,1]
# using the sort nethod to print the highest number in a list
#declaring a variable to hold the range of value
number = [2,8,0,6,16,14,1]
number.sort()
#displaying the last element of the list
print("largest number in the list is:",number... | true |
372c35882c20d508444ea7f46529ac4565742829 | finddeniseonline/sea-c34-python.old | /students/JonathanStallings/session05/subclasses.py | 2,934 | 4.34375 | 4 | from __future__ import print_function
import sys
import traceback
# 4 Questions
def class_chaos():
"""What happens if I try something silly, like cyclical inheritance?"""
class Foo(Bar):
"""Set up class Foo"""
color = "red"
def __init__(self, x, y):
self.x = x
... | true |
2b215df8bea9bdc218cbee6a5a43bf9d6474a00e | finddeniseonline/sea-c34-python.old | /students/MeganSlater/session05/comprehensions.py | 783 | 4.40625 | 4 | """Question 1:
How can I use a list comprehension to generate
a mathmatical sequence?
"""
def cubes_by_four(num):
cubes = [x**3 for x in range(num) if x**3 % 4 == 0]
print cubes
cubes_by_four(50)
"""Question 2:
Can I use lambda to act as a filter for a list already
in existence?
"""
squares = [x**2 for x in ... | true |
8c4e39374ac2c5dc102fd452b5ac4c84249c38f2 | finddeniseonline/sea-c34-python.old | /students/PeterMadsen/session05/classes.py | 577 | 4.21875 | 4 | class TestClass(object):
"""
Can you overwrite the constructor function with one that
contains default values (as shown below the answer is NO)
The way you do it was a little confusing to me, and I hope
to spend more time on it soon.
"""
def __init__(self, x=1, y=2):
self.x = x
... | true |
6170427920af9ef1e1d424c9a8b903438a33a6f7 | finddeniseonline/sea-c34-python.old | /students/YIGU/session03/dictionaries.py | 1,647 | 4.4375 | 4 | # Dictionaries and Sets questions
def q1():
"""What happen when I have the same keys in a dict?"""
q1 = {1: 1, 2: 2, 1: 3}
print q1[1]
print q1
# Anwser: the key get overwrite
# 3
# {1: 3, 2: 2}
q1()
def q2():
"""Can I have dict inside of dict?"""
q2 = {1: {'key1': 'a', 'key2': ... | false |
48ef5affa92f8cc375610ecbe14852eef5aa40b4 | Vahid-Esmaeelzadeh/CTCI-Python | /Chapter3/Q3_1.py | 1,713 | 4.125 | 4 | '''
Three in One: Describe how you could use a single array to implement three stacks.
'''
# region fixed-size
class fixedMultiStack:
def __init__(self, stackSize: int):
self.numberOfStacks = 3
self.stackCapacity = stackSize
self.values = [None for _ in range(stackSize * self.numberOfStack... | true |
38fa747ccf995ee04a0aa5e771b85882e03daed1 | Vahid-Esmaeelzadeh/CTCI-Python | /Chapter8/Q8_2.py | 2,495 | 4.25 | 4 | '''
Robot in a Grid: Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can only move in two directions, right and down, but certain cells are "off limits"such that
the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to
the bottom ... | true |
ef29d4ff21ae527067dddfc8d8de956102d6dccf | Vahid-Esmaeelzadeh/CTCI-Python | /Chapter3/Q3_4.py | 1,258 | 4.21875 | 4 | '''
Queue via Stack: Implement a MyQueue class which implements a queue using two stacks.
'''
class stackQueue:
def __init__(self, capacity):
self.capacity = capacity
self.pushStack = []
self.popStack = []
def add(self, val):
if self.isFull():
print("The stackQueue... | true |
fba8aca7b4a8ecaac6249ef3196599f404bf2194 | zhangsong1417/xx | /nested.py | 213 | 4.125 | 4 | nested = [[1,2],[3,4],[5]]
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
for num in flatten(nested):
print(num)
print(list(flatten(nested))) | false |
94014789fe3a5e8d575dfe704cd5ed21fac51d60 | Ompragash/python-ex... | /HCF_of_a_given_number.py | 407 | 4.21875 | 4 | #Python Program to find H.C.F of a given number
def compute(x, y):
if x < y:
smaller = x
else:
smaller = y
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the sec... | true |
1ad981e7d96940aedadaeb8f229916923b489054 | Ompragash/python-ex... | /Fibonacci.py | 393 | 4.375 | 4 | #Python program to find the fibonacci of a given number
nterm = eval(input("Enter the number: "))
a, b = 0, 1
if nterm <= 0:
print("Please enter a positive number")
elif nterm == 1:
print("Fibonacci sequence upto",nterm,":")
print(a)
else:
print("Fibonacci sequence upto",nterm,":")
while a < nt... | true |
ecacc443035b003d0f728d9b3dc49b453aceb32b | GyutaeSon/hello-world | /noc_09.py | 1,383 | 4.25 | 4 | #スペースで区切られた単語列に対して,各単語の先頭と末尾の文字は残し,
# それ以外の文字の順序をランダムに並び替えるプログラムを作成せよ.
# ただし,長さが4以下の単語は並び替えないこととする.
# 適当な英語の文(例えば”I couldn’t believe that I could actually
# understand what I was reading : the phenomenal power of the human mind .”)を与え,
# その実行結果を確認せよ
#ランダム
import random
def narabi(bun) :
#文字列をスペースで区切ってリスト化
wa... | false |
332dd9a117679d63899f56acb6699d00948e104f | jadentheprogrammer06/lessons-self-taught-programmer | /ObjectOrientedProgramming/ch14moar_oop/square_list.py | 652 | 4.21875 | 4 | # we are creating a square_list class variable. An item gets appended to this class variable list every time a Square object gets created.
class Square():
square_list = []
def __init__(self, name, sidelength):
self.name = name
self.sl = sidelength
self.slstr = str(self.sl)
self.... | true |
896f1909793a98e532b0bfbfa90e645af68819ff | jadentheprogrammer06/lessons-self-taught-programmer | /IntroToProgramming/ch4questions_functions/numsquare.py | 312 | 4.125 | 4 |
def numsquared():
'''
asks user for input of integer number.
returns that integer squared.
'''
while 1 > 0:
try:
i = int(input('what number would you like to square? >>> '))
return i**2
except (ZeroDivisionError, ValueError):
print('Invalid Input, sir. Please try again')
print(numsquared())
| true |
8a7daf6d4675b3be76e8b1457087b7cf728f59e1 | blissfulwolf/code | /hungry.py | 338 | 4.125 | 4 | hungry = input("are you hungry")
if hungry=="yes":
print("eat burger")
print("eat pizza")
print("eat fries")
else:
thirsty=input("are you thirsty?")
if thirsty=="yes":
print("drink water")
print("drink soda")
else:
tired=input("are you tired")
if tired=="yes":
print... | true |
515e10e395e15408b7552d46d53e95d690aea87a | xuetingandyang/leetcode | /quoraOA/numOfEvenDigit.py | 545 | 4.125 | 4 | from typing import List
class Solution:
def numEvenDigit(self, nums:List[int]) -> int:
"""
Find how many numbers have even digit in a list.
Ex.
Input: A = [12, 3, 5, 3456]
Output: 2
Sol.
Use a for loop
"""
count = 0
for num in nums:
... | true |
2ce8e58e240f67128711f9c3f345cc5e867d3abd | CdtDelta/YOP | /yop-week3.py | 917 | 4.15625 | 4 | # This is a script to generate a random number
# and then convert it to binary and hex values
#
# Licensed under the GPL
# http://www.gnu.org/copyleft/gpl.html
#
# Version 1.0
# Tom Yarrish
import random
# This function is going to generate a random number from 1-255, and then
# return the decimal,along with the corr... | true |
881419414edbdc56e6b5a20db9766c19d5540643 | BJahanyar/Data_Mining_Exercises | /2) Class_Excerise/EX_02/EX_05.py | 1,100 | 4.21875 | 4 | Row = int(input("Please Enter Row Number:")) #تعداد درایه های یک سطر را بگیر
Col = int(input("Please Enter Col Number:")) #تعداد درایه های یک ستون را بگیر
Main = [] #یک آرایه برای نگهداری ماتریس ایجاد کن
for i in range(Row): #حلقه را تا کمتر از عدد سطر تکرار کن
TempRow = [] # یک آرایه برای نگه داری سطر ایجاد کن
... | false |
6ae9b4424765d3a40efa4499ea723fbcf802a5ad | EngiBarnaby/Geekbrains_Practice | /Lesson_3/Task_3.py | 496 | 4.40625 | 4 | """
3. Реализовать функцию my_func(),
которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
"""
def my_func(num1, num2, num3):
sort_nums = (sorted((num1, num2, num3)))
return sort_nums[-1] + sort_nums[-2]
print(my_func(int(input("Введите число: ")), int(input("Введите чи... | false |
dd9d5cd2d32fb92c288624ded6f3fc678f6491c2 | EngiBarnaby/Geekbrains_Practice | /Lesson_3/Task_1.py | 628 | 4.1875 | 4 | """
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
"""
def my_func(num_1, num_2):
try:
res = num_1 / num_2
print(res)
except ZeroDivisionError:
print("Де... | false |
2135c333157d201c6a62a194fd6867ca853d1ce7 | nakednamor/naked-python | /samples/dictionary.py | 575 | 4.3125 | 4 | # a Java.Map equivalent in Python is called 'Dictionary'
my_dict = {'some-key' : 'some-value', 'another-key' : 'another-value'}
print(my_dict)
# get the value by key using brackets
print(my_dict['another-key'])
# you can loop through all keys
for k in my_dict.keys():
print(k)
# ommiting .keys() loops also on ke... | false |
23a4519c0d8cdcb3ee96fb3aec1ce39f06786d24 | marilyn1nguyen/Love-Letter | /card.py | 2,696 | 4.3125 | 4 | #Represents a single playing card
class Card:
def __init__(self):
"""
Constructor for a card
name of card
rank of card
description of card
"""
self.name = ""
self.rank = 0
self.description = ""
def getName(self) -> str:
"""
... | true |
d4ca90349aec7b230c1bf3a23626c318a5ae4ae5 | AngelPerezRodriguezRodriguez/CYPAngelPRR | /libro/problemas_resueltos/capitulo3/3_08.py | 278 | 4.125 | 4 | num = int(input("Ingresa un número entero: "))
if num > 0:
while num != 1:
print(num)
if (-1) ** num > 0:
num = num / 2
else:
num = num * 3 + 1
print(num)
else:
print("Tienes que ingresar un número entero positivo")
| false |
d72b4aa2724dcbffa282f956563e814c3197f125 | AngelPerezRodriguezRodriguez/CYPAngelPRR | /Python/Listas/introListas.py | 1,086 | 4.5625 | 5 | print("###Listas")
lista = [] #Primera forma de representar una lista
lista2 = list() #Segunda forma de representar una lista
#Función constructor
print(lista)
print(lista2)
numeros = [2,5,6,8,5,6,3,9,1,9]
#Cada uno de elos elementos, al igual que los strings, están INDEXA... | false |
7af4cb1f0415adbcebf55ea3434d9e383303a6df | ask902/AndrewStep | /practice.py | 1,132 | 4.21875 | 4 | '''
Practice exercises for lesson 3 of beginner Python.
'''
# Level 1
# Ask the user if they are hungry
# If "yes": print "Let's get food!"
# If "no": print "Ok. Let's still get food!"
inp = input("Are you hungry? ")
if inp == "yes":
print("Lets get food")
elif inp == "no":
print("Ok,Lets still g... | true |
b1b6b2ec0a6dbf6c5c2615b4c85f2e6b46e4bf48 | INF1007-2021A/2021a-c01-ch4-exercices-naname1 | /exercice.py | 2,474 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def is_even_len(string: str) -> bool:
if((len(string) % 2) == 0):
return True
return False
def remove_third_char(string: str) -> str:
resultat = ""
for k in range(0, len(string)):
if k == 2:
continue
resultat += string... | false |
74ad71ebae96038fba59c54e75bd676c323e4dbe | hariharaselvam/python | /day3_regex/re1_sumof.py | 424 | 4.34375 | 4 | import re
print "Problem # 1 - regular expression"
print "The sum of numbers in a string"
s=raw_input("Enter a string with numbers ")
#pat=raw_input("Enter the patten : ")
pat=r"\b\d+\b"
list_of_numbers=re.findall(pat,s)
result=0
print list_of_numbers
for l in list_of_numbers:
result=result+float(l)
print "The given ... | true |
631942833993b241647c3c853987bcdf1150eeab | hariharaselvam/python | /day6_logics/nextprime.py | 400 | 4.21875 | 4 | def isprime(num):
for i in range(2,num):
if num % i ==0:
return False
return True
def nextprime(num):
num=num+1
while isprime(num)!= True:
num=num+1
return num
number=input("Enter a number : ")
if isprime(number):
print "The number ",number," is a prime"
else:
print "The number ",number," is not a prime... | true |
b996f6cf67a24047ffb3d6934b37e5acd76869e1 | PravinSelva5/OneMonth | /Python/my_math.py | 318 | 4.15625 | 4 | '''
+ plus
- minus
/ divide
* multiplication
% modulo
** exponents
< less than
> greater than
'''
print("what is the answer to life, the universe, and everything?", int((40 + 30 - 7) * 2 / 3))
print("Is it true that 5 * 2 > 3 * 4")
print(5 * 2 > 3 * 4)
print("What is 5 * 2?", 5 * 2)
print("What is 3 * 4?", 3 * 4) | false |
7321b3bc2e47878871a7ae29d87794c33b852211 | iot49/iot49 | /boards/esp32/libraries/lib/ranges.py | 656 | 4.1875 | 4 | def linrange(start, stop, n=10):
'''generator for n evenly spaced numbers from start to stop
Example:
>>> list(linrange(2, 7, 5))
[2.0, 3.25, 4.5, 5.75, 7.0]
'''
assert n > 0
step = (stop-start)/(n-1) if n>1 else 0
for i in range(n):
yield start + i * step
def logrange(start, ... | false |
72f2efd27f13893f6bd688f920b9f8ce0b49f84a | root-11/graph-theory | /tests/test_facility_location_problem.py | 1,231 | 4.21875 | 4 | from examples.graphs import london_underground
"""
The problem of deciding the exact place in a community where a school or a fire station should be located,
is classified as the facility location problem.
If the facility is a school, it is desirable to locate it so that the sum
of distances travelled by all members... | true |
8a31884880e53891dd239b99ce032f21edac2c8b | atlasbc/mit_6001x | /exercises/week3/oddTuples.py | 475 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 15:22:02 2017
@author: Atlas
"""
def oddTuples(aTup):
'''
aTup: a tuple
returns: tuple, every other element of aTup.
'''
# Your Code Here
tupplelist=[]
print("This is the length of tuple", len(aTup))
for i in range(len(aTup)):
... | true |
cfa4c33da903fc9bb86a278369d276635fab0ac4 | yuangaonyc/lynda_python | /up_n_running_with_py/date_time_n_datetime.py | 2,657 | 4.1875 | 4 | from datetime import date
from datetime import time
from datetime import datetime
def main():
# Date Objects
# get today's date
today = date.today()
print("Today's date is " + str(today))
# get individual components of today's date
print("Date Components: " + str(today.day) + " " + str(today.month) + " " + str(... | false |
8f19194bd265ecd11ea80e6c07601ba32ba79871 | 24gaurangi/Python-practice-scripts | /Capitalize.py | 581 | 4.40625 | 4 | '''
This program takes the input string and capitalizes first letter of every word in the string
'''
# Naive approach
def LetterCapitalize(str):
new_str=""
cc=False
for i in range(len(str)):
if i == 0:
new_str=new_str + str[i].upper()
elif str[i] == " ":
cc=True
... | true |
2682fe48af90b3441b789048b092ab00b4c45b57 | k4rm4/Python-Exercises | /esercizio27.py | 391 | 4.375 | 4 | #scrivi una funzione a cui passerai come parametro una stringa e ti restituirà
#una versione della stessa stringa al contrario (esempio "abcd" --> "dcba")
def reverse (stringa):
stringaReverse = ""
for i in range(len(stringa)-1,-1,-1):
stringaReverse = stringaReverse + stringa[i]
print(stringaRev... | false |
07ae78f4bf5326346ccd4ce4833b110369b963d4 | onestarYX/cogs18Project | /my_module/Stair.py | 2,834 | 4.46875 | 4 | """ The file which defines the Stair class"""
import pygame
class Stair(pygame.sprite.Sprite):
# The number of current stairs existed in the game
current_stairs = 0
color = 255, 255, 255
def __init__(self, pos, screen, speed = 10):
"""
Constructor for Stair objects
=====
... | true |
2b1a87af8a0346792ac0f2777d4d63929786819f | alaesbayji/atelier1-atelier2 | /ex1 Atelier2.py | 824 | 4.4375 | 4 |
#Exercice1 Atelier2
list1 = [3, 6, 9, 12, 15, 18, 21]
list2 = [4, 8, 12, 16, 20, 24, 28]
res = list() #declarer une liste vide
odd_elements = list1[1::2] #une liste qui commence par l'element de position 1 de la liste 1 et saute par 2
print("Element at odd-index positions from list one")
print(odd_elements)
ev... | false |
250b3ad85be16616693856b593611dd01b6d179a | anax32/pychain | /pychain/chain.py | 2,917 | 4.25 | 4 | """
Basic blockchain data-structure
A block is a dictionary object:
```
{
"data": <some byte sequence>,
"time": <timestamp>,
"prev": <previous block hash>
}
```
a blockchain is a sequence of blocks such that
the hash value of the previous block is used in
the definition of the current block hash,
in pseudocode... | true |
aef397049e77a5080a5530d9d100c62e5cd05049 | milfordn/Misc-OSU | /cs160/integration.py | 2,799 | 4.125 | 4 | def f1(x):
return 5*x**4+3*x**3-10*x+2;
def f2(x):
return x**2-10;
def f3(x):
return 40*x+5;
def f4(x):
return x**3;
def f5(x):
return 20*x**2+10*x-2;
# Main loop
while(True):
# get function from user (or quit, that's cool too)
fnSelect = input("Choose a function (1, 2, 3, 4, 5, other/quit): ")
selectedFn = "... | true |
d3c88dd9ea3d2223577142bfde8531a9c510f86c | J-Molenaar/Python_Projects | /02_Python_OOP/Bike.py | 778 | 4.1875 | 4 | class Bike(object):
def __init__(self, price, max_speed):
self.price = price
self.max_speed = max_speed
self.miles = 0
def displayInfo(self):
print self.price
print self.max_speed
print self.miles
def ride(self):
print "Riding"
self.miles += ... | true |
e904af6b143e0576e75e0a7854d7e89a03d0f8a8 | HeidiTran/py4e | /Chap4Ex6computePay.py | 440 | 4.125 | 4 | # Pay computation with time-and-a-half for over-time
try:
hours = int(input("Please enter hours: "))
rate_per_hour = float(input("Please enter rate per hour: "))
if hours > 40:
overtime_rate_per_hour = rate_per_hour * 1.5
print("Gross pay is: ", round(40*rate_per_hour + (hours-40)*overtime_rate_per_hour, 2... | true |
3d6d2f81aae823ee65c3b1d23cb0e72e6947bc1c | HeidiTran/py4e | /Chap8Ex6calMinMax.py | 509 | 4.34375 | 4 | # This program prompts the user for a list of
# numbers and prints out the maximum and minimum of the numbers at
# the end when the user enters “done”.
list_num = list()
while True:
num = input("Enter a number: ")
try:
list_num.append(float(num))
except:
if num == "done":
... | true |
2c4c06ef8427d8b44065ecd9f831957a89c62dd4 | PatchworkCookie/Programming-Problems | /listAlternator.py | 716 | 4.15625 | 4 | '''
Programming problems from the following blog-post:
https://www.shiftedup.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
Problem 2
Write a function that combines two lists by alternatingly taking elements. For example: given the two lists [a, b, c] and [... | true |
4bfa9cbe6169da66fc77958b327cfcec15d0593c | wook971215/p1_201611107 | /w6main(9).py | 384 | 4.125 | 4 | import turtle
wn=turtle.Screen()
print "Sum of Multiples of 3 or 5!"
begin=raw_input("input begin number:")
end=raw_input("input end number:")
begin=int(begin)
end=int(end)
def sumOfMultiplesOf3_5(begin,end):
sum=0
for i in range(begin,end):
if i%3==0 or i%5==0:
sum=sum+i
print sum... | true |
5d043bd427e0164684abb00dc1c2891305634955 | scifinet/Network_Automation | /Python/PracticePython/List_Overlap.py | 907 | 4.34375 | 4 | #!/usr/bin/env python
#"""TODO: Take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
#and write a program that returns a list that contains only the elements that
#are common between the lists (without duplicates). Make sure your pro... | true |
a4ab0332626eeeff5dbf28a1248837b87867a432 | GenerationTRS80/Kaggle | /Kaggle_Lessons/PythonCourse/StringAndDictionaries.py | 2,699 | 4.625 | 5 | # Exercises
hello = "hello\n\rworld"
print(hello)
# >> Strings are sequences
# Indexing
planet = 'Pluto'
print(planet[0])
# Last 3 characters and first 3 characters
print(planet[-3:])
print(planet[:3])
# char comprehesion loop
list = [char + '!' for char in planet]
print(list)
# String methonds
# ALL CAPS
strText... | true |
9b7dc58865cca2f5ee9a8a3877e4dcc2648dab7e | tigranmovsisyan123/introtopython | /week2/homework/problem2.py | 358 | 4.1875 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("text", type=str)
args = parser.parse_args()
odd = int(len(args.text)-1)
mid = int(odd/2)
mid_three = args.text[mid-1:mid+2]
new = args.text.replace(mid_three, mid_three.upper())
print("the old string", args.text)
print("middle three characters", m... | true |
c1a8c6c1307193d59b61ce5cf82cf9143fa94c5c | ayush1612/5th-Sem | /SL-lab/PythonTest/13NovQpaper/9/9.py | 1,230 | 4.4375 | 4 | if __name__ == "__main__": # this line is not necessary in this program (it depicts the main function)
# i) Create a dictionary
atomDict = {
'Na' : 'Sodium',
'K' : 'Potassium',
'Mn' : 'Manganese',
'Mg' : 'Magnesium',
'Li' : 'Lithium'
}
# ii) Adding unique and d... | true |
affa042743329e963d1b14e38af86e50221f96f6 | PedroEFLourenco/PythonExercises | /scripts/exercise6.py | 724 | 4.1875 | 4 | ''' My solution '''
eventualPalindrome = str(input("Give me a String so I can validate if it is a \
Palindrome: "))
i = 0
paliFlag = True
length = len(eventualPalindrome)
while(i < (length/2)):
if eventualPalindrome[i] != eventualPalindrome[length-1-i]:
print("Not a Palindrome")
paliFlag = False
... | true |
86d27e2e2c5cd7e54cb51b9d15a7ce58f5293293 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/Privileges.py | 2,064 | 4.375 | 4 | """9-8. Privileges:
Write a separate Privileges class . The class should have one
attribute, privileges, that stores a list of strings as described in Exercise 9-7 .
Move the show_privileges() method to this class . Make a Privileges instance
as an attribute in the Admin class . Create a new instance of Admin and... | true |
b2b2c5cbe0caaf832f392e52f0e69f260e4a99a2 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-8/8-9. Magicians.py | 379 | 4.15625 | 4 | """ Practica 8-9 - Magicians
Make a list of magician’s names.
Pass the list to a function called show_magicians(),
which prints the name of each magician in the list ."""
def show_messages(mensaje):
for mensaje in mensaje:
print(mensaje)
mensaje = ["Hola soy el mensaje 1", "Hi i am the message ... | true |
33b1739dad1c8aaeb59570ab8a93dcc160815965 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/práctica-2/capítulo-9/OrderedDict Rewrite.py | 1,151 | 4.3125 | 4 | """9-13. OrderedDict Rewrite:
Start with Exercise 6-4 (page 108), where you
used a standard dictionary to represent a glossary. Rewrite the program using
the OrderedDict class and make sure the order of the output matches the order
in which key-value pairs were added to the dictionary."""
from collections impo... | true |
d2f6058cdbe98127e39ccf57a52ef1fea06273a6 | AnhellO/DAS_Sistemas | /Ene-Jun-2022/jesus-raul-alvarado-torres/Practica-5/E1.py | 962 | 4.125 | 4 | from abc import ABC, abstractmethod
class Poligono(ABC):
@abstractmethod
def Num_lados(self):
pass
###Sobrescribiendo el método abstracto Num_lados para los siguientes tipos de figuras:
class Triangulo(Poligono): # Triángulo
def Num_lados(self):
lados = 3
retur... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.