blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4c5a6f6d8e2d5a076872f06d0484d9d5f6f85943 | jacobkutcka/Python-Class | /Week03/rainfall.py | 1,668 | 4.25 | 4 | ################################################################################
# Date: 03/01/2021
# Author: Jacob Kutcka
# This program takes a year count and monthly rainfall
# and calculates the total and monthly average rainfall during that period
###################################################################... | true |
fe40e8644f98b8c2ebf6fedd95938c4dc95175d1 | lukeyzan/CodeHS-Python | /LoopandaHalf.py | 474 | 4.21875 | 4 | """
This program continually asks a user to guess a number until they have guessed
the magic number.
"""
magic_number = 10
# Ask use to enter a number until they guess correctly
# When they guess the right answer, break out of loop
while True:
guess = int(input("Guess my number: "))
if guess == magic_number:
... | true |
2e4d716798afd6e737492f33e56165a5de790aaf | rsaravia/PythonBairesDevBootcamp | /Level3/ejercicio4.py | 418 | 4.4375 | 4 | # Write a Python function using list comprehension that receives a list of words and
# returns a list that contains:
# a. The number of characters in each word if the word has 3 or more characters
# b. The string “x” if the word has fewer than 3 characters
low = ['a','este','eso','aquello','tambien']
lor = [len(x) if... | true |
6e438a337feb8ef59ca8c8deae05ea6bfcbe1c13 | rsaravia/PythonBairesDevBootcamp | /Level1/ejercicio10.py | 543 | 4.28125 | 4 | # Write a Python program that iterates through integers from 1 to 100 and prints them.
# For integers that are multiples of three, print "Fizz" instead of the number.
# For integers that are multiples of five, print "Buzz".
# For integers which are multiples of both three and five print, "FizzBuzz".
l = [x+1 for x in ... | true |
5df3fa2d2ab2671f2302a582e95716d6a57dc09e | mariebotic/reference_code | /While Loops, For Loops, If Else Statements, & Boolean Operators.py | 2,947 | 4.53125 | 5 | # WHILE LOOPS, FOR LOOPS, IF ELSE STATEMENTS, & BOOLEAN OPERATORS
#______________________________________________________________________________________________________________________________________________________________________________#
import random
while True:
user_input = input("Please enter a number be... | true |
5b0b217cb0b2b4ef16066e9f2eb722347a7445ba | emjwalter/cfg_python | /102_lists.py | 1,058 | 4.625 | 5 | # Lists!
# Define a list with cool things inside!
# Examples: Christmas list, things you would buy with the lottery
# It must have 5 items
# Complete the sentence:
# Lists are organized using: ___variables____?????
# Print the lists and check its type
dreams = ['mansion', 'horses', 'Mercedes', 'flowe... | true |
4cd98053e49db7a5422d7ec0c410325f228dd5d2 | emjwalter/cfg_python | /104_list_iterations.py | 707 | 4.34375 | 4 | # Define a list with 10 names!
register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Barry', 'Belle', 'Bertie', 'Becky', 'Belinda']
# use a for loop to print out all the names in the following format:
# 1 - Welcome Angelo
# 2 - Welcome Monica
# (....)
register = ['Bob', 'Billy', 'Brenda', 'Betty', 'Brian', 'Bar... | true |
ee9422e8c3398f0fae73489f6079517f2d3396b5 | scress78/Module7 | /basic_list.py | 718 | 4.125 | 4 | """
Program: basic_list.py
Author: Spencer Cress
Date: 06/20/2020
This program contains two functions that build a list for Basic List Assignment
"""
def get_input():
"""
:returns: returns a string
"""
x = input("Please input a number: ")
return x
def make_list():
"""
... | true |
0ae7ca84c21ffaa630af8f0080f2653615758866 | VertikaD/Algorithms | /Easy/highest_frequency_char.py | 974 | 4.4375 | 4 | def highest_frequency_char(string):
char_frequency = {}
for char in string:
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
sorted_string = sorted(char_frequency.items(),
key=lambda keyvalue: key... | true |
30c2f43d22e30ade58e703b3ac64176db33a3cbf | juancarlosqr/datascience | /python/udemy_machine_learning/02_simple_linear_regression/01_simple_linear_regression.py | 2,083 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 13:49:10 2018
@author: jc
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# data preprocessing
# import dataset
dataset = pd.read_csv('salary_data.csv')
x = dataset.iloc[:, :-1].values
dependant_column_index = 1
y = ... | true |
22ebee6a673d7af7cc1a34744d4efeaa07e5c92b | lukasz-lesiuk/algo-workshop | /algo-workshop.py | 729 | 4.40625 | 4 | def get_even_numbers(x, stop, z):
"""
Returns a list containing first 'x' even elements lower than 'stop'.
Those elements must be divisible by 'z'.
"""
raw_list = []
for i in range(1,(stop//2)):
raw_list.append(2*i)
# print(raw_list)
list_sorted = []
for element in raw_list... | true |
71c4b61ee65ceb5042908accca49af509fc43210 | cyr1z/python_education | /python_lessons/02_python_homework_exercises/ex_03_lists.py | 1,208 | 4.34375 | 4 | """
Exercise: https://www.learnpython.org/en/Lists
In this exercise, you will need to add numbers and strings
to the correct lists using the "append" list method. You must add
the numbers 1,2, and 3 to the "numbers" list, and the words 'hello'
and 'world' to the strings variable.
You will also ha... | true |
8b9d35551a9f5b123a30c3e63ddf7f637eec279a | collins73/python-practice-code | /app.py | 823 | 4.21875 | 4 | # A simple program that uses loops, list objects, function , and conditional statements
# Pass in key word arguments into the function definition my_name
def my_name(first_name='Albert', last_name='Einstein', age=46):
return 'Hello World, my name is: {} {}, and I am {} years old'.format(first_name,last_name, a... | true |
9ef773c250dab6e409f956fb10844b1e3a22015f | Zakaria9494/python | /learn/tuple.py | 804 | 4.25 | 4 | #A tuple is a collection which is ordered and unchangeable.
# In Python tuples are written with round brackets.
thistuple = ("apple", "banana",
"cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[1])
# negative Indexing
#Print the last item of the tuple:
print(thistuple[-1])
#ran... | true |
89d56e31f80950b8003903c7d20044b62d56a72a | eventuallyrises/Python | /CW_find_the_next_perfect_square.py | 821 | 4.15625 | 4 | #we need sqrt() so we import the build in math module
import math
#we start the function off taking in the square passed to it
def find_next_square(sq):
#for later we set up the number one higher than the passed square
wsk=sq+1
# Return the next square if sq is a square, -1 otherwise
#here we look to see... | true |
d0e40a83f302dc6a0117634b7224494dd69ab992 | KuroKousuii/Algorithms | /Prime numbers and prime factorization/Segmented Sieve/Simple sieve.py | 832 | 4.15625 | 4 | # This functions finds all primes smaller than 'limit'
# using simple sieve of eratosthenes.
def simpleSieve(limit):
# Create a boolean array "mark[0..limit-1]" and
# initialize all entries of it as true. A value
# in mark[p] will finally be false if 'p' is Not
# a prime, else true.
mark = [True for... | true |
862b61d7ff0c079159910d20570041da0d4747a3 | jasimrashid/cs-module-project-hash-tables | /applications/word_count/word_count_one_pass.py | 2,043 | 4.21875 | 4 | def word_count(s):
wc = {}
# without splitting string
beg = 0
c = ''
word = ''
word_count = {}
for i,c in enumerate(s):
# if character is end of line, then add the word to the dictionary
if i == len(s)-1: #edge case what if there is a space at the end of line or special... | true |
f5812e58373f52e38f8efa72d8e4a6627526f194 | prateek951/AI-Workshop-DTU-2K18 | /Session1/demo.py | 1,816 | 4.75 | 5 | # @desc Working with Numpy
import numpy as np
# Creating the array using numpy
myarray = np.array([12,2,2,2,2,2])
print(myarray)
# The type of the array is np.ndarray whereas in python it would be list class
print(type(myarray))
# To print the order of the matrix
print(myarray.ndim)
# To print the shape of the a... | true |
58558f014aa28b29b9e2ad662cd783ff524bd220 | prateek951/AI-Workshop-DTU-2K18 | /Session-5 Working on Various Python Library/numpyops.py | 2,447 | 4.375 | 4 | my_list = [1,2,3]
# Importing the numpy library
import numpy as np
arr = np.array(my_list)
arr
# Working with matrices
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
np.array(my_matrix)
# Create an array
np.arange(0,10)
# Create an array keeping the step size as 2
np.arange(0,10,2)
# Arrays of zeros
np.zeros(3)
# Array ... | true |
e4db9a855ebaf188c4190ec4c564a0c46a3c573f | abhiis/python-learning | /basics/carGame.py | 889 | 4.15625 | 4 | command = ""
is_started = False
is_stopped = False
help = '''
start: To start the car
stop: To stop the car
quit: To exit game
'''
print("Welcome to Car Game")
print("Type help to read instructions\n")
while True: #command != "quit": if we write this condition, last else block always gets executed
command = inpu... | true |
409e94361c99c3833dcc7990a2593b3ee5b10f10 | amolgadge663/LetsUpgradePythonBasics | /Day7/D7Q1.py | 393 | 4.1875 | 4 | #
#Question 1 :
#Use the dictionary,
#port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"},
#and make a new dictionary in which keys become values and values become keys,
# as shown: Port2 = {“FTP":21, "SSH":22, “telnet":23,"http": 80}
#
port1 = {21: "FTP", 22:"SSH", 23: "telnet", 80: "http"}
print(port1)... | true |
59125fe5d98160896e811a9be0cf6421a73e711c | DRCurado/Solids_properties | /Circle.py | 744 | 4.21875 | 4 | #Circle shape
#Calculate the CG of a circle.
import math
#insert the inuts of your shape:
unit = "mm"
#insert the dimensions of your shape:
diameter = 100;
#Software do the calculations
Area = math.pi*(diameter/2)**2;
Cgx = diameter/2;
Cgy = diameter/2;
Ix= (math.pi*diameter**4)/64;
Iy= (math.pi... | true |
45e20efd919cb4ab2fc2b6b03449a8066b8f4f2a | alphaolomi/cryptography-algorithms | /transposition_encryption.py | 1,122 | 4.1875 | 4 | # Transposition Cipher Encryption
def main():
my_message = 'Common sense is not so common.'
my_key = 8
cipher_text = encrypt_message(my_key, my_message)
# Print the encrypted string in cipher_text to the screen, with
# a | (called "pipe" character) after it in case there are spaces at
# the en... | true |
ca827f71d84324d576adac8192f0391af29a457c | rragundez/utility-functions | /ufuncs/random.py | 699 | 4.1875 | 4 |
def generate_random_string(length, *, start_with=None,
chars=string.ascii_lowercase + string.digits):
"""Generate random string of numbers and lowercase letters.
Args:
length (int): Number of characters to be generated randomly.
start_with (str): Optional string to s... | true |
c10cb232f6c7b665dbf7fe0b672a8034dd97b6af | lukeitty/problemset0 | /ps0.py | 2,630 | 4.25 | 4 | #Author: Luke Ittycheria
#Date: 3/28/16
#Program: Problem Set 0 Functions
#Function 0
def is_even(number):
'''Returns a value if the number is even or odd'''
if number == 0:
return True
if number % 2 == 0:
return True
else:
return False
return evenOrOdd
#############################################... | true |
39b91946afdb07d27c8314405268e89e842c8840 | benichka/PythonWork | /favorite_languages.py | 707 | 4.40625 | 4 | favorite_languages = {
'Sara' : 'C',
'Jen' : 'Python',
'Ben' : 'C#',
'Jean-Claude' : 'Ruby',
'Jean-Louis' : 'C#',
}
for name, language in favorite_languages.items():
print(name + "'s favorite language is " + language + ".")
# Only for the keys:
print()
for k in favo... | true |
618e1fdc6d658d3fc80cff91737e74f6f8fc30a6 | benichka/PythonWork | /chapter_10/common_words.py | 553 | 4.25 | 4 | # Take a file and count occurences of a specific text in it.
text_file = input("Choose a text file from which to count occurences of a text: ")
occurence = input("What text do you want to count in the file?: ")
try:
with open(text_file, 'r', encoding="utf-8") as tf:
contents = tf.read()
except:
print("... | true |
d8947556c73c79505c31eb54718aecb20f1b1c2b | benichka/PythonWork | /chapter_10/addition.py | 787 | 4.28125 | 4 | # Simple program to add two numbers, with exception handling.
print("Input 2 numbers and I'll add them.")
while (True):
print("\nInput 'q' to exit.")
number_1 = input("\nNumber 1: ")
if (number_1 == 'q'):
break
try:
number_1 = int(number_1)
except ValueError:
print("\nOnly n... | true |
8e0f68898778383bcc958dcade2b9f06910d1b61 | ndpark/PythonScripts | /dogs.py | 949 | 4.21875 | 4 | #range(len(list)) can be used to iterate through lists
dogs = []
while True:
name = input('Dog name for dog # ' + str(len(dogs)+1) + '\nType in empty space to exit\n>>')
dogs = dogs + [name] #Making a new list called name, and then adding it to dogs list
if name == ' ':
break
print ('The dog names are:')
for name ... | true |
8ade98a9e878e8ba1790be5e225372d9482b6cbb | ndpark/PythonScripts | /backupToZip.py | 859 | 4.21875 | 4 | #! python3
# backupToZip.py - Copies entire folder and its content into a zip file, increments filename
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) #Folder must be absolute
#Figures out what the filename should be
number = 1
while True:
zipFilename = os.path.basename(folder) ... | true |
632a672805914b130a2de77eff69cc66af77c25c | rhitik26/python1 | /python assignments/day4b.py | 471 | 4.125 | 4 | def outer(a):
def inner():
print("this is inner!")
print(type(a))
a()
print("Inner finished execution!")
return inner
@outer #By adding this annotation the function will automatically become wrapper function(the concept is Decorator)
def hello():
print("hello World!")
@outer... | true |
13d7ab468faf1f3342bf8f221ca36e51437b131d | bloomsarah/Practicals | /prac_04/lottery_ticket_generator.py | 778 | 4.1875 | 4 | """
Generate program that asks for number of quick picks
print that number of lines, with 6 numbers per line
numbers must be sorted and between 1 and 45
"""
import random
NUMBERS_PER_LINE = 6
MIN = 1
MAX = 45
def main():
number_of_picks = int(input("Enter number of picks: "))
while number_of_picks < 0:
... | true |
a4fe0d90b2772844969b34ce6ffa103c294ddfa1 | timeeeee/project-euler | /4-largest-palindrome-product/main.py | 358 | 4.15625 | 4 | # Find the largest palindrome that is the product of 2 3-digit numbers.
def isPalindrome(x):
string = str(x)
return "".join(reversed(string)) == string
maximum = 0;
for a in range(111, 1000):
for b in range(111, 1000):
product = a * b
if isPalindrome(product) and product > maximum:
... | true |
206deca44b6fa1c1147d3c6d698d92ea2aee44ed | timeeeee/project-euler | /62-cubic-permutations/slow.py | 1,720 | 4.15625 | 4 | """
The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are cube.
"""
from ... | true |
319e95ee89071a5402aaa30aac4f77e2f34a9168 | mkuentzler/AlgorithmsCourse | /LinkedList.py | 771 | 4.1875 | 4 | class Node:
"""
Implements a linked list. Cargo is the first entry of the list,
nextelem is a linked list.
"""
def __init__(self, cargo=None, nextelem=None):
self.car = cargo
self.nxt = nextelem
def __str__(self):
return str(self.car)
def display(self):
if s... | true |
43a5d6ca3431c87af401db8ceda677bca0a1a52e | AjsonZ/E01a-Control-Structues | /main10.py | 2,365 | 4.21875 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # print out 'Greeting!'
colors = ['red','orange',... | true |
9ebc5c4273361512bd5828dee90938820b41f097 | Andrew-2609/pythonbasico_solyd | /pythonbasico/aula11-tratamento-de-erros.py | 872 | 4.21875 | 4 | def is_a_number(number):
try:
int(number)
return True
except ValueError:
print("Only numbers are allowed. Please, try again!")
return False
print("#" * 15, "Beginning", "#" * 15)
result = 0
divisor = input("\nPlease, type an integer divisor: ")
while not is_a_number(divisor):... | true |
bdc98a6f01d7d4a9663fd075ace95def2f25d35c | BipronathSaha99/GameDevelopment | /CurrencyConverter/currencyConverter.py | 608 | 4.34375 | 4 | # >>-----------CurrencyConverter-------------------<<
#To open currency list from text file .
with open("currency.txt") as file:
lines=file.readlines()
#to collect all information create a dictionary
currencyDic={}
for line in lines:
bipro=line.split("\t")
currencyDic[bipro[0]]=bipro[1]
... | true |
163d79e904d442ee971f10f698b79a7ee7bf85fa | micahjonas/python-2048-ai | /game.py | 2,514 | 4.3125 | 4 | # -*- coding: UTF-8 -*-
import random
def merge_right(b):
"""
Merge the board right
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_right(test)
[[0, 0, 2, 8], [0, 2, 4, 8], [0, 0, 0, 4], [0, 0, 4, 4]]
"""
def reverse(x):
return list(reversed(x))
t = m... | true |
f6422f0594441635eac2fd372428aa160ca3bbb3 | HamPUG/meetings | /2017/2017-05-08/ldo-generators-coroutines-asyncio/yield_expression | 1,190 | 4.53125 | 5 | #!/usr/bin/python3
#+
# Example of using “yield” in an expression.
#-
def generator1() :
# failed attempt to produce a generator that yields an output
# sequence one step behind its input.
print("enter generator")
value = "start"
while value != "stop" :
prev_value = value
print("abo... | true |
3af6228c9d8dcc735c52ae7d8375f007145ffe98 | MukundhBhushan/micro-workshop | /tectpy/if.py | 235 | 4.15625 | 4 | num=int(input("Enter the number to be tested: "))
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
| true |
f9f0e8f9212598847750967c8898eefed9e441ed | ryotokuro/hackerrank | /interviews/arrays/arrayLeft.py | 900 | 4.375 | 4 | #PROBLEM
# A left rotation operation on an array shifts each of the array's elements unit to the left.
# For example, if left rotations are performed on array , then the array would become .
# Given:
# - an array a of n integers
# - and a number, d
# perform d left rotations on the array.
# Return the updated array ... | true |
9af20e6ee68952b2f0b61685ce406d13c770cc00 | ryotokuro/hackerrank | /w36/acidNaming.py | 828 | 4.1875 | 4 | '''
https://www.hackerrank.com/contests/w36/challenges/acid-naming
Conditions for naming an acid:
- If the given input starts with hydro and ends with ic then it is a non-metal acid.
- If the input only ends with ic then it is a polyatomic acid.
- If it does not have either case, then output not an aci... | true |
62ad0cdecbb43d25fbae24b2514210a2cd9e56dc | amarjeet-kaloty/Data-Structures-in-Python | /linkedList.py | 1,320 | 4.125 | 4 | class node:
def __init__(self, data=None):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head = node()
#Insert new node in the Linked-List
def append(self, data):
new_node = node(data)
cur_node = self.head
while (c... | true |
e84ebb478878b0eba4403ddca10df99dda752a82 | martinloesethjensen/python-unit-test | /star_sign.py | 960 | 4.125 | 4 | def star_sign(month: int, day: int):
if type(month) == int and month <= 12 and type(day) == int and day <= 32: # todo: test case on .isnumeric()
if month == 1:
if day <= 20:
return "Capricorn"
else:
return "Aquarius"
elif month == 5:
... | true |
2e99e7a24fa53ad663d8d62ee3b2b59d06cf9f11 | Izzle/learning-and-practice | /Misc/decorators_ex.py | 2,915 | 4.53125 | 5 | """
*************************************************
This function shows why we use decorators.
Decorators simple wrap a fucntion, modifying its behavior.
*************************************************
"""
def my_decorator(some_function):
def wrapper():
num = 10
if num == 10:
p... | true |
9fd1d80b44dcea4693cb39f43ddc45a25e654a26 | Izzle/learning-and-practice | /theHardWay/ex6.py | 1,727 | 4.5625 | 5 | # Example 6
# Declares variable for the '2 types of people' joke
types_of_people = 10
# Saves a Format string which inputs the variable to make a joke about binary
x = f"There are {types_of_people} types of people."
# Declaring variables to show how to insert variables into strings.
binary = "binary"
do_not = "don't"... | true |
5fd329e733441ca67be649f8f604538c6697f6a3 | Izzle/learning-and-practice | /python_programming_net/sendEx05.py | 668 | 4.21875 | 4 | # Exercise 5 and 6
# While and For loops in python 3
# Basic while loop
condition = 1
while condition < 10:
print(condition)
condition += 1
# Basic For loop
exampleList = [1, 5, 6, 5, 8, 8, 6, 7, 5, 309, 23, 1]
for eachNumber in exampleList: # Iterates each item in the list and puts it into the variable ... | true |
7c3d1f965818058958bb143b72a6f03b2824a8d6 | dimatkach11/Torno_Subito | /base_python/the_dictionary.py | 2,936 | 4.625 | 5 | #
# ! A dictionary is a set of objects which we can extract from a key
# * The keys in question are the one we used in the phase of the assignment
print('\n\t\t\t\t\t\tDICTIONARY\n')
keynote = dict()
keynote['tizio'] = '333-3333333'
keynote['caio'] = '444-4444444'
print(keynote)
# * copy() :
keynote_copy = keynote.c... | true |
cc0f2bc409cc9d72c792ae38c2b84b353d6bcb3d | ChakshuVerma/Python-SEM-3 | /Question 6/code.py | 1,333 | 4.46875 | 4 |
"""
Q6.Consider a tuplet1 ={1,2,5,7,9,2,4,6,8,10}.
Write a program to perform following operations :
a) Print another tuple whose values are even numbers in the given tuple .
b) Concatenate a tuplet2 = {11,13,15) with t1 .
c) Return maximum and minimum value from this tuple .
"""
ch=0
# Given
len=10
t1=(1,2,5,7,9,... | true |
8c67095e3342ea13f00743a814edd8bd25fc1b2c | AshishGoyal27/Tally-marks-using-python | /tally_marks_using_python.py | 301 | 4.25 | 4 | #Retrieve number form end-user
number = int(input("Input a positive number:"))
#how many blocks of 5 tallies: ||||- to include
quotient = number // 5
#Find out how many tallies are remaining
remainder = number % 5
tallyMarks = "||||- " * quotient + "|" * remainder
print(tallyMarks)
| true |
c9e58aa8af5424e5b96811dd63afa86492c47c48 | lucienne1986/Python-Projects | /pythonRevision.py | 1,692 | 4.40625 | 4 | animals = ['cat', 'dog', 'monkey']
for a in animals:
print(a)
#IF you want access to the index of each element within the body of a loop use enumerate
#enums are constants
#%-style formatting: %s and %r call the Enum class’s __str__() and __repr__() respectively;
#other codes (such as %i or %h for IntEnum) treat t... | true |
94ab43281970119ab3ffe8e723539c0866f5f12c | amsun10/LeetCodeOJ | /Algorithm/Python/palindrome-number-9.py | 1,068 | 4.125 | 4 | # https://leetcode.com/problems/palindrome-number/
# Determine whether an integer is a palindrome. An
# integer is a palindrome when it reads the same backward as forward.
#
# Example 1:
#
# Input: 121
# Output: true
# Example 2:
#
# Input: -121
# Output: false
# Explanation: From left to right, it reads -121. From ri... | true |
cc7abe19bda1f613b2d070d4a2c5ec4eb722107d | oojo12/algorithms | /sort/insertion_sort.py | 612 | 4.34375 | 4 | def insertion_sort(item, least = False):
"""Implementation of insertion sort"""
"""
Parameters:
item - is assumed to be a list item
least - if true returned order is least to greatest. Else it is greatest to least
"""
__author__ = "Femi"
__version__ = "1"
__status__ = "Done"
... | true |
238780e18aa4d804e2c1a07b4a7008719e4d1356 | FaezehAHassani/python_exercises | /syntax_function4.py | 781 | 4.25 | 4 | # Functions for returning something
# defining a few functions:
def add(a, b):
print(f"adding {a} + {b}")
return a + b
def subtract(a, b):
print(f"subtracting {a} - {b}")
return a - b
def multiply(a, b):
print(f"multiplying {a} * {b}")
return a * b
def divide(a, b):
print(f"dividing {a} ... | true |
9a0494e31845de5b3e38b2e1aaf8cae045185634 | vishnusak/DojoAssignments | /12-MAY-2016_Assignment/python/search.py | 1,219 | 4.28125 | 4 | # String.search
# string.search(val) - search string for val (another string). Return index position of first match ( -1 if not found).
# ---- Bonus: Implement regular expression support
def search(string, val):
val = str(val) #convert the to-be-searched string into a string type
if (len(val) == 0): #if the... | true |
ea4f181fd795b69f92fb4385f7fc9ecf00abee65 | vishnusak/DojoAssignments | /3-MAY-2016_Assignment/python/reversearray.py | 956 | 4.59375 | 5 | # Reverse array
# Given a numerical array, reverse the order of the values. The reversed array should have the same length, with existing elements moved to other indices so that the order of elements is reversed. Don't use a second array - move the values around within the array that you are given.
# steps:
# 1. find... | true |
0296ddc0d579edc89013f4034af9b0b0b6aec661 | vishnusak/DojoAssignments | /2-MAY-2016_Assignment/python/swap.py | 759 | 4.53125 | 5 | # Swap Array Pairs
# Swap positions of successive pairs of values of given array. If length is odd, do not change final element. For [1,2,3,4] , return [2,1,4,3] . For [false,true,42] , return [true,false,42] .
# steps:
# 1 - traverse array in for loop
# 2 - increment counter by 2 each time instead of one
# 3 - fo... | true |
f9d1fb27c3ced358419cad969dba71e8f1d56a75 | helderthh/leetcode | /medium/implement-trie-prefix-tree.py | 1,836 | 4.15625 | 4 | # 208. Implement Trie (Prefix Tree)
# https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie:
def __init__(self, val=""):
"""
Initialize your data structure here.
"""
self.val = val
self.children = []
def insert(self, word: str) -> None:
... | true |
af4caae1454e7fdb4b40d5192c45e7ca16783ff2 | juancadh/mycode | /collatz_conjecture.py | 1,118 | 4.59375 | 5 | """
======== COLLATZ CONJECTURE ========
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n.
Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term.
If the... | true |
4d958cd5c394fd27e09703eaf02a5193c88523fa | tanadonparosin/Project-Psit | /time-count.py | 546 | 4.125 | 4 |
# import the time module
import time
# define the countdown func.
def countdown(t):
big = 0
t += 1
while t != big:
hours = big//3600
left = big%3600
mins, secs = divmod(left, 60)
timer = '{:02d}:{:02d}:{:02d}'.format(hours, mins, secs)
print(timer... | true |
c02aa901d795f6ed60a09cb3aee1ee1c3e61ced3 | AnilKOC/some-scripts | /prime-num-is-it.py | 406 | 4.125 | 4 | import math
def main():
number = int(input("Enter your number :"))
isprime = True
for x in range(2, int(math.sqrt(number) + 1)):
if number % x == 0:
isprime = False
break
if isprime:
print("Your number is an prime number : "+str(number))
else:
print("S... | true |
2e4554a4e5d00dedfdf276f950446273d40f45c0 | LyndonGingerich/hunt-mouse | /input.py | 1,224 | 4.40625 | 4 | """Helper methods for getting user input"""
def get_bool_input(message):
"""Gets boolean input from the terminal"""
values = {'y': True, 'yes': True, 'n': False, 'no': False, '': False}
return get_dict_input(message, values)
def get_dict_input(message, values):
"""Selects value from a dictionary by ... | true |
c7a1ed5b4d9eff957d6cebf924aeeb9ab8e0da53 | codingXllama/Tkinter-with-Python | /FirstApp/app.py | 829 | 4.4375 | 4 | import tkinter as tk
# Creating the window
window = tk.Tk()
# Creating a window title
window.title("First Application")
# Creating the window size
window.geometry("400x400")
# creating the LABEL
title = tk.Label(text="Welcome to my First Tkinter APP!",
font=("Times New Roman", 20))
# Placing the ti... | true |
337904dc2450ebaf368a58984385087c15fe2395 | ss4328/project_euler | /problem4.py | 855 | 4.25 | 4 | #The purpose of this program is to find largest 3-digit palindrome product
print("Palindrome problem starting...")
n1 = 100
n2 = 100
ans = 0;
def reverse(num):
rev = 0
while num > 0:
rev = (10 * rev) + num % 10
num //= 10
return rev
def isPalindroms(input):
if(input == reverse(input... | true |
7692e3274550d7ef4dad4e0c3fb65d608d28f7d3 | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_data_assignment_8.py | 1,206 | 4.28125 | 4 | # Difference of two columns in Pandas dataframe
# Difference of two columns in pandas dataframe in Python is carried out by using following methods :
# Method #1 : Using ” -” operator.
import pandas as pd
# Create a DataFrame
df1 = {'Name': ['George', 'Andrea', 'micheal',
'maggie', 'Ravi', 'Xien', 'Ja... | true |
fcc9c9b601411e05ff0d28f5a23f8f4502a3b139 | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_list_comprehension_assignment_1.py | 2,033 | 4.59375 | 5 | # Python List Comprehension and Slicing
# List comprehension is an elegant way to define and create list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp.
#
# A list comprehension generally consist of these parts :
# Output exp... | true |
14226708a9f5473ac80b76c4afe7bc47da5b403b | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_data_assignment_2.py | 1,796 | 4.65625 | 5 | # Syntax:
# DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
# Every parameter has some default values execept the ‘by’ parameter.
# Parameters:
# by: Single/List of column names to sort Data Frame by.
# axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.
# a... | true |
7292e151d67f39b26915ecbb13b9f6389674e2b0 | tracyvierra/vigilant-pancake | /TCPM-LPFS/text-2-speech/text_2_speech_live.py | 1,175 | 4.1875 | 4 | # Author: Tracy Vierra
# Date Created: 3/11/2022
# Date Modified: 3/11/2022
# Description: Text to speech example using user input to speech and saved as a file.
# Usage:
from turtle import right
from gtts import gTTS
import os
import tkinter as tk
from tkinter import filedialog as fd
from tkinter import *
# text ... | true |
e0fab44a525cc912f7f8d43c618af3fc3f9ed711 | abdulwagab/Demopygit | /Operators1.py | 531 | 4.21875 | 4 |
'''Relational Operators Example in Python'''
def operator(x, y, z): # Functions name and its arguments
a = 1 # Assign variables in Function
b = 2
c = 0
x = a or c and b # Compare variables in Logical operators but not print
y = a and c or b # Compare variables in Logical operators but n... | true |
93d669e04066f345afe68017ab73c30d9145e53d | Vanderscycle/lighthouse-data-notes | /prep_work/Lighthouse lab prep mod katas/.ipynb_checkpoints/ch9-linear_algebra-checkpoint.py | 1,504 | 4.15625 | 4 | import numpy as np
x = np.array([1, 2, 3, 4])
print(x)
# Matrix A
A = np.array([[1,2],[3,4],[5,6]])
print(type(A))
# in which the result is a tuple of (columns, rows)|(3x,2y) of the matrix
print(A.shape)
print(x.shape)
print(len(x)) # returns the length of the array (#in the list)
# transpose an a mat... | true |
dee0620a9f930628a7ea44f4d73779e76686b4c2 | melphick/pybasics | /week6/w6e2.py | 342 | 4.28125 | 4 | #!/usr/bin/python
"""
Converts a list to a dictionary where the index of the list is used as the
key to the new dictionary (the function will return the new dictionary).
"""
def list_to_dict(a_list):
a_dict = {}
for i in a_list:
print i
a_dict[i] = a_list[i]
return a_dict
a = range(10)
... | true |
cbd0d974b4b636760e98b1a4da159129e025be14 | patidarjp87/ROCK-PAPER-SCISSOR-GAME | /ROCK.py | 1,438 | 4.1875 | 4 | import random
print("WELCOME TO ROCK PAPER SCISSOR GAME\n")
lst = ["Rock", "Paper", "Scissor"]
computer_score = 0
player_score = 0
game = 0
chance = 6
while game < chance:
choice = random.choice(lst)
turn = input("choose(rock, paper or scissor) : ").lower()
game +=1
if turn == "rock" and choice == "Scis... | true |
650074bf605a56ddb94a4a6ff9ab260cadf72467 | Souravdg/Python.Session_4.Assignment-4.1 | /Filter Long Words.py | 600 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[14]:
##############################################
# A function filter_long_words() that takes a list of words and an integer n and returns
# the list of words that are longer than n
def filter_long_words(lst,length):
newlst = []
for x in range(len(lst)):
i... | true |
4235257b90ca960999d780a44b1f7af7607b8fc8 | cyberchaud/automateBoring | /vid04/vid04.py | 1,183 | 4.1875 | 4 | # pythontutor.com/visualize.html
# Indentation in Python indicates a block of code
# Blocks start where the indentation begins and the block stops where the indentation stops
# if block statements are conditions/expressions
# if the condition evaluates to true; then Python executes the indented code
name = 'Bob'
if ... | true |
8189b5b2488e0f5f91a999c449089c618a576196 | cyberchaud/automateBoring | /vid22/vid22.py | 1,572 | 4.28125 | 4 | #! /usr/bin/python3
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3]!= '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if te... | true |
f407e16b8c2485680862c746d272b752b0d77eb5 | cyberchaud/automateBoring | /vid01/vid01.py | 601 | 4.28125 | 4 | # Python always evaluates down to a single value.
# Integers are whole number
# Any digits with a decimal is a floating point
# Expresssions are made from Values and Operators
print("Adding")
print(2+2)
print("Substraction")
print(5-3)
print("Multiplication")
print(3*7)
print("Division")
print(21/7)
print("PEMDAS")
... | true |
3b06c59a64a82f7fbaa7eeba84c04c2dc020568c | krausce/Integrify | /WEEK_1/Question_4.py | 1,954 | 4.125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 01:24:18 2019
@author: chris
"""
'''
Question 4 asked us to write a function which looks through a list of int's
and returns '1' if a triplet exists and 0 if not.
My approach to this was to first sort the list using the builtin pyth... | true |
fe22ab33e33de67fa988d00f00d58eeb0bb8cb9d | neelima-j/MITOpenCourseware6.0001 | /ps1c.py | 1,967 | 4.3125 | 4 | '''
To simplify things, assume:
1. Your semiannual raise is .07 (7%)
2. Your investments have an annual return of 0.04 (4%)
3. The down payment is 0.25 (25%) of the cost of the house
4. The cost of the house that you are saving for is $1M.
You are now going to try to find the best rate of savings to achieve a down... | true |
361b4561b6a87cba7a2b35a603e86f04274e94bc | skgbanga/AOC | /2020/23/solution.py | 1,899 | 4.40625 | 4 | # The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle.
# The crab selects a destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups... | true |
891c4f8c7b6e238686e43e4e637f988f4c5652b5 | RavensbourneWebMedia/Ravensbourne | /mymodule.py | 1,210 | 4.625 | 5 | ## mymodule: a module containing functions to print a message, convert temperatures and find the 3rd letter of a word ##
# INSTRUCTIONS
# Write code for the three functions below:
# This function should use 'raw_input' to ask for the user's name, and then print a friendly message including
# the user's name to the co... | true |
c47d32391b8c18705ab43c0129135a3ac36f1a3b | myanir/Campus.il_python | /self.py/dateconvert.py | 213 | 4.15625 | 4 | import calendar
user_input = input("Enter a date: ")
# 01/01/2000
year = int(user_input[-4:])
month = int(user_input[3:5])
day = int(user_input[:2])
print(calendar.day_name[calendar.weekday(year, month, day)]) | true |
221a8faf61fc8d5e507718cd06c76d905ffa22d2 | jeffreybrowning/algorithm_projects | /dynamic/minimum_steps.py | 1,583 | 4.34375 | 4 | def get_min_steps (num):
"""
For any positive integer num, returns the amount of steps necessary to reduce
the number to 1 given the following possible steps:
1) Subtract 1
2) Divide by 2
3) Divide by 3
>>>get_min_steps(15)
4
"""
if num <= 0 or type(num) != int: return None
min_steps_list = [... | true |
2692e538d72e8ac46ba2d2cb6db4256b2445e7b4 | henryHTH/Algo-Challenge | /Largest_prime_factor.py | 840 | 4.28125 | 4 | '''
Given a number N, the task is to find the largest prime factor of that number.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains an integer N.
Output:
For each test case, in a new line, print the largest prime factor o... | true |
0b5348cb514686eae1e95606a94c64043db7e51b | suhaylx/for-loops | /main.py | 535 | 4.34375 | 4 | for item in {1,2,3,4,6}:
for values in {'a', 'b','c'}:
print(item, values)
user = {
'name' : 'Suhaylx',
'age' : 18,
'can_swim' : False
}
for dictionary_items in user.values():
print(dictionary_items)
for dict_items in user.items():
print(dict_items)
for keys, item_s in user.items():
print(keys,item_s)
#... | true |
35bf351112ee5abeb120a3989d17e70c095ea189 | tsunny92/LinuxAcademyScripts | /ex1.py | 301 | 4.21875 | 4 | #!/usr/bin/env python3.6
msg = input("Enter the message to echo : ")
count = int(input("Enter the number of times to display message ").strip())
def displaymsg(msg , count):
if count > 0:
for i in range(count):
print(msg)
else:
print(msg)
displaymsg(msg , count)
| true |
da643f117987410670878690fdfea9807efca07a | yiorgosk/python | /polynomials.py | 1,498 | 4.34375 | 4 | import numpy.polynomial.polynomial as poly
import numpy as np
'''The user can enter 2 polynomial functions and perform the basic math praxis of addition, subtraction, multiplication and division.
Also the user is able to discover the roots of the two function and perform for instance an addiction praxis with a polynomi... | true |
04b818d3a8e91e3ec412d008dd23bae7ddafdedb | wenyaowu/leetcode | /algorithm/wildcardMatching/wildcardMatching.py | 1,190 | 4.1875 | 4 | # Wildcard Matching
"""
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMat... | true |
bf3194d31daa0fde740f70f19ef4b502c1d82708 | wenyaowu/leetcode | /algorithm/spiralMatrix/spiralMatrix.py | 948 | 4.1875 | 4 | # Spiral Matrix
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
"""
class Solution:
# @param {integer[][]} matrix
# @return ... | true |
bc8cab306a5c13eb063336a46464b3f29bc03e26 | wenyaowu/leetcode | /algorithm/maximumSubArray/maximumSubarray.py | 525 | 4.15625 | 4 | # Maximum Subarray
"""
Find the contiguous subarray within an array
(containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
... | true |
6c1af79866f6e74500b78fbc1bae00e005ed66dc | ghydric/05-Python-Programming | /Class_Practice_Exercises/Lists/List_Functions_Review/append_list.py | 673 | 4.53125 | 5 | ## Append to list
# This function demonstrates how the append method
# can be usesd to add items to a list
def main():
# initialize empty list
name_list = []
# create a variable to control our loop
again = 'y'
# add some names to the list
while again == 'y':
# get a name from the user... | true |
b2c495513f454f4c992e7c6b89f0a8cb79b7ea69 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Advanced_Functions/map_func.py | 593 | 4.4375 | 4 | # map() function
# calls the specified function and applies it to each item of an iterable
def square(x):
return x*x
numbers = [1, 2, 3, 4, 5]
sqrList = map(square, numbers)
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
... | true |
dbbfec55fae84308c068d8b2db6f5502c6ef29a3 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Advanced_Functions/iter.py | 485 | 4.34375 | 4 | # Python iterator
#old way:
myList = [1,2,3,4]
for item in myList:
print(item)
# what is actually happening using iterators
def traverse(iterable):
it = iter(iterable)
while True:
try:
item = next(it)
print(item)
except StopIteration:
break
L1 = [1,2,3]... | true |
8450a626f5b9179e35e75c4a6296c036913eb583 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Classes/Classes_Exercises_2.py | 2,739 | 4.75 | 5 | """
2. Car Class
Write a class named Car that has the following data attributes:
• __year_model (for the car’s year model)
• __make (for the make of the car)
• __speed (for the car’s current speed)
The Car class should have an __init__ method that accept the car’s year model and make... | true |
679154f4340225e10a6dce151354fd1a1588df40 | bhavyajain190/Guess | /un.py | 553 | 4.125 | 4 | import random
print('Hey what is your name?')
name = input()
print('Welcome ' + name + ' I am thinking of a number between 1 and 10')
Num = random.randint(1,10)
for guessesTaken in range(1,3):
print('Take a guess')
guess = int(input())
if guess < Num:
print('Your guess is a lttle low')
el... | true |
75df037a3564e30b1c2ed8b11598ea52bfdf2fc7 | 01FE16BME072/TensorflowBasics | /Tensor_handling3.py | 1,279 | 4.40625 | 4 | '''
TensorFlow is designed to handle tensors of all sizes and operators that can be used to
manipulate them. In this example, in order to see array manipulations, we are going to
work with a digital image. As you probably know, a color digital image that is a MxNx3
size matrix (a three order tensor), whose components ... | true |
176313e02cb527f58beefa6a979118618da5446e | BohanHsu/developer | /python/io/ioString.py | 1,776 | 4.78125 | 5 | #in this file we learn string in python
s = 'Hello, world.'
#what str() deal with this string
print(str(s))
#what repr() deal with this string
print(repr(s))
#repr() make a object to a string for the interpreter
print(str(1/7))
print(repr(1/7))
#deal with some transforming characters
hello = 'hello, world\n'
helloS... | true |
e1be98d672f2925301e0c273a5c00a69c3d30213 | BohanHsu/developer | /nlp/assign1/hw1-files/my_regexs.py | 655 | 4.1875 | 4 | import re
import sys
# the first argument is a regular expression
# from the second argument are file path
pattern = sys.argv[1]
files = sys.argv[2:]
# reg_find : regular_expression, list_of_file_path -> list of words
# return a list of words which match the regular expression
# this method will concatenate all the l... | true |
4739f2dcad276d9967f2f0d36479e217db737356 | himIoT19/python3_assignments | /assignment_1/Q4.py | 328 | 4.4375 | 4 | # reverse string
def reverse(a_str: str) -> str:
"""
Function used for reversing the string
:param a_str: String
:return: String
"""
string_1 = a_str[::-1]
return string_1
# String to work on
s = "I love python"
print("Old string : {}".format(s))
print(f"New string after reversal: {revers... | true |
014c4247f563ba43e78dd5cc4d3f4f0e19cd41ed | seefs/Source_Insight | /node/Pythons/py_test/test_while.py | 371 | 4.15625 | 4 | #!/usr/bin/python
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
for j in range(9):
print ('The j is:', j)
#// The count is: 0
#// The count is: 1
#// The count is: 2
#// The count is: 3
#// The count is: 4
#// The count is: 5
#// The count is: 6
#// The count is: 7
#// The ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.