blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
71ecdecf27800ad7d75cd6e119fba2697297550e | kolevatov/python_lessons | /week_2/2_16.py | 671 | 4.3125 | 4 | # Сколько совпадает чисел
"""
Даны три целых числа. Определите, сколько среди них совпадающих.
Программа должна вывести одно из чисел: 3 (если все совпадают),
2 (если два совпадает) или 0 (если все числа различны).
Формат ввода
Вводятся три целых числа.
Формат вывода
Выведите ответ на задачу.
"""
A = int(inpu... | false |
d53aa56fa01ed85a564a542ece3f9922d428b3a3 | kolevatov/python_lessons | /week_2/2_28.py | 815 | 4.125 | 4 | # Количество элементов, равных максимуму
"""
Последовательность состоит из натуральных чисел и завершается числом 0.
Определите, какое количество элементов этой последовательности,
равны ее наибольшему элементу.
Формат ввода
Вводится последовательность целых чисел, оканчивающаяся числом 0
Формат вывода
Вывед... | false |
8a67eea89f7418421671b4dd7b23a316bbab0a5f | kolevatov/python_lessons | /week5/5_7.py | 640 | 4.3125 | 4 | # Замечательные числа - 1
"""
Найдите и выведите все двузначные числа,
которые равны удвоенному произведению своих цифр.
Формат ввода
Программа не требует ввода данных с клавиатуры,
просто выводит список искомых чисел.
Формат вывода
Выведите ответ на задачу.
"""
def proc(n):
a = n // 10
b = n % 10
... | false |
6f348b214f3e1ca724a7fbd014fc6c9542b2430c | kolevatov/python_lessons | /week4/4_6.py | 1,089 | 4.1875 | 4 | # Проверка числа на простоту
"""
Дано натуральное число n>1. Проверьте, является ли оно простым.
Программа должна вывести слово YES, если число простое и NO,
если число составное.
Решение оформите в виде функции IsPrime(n), которая возвращает True
для простых чисел и False для составных чисел.
Количество действий в п... | false |
51991312ddcb06ce0b84c16e8ec7f2b83725c6da | kolevatov/python_lessons | /list_management.py | 1,559 | 4.15625 | 4 | # Управление списком значений.
# Поддерживает операции: добавить элемент, удалить элемент, распечатать список, сортировать, удалить дубликаты значений
#
scores = []
menu = None
while menu != '0':
print("""
0 - Выход
1 - Добавить элемент
2 - Удалить элемент
3 - Распечатать список
... | false |
ef5efede1db142e41aba118dc0d78efa371ad209 | vishnuk1994/ProjectEuler | /SumOfEvenFibNums.py | 1,045 | 4.46875 | 4 | #!/bin/python3
import sys
# By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.
# creating dict to store even fib nums, it helps in reducing time at cost of extra space
# by rough estimate; it is better to use space as for high value of n, it will re... | true |
f2c0bda23f4292e676e3d246d28f6f158145f7e9 | ibbur/LPTHW | /16_v4.py | 1,017 | 4.25 | 4 | print "What file would you like to open?"
filename = raw_input("> ")
print "Opening the file %r for you..." % filename
review = open(filename)
print review.read()
target = open(filename, 'w')
print "\n"
print "I will now clear the file contents..."
target.truncate()
print "I will now close the file..."
target.clos... | true |
3dc2910eea2580527783d8e35114c110e44b3f11 | GanSabhahitDataLab/PythonPractice | /Fibonacci.py | 661 | 4.3125 | 4 | # Find PI to the Nth Digit - Enter a number and have the program generate π (pi) up to
# that many decimal places. Keep a limit to how far the program will go
def fibonaccisequence_upton():
askForInput()
def askForInput():
n = int(input("Enter number of Fibonnacci sequence"))
fibgenerate... | true |
226d0e9c413049435046484715560a1a1861dd57 | thu-hoai/daily-coding-practicing | /python/night_at_the_museum.py | 468 | 4.125 | 4 | #!/usr/bin/env python
# https://codeforces.com/problemset/problem/731/A
# Time complexity: O(n)
def calculate_rotations_number(string):
string = 'a' + string
total = 0
for i in range(len(string)-1):
num = abs(ord(string[i+1]) - ord(string[i]))
if num < 13:
total += num
e... | false |
2651c168d0f874b4c897227b11d17cf6678032c9 | roycekumar/C168-Project | /BOOKSHELF.py | 877 | 4.25 | 4 | class Book:
def __init__(self,name,author,price,publishing_year):
self.Book_name=name
self.Book_author=author
self.Book_price=price
self.Book_year=publishing_year
def add_book(self):
print("Book Name: "+str(self.Book_name))
print("Book Author: "+str(self.Book_auth... | false |
3865e1e3cf60023a368f629cb21a3b163d61fa59 | claudiamorazzoni/problems-sheet-2020 | /Task 6.py | 435 | 4.4375 | 4 | # Write a program that takes a positive floating-point number as input and outputs an approximation of its square root.
# You should create a function called sqrt that does this.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
import math
num = float(input("Please enter a posit... | true |
02a11bf65defec6e1280af02fabf2411dea09e85 | Nithinnairp1/Python-Scripts | /lists.py | 1,073 | 4.25 | 4 | my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
print(my_list[-1])
n_list = ["Happy", [2,0,1,5]]
print(n_list[0][1])
print(n_list[1][3])
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
odd = [1, 3, 5]
odd.append(7)
print(... | true |
9e76ed8832052f6d5066700f222bea4d4df69b50 | TrihstonMadden/Python | /plot-dictionary.py | 1,226 | 4.125 | 4 | # plot-dictionary.py
import tkinter as tk
import turtle
def main():
#table is a dictionary
table = {-100:0,-90:10,-80:20,-70:30,-60:40,-50:50,
-40:40,-30:30,-20:20,-10:10,0:0,
10:10,20:20,30:30,40:40,50:50,
60:40,70:30,80:20,90:10,100:0,
}
print(" KEYS ")
print(table.keys())
print(" V... | true |
111b780e317205805f1d5c230bc16d8f9f55eb78 | jpeggreg/CP1404 | /cp1404practicals/prac_02/Automatic_password_generator_custom.py | 1,931 | 4.40625 | 4 | import random
LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"
UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
SPECIAL_CHARACTERS = "!@#$%^&*()_-=+`~,./'[]<>?{}|\\"
def main():
"""Program to get password length and number of each type required."""
password_length = int(input("Enter the password length do you... | false |
0cb9dbd2051790e0992b5a5c55456efe184911d3 | Jethet/Practice-more | /python-katas/EdabPalin.py | 778 | 4.3125 | 4 | # A palindrome is a word, phrase, number or other sequence of characters which
# reads the same backward or forward, such as madam or kayak.
# Write a function that takes a string and determines whether it's a palindrome
# or not. The function should return a boolean (True or False value).
# Should be case insensitive ... | true |
b447f6804b1aaf41f103aa9b75afd2814c207163 | Jethet/Practice-more | /small-projects/inverseRandNum.py | 720 | 4.21875 | 4 | import random
# instead of the computer generating a random number, the user is giving the number
def computer_guess(x):
low = 1
high = x
feedback = ""
while feedback != "c":
# you cannot have low and high be the same:
if low != high:
guess = random.randint(low, high)
... | true |
22800ea3b59510039284cf345034c94c1ee4b99a | Jethet/Practice-more | /python-katas/3_Sum.py | 239 | 4.1875 | 4 | # Return sum of two int, unless values are the same: then return double.
def sum_double(a, b):
if a == b:
return 2 * (a + b)
else:
return a + b
print(sum_double(1,2))
print(sum_double(3,2))
print(sum_double(2,2))
| true |
3f0aa8fd1025b9f1d919f544cbf78dbc91c44699 | Jethet/Practice-more | /python-katas/EdabAltCaps.py | 362 | 4.4375 | 4 | # Create a function that alternates the case of the letters in a string.
# The first letter should always be UPPERCASE.
def alternating_caps(txt):
print(alternating_caps("Hello")) # "HeLlO"
print(alternating_caps("Hey, how are you?")) # "HeY, hOw aRe yOu?"
print(alternating_caps("OMG!!! This website is awesome!... | true |
394c0e41664f79b95e279ff063f7584a49f675cf | Jethet/Practice-more | /python-katas/EdabCountUniq.py | 384 | 4.28125 | 4 | # Given two strings and a character, create a function that returns the total
# number of unique characters from the combined string.
def count_unique(s1, s2):
return len(set(s1 + s2))
print(count_unique("apple", "play")) #➞ 5
# "appleplay" has 5 unique characters:
# "a", "e", "l", "p", "y"
print(count_unique("so... | true |
e398b42c4309d60d59ea97a5e341532502fb0a1c | Jethet/Practice-more | /python-katas/EdabIndex.py | 686 | 4.375 | 4 | # Create a function that takes a single string as argument and returns an
# ordered list containing the indexes of all capital letters in the string.
# Return an empty array if no uppercase letters are found in the string.
# Special characters ($#@%) and numbers will be included in some test cases.
def indexOfCaps(wor... | true |
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 |
138598c6e37b9b525b779902f4172f40e03ca3c2 | kampanella0o/python_basic | /lesson4_home/l4_ex2.py | 515 | 4.21875 | 4 | n = '0'
while int(n) <= 0:
n = input("Please enter a natural number: ")
try:
int(n)
except ValueError:
print("You should enter a natural number!")
n = '0'
number_of_digits = len(n)
if number_of_digits == 1:
summ_of_digits = n
else:
while number_of_digits != 1:
summ... | false |
3a18399d699248a6e85fbe96c6c853b5bacdd0ba | kampanella0o/python_basic | /lesson1/ifelse.py | 1,001 | 4.1875 | 4 | # name = "Da"
# if name == "Max":
# print(name)
# else:
# print('Its not Max')
# a = 10
# b = 15
############################################################
# if a == 10:
# c = True
# else:
# if b == 10:
# c = False
# else:
# c = True
# c = True if a == 10 else False if b == 10... | false |
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 |
f17ba2ede15984ac894cb066f3605989d0116441 | NikitaPlesovskix/Susu-101 | /ex 18 | 977 | 4.1875 | 4 | # Имеются две ёмкости: кубическая с ребром A, цилиндрическая с высотой H и радиусом основания R.
# Определить, можно ли заполнить жидкостью объёма M первую ёмкость, вторую, обе.
import math
A = int(input("Ребро кубической ёмкости "))
R = int(input("Радиус основания цилиндрической ёмкости "))
H = int(input("Высота цилин... | false |
c4fa448d1dcf57c6450378a81f8f465ff4bca213 | zhyordanova/Python-Fundamentals | /04-Functions/Exercise/09_factorial_division.py | 294 | 4.15625 | 4 | def calc_factorial(n):
result = 1
for num in range(2, n + 1):
result *= num
return result
number_1 = int(input())
number_2 = int(input())
factorial_1 = calc_factorial(number_1)
factorial_2 = calc_factorial(number_2)
res = factorial_1 / factorial_2
print(f"{res:.2f}")
| false |
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 |
35c48ed308a44a6dd4c4f2941cc0405ef609edad | kikihiter/PythonLearning | /sortingAlgorithmPython/heapSort.py | 2,764 | 4.125 | 4 | #!user/bin/env python
#python heapSort.py
#kiki 18/04/27
#保证根节点为最大的
def maxChange(heap,size,i): #分别有三个参数,heap为传入的列表,size为列表长度,i为当前根节点索引号
root = i
left = i*2+1 #左子节点
right = i*2+2 #右子节点
"""
if left<size and heap[root]<heap[left]:
heap[root],heap[left] = heap[left],heap[root]
left,roo... | false |
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 |
00b75b92ccda9b8cd04760da415f1aebb5bc0e03 | nikhl/Miscellaneous | /src/multiplication_table.py | 490 | 4.28125 | 4 | # Take as input a number and print all the multiplications from 1 upto that number
def print_multiplication_table(n):
i = 1
while i<=n:
j = 1
while j<=n:
print '%d * %d = %d' % (i,j,(i*j))
j = j+1
i = i+1
# test cases
print_multiplication_table(2)
#>>> 1 * 1 = 1
#>>> 1 * 2 = 2
#>>> 2 * 1 = 2
#>>> 2 * 2 ... | false |
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 |
4996d51a0d79f44c1ed2abf236c1bcf8789bb18a | karanalang/technology | /python_examples/py_bisect.py | 1,332 | 4.15625 | 4 | # https://docs.python.org/3/library/bisect.html
# https://www.tutorialspoint.com/bisect-array-bisection-algorithm-in-python
import bisect
# data = [1, 2, 3,4 ]
#
# idx = bisect.bisect(data, 2)
# print(" bisect.bisect(data, 2) i.e. get the idx to the RIGHT of the elem 2 -> ", idx)
#
# data.insert(idx, 100)
#
# print(... | false |
c276d6f87149f8a9f724e58ad95ba1a1f80296b5 | karanalang/technology | /python_examples/Python_eval.py | 1,472 | 4.21875 | 4 | from math import *
# https://www.geeksforgeeks.org/eval-in-python/
class Python_eval:
def usingEval(self, str):
res = eval(str)
print(" res -> ", res)
def secret_function(self):
return "Secret key is 1234"
def function_creator(self):
expr = input("Enter function in terms... | false |
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 |
6ac581ae0842787a92b863397f609236eb09d0fd | nurSaadat/pythonLearning | /talking_robot.py | 856 | 4.40625 | 4 | # В институте биоинформатики по офису передвигается робот.
# Недавно студенты из группы программистов написали для него программу,
# по которой робот, когда заходит в комнату, считает количество программистов в ней
# и произносит его вслух: "n программистов".
x = int(input())
c = x % 100
d = x % 10
if 0 <= x <= 1000... | false |
4d647b6c3147dec57dd0ab525c5bc97b94f9e459 | lwjNN/leetcode-python | /Python/sword2offer/Offer11.py | 1,044 | 4.4375 | 4 | """
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:
输入:[3,4,5,1,2]
输出:1
示例 2:
输入:[2,2,2,0,1]
输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing imp... | false |
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 |
234fd73fe7facee859d6545a424d1ffcfb5fb4d0 | Ekpreet-kaur/python-files | /venv/python9.py | 216 | 4.1875 | 4 | #assignment operators
num1 = 10 #write operation/ update operation
num1 = 5
num2 = num1 #copy operation |refernce copy
#num1 = num1 + 10
num1 += 5
#print(num1)
# *=,/=,//=,*=,**=
num1 **= 2
num1 //= 2
print(num1) | false |
8d9d40f748d8351017fe52bef8296c45a8bbea76 | botaoap/python_db_proway_2021 | /aula2/class/classes.py | 943 | 4.15625 | 4 | """
classmethod - staticmethod - dcorators
"""
class MinhaClasse:
def __init__(self, nome, idade) -> None:
self.nome = nome
self.idade = idade
def __repr__(self) -> str:
return f"{self.nome}, {self.idade}"
def metodo_de_instancia(self):
print(f"Eu sou uma classe {s... | false |
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 |
becb831554b3c8e678f0450b7db618e008270fb7 | JohnRamonetti/Election_Analysis | /python_practice.py | 1,576 | 4.125 | 4 | # print("Hello World")
# print("Hello world")
# counties = ["A","B","C"]
# # print(counties[1])
# print(len(counties))
voting_data = []
voting_data.append({"county":"Arapahoe", "registered_voters":422829})
voting_data.append({"county":"Denver", "registered_voters":463353})
voting_data.append({"county":"Jefferson","r... | false |
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 |
5b0ea4f7425bc0e6a3a2a7063bd7245dbe6568cb | acheval/python | /ATBSWP/Chapter 7/strip_regex_version.py | 586 | 4.21875 | 4 | #!/bin/python3
import re
def strip_string(context, strip_character):
if strip_character == "":
regex_strip_whitespace = re.compile(r"^\s+|\s+$")
stripped_context = regex_strip_whitespace.sub("", context)
print(stripped_context)
else:
regex_strip_character = re.compile(r"[" + ... | false |
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 |
c791668713d4909d8c20592e729deb879e5fad38 | Alicepeach/plisplis3 | /godofredo.py | 1,100 | 4.15625 | 4 | # Calculadora
ejecutar = 1
while ejecutar == 1:
print("Este programa permite hacer una operación básica con dos números")
print("Para realizar esto, es necesario que me indiques el tipo de operación que deseas:")
print("1) Suma ")
print("2) Resta ")
print("3) Multiplicación ")
print("4) División ")
opcion = in... | false |
b534e7cebb0800baf0b4f4e62da9fe3a522607a9 | Vamicc/OP | /LAB2/LAB2OP.py | 773 | 4.21875 | 4 | print("Enter the x coordinate: ")
x = int(input())
print("Enter the y coordinate: ")
y = int(input()) # просимо ввести координати точки
if x > 0 and y > 0:
result = "The point belongs to the first quadrant."
elif x > 0 and y < 0:
result = "The point belongs to the forth quadrant."
elif x < 0 and y > 0:
result... | false |
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 |
c7fd6e4f93448f7968292d7c41a2c8ccff7db848 | oloj-hub/pythondz | /lab7/ball_lib.py | 1,119 | 4.25 | 4 | class ball():
def move(self):
"""Переместить мяч по прошествии единицы времени.
Метод описывает перемещение мяча за один кадр перерисовки. То есть, обновляет значения
self.x и self.y с учетом скоростей self.vx и self.vy, силы гравитации, действующей на мяч,
и стен по краям окна (раз... | false |
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 |
c052133b3e1f048e9ccc60b431e599ad15ae80d1 | mihirverma7781/Python-Scripts | /chap4/exercise_two.py | 271 | 4.21875 | 4 | def greater(a,b,c):
if a>b and a>c:
return a
else:
if b>a and b>c:
return b
else:
return c
num1 = input('enter num 1 : ')
num2 = input('enter num 2 : ')
num3 = input('enter num 3 : ')
print(greater(num1,num2,num3))
| false |
d704337728a29e47b14ba1e78643b1bef7528919 | mihirverma7781/Python-Scripts | /chap16/property_setter_decorator.py | 1,033 | 4.125 | 4 |
class Phone:
def __init__(self,brand , model , price):
self.brand = brand
self.model = model
self._price = price
# if price > 0:
# self._price = price
# else:
# self._price = 0
# self.complete_info = f"{self.brand... | false |
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 |
06129f5dd4fc8976370406d05bb3ebd6e4a18ac5 | EvelynWangai/RSA-Encryption-Decryption | /encryption.py | 1,415 | 4.3125 | 4 | # library to be imported
import math
# creating my ditionary
my_dict={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,
'm':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,
'y':25,'z':26,' ':27}
## Creating RSA keys and encrypting a message
def ... | false |
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 |
e7f972375ba19e5060b271fc4de2db58cfd317c7 | jack-sneddon/python | /30-data/pandas/box_chart.py | 1,615 | 4.1875 | 4 | # $ pip3 install pandas
# pip3 install matplotlib
# https://www.geeksforgeeks.org/data-visualization-different-charts-python/
# import pandas and matplotlib
import sys
import pandas as pd
import matplotlib.pyplot as plt
### Same code from Dataframe as other charts ###
# create 2D array of table given above
dat... | false |
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 |
cae06ec7c1df47570276ee34b144ad85c5f1e09a | kahee/Python-Study | /data_structure/CH3/list-stack.py | 434 | 4.125 | 4 | def push(item):
stack.append(item)
def peek():
# top 항목 접근
if len(stack) != 0:
return stack[-1]
def pop():
# 삭제 연산
if len(stack) != 0:
# 리스트의 맨 뒤에 있는 항목 제거
item = stack.pop(-1)
return item
stack = []
push('apple')
push('orange')
push('cherry')
print(stack)
prin... | false |
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 |
8f9de6617f089a70ac45e214091830c472fb78cb | Maaleenaa/AlleDaten | /SmartNinjaClasses/Class 8/examples/example_lists.py | 914 | 4.3125 | 4 | # initialize
newList = []
print newList
print #oder print list()
# append single elements - neue Elemente dazuhänge oder +=
newList.append('Banana')
print newList
print
# append add multiple elements with other lists
oldList = ['Milk', 'Honey']
shoppingList = newList + oldList
print shoppingList
print
# refe... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.