blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
88cb18925a67570cc548a039b40ea70fcf473889 | Woutah/AutoConvert | /timer.py | 2,290 | 4.25 | 4 | """Simple timer which can be used to get the wall/cpu time of a process.
Implements the "with x:" to measure timings more easily.
"""
from time import process_time
import time
class CpuTimer:
def __init__(self):
self._start_time = process_time()
self._paused = True
self._pause_time = process_time()
self._... | true |
8c25a31f8dd7dba671150a51ef052880bdc5c402 | Garce09/ShirleysMentees | /logic_recursion.py | 1,856 | 4.375 | 4 | ############ Q1. Ask the user for an integer, multiply it by itself + 1, and print the result
# Topic: user input
############ Q2. Ask the user for an integer
# If it is an even number, print "even"
# If it is an odd number, print "odd"
# Topic: conditionals, user input
############# Q... | true |
b4eddaa8ceada22cdf3d2c3f12e441752cfb6425 | larlyssa/checkio | /home/house_password.py | 1,648 | 4.1875 | 4 | """
DIFFICULTY: ELEMENTARY
Stephan and Sophia forget about security and use simple passwords for everything. Help Nikola develop a password security check module. The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least one digit, as well as containing one up... | true |
f1053a896ab4d62501f8f1930514e2d0e2e08dde | RodrigoAk/exercises | /solutions/ex13.py | 545 | 4.3125 | 4 | '''
You are given a positive integer N which represents the number of steps
in a staircase. You can either climb 1 or 2 steps at a time. Write a function
that returns the number of unique ways to climb the stairs
'''
import math
def staircase(n):
spaces = n//2 + n % 2
num2 = n//2
answer = 0
while(spac... | true |
74ec0c3112aea6992d54a59e2cec323143085df8 | hitanshkadakia/Python_Tutorial | /function.py | 1,419 | 4.75 | 5 | # Creating a Function
# In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
# Calling a Function
# To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
# Arguments
... | true |
5f2b869fad97bd52b0381a4f95ebce15c54c6568 | hitanshkadakia/Python_Tutorial | /if-elsestatement.py | 711 | 4.21875 | 4 | #If statement
a = 33
b = 200
if b > a:
print("b is greater than a")
#elif
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
#else
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print... | true |
17aeb081b24147badad1e1945acae197fe287d43 | BawangGoh-zz/ELEC0088-Lab | /Exercise2.py | 1,122 | 4.125 | 4 | ## Part 1) Implement a DNS querying program that stores the mapping between the names
## into IP addresses. Explicitly define the name of the network into the databases
## Part 2) Allow for the user to query several types of NS record (NS, MX, etc).
# IP addresses query
def IPquery(dct, string):
return dct.get(stri... | true |
8a0a9d68892f0dbac3b8e55eb69e82f1788cc05e | theoliao1998/Cracking-the-Coding-Interview | /02 Linked Lists/2-4-Partition.py | 1,801 | 4.3125 | 4 | # Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "... | true |
6c3b5c12c863b87a0c1d0cdb3ddc164caafb5862 | jimsun25/python_practice | /turtle_race/main.py | 927 | 4.21875 | 4 | from turtle import Turtle, Screen
import random
race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_pos = [-75, -45, -15, 15, 4... | true |
b8ee4804c73a956a36f4b00d94d50551149a2ad5 | sdahal1/pythonoctober | /fundamentals/python_fun/bootleg_functionsbasic2.py | 1,213 | 4.65625 | 5 | # CountUP - Create a function that accepts a number as an input. Return a new list that counts up by 1, from 1 (as the 0th element) up to num (as the last element).
# Example: countup(5) should return [1,2,3,4,5]
# Print and Return - Create a function that will receive a list with three numbers. Print the second val... | true |
1a03184e8ca72e019f6afc71915f90837ecf2c34 | spacecase123/cracking_the_code_interview_v5_python | /array_strings/1.2_reverse_string.py | 788 | 4.3125 | 4 | '''
Implement a function void reverse(char* str) in C or C++ which reverses a null- terminated string.
'''
def reverse(string):
'''reverse in place'''
string_len = len(string)
if string_len <= 1 : return string
last = string_len - 1
string = list(string)
for i in range(string_len / 2):
... | true |
acf1238f2f25e2ba32b1c0086b1a75bcc0c6905a | gauravbachani/Fortran-MPI | /Matplotlib/tutorial021_plotColourFills.py | 1,484 | 4.15625 | 4 | # Plotting tutorials in Python
# Fill colours inside plots
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.style.use('default')
x = np.linspace(-2.0*np.pi, 2.0*np.pi, 201)
C, S = np.cos(x), np.sin(x)
plt.plot(x, C, color='g', label='Cosine')
plt.plot(x, S, color='r', label='Sine')
# ... | true |
60a97cefda9fa31dda0b46740b8dc5de42bc17fe | StephenH69/CodeWars-Python | /8-total-amount-of-points.py | 1,606 | 4.25 | 4 | # Our football team finished the championship. The result of each match look like "x:y".
# Results of all matches are recorded in the collection.
# For example: ["3:1", "2:2", "0:1", ...]
# Write a function that takes such collection and counts the points of our team in the championship.
# Rules for counting points... | true |
57f3618fc797fa6bec6c896585f94685b2265337 | StephenH69/CodeWars-Python | /8-blue-and-red-marbles.py | 1,517 | 4.1875 | 4 | # You and a friend have decided to play a game to drill your
# statistical intuitions. The game works like this:
# You have a bunch of red and blue marbles. To start the game you
# grab a handful of marbles of each color and put them into the bag,
# keeping track of how many of each color go in. You take turns reac... | true |
7c86e26e0bea599be21bc9a00c788f2e9e63cef4 | VaishnaviBandi/6063_CSPP1 | /m4/p3/longest_substring.py | 1,431 | 4.3125 | 4 | '''Assume s is a string of lower case characters.
Write a program that prints the longest
substring of s in which the letters occur in alphabetical order.
For example, if s = 'azcbobobegghakl', then your program should print
Longest substring in alphabetical order is: beggh
In the case of ties, print the first subst... | true |
b61b666855df35a0968802a9018d3baf29187cc2 | VaishnaviBandi/6063_CSPP1 | /m22/assignment1/read_input.py | 426 | 4.375 | 4 | '''
Write a python program to read multiple lines of text input and store the input into a string.
'''
def main():
"""python program to read multiple lines of text
input and store the input into a string."""
string = ''
no_of_lines = int(input())
for each_line in range(no_of_lines):
string =... | true |
264245a0748c7c261abf311076a164b9cd1f4379 | aaronspindler-archive/CSCI1030U | /Labs/lab04.py | 1,453 | 4.375 | 4 | #Date: October 8th 2015
#Practising printing the statment testing 1 2 3...
print("testing 1 2 3...")
#Printing numbers, variables, and num equations
x=8
print(x)
print(x*2)
#Defining other variable types
name = "Carla Rodriguez Mendoza"
length = 14.5
width = 7.25
#Printing statments
print("X: ")
print(x)
print("Nam... | true |
8e1997b194cd3c70b844333b9a91b1a8ffee002b | fergatica/python | /triangle.py | 578 | 4.21875 | 4 | from math import sqrt
def area(first, second, third):
total = (first + second + third) / 2
final = sqrt(total*(total-first)*(total-second)*(total-third))
return final
def main():
first = input("Enter the length of the first side: ")
first = float(first)
second = input("Enter the length of th... | true |
e63094b8a8351924742363fd1e2517272fd2a7e2 | hjungj21o/Interview-DS-A | /lc_bloomberg.py/114_flatten_binary_tree_to_linked_list.py | 1,223 | 4.40625 | 4 | # Given a binary tree, flatten it to a linked list in -place.
# For example, given the following tree:
# 1
# / \
# 2 5
# / \ \
# 3 4 6
# The flattened tree should look like:
# 1
# \
# 2
# \
# 3
# \
# 4
# \
# 5
# \
# 6
# Definition for a binar... | true |
e34f79a5dbe72d7e8fff2f46b5f89f9de50f673a | hjungj21o/Interview-DS-A | /lc_88_merge_sorted_arr.py | 959 | 4.21875 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has enough space(size that is equal to m + n) to hold additional elements from nums2.
# Example:
# Input... | true |
d647fc1babadb96e9d4268d9cd97255efa479bc1 | hjungj21o/Interview-DS-A | /lc_bloomberg.py/21_merge_sorted_list.py | 913 | 4.15625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
while l1 and l2:
... | true |
a8242252ac207c8121d7f75859a97bcd9b873875 | orsnes-privatskole/python-oppgaver | /calculator-deluxe.py | 2,869 | 4.125 | 4 | import time
# Calculator - Deluxe Edition
# Name and version info
version_info = "MyCalculator - Deluxe Edition v0.3"
# Function for getting menu choice
def get_menu_choice():
# Variable used to align the menu to a common width
menu_width = 30
# List of available menu options
valid_menu... | true |
deab4c799195b9bd5b92f3052f10a7ec2c1f1826 | MarcosRS/python_practice | /01_strings.py | 1,548 | 4.21875 | 4 | #escaping characters \' , \" , \t, \n, \\
alison = 'That is Alison\'s cat'
print(alison)
#you can also use raw string and everythig will be interpreted as a string
rawStr = r'nice \' \n \" dfsfsf '
print(rawStr)
# multiline strings. this iincludes new lines as tab directly. Useful when you have a large string
mul = ... | true |
c899ae39957dc75221110be441670016040002d4 | Rachelami/Pyton_day-1 | /ex 03.py | 291 | 4.125 | 4 |
num = 3
def is_even(number):
if isinstance(number, int) == True:
if number == num:
print("True")
return True
else:
print("False")
return False
else:
print ("This is NOT an integer")
exit()
is_even(5)
| true |
376c45f4b21df79d6505234d5d14f4e1e61411c7 | Akansha0211/PythonPrograms | /Assignment4.6.py | 1,295 | 4.40625 | 4 | # 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours.
# Put the logic to do the computation of pay in a function called computepay() and use th... | true |
258d58764350aab386c1fd047b0d72ef47906114 | WangsirCode/leetcode | /Python/valid-parenthesis-string.py | 1,892 | 4.375 | 4 | # Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
# Any left parenthesis '(' must have a corresponding right parenthesis ')'.
# Any right parenthesis ')' must have a corresponding left... | true |
327adc7432d621c66865248250a20d233671e2b9 | MuhammadAzizShobari/praxis-academy | /novice/02-01/latihan/kekekalan.py | 552 | 4.1875 | 4 | mutable_collection = ['Tim', 10, [4, 5]]
immutable_collection = ('Tim', 10, [4, 5])
# Reading from data types are essentially the same:
print(mutable_collection[2]) # [4, 5]
print(immutable_collection[2]) # [4, 5]
# Let's change the 2nd value from 10 to 15
mutable_collection[1] = 15
# This fails with the tuple
i... | true |
3c40edcb6143bd3a72febcac7c4e0f891e571e51 | roopi7760/WebServer | /Client.py | 2,797 | 4.125 | 4 | '''
Author: Roopesh Kumar Krishna Kumar
UTA ID: 1001231753
This is the Client program which sends the request to the server and displays the response
*This code is compilable only with python 3.x
Naming convention: camel case
Ref: https://docs.python.org/3/library/socket.html and https://docs.python.org/3/tutorial/i... | true |
87a51c978d8891d80b1f1eafadbd0e7654e04237 | viseth89/nbapython | /trial.py | 1,042 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 26 19:06:19 2016
@author: visethsen
"""
import matplotlib.pyplot as plt
# Importing matplotlib general way that it is used
x1 = [1,2,3]
y1 = [4,7,5]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x1, y1, label = "first line")
plt.plot(x2, y2, label = 'se... | true |
4b93a00e1ca8e27e19d5c723af42b9b2604d61f4 | NUbivek/PythonBootcamp | /Module6/ex1.py | 1,175 | 4.28125 | 4 | # Exercise 1.
# Write your Binary Search function.
# Start at the middle of your dataset. If the number you are searching for is lower,
#stop searching the greater half of the dataset. Find the middle of the lower half
#and repeat.
# Similarly if it is greater, stop searching the smaller half and repeat
# the proce... | true |
09fdf09fb3393d7081c02d4fb9fbf3efb81e14b0 | NUbivek/PythonBootcamp | /Module1/ex6.py | 748 | 4.28125 | 4 | ##Exercise 6: Write Python program to construct the following pattern, using a nested for loop.
def triangle():
temp_var = ""
for num in range(5):
temp_var += "*"
print(temp_var)
for num in range(5,0,-1):
temp_var = "*"
print(num * "*")
... | true |
075507eb146a94e556b9fe135191c904a4e479ed | 4320-Team-2/endDateValidator | /endDateValidator.py | 1,352 | 4.34375 | 4 | import datetime
class dateValidator:
#passing in the start date provided by user
def __init__(self, startDate):
self.startDate = startDate
def endDate(self):
#loop until user provides valid input
while True:
#try block to catch value errors
try:
... | true |
c72f07976c3d40c88fbef5a39d3bdab8f0a5f202 | divyashree-dal/PythonExercises | /Exercise22.py | 673 | 4.625 | 5 | '''Question 54
Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
Hints:
To override a method in super class, we can define a method with ... | true |
8fd1d34b6a98d4f171c8b7bd138f892a3861800e | deepakmethalayil/PythonCrash | /list_study.py | 785 | 4.125 | 4 | members = ['uthay', 'prsanna', 'karthick']
members_master = members
print(members) # print the entire list
print(members[0]) # print list items one by one
print(members[1])
print(members[2])
msg = "Hello!"
print(f"{msg},{members[0].title()}")
print(f"{msg},{members[1].title()}")
print(f"{msg},{members[2].title()}")
#... | true |
0c885c721e116d2ed482bf53bae8590df0db711e | gauvansantiago/Practicals | /Prac_02/exceptions_demo.py | 1,020 | 4.46875 | 4 | # Gauvan Santiago Prac_02 Task_04 exceptions_demo
try:
# asks to input numerator and denominator
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
# while loop will prevent ZeroDivisionError and ask for a valid denominator
while denominator == 0:
... | true |
a26da98cd7f927a76810f2b9f97a60e896cbd5ee | Anjalibhardwaj1/GuessingGame | /GuessingGame.py | 2,370 | 4.28125 | 4 | #December 30 2020
#Guessing Game
#This program will pick a random number from 1 to 100, and
#it will ask the user to guess the number.
from random import randint
#Welcome Message and Rules
print("\n---------------------- Guessing Game ------------------------------")
print("Welcome!")
print("In this game I wi... | true |
ed294c0d77434c644a4805c6f7a04b1789e1019d | nbrown273/du-python-fundamentals | /modules/module11_list_comprehensions/exercise11.py | 1,384 | 4.34375 | 4 | # List Comprehension Example
def getListPowN(x, n):
"""
Parmaeters: x -> int: x > 0
n -> int: n >= 0
Generate a list of integers, 1 to x, raised to a power n
Returns: list(int)
"""
return [i**n for i in range(1, x) if i % 2 == 0]
# Dictionary Comprehension Example
def getDictC... | true |
2cad47a5a9905de6a6dfc562e71db4f8a6e66ac9 | manmodesanket/hackerrank | /problem_solving/string.py | 683 | 4.34375 | 4 | # You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
#
# For Example:
#
# Www.HackerRank.com → wWW.hACKERrANK.COM
# Pythonist 2 → pYTHONIST 2
# Input Format
#
# A single line containing a string .
#
# Constraints
#0<=len(s)<=1000
#
#... | true |
4d97da83215734d677dd6b7bc15c527b9e6ee262 | srs0447/Basics | /8-calculator.py | 817 | 4.15625 | 4 | # Basic calculator that do the basic calculations like addition, subtraction, multification etc
# declaring the global variables
print("This is the basic calculator")
print("\n********************************************\n")
print("$$$$$$^^^^^^********^^^^^^^$$$$$$$$$$")
number1 = float(input('Please Enter the first nu... | true |
ffb5acfef7395967bfc3a8d62fb981768ef6bae4 | anish-lakkapragada/libmaths | /libmaths/trig.py | 2,884 | 4.28125 | 4 | #Developer : Vinay Venkatesh
#Date : 2/20/2021
import matplotlib.pyplot as plt
import numpy as np
def trigsin(z, b):
'''
In mathematics, the trigonometric functions are real functions which relate
an angle of a right-angled triangle to ratios of two side lengths.
Learn More: https://www.mathsisfun.com/sine... | true |
9d59edf273a76e409ca5ba7a6898c50d130d43c7 | khanmaster/python_modules | /exception_handling.py | 1,246 | 4.1875 | 4 | # We will have a look at the practical use cases and implementation of try, except, raise and finally
we will create a variable to store a file data using open()
Iteration 1
try: # let's use try block for a 1 line of code where we know this will throw an error
file = open("orders.text")
except:
print(" Panic A... | true |
60e0fa3af1eca5fbd52590f7622545097db1a8be | jxhangithub/lintcode | /Tree/480.Binary Tree Paths/Solution.py | 1,853 | 4.15625 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root of the binary tree
@return: all root-to-leaf paths
"""
def binaryTreePaths(self, root):
# write your code ... | true |
1708d66404362fb9a0e18008e6e500453235a49e | chandnipatel881/201 | /chap3.py | 407 | 4.25 | 4 | print "This program illustrates average of numbers"
# total_num = input ("How many numbers you want to average : ")
# sum = 0.0
#
# for i in xrange(total_num):
# sum = sum + input("Enter: " )
# average = sum/total_num
# print average
avg = 0.0
count = 0
while True:
total = avg * count
num = input("Enter ... | true |
d4b2cdb089e531181f30b6130d915878bd5744ef | Aiswarya333/Python_programs | /const5.py | 1,595 | 4.1875 | 4 | '''CELL PHONE BILL - A particular cell phone plan includes 50 minutes of air time and 50 text messages for $15.00 a month. Each additional minute of air time costs
$0.25, while additional text messages cost $0.15 each. All cell phone bills include an additional charge of $0.44 to support 911 call centers, and the enti... | true |
38f3243733f0a36e5c2ca109f986f9fdc94cd9f0 | ed4m4s/learn_python_the_hard_way | /Exercise18.py | 569 | 4.1875 | 4 | #!/usr/bin/python
# Exercise on Names, Variables, Code, Functions
# this one is like the scripts we did with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# Take out the *args as you do not need it
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg... | true |
1f024b3de44ee95d07ab6b44a2c3fcf22079ba09 | pioziela/programming-learning | /Hacker_Rank_Exceptions.py | 965 | 4.25 | 4 | import sys
def divide_exceptions():
"""
divide_exceptions function trying to divide two values.
The user provides data in the following format:
- in the first line the number of divisions to be carried out,
- in the following lines, the user provides two values to divide, the values should be sepa... | true |
a1b191446e960f38e7e6621275d85ac7629d0368 | geetha10/GeeksForGeeks | /basic/factorial.py | 317 | 4.25 | 4 | def factorial(num):
result = 1
for x in range(1, num+1):
result = result*x
return result
num = input("Enter a number for finding factorial")
if num.isdigit():
num = int(num)
fact = factorial(num)
print(f"Factorial of {num} is {fact}")
else:
print("Please enter a valid Integer")
| true |
721b2651ffb8c02d09a2130810f3baf3294c48ec | jayantpranjal0/ITW1-Lab | /python-assignments/3/4.py | 219 | 4.375 | 4 | '''
Python program to read last n lines of a file.
'''
with open("test.txt", "r") as f:
n = int(input("Enter number of lines from last to read: "))
for i in f.readlines()[-n:]:
print(i, end = "") | true |
4bc1c71828f44dda49523303fa15adc3ba9ed9d3 | jayantpranjal0/ITW1-Lab | /python-assignments/1/14.py | 213 | 4.21875 | 4 | '''
Python program to get the number of occurrences of a specified element in an array.
'''
l = input("Enter the array: ").split()
e = input("Enter the element: ")
print("No of occurence: "+str(l.count(e))) | true |
01fe18819e29ae6806c6392f384ce6cbc39c81b7 | KarnolPL/python-unittest | /06_functions/04_tax/tax.py | 511 | 4.25 | 4 | def calc_tax(amount, tax_rate):
"""The function returns the amount of income tax"""
if not isinstance(amount, (int, float)):
raise TypeError('The amount value must be int or float type')
if not amount >= 0:
raise ValueError('The amount value must be positive.')
if not isinstance(tax_ra... | true |
5588dad39ce8b2d00d77f4497371df468016e4fe | Parzha/Assingment3 | /assi3project6.py | 583 | 4.125 | 4 |
flag=True
number_list = []
while flag:
user_input=int(input("Please enter the numbers you want? "))
number_list.append(user_input)
user_input_2=input("If you wanna continue type yes or 1 if you want to stop type anything= ").lower()
if user_input_2=="1" or user_input_2=="yes":
flag=Tr... | true |
e42748ed030e92c694657695e48fdc29a3dafed8 | ConnorHoughton97/selections | /Water_Temp.py | 337 | 4.34375 | 4 | #Connor Houghton
#30/09/14
#telling the user whether ater is frozen, boiling or neither
water_temp = int(input("please enter the temperature of the water: "))
if water_temp >= 100:
print ("The water is boiling.")
elif water_temp <= 0:
print("The water is frozen.")
else:
print("The water is neit... | true |
fbf00374688203f1feacec0636e2f1d385439be0 | zhanshi06/DataStructure | /Project_1/Problem_2.py | 1,375 | 4.375 | 4 | import os
def find_files(suffix, path):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffi... | true |
32e95aacf766b380faaa2b8dc64d13b7bb062f24 | fffelix-jan/Python-Tips | /3a-map-those-ints.py | 239 | 4.15625 | 4 | print("Enter space-separated integers:")
my_ints = list(map(int, input().split())) # collect the input, split it into a list of strings, and then turn all the strings into ints
print("I turned it into a list of integers!")
print(my_ints) | true |
0ff46aa541476ec73d8dbe2de099a11048d0f560 | SS1908/30_days_of_python | /Day 16/properties_of_match.py | 342 | 4.21875 | 4 | """"
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function.
.group() returns the part of the string where there was a match.
"""
import re
str = "The train in Spain"
x = re.search("train",str)
print(x.span())
print(x.str... | true |
d62363750fa06239f769f4490b7c8dea0eeb06eb | SS1908/30_days_of_python | /Day 12/LIst_comprehension.py | 466 | 4.34375 | 4 | """
List Comprehension is defined as an elegant way to define, create a list in Python.
It consists of brackets that contains an expression followed by for clause.
SIGNATURE:
[ expression 'for' item 'in' list 'if' condition]
"""
letters = []
for letter in 'Python':
letters.ap... | true |
c07614f370a9f5b625593569cf89f2e98f15e01a | SS1908/30_days_of_python | /Day 17/type_of_variable_in_class.py | 940 | 4.34375 | 4 | """
we have a two type of variable in class :- 1) instance variable
2)class variable
instance variable is changes object to object.
class variable is same for all the instance/object of the class.
"""
class car:
#this is a class variable
... | true |
9d6e28084ff70545db5ed473b6ca361806566481 | SS1908/30_days_of_python | /Day 6/Comparisons_of_set.py | 406 | 4.25 | 4 | # <, >, <=, >= , == operators
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
# Days1 is the superset of Days2 hence it will print true.
print(Days1 > Days2)
# prints false since Days1 is not the subset of Days2
print(Days1 < Days... | true |
6a1f01bccda41e9216fc389162eaa758f241ac7d | SS1908/30_days_of_python | /Week 1/Day 1/Logical_operator.py | 761 | 4.5625 | 5 | #Logical operators are use to combine conditional statements.
# Operator Description
# and Returns True if both statements are true
# or Returns True if one of the statements is true
# not Reverse the result, returns False if the result is true
pr... | true |
34133a627a028c0b89086bd79ab2928cdd85aa36 | leoweller7139/111-Lab-1 | /calc.py | 1,299 | 4.15625 | 4 | # Method on the top
def seperator():
print(30 * '-')
def menu():
print('\n') #\n is like pressing enter
seperator()
print(" Welcome to PyCalc")
seperator()
print('[1] - Add')
print('[2] - Subtract')
print('[3] - Multiply')
print('[4] - Divide')
print('[x] - Exit')
... | true |
c3b4e2f580b13b04739c2b47b7dd47def850947e | gabe01feng/trinket | /Python Quiz/poolVolume.py | 1,108 | 4.1875 | 4 | import math
name = input("What is your name? ")
pool = input("What shape is your pool, " + name + "? (Use RP for rectangular prism, C for cube, or CY for a cylindrical pool) ")
if pool == "RP":
length = float(input("What is the length of the pool in feet? "))
width = float(input("What is the width of the pool... | true |
d68f4b523b209f3a42cea58cafd8b153eeba6ba2 | Mukosame/learn_python_the_hard_way | /ex25.py | 1,380 | 4.4375 | 4 | def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word... | true |
2aa078dc068d59306dd016ccd5f61591fc6c1214 | aselvais/PythonOOPexample | /libs/animals/AnimalArmy.py | 1,246 | 4.1875 | 4 | """
Class for creating an army of animal
"""
from libs.animals.Dog import Dog
from libs.animals.Duck import Duck
class AnimalArmy:
"""Generates an army of animals
Args:
animal_type (str, optional): duck or dog. Defaults to 'duck'.
army_size (int, optional): Number of animal in the army. Defau... | true |
3807e45d09f23244239ad8db2bdd786c0badc56e | Kota-N/python-exercises | /ex6StringLists.py | 350 | 4.125 | 4 | # An exercise from http://www.practicepython.org/
#6 String Lists
import math
word = input("Enter a word: ")
middleIndex = math.floor(len(word)/2)
firstHalf = word[0:middleIndex]
lastHalf = word[middleIndex+1:]
if firstHalf[::-1] == lastHalf:
print(word, ": Your word is palindrome!")
else:
print(word, ": Y... | true |
906289d11e5d2e0cb23ed09ed268916674ae689f | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/Hacker Chapter--Files/ex.04.py | 2,959 | 4.25 | 4 | '''Here is a file called labdata.txt that contains some sample data from a lab experiment.
44 71
79 37
78 24
41 76
19 12
19 32
28 36
22 58
89 92
91 6
53 7
27 80
14 34
8 81
80 19
46 72
83 96
88 18
96 48
77 67
Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair.
Write a function c... | true |
eaedab6cec968ff2daf1313210d0713a8a397653 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 3/ex.04.py | 1,137 | 4.375 | 4 | '''Football Scores Suppose you’ve written the program below.
The given program asks the user to input the number of touchdowns and field goals scored by a (American) football team,
and prints out the team’s score. (We assume that for each touchdown, the team always makes the extra point.)
The European Union has decid... | true |
8751ce643df7e321eaf0f354e4e2d03641f56778 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 2/ex.08.py | 326 | 4.28125 | 4 | '''Write a program that will compute the area of a rectangle.
Prompt the user to enter the width and height of the rectangle.
Print a nice message with the answer.
'''
## question 9 solution
width = int(input("Width? "))
height = int(input("Height? "))
area = width * height
print("The area of the rectangle is", ... | true |
cd9e9cf99f39ffab5a59d013375ebe2016503dae | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Problem Set--Crypto/commandline.py | 1,150 | 4.53125 | 5 | '''
commandline.py
Jeff Ondich, 21 April 2009
This program gives a brief illustration of the use of
command-line arguments in Python. The program accepts
a file name from the command line, opens the file, and
counts the lines in the file.
'''
import sys
# If the user types too few or too ma... | true |
f81af3b3ee07daecb713502882d235f0b62e0fca | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/List Comprehensions.py | 628 | 4.5 | 4 | '''The previous example creates a list from a sequence of values based on some selection criteria.
An easy way to do this type of processing in Python is to use a list comprehension.
List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
wh... | true |
b1b9abda174eecee080e0bc8b1fa8b424104ea3e | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Problem Set--Crypto/strings2.py | 442 | 4.15625 | 4 | '''strings2.py
Jeff Ondich, 2 April 2009
This sample program will introduce you to "iteration" or
"looping" over the characters in a string.
'''
s = 'two kudus and a newt'
# What happens here?
print('The first loop')
for ch in s:
print (ch)
print()
# And here?
print( 'The second loop')
k = 0
while k ... | true |
6b49356fb32eee0f79ad56e806a41b549b7fc847 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 6/ex.08.py | 337 | 4.28125 | 4 | '''Now write the function is_odd(n) that returns True when n is odd and False otherwise.
'''
from test import testEqual
def is_odd(n):
# your code here
if n % 2 == 0:
return False
else:
return True
testEqual(is_odd(10), False)
testEqual(is_odd(5), True)
testEqual(is_odd(1), True)
testEqual(... | true |
1122da139c723e93234aba0ae35e3ec62f7504b6 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Nested Lists.py | 776 | 4.53125 | 5 | '''A nested list is a list that appears as an element in another list.
In this list, the element with index 3 is a nested list.
If we print(nested[3]), we get [10, 20]. To extract an element from the nested list, we can proceed in two steps.
First, extract the nested list, then extract the item of interest.
It is ... | true |
cbb24873533a63b0842920b265efe25987dca3f3 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 14/ex.06.py | 1,691 | 4.125 | 4 | ''')
(GRADED) Write a new method in the Rectangle class to test if a Point falls within the rectangle.
For this exercise, assume that a rectangle at (0,0) with width 10 and height 5 has open upper bounds on the width and height, i.e.
it stretches in the x direction from [0 to 10), where 0 is included but 10 is exclude... | true |
bd7d3da5c3917644520e2fd9528bee66e85ade32 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 4/ex.02.py | 884 | 4.4375 | 4 | '''Turtle objects have methods and attributes. For example, a turtle has a position and when you move the turtle forward, the position changes.
Think about the other methods shown in the summary above. Which attibutes, if any, does each method relate to? Does the method change the attribute?
'''
'''Write a program tha... | true |
d15fa577adbdc9cf9ac0c3ad0652ad2430eb8bca | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 12/Crypto/Caesar Cipher/caesar01/caesar 02.py | 1,272 | 4.375 | 4 | def caesarCipher(t, s):
"""
caesarCipher(t, s)
Returns the cipher text in a given plain text or vice versa.
Variables:
t - text (input), nt - new text (output)
lc - lowercase, uc - uppercase
pt[c] - nth character of the plain text (also used to get the
... | true |
7f7f4cd5a877fb9a457cd662ec1cbe4f47cba6cb | CriticalD20/String-Jumble | /stringjumble.py | 1,567 | 4.3125 | 4 | """
stringjumble.py
Author: James Napier
Credit: http://stackoverflow.com/questions/12794141/reverse-input-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-... | true |
03478dde7f02433ae2c351c181cefc942e0c75be | parthpanchal0794/pythontraining | /NumericType.py | 1,634 | 4.25 | 4 | """
Numeric types classes
1. Integer e.g 10
2. Float e.g 10.0
3. Complex e.g 3 + 5j
4. Binary type (Class Int)
5. Hexadecimal (Class Int)
6. Octa decimal (Class Int)
"""
# Integer Values
a = 13
b = 100
c = -66
print(a, b, c)
print(type(a))
# Floating values
x = 33.44
y = -8.78
z = 56.0 # with... | true |
a862febaed4059785ab37c810b54b6a1034c6901 | Mohibtech/Mohib-Python | /UrduPythonCourse/List Comprehension.py | 2,248 | 4.75 | 5 | '''
List comprehensions provide a concise way to create lists.
It consists of brackets containing an expression followed by a for clause, then
optional if clauses.
The expressions can be anything, meaning you can put in all kinds of objects in lists.
The list comprehension always returns a result list.
'''
# List co... | true |
3cf56345025b2e3d5581c689813defd14a38feb7 | malhar-pr/side-projects | /pythagorean.py | 2,783 | 4.375 | 4 | import time
pyth_list=[] #Creates an empty list that will hold the tuples containing Pythagorean/Fermat triplets
power_list=[] #Creates an empty list that will cache the value of each index raised to the specified exponent in the given range
print("------------------------------------------------------------------... | true |
e884acf79724ce595323ca07bf8e9783a2698f2e | shubham-bhoite164/DSA-with-Python- | /Reversing the Integer.py | 685 | 4.21875 | 4 | # Our task is to design an efficient algorithm to reverse the integer
# ex :- i/p =1234 , o/p =4321
# we are after the last digit in every iteration
# we can get it with modulo operator: the last digit is the remainder when dividing by 10
# we have to make sure that we remove that digit from the original number
# so w... | true |
1c7a92b66d1999fc6158a0422558668498f5aa0f | hdjsjyl/LeetcodeFB | /23.py | 2,577 | 4.21875 | 4 | """
23. Merge k Sorted Lists
Share
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
## solution1: similar to merge sort algorithm, the time complexity is O(nklogn)
# n is the length ... | true |
aa866eb07967f983e83b81db0dd63ca2237c8935 | marwane8/algorithms-data-structures | /Sorting.py | 2,174 | 4.25 | 4 | import heapq
'''
SORTING ALGORITHMS
-Sorting Algorithms are a common class of problems with many implementation
-This class highlights some of the foundational implmentations of sorting
-SORT FUNCTIONS-
selectionSort: finds the minimum number and pops it into the result array
mergeSort: u... | true |
87784d6b0b95fb4c9b84b0a25d1b9c3423a7a52c | linhdvu14/leetcode-solutions | /code/874_walking-robot-simulation.py | 2,149 | 4.5 | 4 | # A robot on an infinite grid starts at point (0, 0) and faces north. The robot can
# receive one of three possible types of commands:
# -2: turn left 90 degrees
# -1: turn right 90 degrees
# 1 <= x <= 9: move forward x units
# Some of the grid squares are obstacles.
# The i-th obstacle is at grid poin... | true |
7908915172b367d592be102e890a18001709d6e2 | linhdvu14/leetcode-solutions | /code/231_power-of-two.py | 639 | 4.375 | 4 | # Given an integer, write a function to determine if it is a power of two.
# Example 1:
# Input: 1
# Output: true
# Explanation: 20 = 1
# Example 2:
# Input: 16
# Output: true
# Explanation: 24 = 16
# Example 3:
# Input: 218
# Output: false
# ----------------------------------------------
# Ideas: power of two iff... | true |
ded0c70db2cdd448b7041f41266219fe933f1aa7 | linhdvu14/leetcode-solutions | /code/589_n-ary-tree-preorder-traversal.py | 918 | 4.125 | 4 | # Given an n-ary tree, return the preorder traversal of its nodes' values.
# For example, given a 3-ary tree:
# 1
# / | \
# 3 2 4
# / \
# 5 6
# Return its preorder traversal as: [1,3,5,6,2,4].
# Note: Recursive solution is trivial, could you do it iteratively?
# --------------------------------------... | true |
41be3c636e2d3cda64f2b4db81121a7b47ead5f5 | alexresiga/courses | /first semester/fp/assignment1/SetBP10.py | 660 | 4.375 | 4 | # Consider a given natural number n. Determine the product p of all the proper factors of n.
def productOfProperFactors(n):
"""
This function returns the product of all proper factor of a given natural number n.
input: n natural number.
output: a string with the proper factors and the reuslt... | true |
a4e6c461cea4d86d34094af65ca4ee743b7be922 | oneandzeroteam/python | /dev.garam.seo/factorial.py | 227 | 4.25 | 4 | #factorial.py
factorial = 1
number = int (input ("input the number wanted to factorial: "))
print (number)
if (number == 1):
factorial = 1
else :
for i in range (1, number+1):
factorial = factorial * i
print (factorial) | true |
98b8353fedd8c1efa32ef163d62ba63c9cf169c2 | WhySongtao/Leetcode-Explained | /python/240_Search_a_2D_Matrix_II.py | 1,350 | 4.125 | 4 | '''
Thought: When I saw something like sorted, I will always check if binary search
can be used to shrink the range. Here is the same.
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Take this as an example. First let's go to the middle of the f... | true |
b928b09a4b3e417316274d2bd19ddccf31198aff | LeftySolara/Projects | /Classic Algorithms/Collatz_Conjecture/collatz.py | 606 | 4.1875 | 4 | """
Collatz Conjecture:
Start with a number n > 1. Find the number of steps it takes to
reach one using the following process:
If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1
"""
try:
n = int(input("Enter a number greater than one: "))
if n <= 1:
print("Invalid input")... | true |
80f8377d734ff1a9f51ea52956ddbdb172456b78 | lachlankerr/AdventOfCode2020 | /AdventOfCode2020/day09.py | 1,883 | 4.15625 | 4 | '''
Day 09: https://adventofcode.com/2020/day/9
'''
def read_input():
'''
Reads the input file and returns a list of all the lines
'''
lines = []
with open('day09input.txt') as f:
lines = f.read().splitlines()
lines = list(map(int, lines)) # convert list to ints
return li... | true |
90251aa6711f4db8af28ce75d89e4de26552f4a6 | danielmaddern/DailyProgrammer | /easy_challenge_1/challange.py | 611 | 4.25 | 4 | """
create a program that will ask the users name, age, and reddit username. have it tell them the information back, in the format:
your name is (blank), you are (blank) years old, and your username is (blank)
for extra credit, have the program log this information in a file to be accessed later.
"""
name = raw_input(... | true |
5368c1c72141f2c65dc28018a9007b8465b308a4 | neha52/Algorithms-and-Data-Structure | /Project1/algo2.py | 2,928 | 4.21875 | 4 | # -*- coding: utf-8 -*-
array = [] #create an array.
x = float (input ("Enter the value of X: "))
n = int(input("Enter the number of elements you want:"))
if(n<2): #check if array more than two elements.
print ("Enter valid number of elements!")
else:
print ('Enter numbers in array: ') #take i... | true |
679425af21b2ce17248f38b842ab6717df10d1a9 | Langutang/Spark_Basics | /spark_basics_.py | 2,906 | 4.1875 | 4 | '''
Spark is a platform for cluster computing. Spark lets you spread data and computations over clusters with multiple nodes (think of each node as a separate computer).
Splitting up your data makes it easier to work with very large datasets because each node only works with a small amount of data.
As each node works... | true |
d07674970d95b0ab207982ccf70f771840a8486d | Liam1809/Classes | /Polymorphism.py | 798 | 4.28125 | 4 |
a_list = [1, 18, 32, 12]
a_dict = {'value': True}
a_string = "Polymorphism is cool!"
print(len(a_list))
print(len(a_dict))
print(len(a_string))
# The len() function will attempt to call a method named __len__() on your class.
# This is one of the special methods known as a “dunder method” (for double underscore) w... | true |
2ab337712c44f9dd7fffb98548c8e3a7d0cea93f | tillyoswellwheeler/python-learning | /multi-question_app/app.py | 929 | 4.15625 | 4 | #--------------------------------------------
# Python Learning -- Multi-Question Class App
#--------------------------------------------
from Question import Question
#-------------------------------------
# Creating Question Object and App
question_prompts = [
"What colour are apples?\n(a) Red/Green\n(b) Purple... | true |
0443bd0c80489e9a063851c62583a9fb7956bc4a | tillyoswellwheeler/python-learning | /2d-lists_&_nested-loops.py | 625 | 4.40625 | 4 | #-----------------------------------------
# Python Learning -- 2D & Nested Loops
#-----------------------------------------
#-----------------------------------------
# Creating a 2D array
number_grid = [
[1, 3, 4],
[3, 4, 5],
[3, 6, 7],
[2]
]
#-----------------------------------------
# Accessing r... | true |
69e4a76a2265aa14a5efaaef542c8335fdd2a3e1 | tillyoswellwheeler/python-learning | /inheritance.py | 607 | 4.4375 | 4 | #-------------------------------------
# Python Learning -- Inheritance
#-------------------------------------
#-------------------------------------
#
class Chef:
def make_chicken(self):
print("Chef makes chicken")
def make_ham(self):
print("Chef makes ham")
def make_special_dish(self)... | true |
d16589bfe23eaa72097e6fd6ea740bc4008a9415 | tillyoswellwheeler/python-learning | /LPTHW/Ex15.py | 1,123 | 4.40625 | 4 | # ------------------------------------
# LPTHW -- Ex15. Reading Files
# ------------------------------------
from sys import argv
# this means when you run the python, you need to run it with the name of the python command
# and the file you want to read in
script, filename = argv
# This opens the file and assigns ... | true |
0bc1e75b9b72d3dc658993e020e7067a3ad5e468 | sriram161/Data-structures | /PriorityQueue/priorityqueue.py | 1,580 | 4.21875 | 4 | """ Priotity Queue is an abstract data structure.
Logic:
-------
Priority queue expects some sort of order in the data that is feed to it.
"""
import random
class PriorityQueue(object):
def __init__(self, capacity):
self.capacity = capacity
self.pq = []
def push(self, value... | true |
98082b9e10c1250be6b115aa7278315a0a4b9cdc | griffs37/CA_318 | /python/8311.sol.py | 1,013 | 4.15625 | 4 | def make_sum(total, coins):
# Total is the sum that you have to make and the coins list contains the values of the coins.
# The coins will be sorted in descending order.
# Place your code here
greedy_coin_list = [0] * len(coins) # We create a list of zeros the same length as the coins list we read in
i = 0... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.