blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c7c88b39fd14b7dc4c7754df8e4dc2a601cc594f | dorakarkut1/Music-Weather | /get_location.py | 764 | 4.125 | 4 | """Get location
This script based on IP address gets and returns location of user.
This script requires that `re, json, urllib` are installed within the Python
environment you are running this script in.
This file can also be imported as a module and contains the following
function:
* get_location - returns loc... | true |
fd6311b20aa6851ac1dc53420d7faa529bf5d4ab | SuguruChhaya/python-exercises | /Hackerrank 30 days of code/binary.py | 402 | 4.15625 | 4 | print(0b000000001001)
# ?binary numbers 0101 is 5, but I don't understand how a binary number can start with a 0
#!As you can see in the previous examples, the sequence between the first 1 and last 1 is what matters.
#!No matter how many 0s you add before the first 1, the value wouldn't change
#!Addionally, no matter h... | true |
7c042db4f53e1b0cedcf889f8117859845705eea | Martondegz/python-snippets | /par.py | 1,050 | 4.15625 | 4 | # Write a function that return whether or not the input string has balanced parentheses
# Balanced:
# '((()))'
# '(()())'
# Not balanced:
# '((()'
# '())('
# use input for a string
from pythonds.basic.stack import Stack
def parChecker(symbolString):
s = Stack() # stack method applied
balanced = True... | true |
8b599baaa69f6af2e424dba6424c37c38670ba25 | Martondegz/python-snippets | /caps.py | 699 | 4.21875 | 4 | """Write a program that accepts sequence of lines as input and
prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT"""
# create a list variable... | true |
2424df63a9e39b2bc3c9a884963e9b849eed6686 | Martondegz/python-snippets | /larger.py | 490 | 4.125 | 4 | # Given a number whose digits are unique, find the next larger number that can be formed with those digits.
# For example: 241 will output 421, 27 will output 72 and 68734 will output 87643
def larger_num(num):
# convert to string
num_str = str(num)
# create a empty list
# add each the char to list
lst = [x for... | true |
4726176ffbd1b58eb92f860fa4bd3a32e7ca8849 | htjhia/superfluous | /master_101/create_perm.py | 743 | 4.15625 | 4 | def create_perm(actual_list, add_list):
"""
https://stackoverflow.com/questions/64614220/python-permutation-using-recursion
Recursive function for the creation of the permutation
"""
if len(add_list)==1:
# If you reach the last item, print the found permutation
# (add the 0 at the be... | true |
f4fec23292dcc55a195d57b98798f71abcebd306 | CatPhillips103/Python-Crash-Course | /functions/passing_arguments.py | 1,660 | 4.375 | 4 | # T-shirt: Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt.
# The function should print a sentence summarising the size of the shirt and the message printed on it.
# Call the function once using positional arguments to make a shirt. Call the functio... | true |
0f978cb8a0a7c4cc90d8fd827f71249fcb3aa448 | rahulcs754/100daysofcode-Python | /code/files/50.py | 1,992 | 4.125 | 4 | # Python code to demonstrate the working of
# typecode, itemsize, buffer_info()
# importing "array" for array operations
import array
# initializing array with array values
# initializes array with signed integers
arr= array.array('i',[1, 2, 3, 1, 2, 5])
# using typecode to print datatype of array
print ("Th... | true |
7aa725d79bb803f1e1d7f94ce3d26d4cd334fee9 | behrokhGitHub/Ex_Files_Python_EssT | /Exercise Files/Chap15/db-api.py | 1,710 | 4.84375 | 5 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
import sqlite3 as sq
def main():
print('connect')
'''
To create a databases using the connect() function of the sqlite3 module.
db is the connection object.
'''
db = sq.connect('db-api.db')
'''
Create a Cursor ob... | true |
c36f8e781595c203ef9503cda1e9819e668abe22 | shumeiberk/Election-Analysis | /python_practice.py | 2,953 | 4.1875 | 4 | # print("Hello World")
# print(type(3))
# print(type(True))
# voting_data = []
# voting_data.append({"county":"Arapahoe", "registered_voters": 422829})
# voting_data.append({"county":"Denver", "registered_voters": 463353})
# voting_data.append({"county":"Jefferson", "registered_voters": 432438})
# print(voting_data)
... | true |
89278ae5660b4c63bfef73dc9f0eaab4b9bbff62 | haynes1/python-datastructures | /product.py | 304 | 4.21875 | 4 | def multiply(a,b):
product = 0
if b < 0:
a = multiply(a,-1)
b = abs(b)
for i in range(0,b):
product = product + a
return product
print "multiply 2 * 3 ", multiply(2,3)
print "multiply -2 * 3", multiply(-2,3)
print "multiply 2 * -3", multiply(2,-3)
print "multiply -2 * -3", multiply(-2,-3) | true |
54bd12e727969f2e4ee9754c9a0a7d27f9feac91 | necrospiritus/Python-Working-Examples | /P11-Factorial Function/Factorial Function.py | 286 | 4.40625 | 4 | #Factorial Function - Burak Karabey
def factorial_function():
number = int(input("Enter the number: "))
i = 1
factorial = 1
while i <= number:
factorial = factorial * i
i += 1
return print("{}! = {}".format(number, factorial))
#USAGE
factorial_function()
| true |
51286499c8aa00670d9c6e4b1e012dce2a9ee171 | necrospiritus/Python-Working-Examples | /P20-Stack Abstract Data Type/Stack - Reverse Stack.py | 825 | 4.28125 | 4 | """Reverse stack is using a list where the top is at the beginning instead of at the end."""
class Reverse_Stack:
def __init__(self):
self.items = []
def is_empty(self): # test to see whether the stack is empty.
return self.items == []
def push(self, item): # adds a new item to the bas... | true |
ca7b889cc7e389dd81f88edd4823717a3721cfed | seddap/LPTHW | /ex11.py | 532 | 4.28125 | 4 | #Exercise 11: Asking Questions
print ("How old are you?", end =' '),
age = input()
print ("How tall are you?", end =' '),
height = input()
print ("How much do you weigh?", end = ' '),
weight = input()
print ("Give me number:", end = ' ')
number = int(input())
#gets number as string and converts it to int
print ("So y... | true |
6a795e0e3e4eaff44d3b5dc88e7f4046436a58e1 | roderickyao/Projects | /Python/Numbers/fibonacci.py | 376 | 4.21875 | 4 | number = 8
def fibonacci(number):
if number < 2:
raise ValueError("Number has to larger than 2.")
n1, n2 = 1, 1
sum = 0
print(n1, n2, end=' ')
while sum < number:
sum = n1 + n2
if sum > number:
raise ValueError("Does not have Fibonacci sequence match exactly to that number.")
print(su... | true |
6358f5c54d79d21147559e2bff038b85adfb27fc | NCBS-students/Workshop2017 | /material/Python/day1_find_prime_numbers.py | 1,643 | 4.25 | 4 | # Following code finds prime number in first 100 positive integer. Whatever
# is written after "#" is called comment and will NOT be executed by
# compiler. We will use these comments to explain our logic behind every step
# Let us understand logic first.
# Prime number is any number who is not divisible by 1 and its... | true |
ffcc1df0e245da05b3cf4f9b09dbf1ba67ce1b9c | AnkitaDeshmukh/Importing-data-in-python-part2 | /diving deep into the twitter API/Plotting your Twitter data.py | 1,014 | 4.1875 | 4 | #Now you have the number of tweets that each candidate was mentioned in,
#you can plot a bar chart of this data. use the statistical data visualization library seaborn
# You'll first import seaborn as sns. You'll then construct a barplot of the data using sns.barplot,
#passing it two arguments:
#a list of labels an... | true |
b6a2a488c6b408b1e12b7a15e6bc79eeadb622bf | daemonyj/cic | /exercises/CI/linting/resources/src/operations.py | 1,398 | 4.1875 | 4 | """
Calculator operations - module containing classes to perform the mathematical operations
provided through a calculator.
"""
from abc import ABC, abstractmethod
class Operation(ABC):
"""
Abstract class defining required interface for calculator operations
"""
def __init__(self, value):
s... | true |
cc55d0d14b1e5f9b302ad48fec07c807316a2e0c | zeeshan-akram/Python-Code | /exercise 6.py | 363 | 4.28125 | 4 | weight = float(input("Enter weight: "))
unit = input("Kg or Lbs? ").lower()
kilogram = 'kg'
pounds = 'lbs'
if unit == kilogram:
result = weight / 0.45
result = round(result, 2)
unit = 'Lbs'
elif unit == pounds:
result = weight * 0.45
unit = 'Kg'
else:
print("You entered wrong unit!")... | true |
5e3ac49a65d7e562ab4ec1479ca66455775d9c5d | zeeshan-akram/Python-Code | /program 6 formatted strings.py | 423 | 4.28125 | 4 | first_name = input("Enter your first name: ")
last_name = input("Enter your second name: ")
print(f"Your full name is: {first_name} {last_name}")
conformation = input('do you have middle name? ').lower()
if conformation == 'yes':
middle_name = input("Enter middle name as well: ")
print(f'''ok!
Your full... | true |
f81f735b36a8bde8a9686ccb76440bd072882a00 | obabawale/pytricks | /isogram.py | 440 | 4.21875 | 4 | # Check if the word is an isogram
import collections
def main(word):
"""Check if Word is an isoggram or not"""
word_count = collections.Counter(word)
for item in word_count.items():
if item[1] > 1:
print(f"{word} is not an isogram!")
break
else:
print(f"Yippee.... | true |
5938ccad9fef649a6daa799870c1587443e7e5c9 | AmaniEzz/SOLID-principles-Python | /Dependency Inversion/DIP_after.py | 828 | 4.25 | 4 | from abc import ABC, abstractmethod
# define a common interface any food should have and implement
class Food(ABC):
@abstractmethod
def bake(self):
pass
@abstractmethod
def eat(self):
pass
class Bread(Food):
def bake(self):
print("Bread was baked")
def eat(sel... | true |
5928e226eaf690d6b0dd1794069944e4d9d27e61 | shakibul07/com411 | /basics/output/if_elif_else.py | 697 | 4.46875 | 4 | print(" Which direction should I paint (up, down, left or right )")
#asking user for input
directions = input()
#starting if statement
#this is for upward direction
if directions == "up" :
print(" I am printing in the upward direction! ")
#this is for downward direction
elif directions == "down":
print(" I a... | true |
4f109e093c783a514ec4fffc7c6a886f88415396 | shakibul07/com411 | /basics/practice/c4.py | 211 | 4.125 | 4 | insum = int(input("How many numbers should i sum up"))
num = 0
sum = 0
while num < insum :
num += 1
print(f"please enter number {num} of {insum} ..")
numb = int(input())
sum += numb
print(sum) | true |
c903c1570a68b8e0a363f777ed71aaa32af854ba | shakibul07/com411 | /basics/output/nesting.py | 540 | 4.125 | 4 | #Ask user for sequence and marker
print("Please enter a sequence: ")
sequence = input()
print("Please enter the charecter for the marker: ")
marker = input()
#find markers
marker1_position = -1
marker2_position = -1
for position in range (0, len(sequence), 1):
letter = sequence[position]
if letter == marker... | true |
4cd1af78903cac839291ca5865ff94b126fb2922 | CodeSlayer10/school | /school1.py | 455 | 4.21875 | 4 | Ticket_Price = 42
Glasses3D_Price = 5
def Total_Price_Calculator(Ticket_Amount, Glasses3D_Amount):
return Ticket_Price*Ticket_Amount+Glasses3D_Price*Glasses3D_Amount
ticket_requested_amount = int(input("Enter Number of tickets: "))
glasses3d_requested_amount = int(input("Enter Number of 3D glasses: "))
total_cos... | true |
aa53cc27d87b21d9c7f5db722992a03f2f2d5a8d | heyitshelina/HELINA-GWC-2018 | /survey.py | 2,121 | 4.1875 | 4 | import json
#friends = {
# "Tasfia": 16,
#"Mo": 16,
#}
#friendAge = friends["Mo"]
#print (friendAge)
#user = {}
#user['Diana'] = 30
#print (user)
#user['Amy'] = 27
#print (user)
# TODO Part I: Add your survey questions to this empty list.
survey = [
"What is your favorite color?",
"H... | true |
d4d71f74caf95bc7f5956453a5180b3863951f50 | bforman/Generating-map-using-BaseMap-and-querying-the-MSD-via-hdf5_getters | /buildWorldMap.py | 1,019 | 4.1875 | 4 | """
Program: buildWorldMap.py
Author: Benjamin Forman
Description: this script utilizes matplotlib and the basemap package it provides to users. The script produces a map of the world and displays different ways of customizing the map and adding value and detail where desired. pyplot, another package of matplotlib, i... | true |
e400321d0dadaf48afe994f2e18bcb8db65f2642 | Aluriak/24hducode2016 | /src/visualisation/distance.py | 862 | 4.125 | 4 | """
Computes distances between two points from their Gmap coordinates
"""
from math import radians, cos, sin, asin, sqrt
def distance_gps(coordinates_A, coordinates_B):
"""
Input: two tuples of coordinates (longitude, latitude)
Output: distance between the two points
"""
lon1 = coordinates_A[0]
... | true |
b0541487fcfa71828e341258046b1062e858f92e | Angkirat/MachineLearningTutorial | /PythonCode/TensorflowCode/TFKeras_Mnist.py | 2,222 | 4.4375 | 4 | #!/Library/anaconda3/envs/MachineLearning/bin/python
"""
Copyright 2019 The TensorFlow Authors.
This is a modified piece of code copied from the Tensorflow learning link: https://www.tensorflow.org/overview/
This is a documented Hello world program for Tensorflow beginners.
It uses the MNIST data to show how to build... | true |
a99ed52d627dde9157cf08ec2bac2090343ab10e | sydul-fahim-pantha/python-practice | /tutorials-point/function_advance.py | 1,219 | 4.34375 | 4 | #!/usr/bin/python3
print()
print("Function can have four types of argument")
print()
print("Required argument: def func1(arg1)")
print("Invocation: func1(\'value\')")
def func1(arg1):
print("arg1: ", arg1)
return
func1("arg")
print()
print("Keyword argument: def func(id, age, name)")
print("Invocatio... | true |
f9455199dffae5eb9b11b39cfdbb7611e919c49e | all3n/buildfly | /buildfly/utils/string_utils.py | 1,929 | 4.84375 | 5 | import re
def underscore(word):
"""
Make an underscored, lowercase form from the expression in the string.
Example::
>>> underscore("DeviceType")
"device_type"
As a rule of thumb you can think of :func:`underscore` as the inverse of
:func:`camelize`, though there are cases where... | true |
df51e06526f6f724eee94c3a5d2b9ff78af25777 | ValerieMauduit/46-simple-python-exercises | /srcs/ex07.py | 330 | 4.25 | 4 | '''Define a function reverse() that computes the reversal of a string.
For example, reverse("I am testing") should return the string "gnitset ma I".'''
def reverse(txt):
'''
This function computes the reversal of a string
Parameters
----------
txt (string)
Returns
----------
The reversed string
'''
return ... | true |
a16177ca7016c260f6b0c2d70a3d8a886a042d5b | ValerieMauduit/46-simple-python-exercises | /srcs/ex10.py | 652 | 4.21875 | 4 | '''Define a function overlapping() that takes two lists and returns True if they
have at least one member in common, False otherwise. You may use your
is_member() function, or the in operator, but for the sake of the exercise,
you should (also) write it using two nested for-loops.'''
def overlapping(lst1, lst2):
'... | true |
62397ed2e4784fd4a6d0b78c6eb4aa3cac6c58bb | Vantime03/Grading-App | /grading_app.py | 1,958 | 4.5 | 4 | '''
Lab 3: Grading
Let's convert a number grade to a letter grade, using if and elif statements and comparisons.
Concepts Covered
input, print
type conversion (str to int)
comparisons (< <= > >=)
if, elif, else
Instructions
Have the user enter a number representing the grade (0-100)
Convert the number grade to a lette... | true |
be1a74e365c5106c244bbeb226dbc44f32d3f9bd | akmaniatis/Number_Guessing | /main.py | 1,383 | 4.28125 | 4 | # Importing Python libraries
import random
# End Imports
# Global Variables
# Computer generating a random number between 0 and 10
ComputerNumber = random.randint(0,10)
# Defining the largest number of allowable guesses
GuessMax = 3
Win = False
Play = True
print("Welcome to the Number Guessing Game!\n\n")
print("Yo... | true |
c3f0ec0d2ff98427838cec8afb1b07346cddd50f | DivijeshVarma/PythonBasics | /variables&datatypes.py | 909 | 4.34375 | 4 | # variable
message = "hello divi!"
print(message)
# seperator
print("-------------------")
# strings
name = 'divijesh varma'
print(name.title())
print(name.upper())
print(name.lower())
# seperator
print("-------------------")
# variables in strings, f-strings, f is format
# To insert a variable’s value into a s... | true |
5f81e1259ed095fc3fd2e939395ccaa0026ad52f | mryingster/ProjectEuler | /problem_001.py | 318 | 4.15625 | 4 | #!/usr/bin/env python
print("Project Euler - Problem 1")
print("Find the sum of all the multiples of 3 or 5 below 1000.\n")
number = 1
sum = 0
while number < 1000:
if number % 3 == 0:
sum += number
else:
if number % 5 == 0:
sum += number
number += 1
print("Sum: "+str(sum))
| true |
322a637f22f36c79da148cf8920045868c79a896 | vpagano10/Intro-Python-I | /src/13_file_io.py | 1,332 | 4.46875 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close... | true |
ebc19b89794caea4a6de92d71096596e43c4e003 | Git-Good-Milo/Slither_in_to_python_chapter_3 | /exercises.py | 1,879 | 4.375 | 4 | # Question 1
# Assume a population of rabbits doubles every 3 months. How many rabbits after 2 years? Initial population is 11
# First, set up all the required variables
initial_number_of_rabbits = 11
pop_growth_rate_months = 3
time_frame_years = 2
# change time frame from years to months
time_frame_months = time_fra... | true |
66bf61a9c743fb89c506050802c064478ab8e8e1 | SchrodengerY/Python-Programming | /Chapter5/C5.py | 2,371 | 4.53125 | 5 | # 文件和异常
# Read It
# 读取文件
print("Open and close the file.")
text_file = open("read_it.txt","r")
text_file.close()
print("\nReading characters from the file.")
text_file = open("read_it.txt","r")
print(text_file.read(1))
print(text_file.read(5))
text_file.close()
print("\nReading the entire file at once.")
text_file ... | true |
4ffc62c5492842ff6ddbebc1cf58d3718c913a78 | pboonupala/day-3-roller-coaster | /main.py | 292 | 4.1875 | 4 | #Write your code below this line 👇
print("Welcome to the rollercoaster program")
height = int(input("Please input your height"))
age = int(input("Please input your age"))
bill = 0
if height >= 120:
if age < 12:
bill += 5
else:
print("Sorry, you have to grow taller to ride this.") | true |
d546fe562e62d92bd2cde6b14d2926de629cdbae | sdixit03/calc | /calc.py | 1,026 | 4.125 | 4 | print("1. Addition");
print("2. Subtraction");
print("3. Multiplication");
print("4. Division");
try:
print("Enter first value:")
num1 = float(input())
val = float(num1)
except ValueError:
print("No.. input string is not an Integer. It's a string")
exit();
try:
print("Enter second value:")
num... | true |
1a81ee7f39faa01e1ebd045190ca06ad49ab75c6 | jon-jacky/Piety | /samples/writer.py | 2,798 | 4.40625 | 4 | """
writer.py - write to files to demonstrate interleaving concurrency.
Defines class Writer, with a method that writes a single line to the
end of a file. By default, this line contains the file name and a
timestamp. A different function to generate the line in some other
form can be passed as an optional argument ... | true |
529b44a9066658309065e59bdb29a40722286007 | deep-adeshraa/array-kit | /move_nagatives_2.py | 608 | 4.21875 | 4 | # ? https://www.geeksforgeeks.org/rearrange-positive-and-negative-numbers/
# Rearrange positive and negative numbers with constant extra space
# Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additiona... | true |
06a7f11a5cec991f34e88710ea4de3fc172e93dd | volodymyr-1/ARZP | /birsdays.py | 471 | 4.25 | 4 | birthdays = {'Bob': '18 nov', 'Sveta': '8 oct', 'Kristina': '13 june'}
while True:
print('Enter a name: (blanc to quit)')
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name], ' is the birthday of ', name)
else:
print('I don\'t have information of... | true |
96df71545f7733d80686dc898626f805faa81235 | miichy/python_repo | /base_one/str_op.py | 731 | 4.28125 | 4 | #!/usr/bin/python
#string operate
### wrong
#v = '2' - '1'
#print v
#a = 'eggs'/'easy'
#print a
#b = 'third' * 'a charm'
#print b
###
f = 'hello'
b = 'world'
print f + b
var1 = 'hello world'
var2 = 'python programming'
print "var1[0]: ",var1[0]
print "var2[1:5]: ",var2[1:5]
print "updated string :- ",var1[:6] + "p... | true |
3de7c4d3339e9e090a8286288918aadb3be893a6 | rakeshchauhan0007/lab2 | /condition.py/q_2.py | 369 | 4.28125 | 4 | """
if the temperature is greater then 30, its a hot day otherwise
if its less then 10: its a cold day;
otherwise its neither hot not cold
"""
temperature = int(input('temperature:'))
cold_day = 10 > temperature
hot_day = 30< temperature
if cold_day:
print(f' its a old day')
elif hot_day:
print(f'its a hot d... | true |
e414e5c826b30860960ddd9deeed033db24b971e | Gulks/Simple-Games | /check_phrases.py | 623 | 4.375 | 4 | import re
from time import sleep
def reverse(a):
"""Reverses the phrase.
Excludes all the symbols except for the letters and
makes them in lower case."""
a = re.sub("[^A-Za-z]", "", a)
a = a.lower()
return a[::-1]
def is_palindrome(a):
return a == reverse(a)
phr... | true |
827097e041057a830241b5bc8f6526f640930d35 | IngridFanfan/python_course | /function/recursive.py | 458 | 4.28125 | 4 | #Recursive function
#factorial
#fact(n) = n x fact(n-1)
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
#Take care to prevent stack overflow: Tail recursion
#Tail recursion is when a function calls itself when it returns, and the return statement cannot contain an expression.
def fact(n):
... | true |
c1199fbc50a4ffb1a9d31faa36347af554072927 | Mpanshuman/Oretes_test-19-02-21- | /Q6.py | 811 | 4.125 | 4 | import re
sentence = input('Enter The Sentence:')
output = ''
# condition to check any special character
special_character_check = re.compile('[@_!#$%^&*()<>?/\|}{~:.]')
# condition to check any small character
small_character_check = re.compile('[a-z]')
# condition to check any capital character
capital_character_c... | true |
ae9c551f98c10c057b788259916c9cfb361fe4e4 | alikomurcu/ali-burkan-projects | /search method.py | 951 | 4.25 | 4 |
# Here is the find the biggest value.
def Search_method (values, l, r):
# check whether len of array is bigger than 1.
if r >= l:
mid = l + r // 2
# Right values
if (values[mid] > values[mid+1]) and (values[mid] < values[mid-1]):
return binarySe... | true |
545694602e2aa66f044443e3755f98ddce0fed72 | Orchidocx/nato-alphabet | /main.py | 341 | 4.1875 | 4 | import pandas
data = pandas.read_csv("nato_phonetic_alphabet.csv")
nato_alphabet = {row.letter: row.code for (index, row) in data.iterrows()}
word = input("Enter a word: ").upper()
while word != "0":
result = [nato_alphabet[letter] for letter in word]
print(result)
word = input("Enter a new word (enter 0 t... | true |
4ca0463a00a03a4a0aab20e3b38ec0104c6f45e7 | molssi-seamm/seamm_util | /seamm_util/variable_names.py | 795 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""Utility routines to help with variable names for scripts"""
from keyword import iskeyword
import re
def is_valid(name):
"""Check if a variable name is valid and is not a keyword"""
return name.isidentifier() and not iskeyword(name)
def clean(raw_name):
"""Fix up an input str... | true |
cb668bb28e77b20e4dde6a7bd3389d32e9d31b82 | cholleran/python_exercises | /collatzloop.py | 579 | 4.4375 | 4 | # https://en.wikipedia.org/wiki/Collatz_conjecture
# Code based on lecture by Dr Ian McLoughlin
# Week 3 exercise - program which applies Collatz to an integer chosen by the user.
# Student: Cormac Holleran, GMIT - Module: 52167
#input is taken from the user and stored as n.
n = int(input('Please enter and integer:'))... | true |
e66275f1f3bb1b6ad3c6f7a1fa2c6fe95b6b2f9d | ranjennaidu21/python_basic_project | /control_structures/list_functions.py | 426 | 4.25 | 4 | fruits = ["Mango", "Banana", "Orange"]
print(fruits)
#insert element into list (at the end of list automatically)
fruits.append("Apple")
print(fruits)
#insert element into list in a particular position
fruits.insert(2,"PineApple")
print(fruits)
#find the length of the list
print(len(fruits))
#find index/position of... | true |
4428af84147aa3ebc43d27c72861e9d2b8aac020 | PallabDotCom/Python-Basics | /TextReadWrite.py | 1,072 | 4.25 | 4 | #file= open('test.txt', 'r')
# Optimized way to open file is below line. You don't have to close the file at the end.
# with open('test.txt') as file:
#read all lines of file
'''
print(file.read())
'''
#read n number of characters from file
'''
print(file.read(7))
'''
#read one single line at a time
'''
... | true |
526d4bcf20f5022240990c881429df70adc10d75 | manjulamishra/DS-Unit-3-Sprint-2-SQL-and-Databases | /demo_data.py | 954 | 4.59375 | 5 | # import sqlite3 and create a file 'demo_data.sqlite3'
# open a connection
import sqlite3
conn = sqlite3.connect('demo_data.sqlite3')
# create a cursor
curs = conn.cursor()
# create a table
curs.execute('''CREATE TABLE demo
(s text, x INT, y INT)''')
# insert the data into the table
curs.execute("INSERT INTO demo V... | true |
ffae658138f117034f082aca4b4b5e7643b21553 | segerphilip/SoftwareDesign | /inclass/day11/Point1.py | 1,943 | 4.375 | 4 | """
Code example from Think Python, by Allen B. Downey.
Available from http://thinkpython.com
Copyright 2012 Allen B. Downey.
Distributed under the GNU General Public License at gnu.org/licenses/gpl.html.
"""
import math
class Point(object):
"""Represents a point in 2-D space."""
def print_point(p):
"""Pr... | true |
0c0970e05f15cc2eb667389d82206736a5e490c4 | rayruicai/coding-interview | /hash-tables/find-the-length-of-a-longest-contained-interval.py | 1,305 | 4.3125 | 4 | # 12.9 in Elements of Programming Interviews in Python (Sep 15, 2016)
# Write a program which takes as input a set of integers represented by an
# array, and returns the size of a largest subset of integers in the array
# having the property that if two integers are in the subset, then so are all
# integers between the... | true |
b4c58230c0d1a19b7533812fdd30576f7f6823a6 | rayruicai/coding-interview | /stacks-and-queues/normalize-pathnames.py | 1,899 | 4.15625 | 4 | # 8.4 in Elements of Programming Interviews in Python (Sep 15, 2016)
# write a program which takes a pathname, and returns the shortest
# equivalent pathname.
import unittest
# time complexity O(len(string))
# space complexity O(len(string))
class Stack():
def __init__(self):
self.items = []
def isE... | true |
dddf31b5e24c4c3d8db6850a8436cac4e539d769 | SandraEtoile/test-python | /tasks/fundamentals/triangle_are.py | 1,100 | 4.3125 | 4 | import math
def basement_height_area(height, base):
return (height * base) / 2
def two_sides_angle(a, b, angleC):
return (a * b * math.sin(math.radians(angleC))) / 2
print("Welcome to the triangle area calculation tool")
area_calc_user_choice = 0
while area_calc_user_choice < 3:
print("Menu")
pr... | true |
e090b2b6218e561366fcea6a4afa0a2dd1532a20 | error404compiled/py-mastr | /Basics/dict_tuple.py | 1,298 | 4.1875 | 4 | def add_and_multiple(n1,n2):
'''
Exercise 2
:param n1: Number 1
:param n2: Number 2
:return: a tuple containing sum and multiplication of two input numbers
'''
sum = n1 + n2
mult = n1 * n2
return sum, mult
def age_dictionary():
'''
Exercise 1
This program asks for person... | true |
b3891ce670d357b7797a9caf3dd9f905fcc95eb3 | error404compiled/py-mastr | /Basics/Hindi/6_if/6_if.py | 1,067 | 4.34375 | 4 | # while mentioning topics say that timeline is in video description
# so you don't need to watch entire video
n=input("Enter a number")
n=int(n)
if n%2==0:
print("Number is even")
else:
print("Number is odd")
# Show the execution by debugging
# If is called control statement as it controls the flow of code ... | true |
f80608adf67013f2a58cc9472bcd7f97fcef888b | MrChoclate/projecteuler | /python/4.py | 885 | 4.1875 | 4 | """
Largest palindrome product
Problem 4
A palindromic number reads the same both ways. The largest palindrome made from
the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import itertools
def is_palindrome(number):
return str(numbe... | true |
cc180d3c75a1957d96c179ef3d45ef29a2ce7018 | runxunteh/coding-challenges | /CodeChef/Beginner/ICPC16B.py | 1,514 | 4.21875 | 4 | """
Author: Teh Run Xun
Date: 22 February 2019
Problem from: https://www.codechef.com/problems/ICPC16B
.......................
An array a is called beautiful if for every pair of numbers ai, aj, (i ≠ j),
there exists an ak such that ak = ai * aj. k can be equal to i or j too.
This program is to find out whether the giv... | true |
35de3bfc25350f4b604ee67b8e4c9b9de71a0c9b | aonomike/data-structures | /daily_interview_pro/sort_num.py | 453 | 4.1875 | 4 | # Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time.
#Input: [3, 3, 2, 1, 3, 2, 1]
#Output: [1, 1, 2, 2, 3, 3, 3]
def sort_nums(nums):
lookup = {}
for n in nums:
if n in lookup:
print(n)
lookup[n] = lookup[n].append(n)
else:
... | true |
c0fbb241822303cbfa13bfbbeaa0b2cc6d6631ea | brisvv/New-project- | /Martin/BookORelly/built_in_functions.py | 1,802 | 4.28125 | 4 | #https://medium.com/@happymishra66/lambda-map-and-filter-in-python-4935f248593
#Filter (used with lists)
#unction_object is called for each element of the iterable and filter returns only those element
#for which the function_object returns true.
#Like map function, filter function also returns a list of element.
#Unli... | true |
02f09f22ad38f70fe6233f623ab44877a720b9ea | mattycoles/learning_python | /cup_and_ball.py | 1,770 | 4.15625 | 4 | ## Cup and Ball Game
from random import randint
gameon = True
display = ["[x]","[x]","[x]"]
guess = 0
cupandball = 0
score = 0
print("Welcome to the cup guessing game.")
print("Simply guess which cup the ball is in! [x],[x],[x]")
def reset_cups():
display = ["[x]","[x]","[x]"]
return display
... | true |
07fb716d2df31ac5ba9fd1a319cd11533c78ce88 | sourabh-karmarkar/Practicals | /SourabhPractice/Python Training/Day-10/Exercise-3/question1.py | 390 | 4.5625 | 5 | """
1) Write a program which uses a nested for loop to populate a three-dimensional list representing a calendar:
the top-level list should contain a sub-list for each month, and each month should contain four weeks. Each
week should be an empty list.
"""
calendar=[]
for x in range(12):
month=[]
for y in ... | true |
0ade62a85e2dc8f90e174797e58e616e11c38b21 | sourabh-karmarkar/Practicals | /SourabhPractice/Python Training/Day-5/Exercise-3/question2.py | 1,656 | 4.34375 | 4 | """
Write a python program to assign grade to students at the end of the year. The program must do the following:
a. Ask for a student number.
b. Ask for the student's tutorial mark.
c. Ask for the student'a test mark
d. Calculate whether the student's average is high enough for the student to be permitted to writ... | true |
e1a935993ed9bbd8153bda16832f558a0eb8360e | sourabh-karmarkar/Practicals | /SourabhPractice/Python Training/Day-10/Exercise-1/question2.py | 827 | 4.15625 | 4 | """
Write a program which keeps prompting the user to guess a word. The user is allowed upto 10 guesses -
write your code in such a way that the secret word and the number of allowed guesses are easy to change.
Print messages to give the user feedback.
"""
guess_count = 0
secret_word = "ABC"
allowed_guesses = 20
whi... | true |
1707b6ac212ca2ef7a013b9ce6be1f6cada95fef | sourabh-karmarkar/Practicals | /SourabhPractice/Python Training/Day-11/Exercise-3/question2.py | 544 | 4.375 | 4 | """
Some programs ask to input a variable number of data entries, and finally to enter a
specific character or string (called a sentinel) which signifies that there are no more
entries. For example, you could be asked to enter your PIN followed by a hash (#). The hash
is the sentinel which indicates tha... | true |
77a0c8f6718c627e1928da56cc5f31e4e2b8af74 | sourabh-karmarkar/Practicals | /SourabhPractice/Python Training/Day-12/Exercise-1/question1.py | 491 | 4.1875 | 4 | """
1) Find all the syntax errors in the code snippet, and explain why they are errors.
A) - Missing def keyword before myfunction.
- else block without if.
- if statement missing the ' : ' symbol.
- spelling of else is typed wrongly.
- last statement of the program not indented properly.
"""
myf... | true |
a3945b8cb380295d27e3e709ea465638945f7163 | keerthanasiva9/INFO6205_PSA_Spring_2021 | /rotate_image_assign_7.py | 1,273 | 4.25 | 4 | #Rotate Image
#You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
#You have to rotate the image in-place, which means you have to modify the input 2D matrix directly.
#DO NOT allocate another 2D matrix and do the rotation.
#Input: matrix = [[1,2,3],[4,5,6],[7,8,9... | true |
6bdcd2ff8fa1931f67f6435fe2d45907ad13dc3d | Pramod-Mathai/Puzzles | /SumOfPrimes.py | 1,839 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Objective: Test distribution of primes
Created on Tue Nov 17 09:30:49 2015
@author: Pramod Mathai
"""
from IPython import get_ipython
get_ipython().magic('reset -sf') # clear workspace
import math, numpy as np
def sum_of_primes_Sieve(Number):
# Sieve for computing list of ... | true |
1758409ac95768d9edc653e03a1041e1fa0359bb | wy193777/Data-Structure-and-Algorithm-with-Python-and-C-- | /Markov.py | 1,415 | 4.125 | 4 | import random
class Markov(object):
"""A simple trigram Markov model. The current state is a sequence of the
two words seen most recently. Initially, the state is (None, None),
since no words have been seen. Scanning the sentence "The man ate the
pasta" would casue the model to go through... | true |
49240aaf371201a638acf980636c9a610b6d7e14 | rkoehler/Class-Material | /Basic Code (Unorganized)/beginning.py | 234 | 4.15625 | 4 | # Robert Koehler
# Basic program showing input and output
#robkoehler10@gmail.com
print("What's your name")
name = input()
print("Hello " + name)
print("What is the color of your shirt?")
x = input()
print("Hello " +name +", nice "+x+" colored shirt")
| true |
b89789b77bd9272327847e16e7ca92bed7765c52 | rkoehler/Class-Material | /Basic Code (Unorganized)/RemoveChar.py | 335 | 4.28125 | 4 | #overall program takes a charater from one string and places it into a new one.
#assign values to inital string
#take specified value and place into new string
#keep prompting user until first list is depleted
def removeChar(s):
removeList = list(s)
l = len(s)
for t in range(l):
print(remov... | true |
20d1482c0d8b8cb83b817c382ff6417dd108c2ac | rkoehler/Class-Material | /Basic Code (Unorganized)/patientlistapp.py | 1,110 | 4.3125 | 4 | #hospital list
#patient position = Doctor position
#ask user for patient name
#tell program to figure out position of patient name
#tell program to figure out position of doctor name
#tell program to match postion of names
listDoctors = ["Mark", "Steve", "Wayne", "Thomas"]
patients = [["Todd", "Dan"]
,... | true |
1f91d6a306a2cd27a1e93c54097191b642ea1a0b | Fareen14/Python-Projects | /Reverse a String.py | 258 | 4.4375 | 4 | def reverse(string1):
string1 = "".join(reversed(string1))
return string1
s = "The weather is enjoyable today!"
print("The original string is:\n ", end=" ")
print(s)
print("\nThe reversed string(using reversed function) is:\n")
print(reverse(s))
| true |
1dc7167eb52b4dcd1f7232a9fa17db12760d6f73 | Joniel00/StartingOutWPython-Chapter6 | /odd_even_counter.py | 1,210 | 4.1875 | 4 | # June 22nd, 2010
# CS 110
# Amanda L. Moen
# 7. Odd/Even Counter
# In this chapter you saw an example of how to write an algorithm
# that determines whether a number is even or odd. Write a program
# that generates 100 random numbers, and keeps a count of how many
# of those random numbers are even and how many are o... | true |
04d62a0806ee1a90b4bce24211077be8a1019e79 | jblovett/leetcode_practice | /josh_exercises/codebyte/intersection.py | 782 | 4.21875 | 4 | """Find the intersection of two comma seperated strings of numbers. https://coderbyte.com/editor/Find%20Intersection:Python3
The two strings are given in an array.
Concepts: string manipulation. The split() function in str objects removes whitespace around a string by default, and removes a given
character at the begin... | true |
ac3b2cf078214b99119c72482b54e785f849b2b2 | salman6100/python | /exp.py | 553 | 4.125 | 4 | questions ={}
# set ice skating is active.
iceskating_active = True
while iceskating_active:
#prompt user for name
name = input("\nwhat is your name : ")
question = input(" where would you like to ice skate")
#store the question in dictionary
questions[name] = question
repeat = input(" would yo... | true |
ce627bcfa4b4075a1d9414c001e01fd3f5273e89 | salman6100/python | /mountain.py | 530 | 4.1875 | 4 | iceskating = {}
skating_active = True
while skating_active:
# Asker user their name
name = input(" What is your name :")
iceskatings = input ( " where would you like to iceskate : ")
iceskating[name] = iceskatings
repeat = input(" would like to go swimming instead ? ( yes /no )")
if repeat == 'no' :... | true |
6835d9822cb257a92f2dd49e4c318a068b0bfacf | ky822/assignment10 | /jz1584/gradeTesting.py | 2,777 | 4.15625 | 4 | import pandas as pd
from clean_save import cleanGrade
def quantify(grade_list):
"""function code the letter:A,B,C in the grade_list to corresponding
numerical number 3,2,1, returns numerical list
"""
numList=[]
#create an empty list that will include numerical grades from grade_list
... | true |
2eddd8ffc589ef1d0332e0db068d4fadfe0bded0 | ky822/assignment10 | /mj1547/test_grades.py | 1,189 | 4.3125 | 4 | def test_grades(grade_list):
'''
It is a test_grades function which is based on the GRADE list
'''
#grade_list=df.GRADE
#set intital value
value=0
'''
since the date was decreasing compare I Will campare the list from last to firsr
and when the grade from A to B, the grade will be -1... | true |
6ee2a06f7281cca0aa65e89ed459a5ef95cacb39 | clturner/webstack_basics | /0x01-python_basics/5-args.py | 474 | 4.375 | 4 | #!/usr/bin/python3
"""
Prints the number of and the list of its arguments.
"""
import sys
def main():
if len(sys.argv) is 1:
print("0 arguments.")
else:
if len(sys.argv) is 2:
print(len(sys.argv) - 1, "argument:")
else:
print(len(sys.argv) - 1, "arguments:")
... | true |
f5d4d8bff328ecb617ecbb9db28967a199c353de | clturner/webstack_basics | /0x01-python_basics/1-print_comb2.py | 268 | 4.125 | 4 | #!/usr/bin/python3
"""
Prints 0 to 100 in two digits
"""
for num in range(0, 10):
for numm in range(0, 10):
if num is not 9 or numm is not 9:
print("{}{}, ".format(num, numm), end="")
else:
print("{}{}".format(num, numm))
| true |
ae12216c1b0f2a4b22d2d0a3a146fa7cae043fc9 | FarzonaP/Techgrounds | /opdr4-ex2.py | 330 | 4.28125 | 4 | #Print the value of i in the for loop. You did not manually assign a value to i. Figure out how its value is determined.
#Add a variable x with value 5 at the top of your script.
#Using the for loop, print the value of x multiplied by the value of i, for up to 50 iterations
x = 5
for i in range(50):
print(... | true |
fbbfd26ff5d1ec72f03a64bde3a93cae6bcd1855 | lmx0412/LeetCodeInPython3 | /Python/valid_palindrome.py | 2,394 | 4.40625 | 4 | # pylint: disable-all
import unittest
from typing import List
"""
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, retur... | true |
e7915e32e080001671232114f7b684edb7954666 | lmx0412/LeetCodeInPython3 | /Python/Merge_Sorted_Array.py | 1,366 | 4.125 | 4 | # pylint: disable-all
import unittest
"""
Description:
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 greater or equa... | true |
dae9cfb3ad9ec7652809f1d11e4f5511c5f35502 | Pramit356/python-codes | /linearSearch.py | 434 | 4.125 | 4 | def search(list, n, val):
i=0
index=-1
for i in range(n):
if list[i]==val:
index=i
return index
n = int(input("Enter the number of elements: "))
list =[]
for i in range(n):
x = int(input("Enter a value: "))
list.append(x)
val = int(input("Enter the value to search: "))
i... | true |
6e1fafef9bcd500921ba56a8649c6aafd82a2667 | Nihilnia/KeepGoing | /sys module.py | 1,070 | 4.28125 | 4 | # sys Module
# sys module is simply system module of python.
#We can manage our python software with sys module.
import sys
# what is in sys
for f in dir(sys):
print(f)
# exit()
userInput1 = input("What's your name: ")
userInput2 = input("What's your surname: ")
print("Welcome", userInput1... | true |
375f626623c03b98d3f5a15ca330f58442d27542 | fangchingsu/stanCode_SC101_Turing | /stanCode_Projects/hangman_game/rocket.py | 1,832 | 4.125 | 4 | """
File: rocket.py
Name: Fangching Su
-----------------------
This program should implement a console program
that draws ASCII art - a rocket.
The size of rocket is determined by a constant
defined as SIZE at top of the file.
Output format should match what is shown in the sample
run in the Assignment 2 Hando... | true |
82c3c87958a239f830c629863fe75fe920694278 | fangchingsu/stanCode_SC101_Turing | /stanCode_Projects/boggle_game_solver/anagram.py | 2,420 | 4.1875 | 4 | """
File: anagram.py
Name:
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word liste... | true |
8c31b39e91c62ee7f6345f98a3975eb0d032928e | FreddyBarcenas123/Python-lesson-2- | /Excercise5.py | 325 | 4.4375 | 4 | #FreddyB-Exercise 5: Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
print("What is the 100 Fahrenheit in Celsius?")
Celsius = "37.7778 Celsius"
print("Convert 100 to Fahrenheit!")
Fahrenheit = "212 Fahrenheit"
... | true |
f536e4e0a337da3b5a50bf41a8a3b40552701158 | lwaddle/udacity-adventure-game | /dice.py | 2,019 | 4.28125 | 4 | from random import randint
class Dice:
def __init__(self):
pass
def roll_two_dice(self, graphical=True):
"""
Returns a tuple of two integers that simulates a random
dice roll. The return values are between 1 and 6. The optional
graphical parameter displays an ASCII art... | true |
c5ce2c6324be82cf0299a6c74406745f9f63e096 | MakeMeSenpai/Weekly_puzzle | /hole_new_board_game/main.py | 1,400 | 4.3125 | 4 | # 2 x 12 = 24
# 3 x 8 = 24
# so this is possible
def createShape(columns, rows):
board = []
# so lets first create printed arrays for comparison
for i in range(columns):
board.append([])
for j in range(rows):
board[i].append(j+1)
return board
hole = createShape(2, 12)
prin... | true |
8cf47d59134f0e444410f6c166d35a0af5f2a26d | MakeMeSenpai/Weekly_puzzle | /bulbs_and_switches_problem/main.py | 2,351 | 4.15625 | 4 | from random import choice
"""I create a random configuration so that when comming up with a
solution, any switch can match any light bulb during testing. This
problem was hard to translate to code, but why I think it's important
as finding out how to solve real world/challenging problems threw
programming can help th... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.