blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0ac565e0d4d3b948dcf0d8767039d6ccb2d9f71d | Tabsdrisbidmamul/PythonBasic | /Chapter_10_files_and_exceptions/04 guest_book.py | 448 | 4.1875 | 4 | # program that asks the user name, once entered print a prompt to say it was
# accepted and append the string onto the file
filename = 'programming.txt'
while True:
userName = str(input('What is your name? '))
print('Welcome ', userName)
with open(filename, 'a') as file_object:
# the \n is required, as the write... | true |
3c5b8e6838f2ebead83149f9e35c12f3c7a9b96c | Tabsdrisbidmamul/PythonBasic | /Chapter_7_user_inputs_and_while_loops/08 dream_vacation.py | 819 | 4.28125 | 4 | # set an empty dictionary to be filled up with polling later
responses = {}
# make a flag set to true
polling_active = True
while polling_active:
# prompt for user's name and their destination
name = input('\nWhat is your name: ')
dream_vacation = input('What place is your dream vacation? ')
# store ... | true |
24c95a3ab3e6b6e6a6cfa4ab1fbfc0f43dbf9409 | GudjonGunnarsson/python-challenges | /codingbat/warmup1/9_not_string.py | 884 | 4.40625 | 4 | #!/usr/bin/python3
""" This challenge is as follows:
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.
Expected Results:
'candy' -> 'not candy'
'x' -> 'not x'
'n... | true |
915deca3aed8bb835c8d915589a91e5f02cf3f49 | DocAce/Euphemia | /dicey.py | 2,108 | 4.1875 | 4 | from random import randint
def roll_die(sides):
return randint(1, sides)
def flip_coin():
if randint(0, 1) == 0:
return 'Heads'
else:
return 'Tails'
def generate_coin_flip_output(args):
numflips = 1
# just use the first number we find as the number of coins to flip
for arg in ... | true |
71adcc544a902e71d283a4ffefb069622b2a03c6 | vesteinnbjarna/Forritun_Vesteinn | /Lestrarverkefni/Kafli 2/simple_while.py | 251 | 4.15625 | 4 | #simple while
x_int = 0
#test loop-controled variable at the start
while x_int < 10:
print(x_int, end =' ') # print x_each time it loops
x_int = x_int + 1 # changing x_int while in loop
print ()
print ('Final value of x_int: ', x_int)
| true |
e5dbd401cbb63acdd259b185a02eeee98498734e | vesteinnbjarna/Forritun_Vesteinn | /Hlutapróf 2 undirbúningur/longest_word.py | 682 | 4.40625 | 4 |
def open_file(filename):
file_obj = open(filename, 'r')
return file_obj
def find_longest(file_object):
'''Return the longest word and its length found in the given file'''
max_length = 0
longest_word = ""
for word in file_object:
word = word.strip()
length = len(word)
... | true |
e9b16fba6e3a93f03f9e0b4950b9f3692f2a8cc8 | vesteinnbjarna/Forritun_Vesteinn | /Tímaverkefni/Assignment 12/Q4.py | 606 | 4.5 | 4 |
def merge_lists(first_list, second_list):
a_new_list = []
for element in first_list:
if element not in a_new_list:
a_new_list.append(element)
for element in second_list:
if element not in a_new_list:
a_new_list.append(element)
a_new_list = sorted(a_new_li... | true |
e0b0f0b3ec6cfe4adb826d78aadaf9496db112ad | vesteinnbjarna/Forritun_Vesteinn | /Tímaverkefni/Assignment 7/A7.5.py | 699 | 4.1875 | 4 |
import string
# palindrome function definition goes here
def is_palindrom (imported_string):
original_str = imported_string
modified_str = original_str.lower()
bad_chars = string.whitespace + string.punctuation
for char in modified_str:
if char in bad_chars:
modified_str = modi... | true |
17f31ab18c5d3f2d100c967bb88ca7b399d28278 | vesteinnbjarna/Forritun_Vesteinn | /Tímaverkefni/Assignment 7/A7.3.py | 353 | 4.15625 | 4 | # The function definition goes here
def is_num_in_range(number):
if number > 1 and number < 555:
answer = str(number) + " is in range."
else:
answer = str(number) + " is outside the range!"
return answer
num = int(input("Enter a number: "))
result = is_num_in_range(num)
print (resu... | true |
d4321a075f9540f36673bc598bfc9f1990598094 | vesteinnbjarna/Forritun_Vesteinn | /Skilaverkefni/Skilaverkefni 5/project.py | 1,683 | 4.5625 | 5 | # The program should scramble each word in the text.txt
# with the following instructions:
# 1.The first and last letter of each word are left unscrambled
# 2. If there is punctuation attached to a word it should be left unscrambled
# 3. The letter m should not be scrambled
# 4. The letters between the first an... | true |
c55af45dee5dd8861b67840741f798d791302b35 | AHoffm24/python | /Chapter2/classes.py | 999 | 4.40625 | 4 | #
# Example file for working with classes
#
#methods are functions in python
#self argument refers to the object itself. Self refers to the particular instance of the object being operated on
# class Person: #example of how to initalize a class with variables
# def __initialize__(self, name, age, sex):
# s... | true |
e22f5ff5265d5073eeac203c5a6c8e017babdf23 | rodrigo9000/PycharmProjects | /PlayingWithSeries/Mission3_RollTheDice.py | 513 | 4.34375 | 4 | # User should be able to enter how many dices he wants to roll: 1 ,2 or 3. He should pass this value as a parameter in the
# function RollTheDice(num). Dices should show random numbers from 1 to 6.
import random
def main():
def RollTheDice(num):
if num in [1, 2, 3]:
for turns in range(1, (num + ... | true |
b410db6a9ea07a05b7e80afad10bfed4a7d643b6 | 95subodh/Leetcode | /116. Populating Next Right Pointers in Each Node.py | 1,266 | 4.28125 | 4 | #Given a binary tree
#
#struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
#}
#pulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
#
#itially, all next pointers are set to NULL.
#
#te:
#
#u may only use c... | true |
93149f960c8b7d342dde0ea643b3977b3ae35bd3 | 95subodh/Leetcode | /326. Power of Three.py | 240 | 4.34375 | 4 | #Given an integer, write a function to determine if it is a power of three.
from math import *
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return True if n>0 and 3**20%n==0 else False | true |
33fa289bf90d66af8fb90cedcf7d52a4a3613baf | kphillips001/Edabit-Python-Code-Challenges | /usingternaryoperators.py | 380 | 4.34375 | 4 | # The ternary operator (sometimes called Conditional Expressions) in python is an alternative to the if... else... statement.
# It is written in the format:
# result_if_true if condition else result_if_false
# Ternary operators are often more compact than multi-line if statements, and are useful for simple conditiona... | true |
36a0f49179f1135a619d1d694fa71974e0ffb71b | jbulka/CS61A | /hw2_solns.py | 2,545 | 4.15625 | 4 | """Submission for 61A Homework 2.
Name:
Login:
Collaborators:
"""
# Q1: Done
def product(n, term):
"""Return the product of the first n terms in a sequence.
We will assume that the sequence's first term is 1.
term -- a function that takes one argument
"""
prod, k = 1, 1
while k <= n... | true |
215aed3bd3d66a69c49bc841e6dc9011cc8bf156 | QinmengLUAN/Daily_Python_Coding | /wk4_findNumbers.py | 860 | 4.28125 | 4 | """
1295. Find Numbers with Even Number of Digits
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digi... | true |
9261b5b8c174058a10632b6cbe2a580c0a5e9cba | QinmengLUAN/Daily_Python_Coding | /DailyProblem20_maximum_product_of_three.py | 651 | 4.375 | 4 | """
Hi, here's your problem today. This problem was recently asked by Microsoft:
You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array.
Example:
[-4, -4, 2, 8] should return 128 as the largest product can be made by
multiplying -4 * -4 * 8 = 128.
... | true |
99845dad934230a83a99d4e8ac1ab96b24cd0c3f | QinmengLUAN/Daily_Python_Coding | /DailyProblem19_findKthLargest.py | 653 | 4.125 | 4 | """
Hi, here's your problem today. This problem was recently asked by Facebook:
Given a list, find the k-th largest element in the list.
Input: list = [3, 5, 2, 4, 6, 8], k = 3
Output: 5
Here is a starting point:
def findKthLargest(nums, k):
# Fill this in.
print findKthLargest([3, 5, 2, 4, 6, 8], 3)
"""
import he... | true |
5ff35f6f7a920113cec07c88e253ad06a9bdcfec | QinmengLUAN/Daily_Python_Coding | /LC354_maxEnvelopes_DP.py | 2,042 | 4.40625 | 4 | """
354. Russian Doll Envelopes
Hard
You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.
What is the maximum number of envelopes... | true |
dc33830a1d3708345a5d77f6f9dfd86017137e31 | QinmengLUAN/Daily_Python_Coding | /wk2_sqrt.py | 609 | 4.125 | 4 | # Write a function to calculate the result (integer) of sqrt(num)
# Cannot use the build-in function
# Method: binary search
def my_sqrt(num):
left_boundary = 0
right_boundary = num
if num <= 0:
return False
elif num < 1:
return 0
elif num == 1:
return num
while (right_boundary - left_boundary) > 1:
m... | true |
7dab89ca1ef40d80b0ea0728cca5126bd021f291 | QinmengLUAN/Daily_Python_Coding | /wk2_MoeList.py | 1,106 | 4.28125 | 4 | # To understand object and data structure
# Example 1: https://www.w3schools.com/python/python_classes.asp
# Example 2: https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm
# write an object MyList with many methods: MyList, append, pop, print, node
class MyNode:
def __init__(self, value):
s... | true |
c48afae5e64ef91588c53ce962ea8c326a529d1b | QinmengLUAN/Daily_Python_Coding | /LC1189_maxNumberOfBalloons_String.py | 858 | 4.125 | 4 | """
1189. Maximum Number of Balloons
Easy: String, Counter, dictionary
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible.
You can use each character in text at most once. Return the maximum number of instances that can be formed.
Example 1:
... | true |
24b60cb185dcf1770906a0b042b297aa7ea0784b | QinmengLUAN/Daily_Python_Coding | /LC326_isPowerOfThree_Math.py | 420 | 4.25 | 4 | """
326. Power of Three
Easy: Math
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
"""
c... | true |
ea27a81da0146733e81e51b59fcb87622e5f8cea | QinmengLUAN/Daily_Python_Coding | /DailyProblem04_isValid_String.py | 1,649 | 4.21875 | 4 | """
Hi, here's your problem today. This problem was recently asked by Uber:
Leetcode 20
Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using s... | true |
7e4c89bc3812a0bf3707b3de2183ca661b693f3d | QinmengLUAN/Daily_Python_Coding | /LC207_canFinish_Graph.py | 2,214 | 4.1875 | 4 | """
207. Course Schedule
Medium: Graph
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prere... | true |
f27497e9a8acc603807d738e36b3937ad47f1b77 | NkStevo/daily-programmer | /challenge-003/intermediate/substitution_cipher.py | 1,260 | 4.125 | 4 | import json
def main():
with open('ciphertext.json') as json_file:
ciphertext = json.load(json_file)
print("----Substitution Cipher Program----")
choice = input("Input 1 to encode text and 2 to decode text:\n")
if choice == '1':
text = input("Input the text you would l... | true |
505816e71a2df217a36b6dc74ae814e40208b26d | zszinegh/PyConvert | /pyconvert/conversions.py | 1,068 | 4.375 | 4 | """A module to do various unit conversions.
This module's functions convert various units of measurement.
All functions expect a 'float' as an argument and return a 'float'.
'validate_input()' can be used before running any function to
convert the input to a 'float'.
"""
def validate_input(incoming):
"""Conve... | true |
82be926a6549078edf9b27ea2e56c0993d5e6b3a | isaiah1782-cmis/isaiah1782-cmis-cs2 | /Assignment_Guessing_Game.py | 950 | 4.25 | 4 | import math
import random
Minimum_Number = int(raw_input("What is the minimum number? "))
Maximum_Number = int(raw_input("What is the maximum number? "))
print "I'm thinking of a number from " + str(Minimum_Number) + " to " + str(Maximum_Number) + "."
Guess = str(raw_input("What do you think it is?: "))
def Correc... | true |
77069ee92fcb26ff76619058b379d05e8c177153 | kammariprasannalaxmi02/sdet | /python/Activity12.py | 264 | 4.21875 | 4 | #Write a recursive function to calculate the sum of numbers from 0 to 10
def calculate(i):
if i <= 1:
return i
else:
return i + calculate(i-1)
num = int(input("Enter a number: "))
print("The sum of numbers: ", calculate(num))
| true |
26343c2e7d1a57463b71faee58c204afd426b5b8 | noemiko/design_patterns | /factory/game_factory.py | 2,774 | 4.75 | 5 | # Abstract Factory
# The Abstract Factory design pattern is a generalization of Factory Method. Basically,
# an Abstract Factory is a (logical) group of Factory Methods, where each Factory
# Method is responsible for generating a different kind of object
# Frog game
class Frog:
def __init__(self, name):
... | true |
95a9f4e25127241ba07696dacca17dfe3740c930 | vladflore/py4e | /course3/week6/extract-data-json.py | 1,396 | 4.40625 | 4 | # In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The
# program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment
# counts from the JSON data, compute the sum of the numbers in the file and enter the sum... | true |
f7f87810b50c50b2828e2c404763cdb3f44b08a0 | alindsharmasimply/Python_Practice | /seventySecond.py | 307 | 4.21875 | 4 | def sumsum():
sum1 = 0
while True:
try:
a = input("Enter a valid number to get the sum ")
if a == ' ':
break
sum1 = sum1 + a
print sum1, "\n"
except Exception:
print "Enter a valid number only "
sumsum()
| true |
3a50f698d6a65fafa0c72bfc75b8ec175896b9d8 | SimonFromNeedham/Project_Euler_Problems | /euler16.py | 1,072 | 4.125 | 4 | # 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
# What is the sum of the digits of the number 2^1000?
# I'm aware that this approach is more complex than necessary and that I could just use a long to store the number,
# But I honestly find it a lot more interesting to work through the problem tryi... | true |
c0bdf60e9dd878b032e2372faf6babe022ee1201 | littlejoe1216/Daily-Python-Exercise-01 | /#1-Python-Daily-Exercise/Daily Exercise-1-02082018.py | 290 | 4.1875 | 4 | #Joe Gutierrez - Python Daily Exercise - 2/16/18
# 1. Write a statement that concatenates at least two variables (you can have more than 2 for this practice).
name = input('Enter First name:')
sna = input('Enter Last name:')
joe = name + sna
print ('Is your name ' + str(joe))
| true |
518087b3406afc65b712cee808f5849e98d40197 | palepriest/python-notes | /src/ex32.py | 635 | 4.1875 | 4 | # -*- coding:utf-8 -*-
t_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'bananas', 'Blueberries', 'oranges']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# print a integer list
for number in t_count:
print "The number is %d." % number
# print a string list
for fruit in fruits:
print "The fruit type is %s.... | true |
ca03996c06e344c39557e27a53fd7a4b8d243471 | Nasir1004/assigment-3-python-with-dahir | /lopping numbers from one to ten.py | 235 | 4.1875 | 4 | '''
numbers=1
for i in range (1,10):
print(i)
#this is example of for loop numbers from one to ten
'''
# the whileloop example is
current_number = 1
while current_number <=10:
print(current_number )
current_number += 1
| true |
db42b6acb7d451e412f58c2837e4d1c309a412dc | wbluke/python_dojang | /01_input_output.py | 649 | 4.15625 | 4 | # if you divide integer by integer, result is float.
num = 4 / 2
print(num) # 2.0
# convert float to int(int to float)
num = int(4/2)
print(num) # 2
num = float(1+3)
print(num) # 4.0
# delete variable
del num
# if you want to know class' type
print(type(3.3)) # <class 'float'>
# when save input data on variable... | true |
1c5ae131528b6e48953212686c066c5a9736a334 | brandonkbuchs/UWisc-Python-Projects | /latlon.py | 2,073 | 4.5 | 4 | # This program collects latitude and longitude inputs from the user and returns
# Information on the location of the quadrant of the coordinate provided
def latlon(latitude, longitude): # Defines function
# Latitude logic tests.
if latitude == 0: # Test if on equator
print "That location is on the ... | true |
659e981c2f135e1ae4e3db3d62d90d359c787e71 | 21eleven/leetcode-solutions | /python/0673_number_of_longest_increasing_subsequence/lsubseq.py | 1,203 | 4.125 | 4 | """
673. Number of Longest Increasing Subsequence
Medium
Given an integer array nums, return the number of longest increasing subsequences.
Example 1:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [2,2,2,2,2]
... | true |
6a52d60f15ef338e27b8c62ce8c034653c0a0f2f | 21eleven/leetcode-solutions | /python/0605_can_place_flowers/three_slot.py | 1,411 | 4.15625 | 4 | """
605. Can Place Flowers
Easy
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be... | true |
a3f61908d09cba128724d0d6a533c59075156091 | 21eleven/leetcode-solutions | /python/1631_path_with_minimum_effort/bfs_w_heap.py | 2,594 | 4.125 | 4 | """
1631. Path With Minimum Effort
Medium
You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, ... | true |
0790ccdc036798bf7ce9d542345f784dd6009d39 | makhmudislamov/leetcode_problems | /microsoft/arr_and_str/set_matrix_zeroes.py | 2,465 | 4.46875 | 4 | """
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
... | true |
27a566d6f5312cf2b427d42c1e542d53a1384c21 | makhmudislamov/leetcode_problems | /microsoft/arr_and_str/trapping_rain_water.py | 1,224 | 4.28125 | 4 | """
Given n non-negative integers representing an elevation map where the width of each bar is 1,
compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
In this case, 6 units of rain water (blue section) are being trapped.
Thanks Marcos f... | true |
ff83309a29010223b289355195fad25ac86d36c7 | karandevgan/Algorithms | /LargestNumber.py | 779 | 4.28125 | 4 | def compare(number, number_to_insert):
str_number_to_insert = str(number_to_insert)
str_number = str(number)
num1 = str_number + str_number_to_insert
num2 = str_number_to_insert + str_number
if num1 > num2:
return -1
elif num1 == num2:
return 0
else:
return 1
def la... | true |
6b3c9e414503f3b249e372f690c97e6f8cd52d78 | Keikoyao/learnpythonthehardway | /Ex20.py | 881 | 4.25 | 4 | # -- coding: utf-8 --
from sys import argv
script, input_file = argv
#read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中
def print_all(f):
print (f.read())
#seek() 移动文件读取指针到指定位置
def rewind(f):
f.seek(0)
#readline() will read the file line by line as if there is a for next loop automatically vs readlines()一次读取整个文件
def prin... | true |
33e1e11d95b94d22e1fc939c716cd8251d04b034 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex34 - Accessing Elements of Lists.py | 2,096 | 4.21875 | 4 | # Remember, if it says "first," "second," then it's using ORDINAL, so subtract 1.
# If it gives you CARDINAL, like "The animal at 1", then use it directly.
# Check later with Python to see if you were correct.
animal = ['bear','python3.7', 'peacock', 'kangaroo', 'whale', 'platypus']
# Q1. The animal at 1. ... | true |
2ffa957733ffcd46c2fd448b75f6bbe9c64043ec | TwoChill/Learning | /Learn Python 3 The Hard Way/ex32 - Loops and Lists.py | 1,770 | 4.5625 | 5 | hair = ['brown', 'blond', 'red']
eye = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print(f'This is c... | true |
545cbfef3ca36549f96c421a54fafc0c0c92d318 | TwoChill/Learning | /Learn Python 3 The Hard Way/ex15 - Reading Files.py | 1,845 | 4.625 | 5 | # This line imports the variable argument argv from the sys module.
from sys import argv
# These are the TWO command line arguments you MUST put in when running the script.
script, filename = argv
# This line opens the filename argument and puts it content in a variable.
txt = open(filename)
print("\n\nTHIS IS THE ... | true |
4c7fdd6fe35f53ac8a12e8b3a3c69a64e08b3b28 | cazzara/mycode | /random-stdlib/use-random.py | 2,112 | 4.65625 | 5 | #!/usr/bin/env python3
import random
## Create a random number generator object
# This can be used to instantiate multiple instances of PRNGs that are independent of one another and don't share state
r = random.Random()
## Seed random number generator
# This initializes the state of the PRNG, by default it uses the... | true |
8068f6de2b10e0d0673a0d96f8a62135223624f7 | cazzara/mycode | /if-test2/if-test2.py | 380 | 4.1875 | 4 | #!/usr/bin/env python3
# Author: Chris Azzara
# Purpose: Practice using if statements to test user input
ipchk = input("Set IP Address: ")
if ipchk == '192.168.70.1':
print("The IP Address was set as {}. That is the same as the Gateway, not recommended".format(ipchk))
elif ipchk:
print("The IP Address was se... | true |
5eca3115baaf3a1f4d09a92c3e8bef73b5e655e8 | cazzara/mycode | /datetime-stdlib/datetime-ex01.py | 931 | 4.28125 | 4 | from datetime import datetime # required to use datetime
## WRITE YOUR OWN CODE TO DO SOMETHING. ANYTHING.
# SUGGESTION: Replace with code to print a question to screen and collect data from user.
# MORE DIFFICULT -- Place the response(s) in a list & continue asking the question until the user enters the word 'quit'
... | true |
1ed15bd4d250bfc4fc373c26226f84f83c40cdcd | shishir7654/Python_program-basic | /listcomprehension1.py | 513 | 4.375 | 4 | odd_square = [x **2 for x in range(1,11) if x%2 ==1]
print(odd_square)
# for understanding, above generation is same as,
odd_square = []
for x in range(1, 11):
if x % 2 == 1:
odd_square.append(x**2)
print( odd_square)
# below list contains power of 2 from 1 to 8
power_of_2 = [2 ** x f... | true |
c084419e361233b87f85c9a688e29f6471376579 | brennanmcfarland/physics-class | /18-1a.py | 1,469 | 4.125 | 4 | import matplotlib.pyplot as plt
import math
def graphfunction(xmin,xmax,xres,function,*args):
"takes a given mathematical function and graphs it-how it works is not important"
x,y = [],[]
i=0
while xmin+i*xres<=xmax:
x.append(xmin+i*xres)
y.append(function(x[i],*args))
i+=1
... | true |
65a294810e1afc9d10fa24f84d8a4d60b5ec02c3 | jle33/PythonLearning | /PythonMasterCourse/PythonMasterCourse/GenetratorExample.py | 1,494 | 4.25 | 4 | import random
#Generator Example
def get_data():
"""Return 3 random integers between 0 and 9"""
print("At get_data()")
return random.sample(range(10), 3)
def consume():
"""Displays a running average across lists of integers sent to it"""
running_sum = 0
data_items_seen = 0
print("At top of ... | true |
218254f6a4c1152326423160bebdb9d8461d05a2 | jodaz/python-sandbox | /automate-boring-stuff-python/tablePrinter.py | 1,093 | 4.34375 | 4 | #! python3
# tablePrinter.py - Display a list of lists of strings in
# a well-organized table.
table_data = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table(main_arr):
col_widths = [0] * len(main_... | true |
b3bba5c4526cff24bd9b71a60aadddcf6e623228 | jodaz/python-sandbox | /automate-boring-stuff-python/strongPassword.py | 424 | 4.34375 | 4 | #! python3
# strongPassword.py - Find is your password is strong.
import re
password = input('Introduce your password: ')
find_upper = re.compile(r'[A-Z]').findall(password)
find_lower = re.compile(r'[a-z]').findall(password)
find_d = re.compile(r'\d').search(password)
if find_upper and find_lower and find_d and le... | true |
98f72a0486ba5cc22b42028c6bb0cd5e79ca2597 | Peterbamidele/PythonDeitelChapterOneExercise | /2.3 Fill in the missing code.py | 394 | 4.125 | 4 | """(Fill in the missing code) Replace *** in the following code with a statement that
will print a message like 'Congratulations! Your grade of 91 earns you an A in this
course' . Your statement should print the value stored in the variable grade :
if grade >= 90"""
#Solution
grade = 90
if grade >= 90:... | true |
201a2cbfa51168e159fae14bf438adb71c2b129e | cmdellinger/Code-Fights | /Interview Practice/01 Arrays/isCryptSolution.py | 1,213 | 4.1875 | 4 | """
Codefights: Interview Prep - isCryptSolution.py
Written by cmdellinger
This function checks a possible solution to a cryptarithm. Given a solution as a list of character pairs (ex. ['A', '1']), the solution is valid of word_1 + word_2 == word_3 once decoded.
See .md file for more information about cryptarithm... | true |
53bc1949d4d989f076e481341e6c52fffb549da4 | mayakota/KOTA_MAYA | /Semester_1/Lesson_05/5.01_ex_02.py | 655 | 4.15625 | 4 | height = float(input("What is your height?"))
weight = float(input("What is your weight?"))
BMI = 0
condition = "undetermined"
def calcBMI(height,weight):
global BMI,condition
BMI = (weight/height) * 703
if BMI < 18.5 :
condition = "condition is Underweight"
elif BMI < 24.9 :
condition... | true |
9bfca2db61d14c15064ed7c42e3bdeb6714de64c | mayakota/KOTA_MAYA | /Semester_1/Lesson_05/5.02_ex06.py | 559 | 4.25 | 4 | def recursion():
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if username == "username" and password == "password":
print("correct.")
else:
if password == "password":
print("Username is incorrect.")
recursio... | true |
bf23188fb3c90c34da9d2b64ba6aeed16d623fd1 | shashankgargnyu/algorithms | /Python/GreedyAlgorithms/greedy_algorithms.py | 1,920 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains Python implementations of greedy algorithms
from Intro to Algorithms (Cormen et al.).
The aim here is not efficient Python implementations
but to duplicate the pseudo-code in the book as closely as possible.
Also, since the goal is to help students ... | true |
8f2a974d5aa0eb91db1b2978ced812678e34f69f | LYoung-Hub/Algorithm-Data-Structure | /wordDictionary.py | 2,039 | 4.125 | 4 | class TrieNode(object):
def __init__(self):
self.cnt = 0
self.children = [None] * 26
self.end = False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word):
... | true |
cf90416b58d12338fb6c626109ef0ecf11c0807f | sravanneeli/Data-structures-Algorithms | /stack/parenthesis_matching.py | 888 | 4.125 | 4 | """
Parenthesis Matching: whether braces are matching in a string
"""
from stack.stack_class import Stack
bracket_dict = {')': '(', ']': '[', '}': '{'}
def is_balanced(exp):
"""
Check whether all the parenthesis are balanced are not
:param exp: expression in string format
:return: True or False
... | true |
db069f0bdb81b54b5ca7ab589fd8db33bff0368b | lajospajtek/thought-tracker.projecteuler | /p057.py | 1,097 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: Latin1 -*-
# Problem 057
#
# It is possible to show that the square root of two can be expressed as an infinite continued fraction.
#
# √ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
#
# By expanding this for the first four iterations, we get:
#
# 1 + 1/2 = 3/2 = 1.5
# 1 + 1/(2 + ... | true |
4e612bc6b0425b59d37e9341cd4bc8783a2f2bad | sauravgsh16/DataStructures_Algorithms | /g4g/ALGO/Searching/Coding_Problems/12_max_element_in_array_which_is_increasing_and_then_decreasing.py | 1,725 | 4.15625 | 4 | ''' Find the maximum element in an array which is first increasing and then decreasing '''
'''
Eg: arr = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1]
Output: 500
Linear Search:
We can search for the maximum element and once we come across an element less
than max, we break and return max
'''
'''
Bi... | true |
b820d08879eecae30d95bcaa221be073f71a22ad | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Search_Trees/Checking_and_Searching/RN_7_check_each_internal_node_has_exactly_1_child.py | 1,372 | 4.15625 | 4 | ''' Check if each internal node has only one child '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# In Preorder traversal, descendants (or Preorder successors) of every node
# appear after the node. In the above example, 20 is the first n... | true |
1507e2ab37a5f36e5ba8a20fd41acff2815e9fa8 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Checking_and_Printing/24_symmetric_tree_iterative.py | 1,250 | 4.28125 | 4 | ''' Check if the tree is a symmetric tree - Iterative '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def check_symmetric(root):
if not root:
return True
if not root.left and not root.right:
return True
... | true |
06354d4f46de16ca4d0162548992da2fe6061973 | sauravgsh16/DataStructures_Algorithms | /g4g/DS/Trees/Binary_Trees/Checking_and_Printing/26_find_middle_of_perfect_binary_tree.py | 900 | 4.15625 | 4 | ''' Find middle of a perfect binary tree without finding height '''
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
'''
Use two pointer slow and fast, like linked list
Move fast by 2 leaf nodes, and slow by one.
Once fast reaches leaf... | true |
748bccf48ef30c79bb9312e2d3be2c37c66cf459 | HarperHao/python | /mypython/第七章文件实验报告/001.py | 1,235 | 4.28125 | 4 | """统计指定文件夹大小以及文件和子文件夹数量"""
import os.path
totalSize = 0
fileNum = 0
dirNum = 0
def visitDir(path):
global totalSize
global fileNum
global dirNum
for lists in os.listdir(path):
sub_path = os.path.join(path, lists)
if os.path.isfile(sub_path):
fileNum = fileNum + 1
... | true |
6fecf6d2c96d29409c240b76a7a0844668b17594 | kalyanitech2021/codingpractice | /string/easy/prgm4.py | 701 | 4.25 | 4 | # Given a String S, reverse the string without reversing its individual words. Words are separated by dots.
# Example:
# Input:
# S = i.like.this.program.very.much
# Output: much.very.program.this.like.i
# Explanation: After reversing the whole
# string(not individual words), the input
# string becomes
# much... | true |
83b5224314c1eba5d985c0413b69960dc9c26c3a | pavel-malin/new_practices | /new_practice/decorators_practice/abc_decorators_meta.py | 654 | 4.1875 | 4 | ''' Using a subclass to extend the signature of its parent's abstract method
import abc
class BasePizza(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def get_ingredients(self):
"""Returns the ingredient list."""
class Calzone(BasePizza):
def get_ingredients(self, with_egg=False):
e... | true |
9216d686ad0deb206998db55005c4e4889c6332f | courtneyng/Intro-To-Python | /If-exercises/If-exercises.py | 681 | 4.125 | 4 | # Program ID: If-exercises
# Author: Courtney Ng, Jasmine Li
# Period 7
# Program Description: Using if statements
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November']
# months.append('December')
ans = input("Enter the name of a month: ")
i... | true |
2d1e08e74910d00f238f27b705b7196a35dacdf9 | courtneyng/Intro-To-Python | /Tuples_and_Lists/A_List_Of_Numbers.py | 1,727 | 4.28125 | 4 | # Program ID: A_List_Of_Numbers
# Author: Courtney Ng
# Period: 7
# Program Description: List extensions in Python
# numList = [1, 1, 2, 3, 5, 8, 11, 19, 30, 49]
# product = 30*8*11*19*30*49
num1 = int(input("Enter the first number."))
numList = [100, 101, 102]
numList.append(num1)
numList.remove(100)
numLi... | true |
b4a981c76af3be316f3b22b2c0d979bd7386e73c | courtneyng/Intro-To-Python | /Tuples_and_Lists/list_extensions.py | 797 | 4.34375 | 4 | # Program ID: lists_extensions
# Author: Courtney Ng
# Period: 7
# Program Description: List extensions in Python
# Given list
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
# The new list extensions test
fruits.count('apple')
print(fruits.count('apple')) # Added a print stateme... | true |
bcef00fbacb443c75b8a69a97c56d78924ce4d7d | pouya-mhb/University-Excersises-and-Projects | /Compiler Class/prefix suffix substring proper prefix subsequence/substring of a string.py | 454 | 4.53125 | 5 | #substring of a string
stringValue = input("Enter string : ")
def substring(stringValue):
print("The original string is : " + str(stringValue))
# Get all substrings of string
# Using list comprehension + string slicing
res = [stringValue[i: j] for i in range(len(stringValue))
for j in range(... | true |
d6cf7a9f246b4e57cc1f748eccfd1d24dc64575a | shiblon/pytour | /3/tutorials/recursion.py | 1,988 | 4.78125 | 5 | # vim:tw=50
"""Recursion
With an understanding of how to write and call
functions, we can now combine the two concepts in
a really nifty way called **recursion**. For
seasoned programmers, this concept will not be at
all new - please feel free to move on. Everyone
else: strap in.
Python functions, like those in many... | true |
d7771130f1ee54dc2d3924e8266c91c559bf4063 | shiblon/pytour | /3/tutorials/hello.py | 1,596 | 4.71875 | 5 | # vim:tw=50
"""Hello, Python 3!
Welcome to Python version 3, a very fun language
to use and learn!
Here we have a simple "Hello World!" program. All
you have to do is print, and you have output. Try
running it now, either by clicking *Run*, or
pressing *Shift-Enter*.
What happened? This tutorial contains a *Python ... | true |
60b0ff336ec48cb60786c47528fa31777ffc8693 | shiblon/pytour | /tutorials/urls.py | 1,583 | 4.125 | 4 | # vim:tw=50
"""Opening URLs
The web is like a huge collection of files,
all jamming up the pipes as they fall off the
truck. Let's quickly turn our attention there,
and learn a little more about file objects while
we're at it.
Let's use |urllib|
(http://docs.python.org/2/library/urllib.html) to
open the Google Priva... | true |
503f1aa74c5d3c2dbd5f5b4e6f97cdbc67aeaa23 | abhisek08/Basic-Python-Programs | /problem22.py | 1,247 | 4.4375 | 4 | '''
You, the user, will have in your head a number between 0 and 100.
The program will guess a number, and you, the user, will say whether it is too high, too low, or your number.
At the end of this exchange, your program should print out how many guesses it took to get your number.
As the writer of this program, y... | true |
6affb302816e8fcf5015596806c5082fa2d3d30d | abhisek08/Basic-Python-Programs | /problem5.py | 1,248 | 4.25 | 4 | '''
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 program works on two lists of diff... | true |
107a32642f0def5ce58017a4d6156bebf1287a1c | abhisek08/Basic-Python-Programs | /problem16.py | 1,008 | 4.34375 | 4 | '''
Create a program that will play the “cows and bulls” game with the user. The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, they have a “cow”.
For every digit the user guessed correctly in the wr... | true |
cc0fe65d97a1914cc986b3dd480ff97bd8a53320 | wilsouza/RbGomoku | /src/core/utils.py | 1,504 | 4.28125 | 4 | import numpy as np
def get_diagonal(table, offset):
""" Get diagonal from table
Get a list elements referencing the diagonal by offset from main diagonal
:param table: matrix to get diagonal
:param offset: Offset of the diagonal from the main diagonal.
Can ... | true |
7653c8e4c2176b8672a531988ef26c1331540b5d | bsundahl/IACS-Computes-2016 | /Instruction/Libraries/bryansSecondLibrary.py | 245 | 4.4375 | 4 | def factorial(n):
'''
This function takes an integer input and then prints out the factorial of that number.
This function is recursive.
'''
if n == 1 or n == 0:
return 1
else:
return n * factorial(n-1) | true |
7b5e3de71b6bdd958b6debafe5d0882503f87f20 | rahul-pande/ds501 | /hw1/problem1.py | 1,445 | 4.3125 | 4 | #-------------------------------------------------------------------------
'''
Problem 1: getting familiar with python and unit tests.
In this problem, please install python verion 3 and the following package:
* nose (for unit tests)
To install python packages, you can use any python package mana... | true |
7de333d37e0af493325591c525cef536290f13be | GameroM/Lists_Practice | /14_Lists_Even_Extract.py | 360 | 4.21875 | 4 | ## Write a Python program to print the numbers of a specified list after removing
## even numbers from it
x = [1,2,3,4,5,6,7,8,15,20,25,42]
newli = []
def evenish():
for elem in x:
if elem % 2 != 0:
newli.append(elem)
return newli
print('The original list is:', x)
print('The li... | true |
0632f5713b13eb0b83c1866566125a069d4f997d | GameroM/Lists_Practice | /8_Lists_Empty_Check.py | 445 | 4.375 | 4 | ## Write a Python program to check if a list is empty or not
x = []
def creation():
while True:
userin=input('Enter values,type exit to stop:')
if userin == 'exit':
break
else:
x.append(userin)
return x
print('The list created from user input... | true |
8a8ccbf32880b637bba81516a69e23b3cabd2229 | blackseabass/Python-Projects | /Homework/week5_exercise2.py | 1,483 | 4.3125 | 4 | #!/usr/bin/env python
"""
File Name: week5_exercise2.py
Developer: Eduardo Garcia
Date Last Modified: 10/4/2014
Description: User plays Rock, Paper, Sciissors with
the computer
Email Address: garciaeduardo1223@gmail.com
"""
import random
def main():
print("Rock. Paper. Scissors." "\n" "Enter 1 for ... | true |
c8639d6ef1d7044f1a840f7446fc7cfb624a1209 | amitravikumar/Guvi-Assignments | /Program14.py | 283 | 4.3125 | 4 | #WAP to find the area of an equilateral triangle
import math
side = float(input("Enter the side: "))
def find_area_of_triangle(a):
return(round(((1/4) * math.sqrt(3) * (a**2)), 2))
result = find_area_of_triangle(side)
print("Area of equilateral triangle is ", result) | true |
5e5803c836e3d83613e880061b29d6862774836b | amitravikumar/Guvi-Assignments | /Program4.py | 309 | 4.3125 | 4 | #WAP to enter length and breadth of a rectangle and find its perimeter
length, breadth = map(float,input("Enter length and breadth with spaces").split())
def perimeter_of_rectangle(a,b):
return 2*(a+b)
perimeter = perimeter_of_rectangle(length,breadth)
print("Perimeter of rectangle is", perimeter) | true |
1971a9a13cc857df612840450c1fb3f455d8a034 | gitfolder/cct | /Python/calculator.py | 1,680 | 4.21875 | 4 | # take user input and validate, keep asking until number given, or quit on CTRL+C or CTR+D
def number_input(text):
while True:
try: return float(input(text))
except ValueError: print("Not a number")
except (KeyboardInterrupt, EOFError): raise SystemExit
def print_menu():
print("\n1. A... | true |
45b822d5189e7e8317f7deb26deed12e7562d29e | jebarajganesh1/Ds-assignment- | /Practical 5.py | 1,415 | 4.1875 | 4 | #Write a program to search an element from a list. Give user the option to perform
#Linear or Binary search.
def LinearSearch(array, element_l):
for i in range (len(array)):
if array[i] == element_l:
return i
return -1
def BinarySearch(array, element_l):
first = 0
array.sort()
... | true |
cfa2dee09f7d4b7dec7c328f8cef5f085e17dd95 | Amirreza5/Class | /example_comparison02.py | 218 | 4.125 | 4 | num = int(input('How many numbers do you want to compare: '))
list_num = list()
for i in range(0, num):
inp_num = int(input('Please enter a number: '))
list_num.append(inp_num)
list_num.sort()
print(list_num) | true |
5436a11b86faa2784d2a3aab6b9449bbca9df2fd | mynameismon/12thPracticals | /question_6#alt/question_6.py | 1,755 | 4.125 | 4 | <<<<<<< HEAD
# Create random numbers between any two values and add them to a list of fixed size (say 5)
import random
#generate list of random numbers
def random_list(size, min, max):
lst = []
for i in range(size):
lst.append(random.randint(min, max))
return lst
x = random_list(5, 1, 100)
# the lis... | true |
2300e2a3c3ccb603907e2bcbd895f25cbbca504d | Enfioz/enpands-problems | /weekdays.py | 535 | 4.34375 | 4 | # Patrick Corcoran
# A program that outputs whether or not
# today is a weekday or is the weekend.
import datetime
now = datetime.datetime.now()
current_day = now.weekday
weekend = (5,7)
if current_day == weekend:
print("It is the weekend, yay!")
else:
print("Yes, unfortunately today is a weekd... | true |
617d4aa7fd56d6511a28954c6bfd384c8b9251d1 | andreeaanbrus/Python-School-Assignments | /Assignment 1/8_setB.py | 893 | 4.25 | 4 | '''
Determine the twin prime numbers p1 and p2 immediately larger than the given non-null
natural number n. Two prime numbers p and q are called twin if q-p = 2.
'''
def read():
x = int(input("Give the number: "))
return x
def isPrime(x):
if(x < 2):
return False
if(x > 2 and x % 2 ==... | true |
cc608e03490880b23f1cb4e53a781670cb898d01 | vlad-bezden/py.checkio | /oreilly/reverse_every_ascending.py | 1,364 | 4.40625 | 4 | """Reverse Every Ascending
https://py.checkio.org/en/mission/reverse-every-ascending/
Create and return a new iterable that contains the same elements
as the argument iterable items, but with the reversed order of
the elements inside every maximal strictly ascending sublist.
This function should n... | true |
d0ef4d781f2518afb1210abedf14239e6b06c0e2 | vlad-bezden/py.checkio | /oreilly/remove_all_after.py | 1,247 | 4.65625 | 5 | """Remove All After.
https://py.checkio.org/en/mission/remove-all-after/
Not all of the elements are important.
What you need to do here is to remove all of the
elements after the given one from list.
For illustration, we have an list [1, 2, 3, 4, 5]
and we need to remove all the elements tha... | true |
56e4820a3eb210789a5b4d86cf4386d4028edb91 | vlad-bezden/py.checkio | /oreilly/how_deep.py | 1,704 | 4.5625 | 5 | """How Deep.
https://py.checkio.org/en/mission/how-deep/
You are given a tuple that consists of integers and other tuples,
which in turn can also contain tuples.
Your task is to find out how deep this structure is or how deep
the nesting of these tuples is.
For example, in the (1, 2, 3) tuple... | true |
4ea6cc426ebeeaf6f594465a48a6bfb836555467 | vlad-bezden/py.checkio | /mine/perls_in_the_box.py | 2,354 | 4.65625 | 5 | """Pearls in the Box
https://py.checkio.org/en/mission/box-probability/
To start the game they put several black and white pearls in
one of the boxes. Each robot has N moves, after which the
initial set is being restored for the next game.
Each turn, the robot takes a pearl out of the box and put... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.