blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f63cfe08575a4b76beb41bfe211128f4bf5766df | tomasdecamino/CS_TOLIS | /PressButton/PressButton.pyde | 900 | 4.1875 | 4 | # Tomas de Camino Beck
#CS course with Pyhton
# Simple press button code
# button list
# list is organized [x,y,size, True/False]
buttons = [
[10,10,50,True],
[60,10,50, False],
[110,10,50, False],
[160,10,50, False]
]
pressButton = False
def setup():
size... | true |
9cbc49a3f4fd7034880f2b2afae37ba371ace4a5 | rmanovv/python | /task23/overlap_files.py | 950 | 4.1875 | 4 | '''
Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of all
prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers are numbers that can’t be divided by any other number. And yes,... | true |
9a3a63ab84c5b99872331e30e1ac230d76e04982 | rmanovv/python | /checkIO/electronic_station/Clock Angle.py | 1,342 | 4.34375 | 4 | # You are given a time in 24-hour format and you should calculate a lesser angle between the hour and minute hands in degrees.
# Don't forget that clock has numbers from 1 to 12, so 23 == 11. The time is given as a string with the follow format "HH:MM",
# where HH is hours and MM is minutes. Hours and minutes are g... | true |
609940a97b34d5dc2553c55e3b706366d537c647 | brockco1/E01a-Control-Structues | /main10.py | 2,198 | 4.40625 | 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!') # displays the text Greetings! when you run the p... | true |
6bfc6fc9b3e30c9ace200101ca2897a3bae19f2a | doulgeo/project-euler-python | /divisable.py | 872 | 4.25 | 4 | """
The general idea is that each of the numbers that
have to divide the answer, can be assigned to a list of
bools. So if your test number is 2520, then if 11 divides it
then you have a true value appended in a list. If all 8 booleans
in this list are true then that means that every number divides the test.
"""
... | true |
51613767a95f88083e372dd54761467f91241a2b | amresh1495/LPTHW-examples-Python-2.X | /ex19.py | 1,065 | 4.28125 | 4 | # Function to show that variables in a function are not connected to the variables in script.
# We can pass any variable as an arguement of the function just by using "=" sign.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses." % cheese_count
print "You have %d boxes of crack... | true |
b6fa8168713b014478c8057a2ccefa4069d2c998 | gistable/gistable | /dockerized-gists/76d774879245b355e8bff95f9172f9f8/snippet.py | 488 | 4.375 | 4 | # Example of using callbacks with Python
#
# To run this code
# 1. Copy the content into a file called `callback.py`
# 2. Open Terminal and type: `python /path/to/callback.py`
# 3. Enter
def add(numbers, callback):
results = []
for i in numbers:
results.append(callback(i))
return results
def... | true |
bf74fdd5ad7fd81c5f2990d51c114d2347a3c460 | gistable/gistable | /all-gists/1867612/snippet.py | 2,481 | 4.28125 | 4 | class Kalman:
"""
USAGE:
# e.g., tracking an (x,y) point over time
k = Kalman(state_dim = 6, obs_dim = 2)
# when you get a new observation —
someNewPoint = np.r_[1,2]
k.update(someNewPoint)
# and when you want to make a new prediction
predicted_location = k.predict()
NOTE:
Setting state_dim to 3*... | true |
ca98687acf174fa07c31df1305ce8eb81c26b4a9 | gistable/gistable | /all-gists/9231107/snippet.py | 1,103 | 4.3125 | 4 | #!/usr/bin/env python2
# Functional Python: reduce, map, filter, lambda, *unpacking
# REDUCE EXAMPLE
add = lambda *nums: reduce(lambda x, y: x + y, nums)
def also_add(*nums):
'''Does the same thing as the lambda expression above.'''
def add_two_numbers(x, y):
return x + y
return reduce(add_two_nu... | true |
7a106333ddb52a4ea723a68648b65d201a072591 | gistable/gistable | /all-gists/91c49ddaceb38c0a6b241df6831a141b/snippet.py | 2,995 | 4.125 | 4 | import random, math
#Ignore def monte_carlo(): ...im just defining a function
def monte_carlo():
#At the end sums will add up all the f(n)
sums = 0
#just creating a dictionary, ignore this, not too important
functions = {'1': 'x', '2': 'x^2', '3': 'sin', '4': 'cos', '5': 'exp'}
print("Choose your... | true |
523f130fc786632ba04c2fa319472d483395c2f0 | gistable/gistable | /all-gists/1546736/snippet.py | 2,317 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
String to Brainfuck.
Converts a string to a brainfuck code that prints that string.
Author: j0hn <j0hn.com.ar@gmail.com>
"""
import sys
def char2bf(char):
"""Convert a char to brainfuck code that prints that char."""
result_code = ""
ascii_value = ord(char)
... | true |
4953f3f11c03077361bea42f30ecc6f2fb1fb7e3 | gistable/gistable | /dockerized-gists/1253276/snippet.py | 1,145 | 4.21875 | 4 | import datetime
class Timer(object):
"""A simple timer class"""
def __init__(self):
pass
def start(self):
"""Starts the timer"""
self.start = datetime.datetime.now()
return self.start
def stop(self, message="Total: "):
"""Stops the timer. Returns ... | true |
3cc4c5610432cf98e385c8fe476e9554c6f52ab7 | gistable/gistable | /dockerized-gists/2004597/snippet.py | 2,504 | 4.40625 | 4 | # This function prints out all of the values and sub-values in any variable, including
# lists, tuples and classes. It's not very efficient, so use it for testing/debugging
# purposes only. Examples are below:
#-------------------------------------------------------------------------------------
# ShowData(range(10)... | true |
6636fb368009ddcb070c71b5c9900d8856c28501 | chanshik/codewars | /sum_digits.py | 627 | 4.25 | 4 | """
Write a function named sumDigits which takes a number as input
and returns the sum of the absolute value of each of the number's decimal digits.
For example:
sumDigits(10) # Returns 1
sumDigits(99) # Returns 18
sumDigits(-32) # Returns 5
Let's assume that all numbers in the input will be integer values.
... | true |
420879938f42c8d3c2fa6b472f35cb3f1d7f6fad | chanshik/codewars | /triangle_type.py | 1,507 | 4.4375 | 4 | # coding=utf-8
"""
In this kata, you should calculate type of triangle with three given sides a, b and c.
If all angles are less than 90°, this triangle is acute and function should return 1.
If one angle is strictly 90°, this triangle is right and function should return 2.
If one angle more than 90°, this triangle ... | true |
533b8da62de65025cbb71c981eade387bf694d68 | chanshik/codewars | /dragon_curve.py | 1,783 | 4.53125 | 5 | """
The dragon's curve is a self-similar fractal which can be obtained by a recursive method.
Starting with the string D0 = 'Fa', at each step simultaneously perform the following operations:
replace 'a' with: 'aRbFR'
replace 'b' with: 'LFaLb'
For example (spaces added for more visibility) :
1st iteration: Fa -> F ... | true |
a56d602738b04e9e1aafc27f2aeff127da7a82a5 | emretokk/codeforces | /800/word.py | 719 | 4.15625 | 4 | """
that would change the letters' register in every word
so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones.
( tersine )
input :
The first line contains a word s — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
... | true |
355421abb31a6d13fa52ed315082c92ce25e5272 | Deepanshu276/AlgorithmToolbox | /Array/2D-array/creatingArray.py | 281 | 4.25 | 4 | import numpy as np
arr1=np.array([[1,2,3],[4,5,6],[7,8,9]])
"""Time complexity in thios is O(1) as we are simultaneously giving the value in the array
but if we insert the value one by one in the array then the time complexity will be O(m*n)
where m=row and n=column"""
print(arr1) | true |
d84a72df4fd58fba1a1aedfe016ebdb18b33705d | ProProgrammer/asyncio-rp | /theory.py | 1,567 | 4.1875 | 4 | from typing import Generator
from random import randint
import time
import asyncio
def odds(start, end) -> Generator:
"""
Produce a sequence of odd values starting from start until end including end
Args:
start:
end:
Returns: Yield each value
"""
for odd in range(start, end ... | true |
071429abd45ee187f732a3cd50c13088eb94f720 | knparikh/IK | /LinkedLists/clone_arbit_list/clone.py | 2,428 | 4.15625 | 4 | #!/bin/python
class Node:
def __init__(self, node_value):
self.val = node_value
self.next = None
self.arbit = None
# Given a doubly linked list with node having one pointer next, other pointer arbit, pointing to arbitrary node. Clone the list.
# Approach 1: Uses extra space O(n) in hash t... | true |
f8eb3b6c2dc76f5a4c18e962b994df7219510308 | knparikh/IK | /Recursion/class_learnings.py | 2,970 | 4.25 | 4 | def fibo(n):
if (n == 0) or (n == 1):
return n
return fibo(n-1) + fibo(n-2)
# Tips to write recursive functions
# Define function meaningfully
# Think about base cases, what's already defined
# Think about the typical case
# Example:
# Merge sort
# Recurrence relationship
# Define function: merge (a ... | true |
b314f7c064518604957fc677897c33f51afc584e | knparikh/IK | /LinkedLists/median/median.py | 1,741 | 4.125 | 4 | #!/bin/python3
import sys
import os
class LinkedListNode:
def __init__(self, node_value):
self.val = node_value
self.next = None
def _insert_node_into_singlylinkedlist(head, tail, val):
if head == None:
head = LinkedListNode(val)
tail = head
else:
node = LinkedList... | true |
25450a5f381210b30eff26600fdf9377b7762cd4 | joepark92/students_and_grades | /students_n_grades.py | 1,741 | 4.15625 | 4 | studentinfo = []
course_dict = {
1: 'Math',
2: 'Science',
3: 'History'
}
while True:
numStudents = input("How many students do you have: ")
try:
numStudents = int(numStudents)
except:
print('Invalid entry... Try using digits, ex. 1, 2, 3, etc.')
continue
if numStuden... | true |
85490c42ce849d03911999af97526f3dc1ef6c75 | TSantosFigueira/Python_Data-Structures | /Data Structures - Array/ReverseString.py | 456 | 4.34375 | 4 | strings = "Hi, my name is Thiago!"
# approach 01
print(strings[::-1])
# approach 02
def reverseString(strings):
for i in range(len(strings) - 1, -1, -1):
print(strings[i], end='')
#approach 03
def reverseStringWithList(strings):
newStrings = []
for i in range(len(strings) - 1, -1, -1):
newStrings... | true |
a1c101827947b2ebc854c39bcda7bed452c54aa9 | sebastianhlaw/tensorflow-benchmark | /python/playground/get_started_contrib_learn.py | 1,466 | 4.15625 | 4 | # Getting started with TensorFlow
# https://www.tensorflow.org/get_started/get_started
import tensorflow as tf
import numpy as np
# Declare list of features. We only have one real-valued feature. There are many other types of columns that are more
# complicated and useful.
features = [tf.contrib.layers.real_valued_co... | true |
6bd1ef758a24b491de6487685bdba70f50859418 | timsergor/StillPython | /008.py | 283 | 4.125 | 4 | #Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
odd = []
even = []
for i in range(len(A)):
if A[i] % 2 == 0:
even.append(A[i])
else:
odd.append(A[i])
print(even+odd)
| true |
99774c11dcd328634fdfe51602b7453bf243a610 | timsergor/StillPython | /105.py | 1,582 | 4.25 | 4 | #1042. Flower Planting With No Adjacent. Easy. 47.7%.
#You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
#paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
#Also, there is no garden that has more than 3 paths coming into or lea... | true |
4be06146f86619793040004e9139480283895ba7 | Skippi-engineer/Console-Games | /Rock paper scissors.py | 1,207 | 4.15625 | 4 | #
# Simple console game rock paper scissors:
#
from random import*
game = True
while game:
player = (input("rock/paper/scissors: ")).lower()
rand = randint(1, 3)
if rand == 1:
print("rock")
if player == "rock":
print("Tie!")
elif player == "paper":
... | true |
65779d0cd88f215d09e94b49567fe0ebdec5c83c | donaq/scramblecheatpy | /scramblecheat.py | 1,524 | 4.21875 | 4 | #!/usr/bin/python
import sys
import readline
from scheathelpers import *
if len(sys.argv)!=2:
print "Usage: scramblecheat.py <dictionary file>"
exit()
words = read_dictionary(filename=sys.argv[1])
if not words:
exit()
print "\nFor instructions, type 'help'. To exit the program, press the Enter key.\n"
instructio... | true |
be0404d73463c30014cddb01f3ba109e5c04b94d | chaitan64arun/algo-ds | /array_element_appearance.py | 623 | 4.34375 | 4 | #!/usr/bin/python
"""
https://www.careercup.com/question?id=5664477329489920
You have given an array of integers. The appearance of integers vary (ie some integers appears twice or once or more than once)
How would you determine which integers appeared odd number of times ?
a[] = { 1,1,1, 2,5,10000, 5,7,4,8}
as you... | true |
bb5a6198910d5e8cb45c4e0ac03002e33b5c3cbb | Elvis-IsAlive/python | /printDirectory.py | 1,901 | 4.15625 | 4 | #! /usr/bin/python3
"""List the content of a directory to the depth of -directory"""
import os
import sys
import argparse
def printDir(directory, depth, lvl = 0):
"""prints the directories and files of a directory"""
os.chdir(directory)
for e in sorted(os.listdir()):
#only non-hidden elements
... | true |
c0f083cbddfb27401321e3d95d30056d42d0e81a | m2mathew/learn-python-in-one-day | /03_variables.py | 730 | 4.25 | 4 | # Chapter 3: The World of Variables and Operators
userAge = 0
userAge, userName = 30, 'Peter'
'''
Variable names can contain letters, numbers, or underscores
But they cannot start with a number
Can only start with a letter or underscore
'''
# Here we go
x = 5
y = 10
# x = y
y = x
print ('x = ', x)
print ('y = ', ... | true |
36b7c19b65d70daf224f1f10e07986107572ab00 | dconn20/labs.2020 | /student.py | 609 | 4.1875 | 4 | # A Program that reads in students
# until the user enters a blank
# and then prints them all out again
students = []
firstname = input("Enter first name (blank to quit): ").strip()
while firstname != "":
student = {}
student ["firstname"] = firstname
lastname = input ("Enter lastname: ").strip()
stud... | true |
0cd0946d99ab89504458e247982945c91fdeeebf | jmanndev/41150-Exercises | /Tutorial2/calculator-with-tax.py | 775 | 4.375 | 4 | # 1. Write a python program that act as a cashier which will prompt the user
# for numbers that can be either integers or floats until the user enters 0.
# The program should accumulate all the entered numbers up until the 0
# and provide the total before and after tax. Tax is 0.05
def inputNumber(prompt):
while ... | true |
477b7094c6ee99f09ac6d61a4d571f06b570bacf | Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne | /Exercises-for Teach Your Kids to Code by Bryson Payne/What_to_wear.py | 473 | 4.28125 | 4 | # What to wear?
rainy=input("How's the weather? Is it raining? (y/n)").lower()
cold=input("Is it cold today? (y/n)").lower()
if (rainy=='y' and cold=='y'):
print("You'd better wear a raincoat.")
elif (rainy=='y' and cold!='y'):
print("Carry an umbrella with you.")
elif (rainy!='y' and cold=='y'):
pr... | true |
a2ac7d561a73a8d5ed225aa1e9385b01b85c9f01 | Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne | /Exercises-for Teach Your Kids to Code by Bryson Payne/Pizza_calculator.py | 663 | 4.34375 | 4 | # Pizza cost calculator
# How many pizzas they want
number_of_pizzas=eval(input("how many pizzas do you want? "))
# Cost of each pizza
cost_per_pizza=eval(input("how much does each pizza cost? "))
# Calculate the total cost of the pizzas as our subtotal
subtotal=number_of_pizzas*cost_per_pizza
# Calculat... | true |
bd4e1edd47f082abe6726aab34a9741e71f991b9 | KolienPleijsant/assignment | /assignment_2_Kolien.py | 2,241 | 4.34375 | 4 | #open the csv file
politicians = open("politicians.csv")
#make a multidimensional list and set indext to 0
newlist = []
index = 0
#strip the csv and make it a multidimensional list
for info in politicians:
infosplit = info.strip().split(",")
newlist.append(infosplit)
firstname = infosplit[0]
lastname = infosplit[... | true |
890a2648b66de9c0746fb84e17d227f4569e1044 | maddurivenkys/trainings | /AI_ML/training/Day1/home_work/median.py | 487 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 21:55:07 2019
@author: e1012466
"""
# is a floor division operator which will round the result to nearest integer
# Python program to print
# median of elements
# list of elements to calculate median
n_num = [1, 2,7, 8, 9,3, 4, 5,6]
n = len(n_num)
n_num.sort()
... | true |
ed71969d9316cc5e19d9a2e706eed432c499af66 | freena22/Python-Practice-Book | /09_function_design.py | 2,861 | 4.4375 | 4 |
# Functions and Function Design
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "... | true |
26749abc649c1667a32bc15e118615cf5aa7ea90 | nicsins/PLDC1150 | /week3/practice.py | 323 | 4.3125 | 4 | from datetime import date
from datetime import time
from datetime import datetime
print(f"Todays date is {date.today()}")
print(f"The time is {datetime.time(datetime.now())}")
print(f"Todays date and time is {datetime.today()}")
city="Minneapolis"
date=date.today()
print(f'in the city of {city} and the date is {date... | true |
69353e9ee5e34e7ea82bc96ca05e5a4c7465b623 | nicsins/PLDC1150 | /Week5/texbook.py | 2,395 | 4.28125 | 4 | ''' texbook program
author =__DomiNic__
this is an example program of ways to
use data validation for integers and floats
along with presenting a solid example of nested loops
**improved from lab notes***'''
print('Welcome to the book shop')
#start with getting user input and defining variables
head="*"*40#simple deco... | true |
28ccf0700be7b1acdcb4faace4b4b85c26ee6c20 | nicsins/PLDC1150 | /Week2/practice.py | 643 | 4.15625 | 4 | def getInput():
return [int(input(f'enter score for test # {i+1}'))for i in range( int (input('How many test scores would you like to enter')))]
def print_Output(nums):
print('the values entered are ',end='')
[print(i,' ',end='')for i in nums]
print()
print(f'The highesty score was {max(nums)}')
... | true |
07e258168dc94bf9a5f50ff74a3d15270ee86785 | tessam30/Python | /examples/katrina.py | 1,005 | 4.125 | 4 | # Answering questions about Katrina text using Python text handling abilities
f = open("katrina_advisory.txt")
text = f.read()
f.close()
print 'Content of "katrina_advisory.txt"'
print '-' * 51
print
print text
# Q1. Strip leading spaces and make everything lowercase
text_clean = text.lower().strip()
print text_clean... | true |
72b9ddc4835863a9d492f7164d30dcb70dc5be1e | caspian2012/Wang_Ke_python | /HW1_12.py | 1,595 | 4.25 | 4 | """ Question 12"""
# Import defaultdict function.
from collections import defaultdict
def ana_finder(file_name):
# Open the file, read it and add the raw stripped words into a list.
words = []
with open(file_name, 'r') as f:
for line in f:
words.append(line.rstrip())
# We find wo... | true |
14e196f86efa736320d4cbadae7ae7356813f13c | caspian2012/Wang_Ke_python | /HW1_2.py | 739 | 4.53125 | 5 | """ Question 2"""
# Construct a funtion to find semordnilap that finds semordnilap pairs of a
# list of words.
def semordnilap(file):
# Access a file, read its content and split the list of words into
# individual ones.
file = open ('sample.txt').read()
words = file.split()
# Set the default... | true |
52eddb29c7f0432d6837f9871af6fe604db1e06c | Jack-Sh/03_Higher_Lower | /03_secret_compare.py | 1,847 | 4.125 | 4 | # HL component 3 - compare secret and users guess
# To Do
# If users guess is below secret print too low
# If users guess is above secret print too high
# If users guess is the secret print congratulations
# Function to check low, high, guess, and round numbers
def int_check(question, low=None, high=None):
sit... | true |
4429b8da21d51288c7d4a9edd88568c7712cfb51 | mdsksadi/python | /List_in_Python.py | 2,377 | 4.53125 | 5 | '''
In a variable we can assign only one value. But if we assing multiple values into the variable,
we need to use a list.
For diclaring a list, we need to use box bracket "[]"
We can assign both number and string type values.
List is mutable (We can chagne the values).
'''
nums= [2,4,20,54,120] #We diclear a lis... | true |
df20b2381136f21dd85ab4316491e8d9f90c619f | mdsksadi/python | /Dictionary.py | 2,416 | 4.15625 | 4 |
'''
List: It's orderd. It's mantain the sequence.
Set: It does not maintain the sequence.
Dictionary: Differenty key for different element.
Example: Phone book. If we search a name, we get a number against that name.
Every value has a different key given by me.
But in list, the key... | true |
c48c13d876895eafa0724f5d6b9000e8208708a7 | saida93522/HelloPython | /birthday.py | 586 | 4.28125 | 4 | import datetime
date = datetime.datetime.now() # date class.
# formatting date to string. %B returns full month name.
currMonth = date.strftime("%B").lower()
def birthday():
name = input('What is your name?\t').capitalize()
month = input(f'Hi {name}!, what month were you born in?\t').lower()
# check if... | true |
77746a97fcceca80de494fb8ff0765df5fba6c0d | ToscaMarmefelt/CompPhys | /PS3Q1.py | 1,494 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 09:26:27 2018
@author: Tosca
"""
import random
import numpy as np
# Decide on number of columns and rows for test matrices A and B
col_a = random.randint(1,10) #Range 1-10 for simplicity
row_a = random.randint(1,10)
col_b =... | true |
37e4a5af48a708dbbf381bc7189e500cf9aa35bf | SolidDarrama/Python | /area_calculation.py | 1,203 | 4.3125 | 4 | #Billy Leager
#10/1/2014
#Practice Program - Menu
def rectangle_area():
side1 = int(input('Enter the value of the first side:'))
side2 = int(input('Enter the value of the second side:'))
print('The area of the rectangle is', (side1 * side2))
def triangle_area():
height = int(input('Enter the... | true |
68ea74d5b245e9d3df91c79e5fa7ba55a1b4be3a | SolidDarrama/Python | /Ch3 Ex/Chapter 3 Exercises 7.py | 977 | 4.15625 | 4 | #Jose Guadarrama
#9/20/2014
#CH3 EX7
#user input 1
primary1=str(input('Enter the 1st Primary Color: '))
#if else 1
while primary1 != "red" and primary1 != "blue" and primary1 != "yellow":
primary1 = input("\nerror message")
#user input 2
primary2=str(input('Enter the 2nd Primary Color: '))
#if els... | true |
c3edbfd23f522eef4534fd2feb11d6a6c9bb0b68 | dheerajdbaudb22/Devops21 | /Treasure_island.py | 609 | 4.125 | 4 | print("Welcome to Treasure island.")
print("Your mission is to find the treasure.")
task1 = input("Do you want to take left or right? \n")
t1 = task1.lower()
if ( t1 == "right" ):
print("Your game is over !")
else:
t1 == "left"
task2 = input("Do you want to swim or wait? \n")
t2 = task2.lower()
if ... | true |
45a110c28232c1b28e8a8cabb1695979e8848c8f | rageshm110/python3bootcamp | /lists.py | 1,100 | 4.65625 | 5 |
# Lists are ordered sequences that can hold a variety of object types
# they use [] and , to separate objects in list
# ex: [1,2,3,4] | ["Ragesh","TechM", 4] | ["Adhik", [2007, 20, 05]]
# lists supports indexing and slicing. Lists can be nested
# and also have a variety of useful methods that can be called
# off of ... | true |
63dad4f2c002647474a4d418ac17578744dac437 | AlanMalikov777/Task1_Python | /first.py | 695 | 4.3125 | 4 |
def toSwap(listToEnter,x,y):#swaps two variables
listToEnter[x],listToEnter[y]=listToEnter[y],listToEnter[x]
# toPermute uses a heap's algorithm
def toPermute(list, current, last):#takes a list, starting index and last index
if last<0:
print("")
elif current == last:# if starting and last indexes w... | true |
272ff75f4d102f291fbd318b92937d8f1b5c2b45 | tkern0/misc | /School/guessNum.py | 1,430 | 4.125 | 4 | import random
# Gets the user's name, allowing only letters, spaces and hyphens
letters = "qwertyuiopasdfghjklzxcvbnm- "
while True:
try:
name = input("What is your name? ")
for i in name:
if i.lower() not in letters: raise ValueError
except ValueError: print("Please use only... | true |
27a866921ee473a17cc635df89e44c516e6cbff5 | devashishtrident/progressnov8 | /scope.py | 1,742 | 4.25 | 4 | '''x =25
def my_func():
x = 50
return x
"/the only x the program is aware of is global variable"
#print(x)
"this is looking at the myfunc scope only"
#print(my_func())
"what confuses the people most is calling the function first and getting the very next value we get x will be called but a global variab... | true |
5d5aa60886dd4729e839956378ab1e9575f5b8a2 | ChristinaEricka/LaunchCode | /unit1/Chapter 09 - Strings/Chapter 09 - Studio 8 - Bugz - Bonus Mission.py | 1,851 | 4.25 | 4 | # Bonus Mission
#
# Write a function called stretch that takes in a string and doubles each
# of the letters contained in the string. For example,
# stretch("chihuahua") would return “cchhiihhuuaahhuuaa”.
#
# Add an optional parameter to your stretch function that indicates how
# many times ea... | true |
5991435ff06a5927e9d0e5c7d92a6973e1b1982d | ChristinaEricka/LaunchCode | /unit1/Chapter 08 - More About Iteration/Chapter 08 - Exercise 06.py | 628 | 4.1875 | 4 | # Write a program to remove all the red from an image.
#
# For this and the following exercises, use the luther.jpg photo
import image
img = image.Image("luther.jpg")
win = image.ImageWin(img.getWidth(), img.getHeight())
img.draw(win)
img.setDelay(1, 15) # setDelay(0) turns off animation
for row in range(img.get... | true |
62c17fd1f2fd0dcccf78a7ce41dbf87ab3ce075e | ChristinaEricka/LaunchCode | /unit1/Chapter 09 - Strings/Chapter 09 - Exercise 02.py | 554 | 4.125 | 4 | # Write a function that will return the number of digits in an integer
import string
def num_digits(n):
"""Return number of digits in an integer"""
count = 0
for char in str(n):
if char in string.digits:
count += 1
return count
def main():
"""Cursory testing of num_digits"... | true |
783fa5014f0e5df887b967f03de35622ebf59417 | ChristinaEricka/LaunchCode | /unit1/Chapter 07 - Exceptions and Problem Solving/Chapter 07 - Exercise 10.py | 1,039 | 4.28125 | 4 | # Write a function triangle(n) that returns an upright triangle of height n.
#
# Example:
# print(triangle(5))
#
# Output:
#
# #
# ###
# #####
# #######
# #########
def line(n, str):
"""Return a line consisting of <n> sequential copies of <str>)"""
return_value = ''... | true |
4b2c398683572555cb7fae39882fe1e648b7b217 | ChristinaEricka/LaunchCode | /unit1/Chapter 11 - Dictionaries and Tuples/Chapter 11 - Studio 10 - Yahtzee.py | 2,598 | 4.1875 | 4 |
import random
# The roll_dice function simulates the rolling of the dice. It
# creates a 2 dimensional list: each column is a die and each
# row is a throw. The function generates random numbers 1-6
# and puts them in the list.
def roll_dice(num_dice, num_rolls):
# create a two-dimensional (num_dice by num_rol... | true |
1dedaceb98c59184781af863a5a44540a832bb9e | ChristinaEricka/LaunchCode | /unit1/Chapter 09 - Strings/Chapter 09 - Exercise 09.py | 1,185 | 4.65625 | 5 | # Write a function called rot13 that uses the Caesar cipher to encrypt a
# message. The Caesar cipher works like a substitution cipher but each
# character is replaced by the character 13 characters to “its right” in the
# alphabet. So for example the letter “a” becomes the letter “n”. If a letter
# is past the mi... | true |
46e0b03dec67ab8b34ebeeb96ae2a4a52c500e9f | ChristinaEricka/LaunchCode | /unit1/Chapter 08 - More About Iteration/Chapter 08 - Exercise 03.py | 1,818 | 4.3125 | 4 | # Modify the turtle walk program so that you have two turtles each with a
# random starting location. Keep the turtles moving until one of them leaves
# the screen.
import random
import turtle
def is_in_screen(screen, t):
left_bound = - screen.window_width() / 2
right_bound = screen.window_width() / 2
... | true |
dd81c3c278398a8bea81d19dad23fca4fca0ca9d | sravyaysk/cracking-the-coding-interview-solutions | /LeetCode/searchInRotatedArray.py | 2,629 | 4.1875 | 4 | '''
She asked for binary search functionality which tells no exists in array or not. Generally we find mid element through (low+high)/ 2 so she asked to change that and use random function to decide mid. Binary search is performed on sorted array but here unsorted array is given.
Two modifications are performed on ... | true |
cb8d29bd928f567faf99e220423b583aab63cb97 | ajay946/python-codes | /PrimeNum.py | 328 | 4.125 | 4 | # To find prime number in a given range
start = int(input("Start: "))
end = int(input("End: "))
for i in range(start, end +1):
# if number is divisible by any number between 2 and i it is not prime
if i >1 :
for j in range(2,i):
if(i%j)==0:
break
else:
p... | true |
30b51090fcc64881051a00b755a8111d6482d28d | atafs/BackEnd_Python-language- | /language/americoLIB_006_VARIABLES.py | 1,249 | 4.21875 | 4 | #!/usr/bin/python
#**************************
#IMPORTS
import sys
#VARIABLES
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
#MULTI ASSIGNMENT
multi1 = multi2 = multi3 = 1
multi4, multi5, multi6 = 1, 2, "john"
#PRINT
print("")
print("PYTHON:... | true |
baafacd76c43bc5077924f822d32bab2a933aad5 | kevincdurand1/Python-Data-Science-Examples | /Normalization.py | 623 | 4.125 | 4 | #Normalization
#Data normalization is used when you want to adjust the values in the feature vector
#so that they can be measured on a common scale. One of the most common forms of normalization
#that is used in machine learning adjusts the values of a feature vector so that they sum up to 1.
#Add the following lin... | true |
7063ed0f8969fdfc8e5998ce83473afedea34160 | anhnh23/PythonLearning | /src/theory/control_flow/functions/__init__.py | 2,196 | 4.28125 | 4 | '''
Syntax:
def function-name(parameters):
statement(s)
Explaination:
+ parameter - can be indentifier=expression
'''
# be keys into a dictionary
dic = {'a':10, 'b':20, 'c':30}
inverse = {}
for f in list(dic):
inverse[dic[f]] = f
print(dic)
print(inverse)
"""This is case parameter is indentifier=expre... | true |
e58a6f27c032f2a349dbd6c95c674ad8807df85d | anhnh23/PythonLearning | /src/theory/io/io_module.py | 2,080 | 4.125 | 4 | #str() returns representations of value which are fairly human-readable
#repr() generate representation which can be read by the interpreter
s = 'Hello,\n world.'
print(str(s))
print(repr(s))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
'''str()
1. rjust right justifies
2... | true |
4fb27d914ed56b2ce789e9cc45152f90520390b7 | perzonas/euler | /Euler_1.py | 318 | 4.15625 | 4 | # If we list all the natural numbers below 10 that are
# multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
sum = 0
for i in range(3, 1000, 3):
if i % 5 != 0:
sum += i
for i in range(5, 1000, 5):
sum += i
print(sum) | true |
571018d26e98b054e6fee8d204d4b124f262f6a5 | mhhg/acm | /1_array_string/two_pointers/1_two_sum/two_sum/two_sum.py | 764 | 4.21875 | 4 | from typing import Dict, List
"""
TwoSum Given an array of integers, find two numbers such that they add up to
a specific target number.
The function twoSum should return indices of the two numbers such that they add
up to the target, where index1 must be less than index2.
Please note that your returned answers (bo... | true |
60d931a8ac4ea9d4b4047d68903ef8c50328a300 | crazyAT8/Python-Projects | /While Loop.py | 2,373 | 4.25 | 4 |
# i = 1 # Initialization
# while i<=5: # Condition
# print("william")
# i = i + 1 # Increment/Decrement
# the objective here is to print my name 5 times in a row
# without the Increment/Decrement the loop would go on forever
# when using ... | true |
e6045dc8607f166a7d9ea877b0e3af73fb0303a3 | Absurd1ty/Python-Practice-All | /problems_py7/power_of_3.py | 598 | 4.25 | 4 | """Given an integer n, return true if it is a power of three.
Otherwise, return false. An integer n is a power of three,
if there exists an integer x such that n == 3x."""
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n==0:
return False
if n==3 or n==1... | true |
9a9fdc10a372dad407a03275064b54508d07dff4 | Raj-Madheshia/Datastructure | /Dynamic Programming/multipleMatrixMultiplication.py | 620 | 4.15625 | 4 | """
The logic behind multiple matrix mutiplication is as given below
A = 10*30
B = 30*5
C = 5*60
ABC = (AB)C || A(BC)
ABC = (AB)C
= 10*30*5 + 10*5*60 operations
= 4500 operation
----OR----
ABC = A(BC)
= 30*5*60 + 10*30*60 operations
= 27000 operation
So to get which combination will requir... | true |
35b52d6776d6a4ab71caa79644f614a569f39ef5 | tchrlton/Learning-Python | /HardWay/ex20.py | 1,683 | 4.3125 | 4 | #from the module sys, import the function or paramater argv
from sys import argv
#The two arguments in argv so it has the script (ex20.py) and
#input_file (test.txt or whatever file you input).
script, input_file = argv
#The function that will print the whole txt file after it reads it
def print_all(f):
print(f.read... | true |
6b18af9ead2fc973094c40dab143633e9be352dd | SDSS-Computing-Studies/006b-more-functions-bonhamer | /task3.py | 461 | 4.46875 | 4 | #!python3
"""
Create a function that determines the length of a hypotenuse given the lengths of 2
shorter sides
2 input parameters
float: the length of one side of a right triangle
float: the length of the other side of a right triangle
return: float value for the length of the hypotenuse
Sample assertions:
assert hyp... | true |
bd5487e173f2eb396eff5d2929288c9894e70896 | WhaleJ84/com404 | /1-basics/ae1-mock-paper/q2-decision.py | 254 | 4.28125 | 4 | # Q2) Decision
print("Please enter a whole number:")
num = int(input())
# an if statement that divides the input number by 2 and checks to see if it has a remainder; if so it is odd.
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
| true |
e68b1523babc3f2820dae5d89fa90efa7bf8c1c4 | WhaleJ84/com404 | /1-basics/4-repetition/1-while-loop/bot.py | 484 | 4.15625 | 4 | # Ask user for number of robots
print("How many ascii robots should I draw?")
number_robots = int(input())
ROBOT = """
#########
# #
# O O #
| V |
| --- |
|_______|
"""
robots_displayed = 0
MAX_ROBOTS = 10
# Display robots
if number_robots <= MAX_ROBOTS:
while robots_displayed < (number_robots):
... | true |
8c7a480827e7924c2ce43947e0c22e1823d0e39b | WhaleJ84/com404 | /1-basics/6-review/1-input-output/3-interest.py | 449 | 4.15625 | 4 | # Read current amount from user
print("What is your current amount in savings? (£)")
current_amount = float(input())
# Read interest rate from user
print("What is your interest percentage rate? (%)")
interest_rate = float(input())
# Calculate new amount
interest_amount = (interest_rate / 100) * current_amount
new_amo... | true |
b2d50fa5197a9e4906ec9ecc6c5339cd1dc9c14d | rkc98/Python_100_days_challenge | /day_10/fisrt_word_capital.py | 347 | 4.1875 | 4 |
first_name=input("what is your first name ?\n")
last_name=input("what is your last name ?\n")
def format_name(first,last):
if first=='' and last=='':
return "check your inputs"
f_name=first.title()
l_name=last.title()
return f_name+" "+l_name
fullname=format_name(first=first_name,last=last_na... | true |
6d44e6b86da192c3afae09ed13c5b507b15eadd8 | mve17/SPISE-2019 | /Day 1/Choose Your Own Adventure 6.py | 2,084 | 4.125 | 4 | name=input("Please Enter Your Name: ")
intro_text='''
You've woken up with a splitting headache. Fumbling in the dark, your hand brushes against a cold metallic object in the sand.
Maybe it will be useful. Would you like to take it with you? [y/n] '''
intro_response=input("\nBad news, "+name+". "+intro_text)
... | true |
e3b34d927246002048c1b992eb6af41dbb7c68f1 | mve17/SPISE-2019 | /Day 6/testing.py | 588 | 4.15625 | 4 | def reverse_digits(number):
negative=number<0
number=abs(number)
reversed_number=int(str(number)[::-1])
if negative:
reversed_number*=-1
return reversed_number
############
#TEST CASES#
############
#Test 1: 0
print("Testing 0")
if reverse_digits(0)==0:
print('passed!')
else:
prin... | true |
0932d8c4c24a6b33759f55142a466e26ba3b0ab5 | Madhan911/nopcommerceApp | /BasicPrograms/AsendingOrder.py | 765 | 4.1875 | 4 |
#In programming, a flag is a predefined bit or bit sequence that holds a binary value. Typically, a program uses a flag to remember something or to leave a sign for another program.
list_one = [1,2,3]
flag = 0
if list_one == sorted(list_one):
flag = 1
if flag:
print("list is sorted")
else:
print("list ... | true |
7ca57bbfa2bec5c1d11a4e30f1032d2987f0b6d5 | Madhan911/nopcommerceApp | /BasicPrograms/RecursionFactorial.py | 421 | 4.28125 | 4 | def fact(n):
return 1 if (n == 0 or n == 1) else n * fact(n - 1)
num = 3
print("Factorial of", num, "is", fact(num))
'''
num = int(input("enter the number : "))
factorial = 1
if num < 0:
print("number is a negative number")
elif num ==0:
print("factorial number one is 0 ")
else:
for i in range(1,... | true |
c777da622c52236d1e7dd664818824cc1fae46ff | AA-anusha/pythonclasses | /formatting.py | 448 | 4.25 | 4 | first_name = raw_input('Your first name: ')
last_name = raw_input('Your last name: ')
# Old style formatting.
print('Hello %s %s!' % (first_name, last_name))
# New Style formatting
print('Hello {} {}!'.format(first_name, last_name))
print('Hello {0} {1}!'.format(first_name, last_name))
# This is where, you will feel... | true |
2ef3ef7ea96277d3dafbd81da73dc63afd2898e2 | aoracle/hackerank | /all_domains/python/data_types/sets.py | 573 | 4.1875 | 4 | # Task
# Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
# Input Format
# The first line of input contains an integer, .
# The second line contains space-separated integers.
#... | true |
dd2547464d148487e2214804d2ff1a53c25bdd88 | DanielMafra/Python-LanguageStudies | /exercise075.py | 486 | 4.125 | 4 | number = (int(input('Enter a number:')),
int(input('Enter another number:')),
int(input('Enter one more number:')),
int(input('Enter the last number:')))
print(f'You entered the values {number}')
print(f'The value 9 appeared {number.count(9)} times')
if 3 in number:
print(f'The value... | true |
e36d10ebe0613d79cce471d872756947965708f6 | DanielMafra/Python-LanguageStudies | /exercise032.py | 345 | 4.34375 | 4 | from datetime import date
year = int(
input('What year do you want to analyze? Enter 0 to analyze the current year: '))
if year == 0:
year = date.today().year
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('The year {} is a leap year.'.format(year))
else:
print('The year {} is not a l... | true |
4a90435d940ba7b25452972abbc8e83709c061dd | mmilade/Tic-Tac-Toe | /Problems/Plus one/task.py | 437 | 4.375 | 4 | # You are given a list of strings containing integer numbers. Print the list of their values increased by 1.
# E.g. if list_of_strings = ["36", "45", "99"], your program should print the list [37, 46, 100].
# The variable list_of_strings is already defined, you don't need to work with the input.
# list_of_strings = ["... | true |
b7af78cdca8b3e3df7e070410c229f5cdaa4908c | SVMarshall/programming-challanges | /leetcode/implement_stack_using_queues.py | 1,353 | 4.25 | 4 | # https://leetcode.com/problems/implement-stack-using-queues/
class Stack(object):
# simulating first a stack
class Queue():
def __init__(self):
self.queue_list = []
def push(self, x):
self.queue_list.append(x)
def pop(self):
return self.queue_list.p... | true |
9727529e9542a4ec8fdef1092770e5cd58db6228 | yaelBrown/pythonSandbox | /pythonBasics/decorators/decoratorz.py | 857 | 4.5 | 4 | '''
Example of python decorators
'''
# have function that returns a function
def func(aa="cookies"):
print("This is the default function")
def one():
return 1
def eleven():
return 11
if aa == "cookies":
return one()
else:
return eleven()
# print(func())
# can pass a function into a funct... | true |
70c559449bd39e24557ce664afb47ca8e7359de4 | yaelBrown/pythonSandbox | /LC/_sumProduct.py | 2,616 | 4.65625 | 5 |
def sum_product(input_tuple):
prod = 1
s = 0
for i in input_tuple:
s += i
prod *= i
return s, prod
def sum_product(t):
sum_result = 0
product_result = 1
for num in t:
sum_result += num
product_result *= num
return sum_result, pro... | true |
1aa62001f4c84e91942fa762495f0ec252bc2412 | yaelBrown/pythonSandbox | /LC/LC535-EncodeDecodeTinyURL.py | 1,524 | 4.375 | 4 | """
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.
There is... | true |
79abaed44a11e0c6cdd108e345267a3b47b08b9b | yaelBrown/pythonSandbox | /LC/_maxProduct.py | 2,131 | 4.4375 | 4 | def max_product(arr):
# Initialize two variables to store the two largest numbers
max1, max2 = 0, 0 # O(1), constant time initialization
# Iterate through the array
for num in arr: # O(n), where n is the length of the array
# If the current number is greater than max1, update max1 and max2
... | true |
7c0aed711b26257167682c4ac1eae247abe451fe | 17hopkinsonh/RPG_Game | /file1.py | 875 | 4.34375 | 4 | """
Author: Hayden Hopkinson
Date: 15/09/2020
Description: A start screen explaining to the user how the game works
version: 1.0
improvements from last version:
"""
# libraries
# functions
def explain_game():
"""this will print out a explanation of the game to the user. Takes no ... | true |
19760386a0ab964d8bd37d8edb421a72f52c6fbe | kyeeh/holbertonschool-interview | /0x09-utf8_validation/0-validate_utf8.py | 1,247 | 4.34375 | 4 | #!/usr/bin/python3
"""
Write a method that determines if a given data set represents a valid
UTF-8 encoding.
Prototype: def validUTF8(data)
Return: True if data is a valid UTF-8 encoding, else return False
A character in UTF-8 can be 1 to 4 bytes long
The data set can contain multiple characters
Th... | true |
9d967f528151f408f84ff63ca8866ff204e7cfcf | wakoliVotes/Sorting-Elements-Python | /SortListElementsPython.py | 2,284 | 5 | 5 | # In python, we can adopt proper statements and tools that can help sort values
# One can sort values in ascending or sort them in descending order
# In this short example, we are demonstrating sorting items in ascending order
print("|----------------------------------------------------------------------------------... | true |
6adfdb3b77ea3fa1eca8ff303de96769616696e2 | Mguer07/script | /Dice game.py | 325 | 4.125 | 4 | import random
min = 1
max = 12
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling the dices")
print ("The values are....")
print ("person 1:",random.randint(min, max))
print ("person 2:",random.randint(min, max))
roll_again = input("Roll the dices again... | true |
2a9729d52e06fc08d9fd0a08053ec2aa2f14bdf1 | yckfowa/codewars_python | /6KYU/Count characters in your string.py | 442 | 4.21875 | 4 | """
count the number of times a character shows up in the string and output it as a dictionary
"""
def count(string):
new_dict = {}
for ch in string:
if ch not in new_dict:
new_dict[ch] = 1
else:
new_dict[ch] += 1
return new_dict
-------------------------------
#... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.