blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a6ce2c96ee05be77b390674cd3fee3ab39771cd8 | ralevn/Python_scripts | /hackerranked/evallistcmd.py | 1,351 | 4.3125 | 4 | """
Lists
onsider a list (list = []). You can perform the following commands:
nsert i e: Insert integer e at position i.
rint: Print the list.
emove e: Delete the first occurrence of integer e.
ppend e: Insert integer e at the end of the list.
ort: Sort the list.
op: Pop the last element from the list.
reverse... | true |
039a21334b04575a8bfe49c7c2e70bdefa68314a | rkmsh/Cracking-The-Coding-Interview | /Linked LIsts/Kth_to_last.py | 2,117 | 4.40625 | 4 | # It is an iterative solution
# Defining the Node
class Node:
def __init__(self, data = None):
self.data = data
self.next = None
#Defining the Linked List class
class linkedList:
def __init__(self):
self.head = None
self.tail = None
# Method to add data to the linked List
... | true |
fe7ee2f14a108ec6b2916047bd78a9d2de814b7b | rkmsh/Cracking-The-Coding-Interview | /Stacks_and_Queues/Stack_min.py | 1,767 | 4.15625 | 4 | #!/usr/bin/python3
#
#
# This program always return the minnimum element in the stack
# Defining the class min_stack()
#
class min_stack:
def __init__(self):
self.stack = []
self.stack_min = []
self.tail = -1
self.small = None
# Defining a method push() to add data into the stack... | true |
38366a23768de52af0ed9bb449b7acb1abc2a6a3 | saqibwaheed786/100DayofCode | /Day22/exercise6.3.py | 916 | 4.5 | 4 | # 6-3. Glossary: A Python dictionary can be used to model an actual dictionary.
# However, to avoid confusion, let’s call it a glossary.
# • Think of five programming words you’ve learned about in the previous
# chapters. Use these words as the keys in your glossary, and store their
# meanings as values.
# • Print each... | true |
0af09664e9f0f59c9d9cceb3acdc6544f5e9034c | saqibwaheed786/100DayofCode | /Day18/cars.py | 1,010 | 4.625 | 5 | #Organizing a List
#Sorting a List Permanently with the sort() Method
#..................................................................
cars = ['bmw', 'audi', 'toyata', 'subaru']
#cars.sort()
#print(cars)
#reverse alphabetical order
#...................................................................
#cars.sort(reve... | true |
f6997fa0958705d2caa9a09634288764f93ff4fb | saqibwaheed786/100DayofCode | /DAY28/exercise8.4.py | 646 | 4.625 | 5 | # 8-5. Cities: Write a function called describe_city() that accepts the name of
# a city and its country. The function should print a simple sentence, such as
# Reykjavik is in Iceland. Give the parameter for the country a default value.
# Call your function for three different cities, at least one of which is not in t... | true |
99120e4273b991b291d2b93c757488d1d70a9ae6 | AnkithaBH/Python | /Basics/Armstrong.py | 300 | 4.3125 | 4 | #Armstrong number is a number that is equal to the sum of cubes of its digits
num=int(input("Enter any number:"))
num=str(num)
sum=0
for i in num:
sum=sum+((int(i))**3)
num=int(num)
if num==sum:
print("It is an armstrong number")
else:
print("It is not an armstrong number")
| true |
7c2dc69e4f05e974d0bce71d6f50f2cb1f1c07ab | MrVJPman/Teaching | /ICS3U1/Exercise Solutions/Exercise 15 Solutions.py | 1,621 | 4.40625 | 4 | #Question 1) https://www.w3schools.com/python/exercise.asp?filename=exercise_functions1
#Question 2)
#Create a function with no input that also return None as an output. You must write the return statement!
#Call the function, and verify that the function call output None via print()
def no_input_return_None() : ret... | true |
f2ef69222b15ad8d9ec8c27914e8efb207960082 | ursstaud/PCC-Basics | /admin.py | 1,251 | 4.21875 | 4 | class Users:
"""simple class example with users"""
def __init__(self, first_name, last_name, age, location):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.location = location
def describe_user(self):
"""describing the user example"""
print(f"This user's full name ... | true |
5ba68977acc13f9a1950725fec6801ba75a56364 | ursstaud/PCC-Basics | /roller_coaster.py | 226 | 4.21875 | 4 | height = input("How tall are you in inches?")
height = int(height)
if height >= 48:
print("\nYou are tall enought to ride!")
else:
print("\nSorry, you cannot ride. You'll be able to ride when you're a little older.") | true |
b0dd78793d95a2967eaedf9650d6c9d9d5a5346b | samyak1903/Data-Types-1 | /A7.py | 356 | 4.1875 | 4 | #Q.1- Count even and odd numbers in that list.
l=[]
even,odd=0,0
elements=int(input("Enter the number of elements to be added in list"))
for num in range(elements):
num=int(input("Enter the value"))
l.append(num)
for n in l:
if n%2==0:
even=even+1
else:
odd=odd+1
print("Even count=%d\n O... | true |
39cfb3684e1cbfa747f4791f0a3ee45c2451a60e | tbcodes/Simple_Python_Game_Guess_the_word | /2-Guess_the_word_game.py | 1,604 | 4.21875 | 4 | # Guess the Word - Python Game - Truzz Blogg
# Youtube link: https://youtu.be/2kVb0_EJgn4
import random
import sys
players = 'Cristiano, Hazard, Messi, VanDijk, Neymar, Salah, Dybala, Mbappe, Kane, Mane, Benzema, Kroos, Aguero, Ozil, Oblak, Coutinho, Modric, DeBruyne'
players = players.split(',')
final_player... | false |
6a8647d83cd511344e06c8f2519fff71e88f5347 | Jackson201325/Python | /Python Crash Course/Chapter 3 Lists/More_guest(3.6).py | 824 | 4.46875 | 4 | # You just found a bigger dinner table, so now more space is available. Think of three more guest to invite
# Use insert() to add new guesto to the beginning of your list
# Use insert() to add one new guest to the middle of the list
# Use append() to add new guest to the end of your list
names = ['Jackson', 'David', '... | true |
790e577ae58d26aed9e2806cd77c874ad6056771 | Jackson201325/Python | /Python Crash Course/Chapter 3 Lists/Seeing_the_world(3.8).py | 989 | 4.625 | 5 | # Store the locations in a list. Make sure the list is not in alphabetical order
# Print your list in its iriginal order
# Use sorted() to print your list in alphabetical order
# Show that your list is still in its original order by printing it
# Use sorted() to print your list in reverse alphaetical order without chan... | true |
d848d874f72772dfdddfb9b90213a6758e19dc75 | kmg1905/algorithms | /computer_science/algorithms/sorting/randomized_quick_sort.py | 1,820 | 4.1875 | 4 | """
Intuition: Since quicksort algorithm has a worst case time complexity of O(n*2) for certain input arrays. We need
to some how mitigate this problem and make sure the worst case time complexity is made equal to average case time
complexity. For this purpose, we can use new sorting algorithm called as "randomized qu... | true |
6fe3bcd9fafcec2375b35812674090c504b8a68c | clubofcodes/python_codes | /Ass 1.2/O&E_Label_Till_N.py | 247 | 4.125 | 4 | def showNumbers(limit):
print("List of Odd & Even Numbers till index :",limit-1)
for n in range(0,limit):
if n%2==0:
print(n,"EVEN")
else:
print(n,"ODD")
showNumbers(int(input("Enter the limit : "))) | true |
7a34fa348cb1f5f3a2045a20bbb67f4988d778f0 | lerahkp/Tip-Calculator | /main.py | 635 | 4.125 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: You might need to do some research in Google to figure out how to do this.
print("Welcome to the tip calculator")
bill = float(input("What was the tota... | true |
037c7de9aadf7a8f204234538d8d1b2ab7c44646 | Marcin-Marcinek/Python | /script1.py | 292 | 4.125 | 4 | #!/usr/bin/python3
print("Debt calculator")
debt = float(input("Ammount of debt (in PLN):"))
daily_interest = float(input("Late fees per day: "))
days = int(input("Number of days since paydate: "))
total_debt = debt + daily_interest * days
print("Total ammount of debt: ", total_debt, "PLN")
| true |
8bd98e5cb50e1c3d290da4520cb9cc41ba5245c6 | vinnykuhnel/MethodsToolsUnitTest | /homework4/functions.py | 2,146 | 4.1875 | 4 | #Della Jones dj1069
#Teddy Lander tel127
#Raleigh Bumpers reb560
#Adam Kuhnel vak58
import math
## opens a file in read mode
## filename received as a parameter
def openFile(filename):
try:
infile = open(filename, "r")
print("File opened.")
except ValueError:
print("T... | true |
0b5b5f32bb9c6cfe64bd664e35e0a8c3617efa72 | Sarlianth/python-problems | /07-palindrome.py | 522 | 4.46875 | 4 | # Function that tests whether a string is a palindrome
# Author: Adrian Sypos
# Date: 23/09/2017
# Ask user to input a string
print("Please enter a word to check for palindrome: ")
# Read in the string
word = input()
# Bring the string to lower case for obvious comparison reasons
word = word.casefold()
# Logical state... | true |
b92a50ad18a8aca63b7c6a6af48fdae124818fb1 | jaford/thissrocks | /daily_code/JF_Daily_Code_10:26_input+reverse.py | 362 | 4.4375 | 4 | #Write a Python program which accepts the user's first and last name
# and print them in reverse order with a space between them.
first_name = input('What is your first name? ')
last_name = input('What is your last name? ')
print('I will now attempt to print the last name first followed by the first name')
print(f'Y... | true |
43c8784d884e799caf5fba76f59c61f5a1c441b1 | jaford/thissrocks | /jim_python_practice_programs/15.60_voting.py | 247 | 4.28125 | 4 | # Write a program that will let the user know if they can vote or not
def voting():
age = int(input('How old are you? '))
# check if eligible to vote
if age >= 18:
print('Can Vote')
else:
print('Cannot Vote')
voting() | true |
23ecedd3b431e13c9c9f1048e32db3c55fe86820 | jaford/thissrocks | /jim_python_practice_programs/29.60_print_user_input_fibonacci_numbers.py | 440 | 4.34375 | 4 | # Write a program that will list the Fibonacci sequence less than n
def fib_num_user():
n = int(input('Enter a number: '))
t1 = 1
t2 = 1
result = 0
# loop as long as t1 is less than n
while t1 < n:
# print t1
print(t1)
# assign sum of t1 and t2 to result
result... | true |
96eef37fd0286a7e063d61a83e1e460007f7bc05 | jaford/thissrocks | /daily_code/JF_Daily_Code_8:2.py | 744 | 4.21875 | 4 | #random number guessing game
#TODO: add guess counter
import random
correct_guess = random.randint(1,10)
print("Random number is", correct_guess) #error checking for number
guess = 0
attempts = 3
while correct_guess != guess:
guess = int(input("I'm thinking of a number between 1 and 10, can you guess it in three gu... | true |
e303b8bcd7c9e2c212617fbc80ea4e5940117734 | jaford/thissrocks | /daily_code/JF_Daily_Code_9:23_C_to_f_v2.py | 711 | 4.3125 | 4 | # This program is desgined to convert fahrenheit to celcius
user_choice = int(input('Choose 1 or 2. CHOICE 1 will convert Celcius to Fahrenheit. CHOICE 2 will convert Fahrenheit to Celcius.'))
if user_choice == 1:
celcius_temp = int(input('Enter a temperature in Celcius: '))
f_to_c_temp = (celcius_temp * 9 / 5... | true |
e836f5453c15f61aec0832439da763dae8278e56 | jaford/thissrocks | /programs/shortScripts/characterCounter.py | 819 | 4.28125 | 4 |
# Enter a string that starts with a $ for this example
# userInput = input('Enter random characters that check how many numbers and symbols there are! ---> ')
# Test strings
# $samh51jcj
# $143718ash
userInput = '$143718ash'
for i in userInput:
print('CHECK 1')
print(i)
if i[0] == "$":
for v in ra... | false |
2a8a8c3f1ef8ad752ec0d918bd2a4221f12d907d | jaford/thissrocks | /jim_python_practice_programs/26.60_numbers_until_0.py | 319 | 4.375 | 4 | # Write a program that will print the number the user enters except 0.
# run a while loop that is always true
while True:
# take input for number
number = int(input('Enter a number: '))
# terminate the loop if the user input is 0
if number == 0:
break
# print the number
print(number) | true |
2542a15861404db1e90b01e5bc59f91f49eb58c2 | jaford/thissrocks | /jim_python_practice_programs/18.60_smallest_of_three.py | 340 | 4.21875 | 4 | # Replace ___ with your code
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))
number3 = int(input('Enter third number: '))
# check for smallest number using if...elif...else statement
if number1 < number3:
print(number1)
elif number2 < number1:
print(number2)
else:
... | false |
2cd997338553f3d3297869b28418cad32f0f66fb | jaford/thissrocks | /daily_code/JF_Daily_Code_10:13_Interview_Question.py | 565 | 4.125 | 4 | #You have two strings 'abcde' and 'abcdXe' write a function that would print the difference
def string_comparison (str1, str2):
first_set = set(str1)
second_set = set(str2)
difference = first_set.symmetric_difference(second_set)
print(difference)
string_comparison('abcde', 'abcdXe')
## print(... | true |
e920adb3de67923a46e151a9c2ebe2742f3f0518 | jaford/thissrocks | /Python_Class/py3intro3day 2/EXAMPLES/fmt_params.py | 457 | 4.34375 | 4 | #!/usr/bin/env python
person = 'Bob'
age = 22
print("{0} is {1} years old.".format(person, age)) # <1>
print("{0}, {0}, {0} your boat".format('row')) # <2>
print("The {1}-year-old is {0}".format(person, age)) # <3>
print("{name} is {age} years old.".format(name=person, age=age)) # <4>
print()
print("{} ... | false |
823b05a2f5f1df65bf2fcb1459db377897c7b2e0 | RiflerRick/codemonk2017 | /NumberTheory/ClosedGiftFinalSolution.py | 1,732 | 4.25 | 4 | """
This solution uses a very efficient method of finding out whether a number is prime or not.
This algorithm is really fast for finding if a number is prime or not.
The loop part is executed for numbers greater then 25. We start from 5 and alternately add 2 and 4 at each step. Remember that primes are always in the f... | true |
e79d0e8eec67f6f1766f27ef021ad5a2e885970b | yang7988/python-foundation | /function/say_hello.py | 1,005 | 4.125 | 4 | # 函数(Functions)是指可重复使用的程序片段。它们允许你为某个代码块赋予名字,允许你
# 通过这一特殊的名字在你的程序任何地方来运行代码块,并可重复任何次数。这就是所谓的
# 调用(Calling)函数。我们已经使用过了许多内置的函数,例如 len 和 range 。
# 函数概念可能是在任何复杂的软件(无论使用的是何种编程语言)中最重要的构建块,所以
# 我们接下来将在本章中探讨有关函数的各个方面。
# 函数可以通过关键字 def 来定义。这一关键字后跟一个函数的标识符名称,再跟一对圆括
# 号,其中可以包括一些变量的名称,再以冒号结尾,结束这一行。随后而来的语句块是函数
# 的一部分。下面的案例将会展示出这其实非常简单... | false |
52d3ea61c4b3321e95c03baeec30d6354b8422cb | yang7988/python-foundation | /foreach/break.py | 856 | 4.1875 | 4 | # break 语句用以中断(Break)循环语句,也就是中止循环语句的执行,即使循环条件没有
# 变更为 False ,或队列中的项目尚未完全迭代依旧如此。
# 有一点需要尤其注意,如果你的 中断 了一个 for 或 while 循环,任何相应循环中的
# else 块都将不会被执行。
def while_break():
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
prin... | false |
9e23255dcba3742c9caffbcb17a720e7e5dbb6fd | haptikfeedback/python_basics | /masterticket.py | 1,078 | 4.1875 | 4 | SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
def calculate_price(number_of_tickets):
return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE
while tickets_remaining >= 1:
print("There are {} tickets remaining".format(tickets_remaining))
name = input("What is your name? ")
num_tic... | true |
8e4751931f1fc41b1b720e38e2774d0010550e9f | MAMBA-python/course-material | /Exercise_notebooks/Intermediate/04_modules_and_packages/example_package/somepackage/shout.py | 655 | 4.15625 | 4 | from .add import my_add
def shout_and_repeat(text):
"""
Describe here what this function does,
its input parameters, and what it returns.
In this example the function converts the input string
to uppercase and repeats it once.
"""
t = _shout(text)
result = my_add(t, t)
return resu... | true |
25867f1be45091c3f969ff874c955cf5e417423e | HYnam/Python-basic | /list_length.py | 416 | 4.28125 | 4 | # Write code to create a list of word lengths for the words in original_str using the accumulation pattern
# and assign the answer to a variable num_words_list. (You should use the len function).
original_str = "The quick brown rhino jumped over the extremely lazy fox"
split_str = original_str.split()
num_words_... | true |
d2240aea2debd56e1690e736165b184992707785 | KayleighPerera/COM411 | /Basics/Week2/or_operator.py | 394 | 4.28125 | 4 | # Ask user to enter type of adventure
print ("what is the adventure type?")
adventure_type = input()
# detrmine what the type of adventure is
if ( (adventure_type == "scary") or (adventure_type == "short") ):
print("\nEntering the dark forest!")
elif ( (adventure_type == "safe") or (adventure_type == "long") ):
pr... | true |
32e239e5a27031de5df104824df9f6425f7ce8b7 | devmohit-live/Adv_Python_Rev | /Collections files/ordered_dictionaries.py | 1,330 | 4.125 | 4 | # Keeps track of keys order (order in which the key,values are added)
from collections import OrderedDict
od = OrderedDict()
normal_dict = {}
od['Name'] = 'Mohit'
od['Branch'] = 'IT'
od['Year'] = 3
od['City'] = 'xyz'
od2=OrderedDict()
od2['Year'] = 3
od2['City'] = 'xyz'
od2['Name'] = 'Mohit'
od2['Branch'] = 'IT'
norma... | true |
e7b7507a053b8ea026876b12c2cf35e3a4736a03 | mkeita94/OOP-Practice | /Python/abstract.py | 575 | 4.1875 | 4 | # Cannot create an instance of an abstract class
# Abstraction in Python
# ABC- Abstract Base
# All classes that extend or inherit an abstract class
# should implements all the methods in in the abstract class
from abc import ABC, abstractmethod
class Computer(ABC):
@abstractmethod
def process(self)... | true |
638bfda8545df013e944dcad2f3f36eeb43fc72c | guoliangxd/interview | /huawei/Python/findLastWordLen.py | 412 | 4.15625 | 4 | # 返回最后一个单词长度
def findLastWordLen(arg):
""" 将输入的字符串去掉首尾空格后按空格分隔为字串列表,返回最后一个字串的长度"""
if(arg.find(" ") == -1):
#输入无空格时直接返回字符串长度
return len(arg)
arg = arg.strip()
substr = arg.split(' ')
return len(substr[-1])
str = input()
print(findLastWordLen(str))
| false |
05b03f1904bba186449fb93d12db66bc58eb712a | augustomy/Curso-PYTHON-01-03---Curso-em-Video | /desafio033aula10.py | 665 | 4.125 | 4 | n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
n3 = float(input('Digite o terceiro número: '))
if n1 >= n2 >= n3:
print('Maior número: {}\nMenor número: {}'.format(n1, n3))
if n1 >= n3 >= n2:
print('Maior número: {}\nMenor número: {}'.format(n1, n2))
if n2 ... | false |
74bae85dd8a1e73c26996a2c80c9a2ed9febd8c3 | Luksos9/LearningThroughDoing | /automateboringstuff/someSimplePrograms/TablePrinter.py | 928 | 4.40625 | 4 | #!/usr/bin/python3
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
#Create a list with each element representing columns that will store each column max width
columnWithds = [0]... | true |
d10f7b805e2229dad381280cbf2dc817235f08e5 | dhananjay-arora/Coin-Changes-Greedy-Algorithm | /Answer3.py | 1,002 | 4.3125 | 4 | # Assumption: One coin_denominations should be penny.
# O(nk)-time algorithm that makes change for any set of k different coin denominations
n = int(input("Enter the value in cents you want change for:"))
denomination_number = int(input("Enter how many coin_denominations you want to enter: "))
print("Enter the co... | true |
32bf723ebd71f8ae30fa1c5f56d3a712a55280fd | danielscarvalho/FTT-Compiladores-Python-2 | /p12.py | 401 | 4.28125 | 4 |
while True:
number = input("Entre com um valor: ")
if len(number) == 0:
break
number = float(number)
if number > 2:
print("Number is bigger than 2.")
elif number < 2: # Optional clause (you can have multiple elifs)
print("Number is smaller than 2.")
else: #... | true |
dbf474b0b2a9fccb8cd8b3fbe5b5c7379bc4c108 | hinsonan/ThinkPython | /ThinkPython/Chap8/8.2.py | 428 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 08:00:54 2018
@author: hinson
There is a string method called count that is similar to the function in Section 8.7.
Read the documentation of this method and write an invocation that counts the number of a’s in
'banana'.
"""
def main():
string = 'bana... | true |
8ecd0ce4a6322306888bf8b93a06f8091785f63c | hinsonan/ThinkPython | /ThinkPython/Chap3/3.1.py | 303 | 4.125 | 4 | #Write a function named right_justify that takes a string named s as a parameter
#and prints the string with enough leading spaces so that the last letter of the string is in column 70
#of the display.
def right_justify(s):
print (' '*(70-len(s))+s)
def main():
right_justify('Becca')
main() | true |
62383654407fafcea774eb6a7928e564efd143be | adang1345/Project_Euler | /5 Smallest Multiple.py | 855 | 4.25 | 4 | """Computes the smallest number that is divisible by 1 through 20"""
def isdivisible(num):
"""Determines whether num is divisible by 1 through 20. If and only if num is divisible by 11, 13, 14, 16, 17, 18,
19, and 20, then num must be divisible by all numbers from 1 through 20. Assume num is a positive integer... | true |
f5b3a50f2885bc847caf3b55daca9c58b7b241d0 | adang1345/Project_Euler | /3 Largest Prime Factor.py | 1,379 | 4.15625 | 4 | """Computes the largest prime factor of 600851475143"""
def isprime(num):
"""Determine whether num is prime.
If any integer from 2 to the square root of num divides evenly into num, then num is composite.
Otherwise, num is prime. Assume that num is an int greater than or equal to 2."""
for x in range... | true |
55280d87e90267b0f9d9355ef944f72b32afa817 | adang1345/Project_Euler | /60 Prime Pair Sets.py | 2,383 | 4.25 | 4 | """The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the
result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes,
792, represents the lowest sum for a set of four primes with this property.
Fi... | true |
b8043956a641116eaf01cf334bd15e01bf5d5e8c | adang1345/Project_Euler | /41 Pandigital Prime.py | 1,301 | 4.1875 | 4 | """We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example,
2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?"""
from itertools import permutations
def isprime(num):
"""Determine whether num is p... | true |
ad9134b038e359b4ebdf81b9b797db5cbe768576 | OcanoMark/CodingBat | /Python/String-1/03_make_tags.py | 346 | 4.34375 | 4 | # The web is built with HTML strings like "<i>Yay</i>" which draws Yay
# as italic text. In this example, the "i" tag makes <i> and </i> which
# surround the word "Yay". Given tag and word strings, create the HTML
# string with tags around the word, e.g. "<i>Yay</i>".
def make_tags(tag, word):
return "<" + tag + ">" ... | true |
462ac9a85d6bc6fb7b67357293dc32fc8f1a8490 | shouliang/Development | /Python/LeetCode/102_binary_tree_level_order_traversal.py | 2,498 | 4.21875 | 4 | '''
二叉树按层次遍历
102. Binary Tree Level Order Traversal:https://leetcode.com/problems/binary-tree-level-order-traversal/
思路: 使用队列这种数据结构:首先根节点进入队列,然后在队列头部弹出节点的同时,将其左右分支依次插入队列的尾部,
直至队列为空
其实这就是图的bfs,但是二叉树就是一种特殊的图
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
... | false |
b6fb84a877ad38392216216fd2b11b53fdefdd21 | shouliang/Development | /Python/LeetCode/ByteDance/103_zigzag_level_order_in_bs.py | 2,246 | 4.125 | 4 | '''
Z字型遍历二叉树
103. Binary Tree Zigzag Level Order Traversal:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
解释:
给定一个二叉树,返回其节点值的锯齿形层次遍历。
(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
... | false |
78a7aac950c98a644b7a40f02dd91d1dd750ec95 | shouliang/Development | /Python/LeetCode/ByteDance/122_best_time_to_buy_sell_stock_II.py | 2,939 | 4.34375 | 4 | '''
买卖股票的最佳时机(最大利润):可以交易多次
122. Best Time to Buy and Sell Stock II:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
解释:
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
思路:
贪心法:既然能买卖任意次,那最大收益的方法就是尽可能多的低入高抛。只要明天比今天价格高,就应该今... | false |
a8659f5d1210f3b9259a8b64456aca02b02c3549 | shouliang/Development | /Python/PythonBasic/range.py | 429 | 4.375 | 4 | # coding=utf-8
# range()返回一个可迭代对象,
# range(start,stop[, step])
# start:默认0
# end:计数到stop结束,但是不包括stop
# step:默认1
# list()函数是对象迭代器,可以把range()返回的可迭代对象转为一个列表
for i in range(5):
print(i)
print('----------')
r1 = list(range(5))
print(r1)
r2 = list(range(0, 10, 2))
print(r2)
r3 = list(range(0, 11, 2))
print(r... | false |
111695137d815680b1701cd420e75a34ba89e801 | DrCarolineClark/CtCI-6th-Edition | /Python/Chapter2/24Partion.py | 1,656 | 4.15625 | 4 | class node:
def __init__(self):
self.data = None # contains the data
self.next = None # contains the reference to the next node
class linked_list:
def __init__(self):
self.head = None
self.last_element = None
def add_node(self, data):
new_node = node() # create a ne... | true |
8584ffe1668412fb151552496023ce7ca32a3721 | alexh13/practicing-using-pandas | /pandas-intro.py | 1,188 | 4.5625 | 5 | # -pandas is a library used for data structures and data analysis tools.
# -used for loading data, web-scraping, loading & analyzing data from excel files
# * type ipython into to terminal *
import pandas
df1 = pandas.DataFrame([[2, 4, 6], [10, 20, 30]]) # Create a dataframe named df1
print(df1) # output dataFrame,... | true |
08fcdf096a5476868f6c0c66a7db9619003f306d | Nvardharutyunyan/group-sudo | /nvard/python/#2/sumDigits_R.py | 297 | 4.21875 | 4 | #!usr/bin/env python3
def sumOfNum_R(number):
if number == 0:
return 0
else:
return (number % 10) + sumOfNum_R(number // 10)
num = int(input("Enter the number : "))
if num < 0 :
print ("Your number is not natural!")
else :
print("The sum of number is equal ", sumOfNum_R(num))
| true |
8a651d47bd71be5a3b86d3c74ac7d07959bd516d | LaKeshiaJohnson/MasterTicket | /masterticket.py | 1,547 | 4.3125 | 4 | #Run code until tickets run out
#Output how many tickets remaining using tickets_remaining variable
#Gather the user's name and assign it to a new variable
#Prompt user by name to ask how many tickets they would like
#Calculate price and output to screen
#Prompt user if they want to continue. Y/N
#if they want to proce... | true |
20af00eb4cef13ab24fa2ca2705b743383d20b39 | colknives/basic-python | /sample/test.py | 2,647 | 4.3125 | 4 | ''' Sample print function '''
print('This is an example of a print function')
''' Sample variable '''
testVar = "Sample text"
print(testVar)
''' Sample packing '''
x,y = (3,5)
print(x)
print(y)
''' Sample while condition '''
condition = 1
while condition < 10:
print(condition)
condition += 1
''' Sample... | false |
753d7fba1cc4654f8f184342bc35258becc8cb3f | nutcheer/pythonlearning | /pr4_10.py | 291 | 4.5625 | 5 | names = ['one','two','three','four','five']
print("The first three names are ")
for name in names[:3]:
print(name)
print("Three items from the middle of the list are ")
for name in names[1:4]:
print(name)
print("The last three items in the list are ")
for name in names[-3:]:
print(name)
| false |
a2dd2109b50309900c072eec2a595f18527b4339 | nutcheer/pythonlearning | /pr6_6.py | 346 | 4.15625 | 4 | favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
names = ['jen', 'sarah', 'tiffany', 'nutcheer']
for name in favorite_languages.keys():
if name in names:
print(name+", thank you for your attending!")
else:
print(name+", I am glad to in... | true |
7e54459b7677906d392f6da4cc03e9662128de8e | sinitsa2001/h_work | /Lesson2/Home2.2.py | 1,175 | 4.25 | 4 | #Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
# не понимаю - как завести в цикл...не ра... | false |
cd045d94572fd6ae5c50ef2a06c5d33055411977 | AYAN-AMBESH/learning-Python | /ex17.py | 391 | 4.1875 | 4 | #Write a Python program to calculate the sum of three given numbers, if the values are equal then return thrice of their sum.
num1 = input("ENTER NUMBER: ")
num3 = input("ENTER NUMBER: ")
num2 = input("ENTER NUMBER: ")
def Sum_of_num(num1,num2,num3):
sum = num1 + num2 + num3
if num1 == num2 == num3:
sum... | true |
7d0b68ff37e131779042de77c5510b177cc86fba | AYAN-AMBESH/learning-Python | /ex25.py | 281 | 4.40625 | 4 | #Write a Python program to find whether a given number (accept from the user) is even or odd,
#print out an appropriate message to the user
n = int(input("Enter a number: "))
if n%2==0:
print("{} is a even number. ".format(n))
else:
print("{} is a odd number. ".format(n)) | true |
296f5548557486ae7a0e4127e179e4944ed2ff03 | AYAN-AMBESH/learning-Python | /ex7.py | 245 | 4.125 | 4 | #Write a short Python function that takes a positive integer n and returns
#the sum of the squares of all the positive integers smaller than n
def Square(n):
Sum=0
for i in range(0,n):
Sum += i**2
return Sum
print(Square(5))
| true |
34047e9fb0c2f4e04c39edb80bc590794d34c027 | atavener68/intro_to_python | /problem4.py | 806 | 4.34375 | 4 | # Write a function named reverse_me that
# takes a string as a parameter,
# and returns the reversed string.
#
# Do this without using pythons [::-1] slice shortcut,
# or the built in reversed() method
#
# You will need to count down from the length of the string,
# and build up the output one piece at a time.
#
# The ... | true |
0a7cb008779c84830c21a282b2e9ded30dfb3aeb | GRustle00/pathofpython | /lpthw/ex19/ex19.py | 1,304 | 4.125 | 4 | #call defined function cheese_and_crackers where the argumens are cheese_count, boxes_of_crackers
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("... | true |
ae277b3a45616ff0f07b57049489dd243cafdfb8 | MAdisurya/data-structures-algorithms | /questions/reverse_words.py | 2,775 | 4.6875 | 5 | """
Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault.
The message has been mostly deciphered, but all the words are backward! Your colleagues have handed off the last step to you.
Write a function reverse_words() that takes a message as a list... | true |
624a613e35444aa6259e6de55f6210228b86f6b1 | dallasmcgroarty/python | /General_Programming/strings/strings.py | 437 | 4.28125 | 4 | #f-strings in python3
#places a value in a string
x = 10
print(f"I've told you {x} times already")
#join function
#can use logic in the join argument
#takes a list and joins them together in a string
names = ["hey","there","tom"]
names_str = ' '.join(names)
print(names_str)
#takes a list of numbers and converts the... | true |
64f357e4af0bd381e65e4fc98ae074303a8cad4d | dallasmcgroarty/python | /DataStructures_Algorithms/trees/bst_problems.py | 2,459 | 4.15625 | 4 | # bst problems
from bst import *
# problem 1
# given a binary tree, determine if its a binary search tree or not
def bst_check(tree):
# binary search tree orders lower to left and greater to right
# therefore if we do a inorder traversal the values should be sorted
# if not then we dont have a bst
valu... | true |
e32d47e35b1cc18e29f8a3d9baaf20707befcb20 | dallasmcgroarty/python | /General_Programming/BI_Functions/zip.py | 1,618 | 4.46875 | 4 | # zip function
# makes an iterable that takes elements from each of the iterables
# takes elements from each iterable at the same positon and creates a pair,triplet,etc
nums1 = [1,2,3,4,5]
nums2 = [6,7,8,9,10]
z = zip(nums1,nums2)
z1 = zip(nums1,nums2)
p = zip(nums1,nums2)
# use list or dict to convert zip object
prin... | true |
b575310940f81b968bd1662c9d9936579f93f701 | dallasmcgroarty/python | /General_Programming/OOP/grumpy_dict.py | 665 | 4.40625 | 4 | # overriding dictionary object in python
# using magic methods we can override how a dictionary functions
# this can also be applied to other objects as well
class grumpyDict(dict):
def __repr__(self):
print("None of Your Business")
return super().__repr__()
def __missing__(self, key):
... | true |
c848222cb081dc5f99321f079447b6ee37f36395 | stasDomb/PythonHomeworkDombrovskyi | /Lesson3Homework/LessoneExerc4.py | 635 | 4.28125 | 4 | # Задача-4
# Изменить исходную строку на новую строку в которой первый и последний символы строки поменяны местами.
def modify_string(example_string):
the_begin = example_string[:1]
the_end = example_string[len(example_string) - 1:]
new_string = the_end + example_string[1:] + the_begin
return new_stri... | false |
437fa5e62f044e2799791dc91a80c1a0af0a1766 | shuvava/python_algorithms | /permutations/heap_algorithm.py | 1,794 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2020-2022 Vladimir Shurygin. All rights reserved.
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
"""
Heap's algorithm
https://en.wikipedia.org/wiki/... | true |
e4d68156d2c5e8dfe2299b94ed6373fbff14f555 | Rhabersh/brown-repo | /oscar_project/oscar_table_create.py | 1,822 | 4.25 | 4 | import sqlite3
from sqlite3 import Error
#Create class, pass through
def sqlite_connect():
"""
This function will use the sqlite3 module to connect to a database. If the
specified database is not found in the local directory, a new one with
the given name will be created.
... | true |
ea7609c525852a1e26b665cf8ff0ac4322e9fbce | thefirstcomma/Learn-Python-the-Hard-Way | /flowcharts/astronaut.py | 1,883 | 4.125 | 4 | def alien():
print "Are You really just in it to meet the Aliens? (y/n)"
alien = raw_input('> ')
if alien == 'y':
print "Seti Researcher, until all the funding is pulled out."
elif alien == 'n':
print "They won't live up to the hype huh."
print "Sci-Fi Writer for you."
def not_input():
print ... | false |
a5c1d3bf022385a9b65a5b6216f5bc007b8d4584 | cielliyuanpeng/learn_Python_in_hard_way | /ex39.py | 1,214 | 4.21875 | 4 | # create a mapping of state to abbreviation
states = {
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
}
cities = {
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksoville'
}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
#print cities
print('-'... | false |
aea792baa1a8e9cee6611f2a5409c5bdb036b88b | Sam-Whitley/petrikuittinen_assignments | /lesson_python_basics/for_reversed.py | 278 | 4.125 | 4 | names = ["Bill", "James", "Paul", "Paula", "Jenny", "Kate"]
# normal order
for name in names:
print(name)
print("Reverse order:")
for name in reversed(names):
print(name)
print("Don't code like this")
i = len(names)-1
while i >= 0:
print(names[i])
i = i-1
| true |
dc567267261b2cf45c92e9d7dc6926ec1ae28432 | Zivilevs/Python-programming | /temp_graf.py | 1,244 | 4.25 | 4 | #!/usr/bin/python
# Program to convert Celsius to Fahrenheit using a simple
# graphical interface.
from graphics import *
def main() :
win = GraphWin( "Celsius Converter" , 400 , 300)
win.setCoords (0.0, 0.0 , 3.0, 4.0)
win.setBackground("white")
# Draw the interface
label1 = Text(Point(1,3)... | true |
b901ec9ccec8c27a6010deae9cd372c7f19261f7 | ryanlkraemer/RK-engineering-class | /LearningPythonTheHardWay/ex7.py | 916 | 4.28125 | 4 | #prints a straight string
print("Mary had a little lamb")
#prints a string by leaving a { in a string, then .formatting to fill it with 'snow'. Format takes whatever is in front, either a variable
#defined to be a string or a string (always with a {} and puts the thing in the parentheses after the format into the {} ... | true |
de6237b74bb8eeda49cbdd2a7bb42968fe79815c | ryanlkraemer/RK-engineering-class | /LearningPythonTheHardWay/ex29.py | 444 | 4.15625 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print("Too many cats!")
if people > cats or dogs < cats:
print("idc bro")
if people > dogs and dogs != cats:
print("wet world")
if people > dogs:
print("dry world")
dogs += 5
if people >= dogs:
print("people are greater than or equal to dogs.")... | false |
0830ef6c3d547d2ade1beb51446e9b4648b27743 | ryanlkraemer/RK-engineering-class | /LearningPythonTheHardWay/ex15.py | 671 | 4.15625 | 4 | #takes the module argv from system, allowing me to input the meat of the matter
from sys import argv
#defines the things in that order for me to input with argv
script, filename = argv
#defines txt as the file that i input
txt = open(filename)
#says a useless thing
print(f"""Here's your file {filename}.
""")
#reads ... | true |
7764bd7f4d1dc3ebb76b6fe154fc5055282be820 | cjreynol/willsmith | /willsmith/action.py | 1,394 | 4.28125 | 4 | from abc import ABC, abstractmethod
class Action(ABC):
"""
Abstract base class for game actions.
Subclasses are convenient containers to remove the reliance on nested
tuples and the copious amounts of packing and unpacking required by
them.
The parse_action method is used to convert string... | true |
5933bc9b90a669e673ab82ed3b7b2893f96e7ddc | bingely/PythonLearning | /函数/函数的参数.py | 1,116 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 默认参数
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
print(power(2, 5))
print(power(3))
def add_end(L=[]):
L.append('END')
return L
def add_end_improve(L=None): # 定义默认参数要牢记一点:默认参数必须指向不变对象!
if L is None:
... | false |
f5020fc8bb541dbfc85b1372ea762a19360983fb | DarkCron/PythonBvP | /Oefenzitting4/E2B.py | 442 | 4.15625 | 4 | def FibonNum (n):
if(n==1):
return 1
fibonMinus1 = 1
fibonMinus2 = 1
highestFibon = 2
counter = 1
while n > highestFibon:
highestFibon = fibonMinus1+fibonMinus2
fibonMinus2 = fibonMinus1
fibonMinus1 = highestFibon
counter+=1
if(n==highestFibon):
... | false |
a282df0e875513863718d2b3f2a8ba6cc4390a60 | DarkCron/PythonBvP | /Oefenzitting2/Letters to grades P3.12.py | 1,655 | 4.15625 | 4 | print("Enter a letter grade: ")
lettergrade = input("")
numberGrade = 0.0
DEFAULT_A = 4.0
DEFAULT_B = 3.0
DEFAULT_C = 2.0
DEFAULT_D = 1.0
DEFAULT_F = 0.0
DEFAULT_MOD = 0.3
currentValue = 0.0
printValue = ""
if (lettergrade).startswith("A"):
currentValue = DEFAULT_A
elif (lettergrade).startswith("B"):
curren... | false |
b6f0bb3b88752eecdccd8ccda259bd94e33f6bca | DarkCron/PythonBvP | /Oefenzitting1/Extra/P2-11p81.py | 553 | 4.25 | 4 | gallons_gas = float(input("The number of gallons of gas in tank: "))
miles_per_gallon = float(input("The fuel efficiency in miles per gallon: "))
price_per_gallon = float(input("The price of gas per gallon: "))
DISTANCE = 100
drivable_distance = gallons_gas * miles_per_gallon;
# x miles = 1 gallon
# 100 miles = 1 / ... | true |
f8dd76c62b60151dcf6e3d4b1dfdcfdc45ede397 | reneafranco/Course | /POO/main.py | 2,204 | 4.46875 | 4 | """CLASE
una clase es un molde para crear varios objetos con caracteristicas parecidas
ATRIBUTOS
son las particulidades de la clase como nombre y propiedades
METODOS
son las funciones de la clase basicamente las funciones que le otorgues para que pueda realizarse"""
#Definir una clase (Molde para crear mas objetos de ... | false |
7938b5edcf60ed84bf79296e95e40a41533f8909 | hugolribeiro/Python_Projects | /Dice Rolling Simulator.py | 1,493 | 4.5625 | 5 | # 1. Dice Rolling Simulator The Goal: Like the title suggests, this project involves writing a program that simulates
# rolling dice. When the program runs, it will randomly choose a number between 1 and 6. (Or #whatever other integer
# you prefer — the number of sides on the die is up to you.) The program will print w... | true |
2139b3e6a019ead6728fbb21595cb7ac2ce2d70a | Cabottega/python_exercises | /python_index_based_interpolation.py | 907 | 4.5 | 4 | # instructor notes from python documentation website.
# str.format(*args, **kwargs)
# Perform a string formatting operation. The string on which this method is called can contain literal text or >replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional >argumen... | true |
baec7769933fea8a98842aab9d80a8ff7f88d545 | Cabottega/python_exercises | /looping_over_characters.py | 290 | 4.6875 | 5 | alphabet = 'abcdef'
for letter in alphabet:
print(letter)
# instructor notes:
# alphabet = 'abcdef'
# for letter in alphabet:
# print(letter)
# """
# you have a string here
# a for in loop allows you to access them just like a string/collection
# 'a', 'b', 'c', 'd' ect
# """
| true |
0985ed07d4a2dd7331e6b4a978fe8e1a75d00b30 | Cabottega/python_exercises | /tuples_delete_elements.py | 994 | 4.3125 | 4 | post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published')
# Removing elements from end
post = post[:-1]
# Removing elements from beginning
post = post[1:]
# Removing specific element (messy/not recommended)
post = list(post)
post.remove('published')
post = tuple(post)
print(post)
#... | true |
6e44076369067e868300c1341c8e1856c0449253 | bglajchen/MIT-Intro-to-Python-6.0001 | /ps1/ps1c.py | 1,839 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 7 13:35:24 2020
@author: bglajchen
"""
annual_salary = float(input("Enter your annual salary: "))
total_cost = 1000000
semi_annual_raise = 0.07
portion_down_payment = total_cost * 0.25
current_savings = 0
number_of_months = 0
possible = True
ste... | true |
f6abe0260a989a51b762704a4e995e5def0a787a | venkatsvpr/Problems_Solved | /LC_Smallest_String_With_Swaps.py | 2,349 | 4.15625 | 4 | """
1202. Smallest String With Swaps
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest s... | true |
7dcc423ef57281c3b751539fd5f7d0a3c61ec863 | awalGaurab/fahrenheit_to_celsius | /converter.py | 388 | 4.21875 | 4 | def converter(fahren):
converted_value = (fahren - 32)/1.8
return converted_value
try:
input_val = float(input("Enter temperature in fahrenheit: "))
converted_temp = converter(input_val)
print("{} fahrenheit is equivalent to {} degree celsius value.".format(round(converted_temp,2),input_val))
excep... | false |
c031dddd3c3e0685e82ef5f5934654765ddb7ab7 | alakamale/888 | /Tree/src/internal_node.py | 530 | 4.21875 | 4 | # 1. Find internal nodes
# Let's assume we have a generic tree, such as follows (node values are simply identifiers):
# Then we define this tree with a list L: [4, 2, 4, 5, -1, 4, 5] such as L(i) identifies the parent of i (the root has no parent and is denoted with -1).
# An internal node is any node of a tree that ha... | true |
e43de700059c31e5db0c7a7f6e837c0556186b3b | ChiselD/pyglatin | /pyglatin.py | 2,946 | 4.21875 | 4 | # THINGS TO FIX
# 1. multiple consonants at start of word - DONE!
# 2. printing on separate lines - DONE!
# 3. non-alphabetical strings
# 3a. if user includes numbers, return error - DONE!
# 3b. if user includes punctuation, move it to correct location
# 4. omitted capitalization
# separate variables for the two possi... | true |
513be128e24652eb1eef63f752fbabcae68c7437 | junweitan1999/csci1100 | /homework/hw4/hw4Part1.py | 2,225 | 4.40625 | 4 | # function to define the word is alternating or not
def is_alternating(word):
#initializing
vowels = []
letter=['a','b','c','d','e','f','g','h','j','k','l','i','o','u','m','n','p','q','r','s','t','v','w','x','y','z']
judge = True
same_or_not = True
judgment =False
word_copy=... | true |
2f1757c8454ec56b1cf3360f486c54ab8230eb2f | chandni-s/NewsFlash | /src/model.py | 1,538 | 4.3125 | 4 | class Model():
"""A database model. Objects that interact with the database (add, get,
delete, etc...) should be derived from this class. This helps create a
consistent interface for the database to use to implement its functions
(and prevents lots of repetition in queries as a bonus)."""
# (str)
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.