blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e79e52b336b37444bcdc95b151c50e080e8ab2e3 | Jethet/Practice-more | /python-katas/28_Last2.py | 300 | 4.15625 | 4 | # Given a string, return the count of the number of times that a substring
# length 2 appears in the string and also as the last 2 chars of the string,
# so "hixxxhi" yields 1 (we won't count the end substring).
def last2(str):
x = str[-2:]
return str.count(x) - 1
print(last2('axxxaaxx'))
| true |
3837c735626d9ea89162da3f3f15e3514bcd859a | Jethet/Practice-more | /python-katas/EdabCheckEnd.py | 646 | 4.5 | 4 | # Create a function that takes two strings and returns True if the first
# argument ends with the second argument; otherwise return False.
# Rules: Take two strings as arguments.
# Determine if the second string matches ending of the first string.
# Return boolean value.
def check_ending(str1... | true |
baf3c6195df0fc2638e72ae9f9bf4be5bba73e38 | Jethet/Practice-more | /python-katas/EdabTrunc.py | 684 | 4.3125 | 4 | # Create a one line function that takes three arguments (txt, txt_length,
# txt_suffix) and returns a truncated string.
# txt: Original string.
# txt_length: Truncated length limit.
# txt_suffix: Optional suffix string parameter.
# Truncated returned string length should adjust to passed length in parameters
... | true |
bd0304c63470267b120d29de75b00b480960a0a7 | Jethet/Practice-more | /python-katas/EdabAddInverse.py | 333 | 4.125 | 4 | # A number added with its additive inverse equals zero. Create a function that
# returns a list of additive inverses.
def additive_inverse(lst):
print(additive_inverse([5, -7, 8, 3])) #➞ [-5, 7, -8, -3]
print(additive_inverse([1, 1, 1, 1, 1])) #➞ [-1, -1, -1, -1, -1]
print(additive_inverse([-5, -25, 35])) #➞ [5, 25... | true |
5797703b59a09ee3915451417c6e4205feb47ee5 | Marhc/py_praxis | /hello.py | 1,590 | 4.4375 | 4 | """A simple **"Hello Function"** for educational purposes.
This module explores basic features of the Python programming language.
Features included in this module:
- Console Input / Output;
- Function Definition;
- Module Import;
- Default Parameter Values;
- String Interpolation (**'fstrings'**)... | true |
cf3c88cf74d7f26207959aaa43329d8332c9a673 | beanj25/Leap-year-program | /jacob_bean_hw1_error_handling.py | 1,020 | 4.125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Jacob
#
# Created: 15/01/2021
# Copyright: (c) Jacob 2021
# Licence: <your licence>
#-------------------------------------------------------------------------------
def... | true |
33b7628e6bdb51f4f146db155335768f3d873892 | Ayesha116/piaic.assignment | /q19.py | 340 | 4.28125 | 4 | #Write a Python program to convert the distance (in feet) to inches, yards, and miles. 1 feet = 12 inches, 3 feet = 1 yard, 5280 feet = 1 mile
feet = float(input("enter height in feet: "))
print(feet,"feet is equal to",feet*12, "inches ")
print(feet, "feet is equal to",feet/3, "yards")
print(feet, "feet is equal to",... | true |
96f67acf3b9cae1727f5ae4737edb54ea4a5f6c1 | helloprogram6/leetcode_Cookbook_python | /DataStruct/BiTree/字典树.py | 1,390 | 4.21875 | 4 | # -*- coding:utf-8 -*-
# @FileName :字典树.py
# @Time :2021/3/20 13:37
# @Author :Haozr
from typing import List
class TrieNode:
def __init__(self, val=''):
self.val = val
self.child = {}
self.isWord = False
class Trie:
def __init__(self):
"""
Initialize your data ... | true |
7c1dfbbc1baf98904272f598608d04659b7b9053 | jorzel/codefights | /arcade/python/competitiveEating.py | 930 | 4.21875 | 4 | """
The World Wide Competitive Eating tournament is going to be held in your town, and you're the one who is responsible for keeping track of time. For the great finale, a large billboard of the given width will be installed on the main square, where the time of possibly new world record will be shown.
The track of ti... | true |
72b951eebf3317d9a36822ef3056129257781ef1 | jorzel/codefights | /challange/celsiusVsFahrenheit.py | 1,549 | 4.4375 | 4 | """
Medium
Codewriting
2000
You're probably used to measuring temperature in Celsius degrees, but there's also a lesser known temperature scale called Fahrenheit, which is used in only 5 countries around the world.
You can convert a Celsius temperature (C) to Fahrenheit (F), by using the following formula:
F = 9 *... | true |
658593501932b67c86b33a4f1a0ba2a1257e2de5 | jorzel/codefights | /interview_practice/hash_tables/possibleSums.py | 876 | 4.28125 | 4 | """
You have a collection of coins, and you know the values of the coins and the quantity of each type of coin in it. You want to know how many distinct sums you can make from non-empty groupings of these coins.
Example
For coins = [10, 50, 100] and quantity = [1, 2, 1], the output should be
possibleSums(coins, quant... | true |
4193ada270f7accddd799997c1c705545eb243f3 | jorzel/codefights | /arcade/core/isCaseInsensitivePalindrome.py | 742 | 4.375 | 4 | """
Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters.
Example
For inputString = "AaBaa", the output should be
isCaseInsensitivePalindrome(inputString) = true.
"aabaa" is a palindrome as well as "AABAA", "aaBaa", etc.
For inputString = "abac", the output shou... | true |
495f3051e8737856cf1adbc0dbd601166b185ec5 | jorzel/codefights | /arcade/intro/evenDigitsOnly.py | 346 | 4.25 | 4 | """
Check if all digits of the given integer are even.
Example
For n = 248622, the output should be
evenDigitsOnly(n) = true;
For n = 642386, the output should be
evenDigitsOnly(n) = false.
"""
def evenDigitsOnly(n):
el_list = [int(i) for i in str(n)]
for p in el_list:
if p % 2 != 0:
ret... | true |
051faa94e67dcb9db8c35ec2bb577d8fb0598c32 | jorzel/codefights | /arcade/intro/growingPlant.py | 704 | 4.625 | 5 | """
Each day a plant is growing by upSpeed meters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.
Example
For upSpeed = 10... | true |
455f2a51259a5c06c167a5c6560cf0a22e4f2ce3 | jorzel/codefights | /arcade/python/tryFunctions.py | 1,035 | 4.125 | 4 | """
Easy
Recovery
100
Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.
You've been working on a numerical analysis when something went horribly wrong: your solution returned completely unexpected results. It looks like you apply a wrong function at some point of calculation.... | true |
94c2397a4ecb9cbfbe88f8b5c7831805fc246562 | jorzel/codefights | /interview_practice/arrays/rotateImage.py | 471 | 4.46875 | 4 | """
Note: Try to solve this task in-place (with O(1) additional memory), since this is what you'll be asked to do during an interview.
You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).
Example
For
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
the output should ... | true |
7757551f8a04e9875fd09f7cce05b1a06aafab49 | jorzel/codefights | /arcade/intro/longestDigitsPrefix.py | 439 | 4.15625 | 4 | """
Given a string, output its longest prefix which contains only digits.
Example
For inputString="123aa1", the output should be
longestDigitsPrefix(inputString) = "123".
"""
def longestDigitsPrefix(inputString):
max_seq = ""
for i, el in enumerate(inputString):
if i == 0 and not el.isdigit():
... | true |
bfc993bfda53b5a1e69f4b1feefc9b0eea4bdb22 | jorzel/codefights | /arcade/core/concatenateArrays.py | 282 | 4.15625 | 4 | """
Given two arrays of integers a and b, obtain the array formed by the elements of a followed by the elements of b.
Example
For a = [2, 2, 1] and b = [10, 11], the output should be
concatenateArrays(a, b) = [2, 2, 1, 10, 11].
"""
def concatenateArrays(a, b):
return a + b
| true |
cc9e43e94fd96b2407b289ef20cf5a7c04652c3d | jorzel/codefights | /interview_practice/strings/findFirstSubstringOccurence.py | 751 | 4.3125 | 4 | """
Avoid using built-in functions to solve this challenge. Implement them yourself, since this is what you would be asked to do during a real interview.
Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicat... | true |
df6930a4776a2e67381065e5dbfc8d5dfe64bf03 | jorzel/codefights | /arcade/python/isWordPalindrome.py | 374 | 4.625 | 5 | """
Given a word, check whether it is a palindrome or not. A string is considered to be a palindrome if it reads the same in both directions.
Example
For word = "aibohphobia", the output should be
isWordPalindrome(word) = true;
For word = "hehehehehe", the output should be
isWordPalindrome(word) = false.
"""
def i... | true |
d800d63f49158fcbb0f2af79a9d315061e028fdb | jorzel/codefights | /arcade/intro/biuldPalindrome.py | 575 | 4.25 | 4 | """
Given a string, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome.
Example
For st = "abcdc", the output should be
buildPalindrome(st) = "abcdcba".
"""
def isPalindrome(st):
for i in range(len(st) / 2):
if st[i] != st[-1 -... | true |
0725fe8ef04175b03de2315a61be93a6bbf4aa2e | jorzel/codefights | /arcade/intro/firstDigit.py | 414 | 4.28125 | 4 | """
Find the leftmost digit that occurs in a given string.
Example
For inputString = "var_1__Int", the output should be
firstDigit(inputString) = '1';
For inputString = "q2q-q", the output should be
firstDigit(inputString) = '2';
For inputString = "0ss", the output should be
firstDigit(inputString) = '0'.
"""
def fi... | true |
e520b1fc70883eacd427dc2b6ffe006d2f75d926 | jorzel/codefights | /interview_practice/dynamic_programming_basic/climbingStairs.py | 688 | 4.1875 | 4 | """
Easy
Codewriting
1500
You are climbing a staircase that has n steps. You can take the steps either 1 or 2 at a time. Calculate how many distinct ways you can climb to the top of the staircase.
Example
For n = 1, the output should be
climbingStairs(n) = 1;
For n = 2, the output should be
climbingStairs(n) = 2.... | true |
7872f5adf499f79df9cec821fb8020c8f3bbadbb | jorzel/codefights | /arcade/core/fileNames.py | 856 | 4.15625 | 4 | """
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will... | true |
79907a750c9bffa2f140a3f1be68acf207da1f59 | jorzel/codefights | /interview_practice/common_techinques_basic/containsDuplicates.py | 640 | 4.15625 | 4 | """
Given an array of integers, write a function that determines whether the array contains any duplicates. Your function should return true if any element appears at least twice in the array, and it should return false if every element is distinct.
Example
For a = [1, 2, 3, 1], the output should be
containsDuplicate... | true |
388748ed56911db4eefc35817dee3e0bafe07404 | jorzel/codefights | /challange/maxPoints.py | 1,212 | 4.15625 | 4 | """
World Cup is going on! One of the most fascinating parts of it is the group stage that has recently ended. A lot of great teams face each other to reach the playoff stage. In the group stage, each pair of teams plays exactly one game and each team receives 3 points for a win, 1 point for a draw and 0 points for a l... | true |
ca8dd729003dd665c4e3fba57289fc4b315128ec | MulderPu/legendary-octo-guacamole | /pythonTuple_part1.py | 767 | 4.15625 | 4 | '''
Write a Python program to accept values (separate with comma) and store in tuple.
Print the values stored in tuple, sum up the values in tuple and display it. Print the maximum and
minimum value in tuple.
'''
user_input = input("Enter values (separate with comma):")
tuple = tuple(map(int, user_input.split(',')))
... | true |
71c4d79d3e982de8875def381e621b8a8dd46247 | MulderPu/legendary-octo-guacamole | /guess_the_number.py | 801 | 4.25 | 4 | import random
print('~~Number Guessing Game~~')
try:
range = int(input('Enter a range of number for generate random number to start the game:'))
rand = random.randint(1,range)
guess = int(input('Enter a number from 1 to %i:'%(range)))
i=1
while (i):
print()
if guess == 0 or gue... | true |
ce71585126ae1e765a99600203ba6e2585860f60 | ProNilabh/Class12PythonProject | /Q11_RandomGeneratorDICE.py | 307 | 4.28125 | 4 | #Write a Random Number Generator that Generates Random Numbers between 1 and 6 (Simulates a Dice)
import random
def roll():
s=random.randint(1,6)
return s
xD= str(input("Enter R to Roll the Dice!-"))
if xD=="r":
print(roll())
else:
print("Thanks for Using the Program!") | true |
014674cad94445da44a1c2f258777d6529687270 | Raghavi94/Best-Enlist-Python-Internship | /Tasks/Day 8/Day 8.py | 2,983 | 4.21875 | 4 | #TASK 8:
#1)List down all the error types and check all the errors using a python program for all errors
#Index error
#Name error
#zerodivision error
a=[0,1,2,3]
try:
print(a[1])
print(a[4],a[1]//0)
except(IndexError,ZeroDivisionError):
print('Index error and zero division error occured')
... | true |
19b00f3cace5617652435d104b04dc24b68513ea | ezekielp/algorithms-practice | /integer_break.py | 1,227 | 4.25 | 4 | """
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Not... | true |
679b8b24eda016b5e320624a0ead00bfdf12903b | dple/Strings-in-Python | /pangram.py | 706 | 4.15625 | 4 | """
A pangram is a string that contains every letter of the alphabet.
Given a sentence determine whether it is a pangram in the English alphabet.
Return either pangram or not pangram as appropriate.
For example:
Input: We promptly judged antique ivory buckles for the next prize
Output: pangram
"""
def pangrams(s):
... | true |
31c86f9b3b49aca2002fa01058ca4763312c3046 | Gaurav1921/Python3 | /Basics of Python.py | 1,703 | 4.375 | 4 | """ to install any module first go in command prompt and write 'pip install flask' and then come here and write
modules are built in codes which makes our work more easier and pip is package manager which pulls modules """
import flask
""" to print something the syntax for it is """
print("Hello World")
""" us... | true |
d1ee3c94491b93693cd9bd09f65e7e4d31ad4511 | Enin/codingTest | /amazon/6_determine_if_a_binary_tree_is_a_binary_search_tree.py | 2,728 | 4.28125 | 4 | ###
# Given a Binary Tree, figure out whether it’s a Binary Sort Tree.
# In a binary search tree, each node’s key value is smaller than the key value of all nodes in the right subtree,
# and is greater than the key values of all nodes in the left subtree.
# Below is an example of a binary tree that is a valid BST.
impo... | true |
74af819f062dc0dff568fbbfdd2767be07f4f603 | Enin/codingTest | /amazon/7_string_segmentation.py | 907 | 4.375 | 4 | # You are given a dictionary of words and a large input string.
# You have to find out whether the input string can be completely segmented into the words of a given dictionary.
# The following two examples elaborate on the problem further.
import collections
# recursion과 memoization을 사용
given_dict = ['apple', 'apple'... | true |
d3302d00ebca7dd0ff302f38cd78d1b87ccb5c1f | AdishiSood/Jumbled_Words_Game | /Jumbled_words_Game.py | 2,419 | 4.46875 | 4 | #To use the random library, you need to import it. At the top of your program:
import random
def choose():
words=["program","computer","python","code","science","data","game"]
pick=random.choice(words) #The choice() method returns a list with the randomly selected element from the specified sequence.
... | true |
bb984eb7c1ecb5e4d1407baa9e8599209ff05f3b | xASiDx/other-side | /input_validation.py | 794 | 4.25 | 4 | '''Input validation module
Contains some functions that validate user input'''
def int_input_validation(message, low_limit=1, high_limit=65536, error_message="Incorrect input!"):
'''User input validation
The function checks if user input meets set requirements'''
user_input = 0
#we ask user to e... | true |
d0219bd6ffe2d00bba2581b72b852b858c8c1a07 | QARancher/file_parser | /search/utils.py | 710 | 4.1875 | 4 | import re
from search.exceptions import SearchException
def search(pattern,
searched_line):
"""
method to search for string or regex in another string.
:param pattern: the pattern to search for
:param searched_line: string line as it pass from the file parser
:return: matched object of... | true |
74e87bf28436a832be8814386285a711b627dab9 | ohaz/adventofcode2017 | /day11/day11.py | 2,179 | 4.25 | 4 | import collections
# As a pen&paper player, hex grids are nothing new
# They can be handled like a 3D coordinate system with cubes in it
# When looking at the cubes from the "pointy" side and removing cubes until you have a
# plane (with pointy ends), each "cube" in that plane can be flattened to a hexagon
# This mean... | true |
9e9f9151efbe59c7e0100048c3d46f7d8786bba5 | dennis-omoding3/firstPython | /task.py | 630 | 4.15625 | 4 | taskList=[23,"jane",["lesson 23",560,{"currency":"kes"}],987,(76,"john")]
# 1. determine the type of var in task list using an inbuilt function
print(type(taskList))
# 2.print kes
print(taskList[2][2]["currency"])
# 3.print 560
print(taskList[2][1])
# 4. use a function to determine the length of taskList
print(len(ta... | true |
ea53fb163337a49762314dbc38f2788a74846343 | SaretMagnoslove/Python_3_Basics_Tutorial_Series-Sentdex | /Lesson24_multiline_print.py | 666 | 4.5 | 4 | # The idea of multi-line printing in Python is to be able to easily print
# across multiple lines, while only using 1 print function, while also printing
# out exactly what you intend. Sometimes, when making something like a text-based
# graphical user interface, it can be quite tedious and challenging to make every... | true |
77181ee32df9fc60121bcdb41aca5717c4245405 | HarrietLLowe/python_turtle-racing | /turtle_race.py | 1,278 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a colour: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
for x in r... | true |
28d4c117c564ad0926fafd890f182ec7c3938c22 | Deepu14/python | /cows_bulls.py | 1,637 | 4.28125 | 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 ... | true |
25697204d6da732977cef03994324d00368ce1cb | hari1811/Python-exercises | /Quiz App/common.py | 685 | 4.15625 | 4 |
def get_int_input(prompt, high):
while(1):
print()
try:
UserChoice = int(input(prompt))
except(ValueError):
print("Error: Expected an integer input!")
continue
if(UserChoice > high or UserChoice < 1):
print("Error: Please e... | true |
a20fc079740a8d7ff9b022fe5e491b3218b2559a | acheval/python | /python_exercices/exercice06.py | 402 | 4.3125 | 4 | #!/bin/python3
# 6. Write a Python program to count the number of characters in a string.
# Sample String : 'google.com' Expected Result : {'o': 3, 'g': 2, '.': 1, 'e':
# 1, 'l': 1, 'm': 1, 'c': 1}
string = 'google.com'
d = dict()
for letter in string:
if letter in d:
d[letter] = d[letter]+1
else:... | true |
358cb695ab1430599eba277be1d2873ae862ccb8 | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/numbers_dates_times/rounding_numerical_values.py | 1,408 | 4.125 | 4 | # rounding numerical values
# simple rounding
print(round(1.23, 1))
print(round(1.27, 1))
print(round(1.25362, 3))
a = 1627731
print(round(a, -1))
print(round(a, -2))
print(round(a, -3))
x = 1.23456
print(format(x, '0.2f'))
print(format(x, '0.3f'))
print('value is {:0.3f}'.format(x))
a = 2.1
b = 4.2
c = a + b
# c = ... | true |
f8d026245e19a202915e9cdc57dd0e9e4949760a | pranavchandran/redtheme_v13b | /chapter_2_strings_and_text/matching_string_using_shell_wild_cards/aligning _text_strings.py | 718 | 4.3125 | 4 | # Aligning of strings the ljust(), rjust() and center()
text = 'Hello World'
print(text.ljust(20))
print(text.rjust(20))
print(text.center(20))
print(text.rjust(20, '='))
print(text.center(20,'*'))
# format() function can also be used to align things
print(format(text, '>20'))
print(format(text, '<20'))
print(format... | true |
1d34800f127f69e26a9622e5e42407420657a055 | akhilavemuganti/HelloWorld | /Exercises.py | 2,984 | 4.1875 | 4 | #Exercises
#bdfbdv ncbgjfv cvbdggjb
"""
Exercise 1: Create a List of your favorite songs. Then create a list of your
favorite movies. Join the two lists together (Hint: List1 + List2). Finally,
append your favorite book to the end of the list and print it.
"""
listSongs=["song1","song2","song3","song4"]
listMovies=["... | true |
6d63007d90bae6eb2137cced9d5ee0b47665d547 | rvcjavaboy/udemypythontest | /Methods_and_Functions/function_test/pro4.py | 229 | 4.15625 | 4 | def old_macdonald(name):
result=""
for c in range(0,len(name)-1):
if c==0 or c==3:
result+=name[c].upper()
else:
result+=name[c]
return result
print(old_macdonald('macdonald'))
| true |
8d90a7edcc4d49f85ea8d35dda6d58dcb7654bd0 | PinCatS/Udacity-Algos-and-DS-Project-2 | /min_max.py | 1,298 | 4.125 | 4 | def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if ints is None:
return None
if len(ints) == 1:
return (ints[0], ints[0])
minValue = None
maxValue = ... | true |
c1d957f7ca914ba5113124684e8b0c21663df2bd | sakshigupta1997/code-100 | /code/python/day-1/pattern15.py | 326 | 4.1875 | 4 | '''write a program to print
enter the number4
*
**
***
****'''
n=int(input("enter the number"))
p=n
k=0
for row in range(n):
for space in range(p,1,-1):
print(" ",end='')
#for star in range(row):
for star in range(row+1):
print("*",end='')
print()
p=p-1
... | true |
e02ba552e441eb412b25f7f9d15299288e34ad37 | Iansdfg/9chap | /4Binary Tree - Divide Conquer & Traverse/85. Insert Node in a Binary Search Tree.py | 857 | 4.125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of the binary search tree.
@param: node: insert this node into the binary search tree
@return: The root of the new bin... | true |
399106fc8885d5f892d49b080084a393ab5dbb4a | jack-sneddon/python | /04-lists/list-sort.py | 596 | 4.46875 | 4 |
# sort - changes the order permenantly
cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla']
cars.sort()
print (cars)
# reverse sort
cars.sort(reverse = True)
print (cars)
# temporary sort - sorted
cars = ['honda', 'suburu', 'mazda', 'acura', 'tesla']
print("here is the original list:")
print (cars)
print("here is ... | true |
9a6c909e0fec1e2b90318ed7644d97e8a1663182 | jack-sneddon/python | /04-lists/lists-while-loop.py | 2,007 | 4.40625 | 4 | # a for loop is effective for looping through a list, but you shouldn't modify a
# list inside for loop because Pything will have trouble keeping track of the items
# in the list. To modify a list as you work throuh it, use a while loop.
# Using while loops with lists and dictionaries allows you to collect, store, ... | true |
17ff6eaf25026ada4fd159e2ae3905854fd56d2f | GeoMukkath/python_programs | /All_python_programs/max_among_n.py | 280 | 4.21875 | 4 | #Q. Find the maximum among n numbers given as input.
n = int(input("Enter the number of numbers : "));
print("Enter the numbers: ");
a = [ ];
for i in range(n):
num = int(input( ));
a.append(num);
maximum= max(a);
print("The maximum among the given list is %d" %maximum); | true |
b9a895f074168c0be5f86592214a316b46bbc98b | JLarraburu/Python-Crash-Course | /Part 1/Hello World.py | 1,574 | 4.65625 | 5 | # Python Crash Course
# Jonathan Larraburu
print ("Hello World!")
# Variables
message = "Hello Python World! This string is saved to a variable."
print(message)
variable_rules = "Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a n... | true |
c9c2548eb74b5375baeea0d7d526d0dd8446e653 | Varun-Mullins/Triangle567 | /Triangle.py | 1,623 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Updates on Friday January 31 2020
@author: Varun Mark Mullins
cwid:10456027
This file takes in three lengths of a triangle and checks the validity of the triangle and returns the type of
triangle and checks if it is a right angle triangle or not.
"""
def classifyTriangle(a, b, c):
""... | true |
ac349eb4da08279d11d242bf2bb67556729f4393 | zeirn/Exercises | /Week 4 - Workout.py | 815 | 4.21875 | 4 | x = input('How many days do you want to work out for? ') # This is what we're asking the user.
x = int(x)
# These are our lists.
strength = ['Pushups', 'Squats', 'Chinups', 'Deadlifts', 'Kettlebell swings']
cardio = ['Running', 'Swimming', 'Biking', 'Jump rope']
workout = []
for d in range(0, x): # This is ... | true |
3186c75b82d1877db3efe13a8a432355503ec9f3 | TMcMac/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 526 | 4.28125 | 4 | #!/usr/bin/python3
"""This will get a line count on a text file"""
def number_of_lines(filename=""):
"""
A function to get a line count on a file
parameters - a file
"""
line_count = 0
with open(filename, 'r') as f:
"""
Opens the file as f in such as way that
we don't n... | true |
5c8df2051d971311883b58f15fbf17a1987655fd | TMcMac/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 831 | 4.46875 | 4 | #!/usr/bin/python3
"""Defines class square and takes in a size to intialize square"""
class Square():
"""Class Square for building a square of #s"""
def __init__(self, size=0):
"""Initializes an instance of square"""
self.size = size
def area(self):
"""Squares the size to get the ... | true |
6191e450436393fc4ac30c36d1e16665b9cebdb2 | wahahab/mit-6.0001 | /ps1/ps1c.py | 1,204 | 4.21875 | 4 | # -*- coding: utf-8 -*-
import math
from util import number_of_month
SCALE = 10000
if __name__ == '__main__':
months = 0
current_savings = 0
portion_down_payment = .25
r = .04
min_portion_saved = 0
max_portion_saved = 10000
best_portion_saved = 0
semi_annual_raise = .07
total_cos... | true |
bc9a56767843484f90d5fe466adee8c1289a9052 | JohanRivera/Python | /GUI/Textbox.py | 1,360 | 4.125 | 4 | from tkinter import *
raiz = Tk()
myFrame = Frame(raiz, width=800, height=400)
myFrame.pack()
textBox = Entry(myFrame)
textBox.grid(row=0,column=1) #grid is for controlate all using rows and columns
#Further, in .grid(row=0, column=1, sticky='e', padx=50) the comand padx o pady move the object, in this case
#50 pixel... | true |
5f004bd21d1553a87a446be505865cba2acd19a7 | JustinCThomas/Codecademy | /Python/Calendar.py | 2,021 | 4.125 | 4 | """This is a basic CRUD calendar application made in Python"""
from time import sleep, strftime
NAME = "George"
calendar = {}
def welcome():
print("Welcome", NAME)
print("Opening calendar...")
sleep(1)
print(strftime("%A %B %d, %Y"))
print(strftime("%H:%M:%S"))
sleep(1)
print("What would you like to do... | true |
765d21e3ef208f0a197c71a5b1543f71fd7aa4dc | penroselearning/pystart_code_samples | /16 Try and Except - Division.py | 415 | 4.125 | 4 | print('Division')
print('-'*30)
while True:
try:
dividend = int(input("Enter a Dividend:\n"))
divisor = int(input("Enter a Divisor:\n"))
except ValueError:
print("Sorry! You have not entered a Number")
else:
try:
result = dividend/divisor
except ZeroDivisionError:
print("Division ... | true |
6716efaf012f7ed75775f9dca8dad3593c5a4773 | venkatakaturi94/DataStructuresWeek1 | /Task4.py | 1,271 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
list_tele_marketers=[]
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
list_from =[]
list_to =[]
for to in texts:
list_from.append(to[0])
list_to.append(to... | true |
c4c760f5840cd67678114569f3fe0cc890f501ac | codeguru132/pythoning-python | /basics_lists.py | 526 | 4.34375 | 4 | hat_list = [1, 2, 3, 4, 5] # This is an existing list of numbers hidden in the hat.
# Step 1: write a line of code that prompts the user
# to replace the middle number with an integer number entered by the user.li
hat_list[2] = int(input("ENter a number here: ..."))
# Step 2: write a line of code that removes... | true |
32e14721978cac96a0e1c7fe96d1e7088f928658 | rciorba/plp-cosmin | /old/p1.py | 1,246 | 4.21875 | 4 | #!/usr/bin/python
# Problem 1:
# Write a program which will find all such numbers which are divisible by 7 but
# are not a multiple of 5, between 2000 and 3200 (both included).
# The numbers obtained should be printed in a comma-separated sequence on a
# single line.
# to nitpick: min and max are builtin functions... | true |
a57e1fe462002e2797275191cba5b2ebd0d2cfc5 | ak45440/Python | /Replace_String.py | 667 | 4.1875 | 4 | # Write a Python program to find the first appearance of the substring 'not' and 'poor' from a given string,
# if 'not' follows the 'poor', replace the whole 'not'...'poor' substring with 'good'. Return the resulting string.
# Sample String : 'The lyrics is not that poor!'
# 'The lyrics is poor!'
# Expected Result :... | true |
41126620e671d2c5298381eeda1f0a67b8f6a560 | Wei-Mao/Assignments-for-Algorithmic-Toolbox | /Divide-and-Conquer/Improving QuickSort/quicksort.py | 2,645 | 4.5 | 4 | # python3
from random import randint
from typing import List, Union
def swap_in_list(array, a, b):
array[a], array[b] = array[b], array[a]
def partition3(array: List[Union[float, int]] , left: [int], right: [int]) -> int:
"""
Partition the subarray array[left,right] into three parts such that:
array[... | true |
26ab13287b1ea07319831266fe190de1762bb084 | pombredanne/Revision-Scoring | /revscores/languages/language.py | 591 | 4.125 | 4 | class Language:
"""
Constructs a Language instance that wraps two functions, "is_badword" and
"is_misspelled" -- which will check if a word is "bad" or does not appear
in the dictionary.
"""
def __init__(self, is_badword, is_misspelled):
self.is_badword = is_badword
self.is_missp... | true |
10fed729debcd5ba51cfa9da23c2a6e548f6a0ac | kunalrustagi08/Python-Projects | /Programming Classroom/exercise7.py | 920 | 4.21875 | 4 | '''
We return to the StringHelper class, here we add another static method called
Concat, this method receives a single parameter called Args, which is a
"Pack of parameters", which means that we can pass as many parameters as we
want, then, within this function there will be A variable called Curr that
will be ini... | true |
580438f74309cbffd7841166b374f8814c04eea3 | kunalrustagi08/Python-Projects | /Programming Classroom/exercise3.py | 1,441 | 4.46875 | 4 | '''
Create a class called Calculator. This class will have four static methods:
Add()
Subtract()
Multiply()
Divide()
Each method will receive two parameters: "num1" and "num2" and will return the
result of the corresponding arithmetic operation.
Example: The static addition method will return the sum of num1 and num2... | true |
130d9e5dd29b1f817b661e9425ffe278ccc44e8d | rebht78/course-python | /exercises/solution_01_04.py | 347 | 4.125 | 4 | # create first_number variable and assign 5
first_number = 5
# create second_number variable and assign 5
second_number = 5
# create result variable to store addition of first_number and second_number
result = first_number + second_number
# print the output, note that when you add first_number and second_number you ... | true |
39e669b95b5b08afdab3d3b16cb84d673aecbf8e | ctsweeney/adventcode | /day2/main.py | 2,106 | 4.375 | 4 | #!/usr/bin/env python3
def read_password_file(filename: str):
"""Used to open the password file and pass back the contents
Args:
filename (str): filepath/filename of password file
Returns:
list: returns list of passwords to process
"""
try:
with open(filename, "r") as f:
... | true |
017a3268e5de015c8f0c25045f44ae7a4ffe7a50 | dky/cb | /legacy/fundamentals/linked-lists/03-08-20/LinkedList.py | 1,893 | 4.1875 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
# We always have a dummy node so the list is never empty.
self.head = Node("dummy")
self.size = 0
def __str__(self):
out = ""
cu... | true |
9390e6095c6140ba0117bfd18fb63844189d7a68 | abhijnashree/Python-Projects | /prac1.py | 218 | 4.28125 | 4 | #Read Input String
i = input("Please insert characters: ")
#Index through the entire string
for index in range(len(i)):
#Check if odd
if(index % 2 == 0):
#print odd characters
print(i[index])
| true |
e0c62280d0a17510b152d5aff2671bc89e0de4d4 | DevOpsStuff/Programming-Language | /Python/PythonWorkouts/NumericTypes/run_timings.py | 488 | 4.125 | 4 | #!/usr/bin/env python
def run_timing():
"""
Asks the user repeatedly for numberic input. Prints the average time and number of runs
"""
num_of_runs = 0
total_time = 0
while True:
one_run = input('Enter 10 Km run time: ')
if not one_run:
break
num_of_runs ... | true |
1aa76c29644208c7094733bfbb3a876c1ffb9b83 | aswathyp/TestPythonProject | /Assignments/Loops/2_EvenElementsEndingWith0.py | 362 | 4.1875 | 4 |
# Even elements in the sequence
numbers = [12, 3, 20, 50, 8, 40, 27, 0]
evenElementCount = 0
print('\nCurrent List:', numbers, sep=' ')
print('\nEven elements in the sequence: ')
for num in numbers:
if num % 2 == 0:
print(num, end=' ')
evenElementCount = evenElementCount + 1
print('\n\nTotal Co... | true |
e0fe9a4a068ebbdd0956bbfc525f83551b75b2b0 | gowtham9394/Python-Projects | /Working with Strings.py | 788 | 4.40625 | 4 | # using the addition operator without variables [String Concatenation]
name = "Gowtham" + " " + "Kumar"
print(name)
# using the addition operator with variables
first_name = "Gowtham"
last_name = "Kumar"
full_name = first_name + " " + last_name
print(full_name)
# using the new f strings [after python 3.6]
print( f"... | true |
f9bfecf22f03336080907a61c1f21adc95668396 | pinnockf/project-euler | /project_euler_problem_1.py | 490 | 4.3125 | 4 | '''
Multiples of 3 and 5
Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
def main(threshold):
multiples = []
for number in range(threshold):
if number... | true |
3654c2a1ca8756660b6da99b2d571c6a508a9568 | shefali-pai/comp110-21f-workspace | /exercises/ex07/data_utils.py | 2,561 | 4.15625 | 4 | """Utility functions."""
__author__ = "730466264"
from csv import DictReader
def read_csv_rows(filename: str) -> list[dict[str, str]]:
"""Read the rows of a csv into a 'table'."""
result: list[dict[str, str]] = []
file_handle = open(filename, "r", encoding="utf8")
csv_reader = DictReader(file_handle... | true |
57b07d75c2d81356bab342880380353f6debbc25 | meginks/data-structure-notes | /Queues/queues.py | 2,152 | 4.15625 | 4 | class ListQueue:
def __init__(self):
self.items = []
self.size = 0
def enqueue(self, data):
"""add items to the queue. Note that this is not efficient for large lists."""
self.items.insert(0, data) #note that we could also use .shift() here -- the point is to add the new t... | true |
319d2d9261047ba9218b7b696fb33ad7fc1895a3 | neelindresh/try | /VerificationFunctions.py | 2,729 | 4.1875 | 4 | import numpy as np
import pandas as pd
import operator
def check_column(df, ops, first_mul, col_name, oper, value):
'''
This function will return the list of valid and invalid rows list after performing the operation
first_mul * df[col_name] oper value ex: [ 1*df['age'] >= 25 ].
'''
valid_... | true |
d8d791d01895b3a173b4d8003b2e2b648905b3da | AlirezaTeimoori/Unit_1-04 | /radius_calculator.py | 480 | 4.125 | 4 | #Created by: Alireza Teimoori
#Created on: 25 Sep 2017
#Created for: ICS3UR-1
#Lesson: Unit 1-04
#This program gets a radius and calculates circumference
import ui
def calculate_circumferenece(sender):
#calculate circumference
#input
radius = int(view['radius_text_field'].text)
#process
... | true |
e2c0ea3f0638d3d181a0d291eb488839f1596001 | Yasin-Yasin/Python-Tutorial | /005 Conditionals & Booleans.py | 1,415 | 4.375 | 4 | # Comparisons
# Equal : ==
# Not Equal : !=
# Greater Than : >
# Less Than : <
# Greater or Equal : >=
# Less or Equal : <=
# Object Identity : is
# if block will be executed only if condition is true..
if True:
print("Conditinal was true")
if False:
prin... | true |
f17feb86a3277de3c924bcecb2cc62dee8801e1b | Yasin-Yasin/Python-Tutorial | /014 Sorting.py | 1,686 | 4.28125 | 4 | # List
li = [9,1,8,2,7,3,6,4,5]
s_li = sorted(li)
print("Sorted List\t", s_li) # This function doesn't change original list, It returns new sorted list
print('Original List\t', li)
li.sort() # sort method sort original list, doesn't return new list, this method is specific to List obj
print('Original List, Now So... | true |
074ac0d3a6836dbf02831280eb8cd55adb3a508d | ZHANGYUDAN1222/Assignment2 | /place.py | 1,282 | 4.3125 | 4 | """
1404 Assignment
class for functions of each place
"""
# Create your Place class in this file
class Place:
"""Represent a Place object"""
def __init__(self, name='', country='', priority=0, v_status=''):
"""Initialise a place instance"""
self.name = name
self.country = country
... | true |
79144ad6f7efd0fcdc7d3fe20e04a881cb1b544a | Diwyang/PhytonExamples | /demo_ref_list_sort3.py | 1,206 | 4.40625 | 4 | # A function that returns the length of the value:
#list.sort(reverse=True|False, key=myFunc)
#Sort the list descending
cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)
#Sort the list by the length of the values:
# A function that returns the length of the value:
def myFunc(e):
return len(e)
... | true |
ba6e01baaa2b69497ede48f24737831c8d35fa68 | Diwyang/PhytonExamples | /Example4.py | 531 | 4.21875 | 4 | # My Example 3
"""There are three numeric types in Python:
int - Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
float - Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
complex - Complex numbers are writt... | true |
a6158f2bf6ce87e6213cb5de60d4b82d9cd5000c | guoguozy/Python | /answer/ps1/ps1b.py | 648 | 4.21875 | 4 | annual_salary = float(input('Enter your annual salary: '))
portion_saved = float(
input('Enter the percent of your salary to save, as a decimal: '))
total_cost = float(input('Enter the cost of your dream home: '))
semi_annual_raise = float(input('Enter the semiannual raise, as a decimal: '))
current_savings =... | true |
123f44d763fe59334151321a24a1c3a3cf7b284c | Ret-David/Python | /IS 201/Concept Tests/CT05_David_Martinez.py | 689 | 4.21875 | 4 | # David Martinez
# Write a pseudo code to design a program that returns the # of occurrences of
# unique values but sorted from the list. For example, with the input list
# [1, 2, -2, 1, 0, 2, 4, 0], the program should provide the output as follows:
# unique value (# of occurrences)
# -2(1)
# ... | true |
879206042b294d5da53faf0c85858394a2e7b28e | Ret-David/Python | /IS 201/Module 1/HOP01.py | 1,789 | 4.34375 | 4 | # HOP01- David Martinez
# From Kim Nguyen, 4. Python Decision Making Challenge
# Fix the program so that the user input can be recognized as an integer.
# Original Code
guess = input("Please guess a integer between 1 and 6: ")
randomNumber = 5
if (guess == randomNumber):
print("Congrats, you got it!")
else:
... | true |
0d022905006e7bb3113a9726c9780b13eb55b544 | Ret-David/Python | /IS 201/Practical Exercises/PE05_David_Martinez_4.py | 1,725 | 4.34375 | 4 | # David Martinez
# Make two files, cats.txt and dogs.txt.
# Store at least three names of cats in the first file and three names of dogs in
# the second file.
# Write a program that tries to read these files and print the contents of the file
# to the screen.
# Wrap your code in a try-except block to catch the... | true |
92acf42a33fefc55d10db64cb4a2fd7856bc21de | Ret-David/Python | /IS 201/Concept Tests/CT09_David_Martinez.py | 616 | 4.375 | 4 | # David Martinez
# Write a pseudo code to design a program that returns I-th largest value
# in a list. For example, with the input list [3, 2, 8, 10, 5, 23]
# and I = 4, the program prints the value 5 as it is 4 th largest value.
# ========== My Pseudo Code ==========
# >> 5 is in index 4 position but is the... | true |
5e7b828d0d74462a10fefbbee34d14c3f29f4c0c | ChloeDumit/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,674 | 4.28125 | 4 | #!/usr/bin/python3
""" Write the class Rectangle that inherits from Base"""
from .rectangle import Rectangle
"""
creating new class
"""
class Square(Rectangle):
""" class Square """
def __init__(self, size, x=0, y=0, id=None):
"initializes data"
self.size = size
super().__init__(sel... | true |
b12bbaf3e31c5362fd198c6512d76d858470ac8d | jinayshah86/DSA | /CtCI-6th-Edition/Chapter1/1_6/string_compression_1.py | 1,653 | 4.1875 | 4 | # Q. Implement a method to perform basic string compression using the counts
# of repeated characters. For example, the string 'aabcccccaaa' would become
# 'a2b1c5a3'. If the "compressed" string would not become smaller than the
# original string, your method should return the original string. You can
# assume the stri... | true |
bfb24a739c79bffb1f60dbb54481ceb9ecd13ceb | BoynChan/Python_Brief_lesson_answer | /Char7-Import&While/char7.1.py | 511 | 4.125 | 4 | car = input("What kind of car do you want to rent?: ")
print("Let me see if I can find you a "+car)
print("------------------------------")
people = input("How many people are there?: ")
people = int(people)
if people >= 8:
print("There is no free table")
else:
print("Please come with me")
print("-----------... | true |
529402a5a5de14174db8206be4d1d24cef30396b | veshhij/prexpro | /cs101/homework/1/1.9.py | 422 | 4.21875 | 4 | #Given a variable, x, that stores
#the value of any decimal number,
#write Python code that prints out
#the nearest whole number to x.
#You can assume x is not negative.
# x = 3.14159 -> 3 (not 3.0)
# x = 27.63 -> 28 (not 28.0)
x = 3.14159
#DO NOT USE IMPORT
#ENTER CODE BELOW HERE
#ANY CODE ABOVE WI... | true |
01ccaa78ebe6cc532d8caca853365d8d05f29b22 | francomattos/COT5405 | /Homework_1/Question_08.py | 2,021 | 4.25 | 4 | '''
Cinderella's stepmother has newly bought n bolts and n nuts.
The bolts and the nuts are of different sizes, each of them is from size 1 to size n.
So, each bolt has exactly one nut just fitting it.
These bolts and nuts have the same appearance so that we cannot distinguish a bolt from another bolt,
or a nut fro... | true |
db0682bd8033187a2ec73514dd2d389fb30ff2d0 | wpiresdesa/hello-world | /stable/PowerOf2.py | 639 | 4.5625 | 5 | #!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# Add this line today - 29/October/2018 11:08Hs
# Add another line (this one) today 29/October/2018 11:10Hs
# Add another line (this one) today 29?october/2018 11:18Hs
# Python Program to display the powers of 2 using anonymous function
# Change this value for a differe... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.