blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0a345474c0bc7e96e49501cf52e4f5f42f156fa1 | vanillaike/python-fizzbuzz | /fizzbuzz/calculator.py | 358 | 4.15625 | 4 | '''
This module performs the fizzbuzz calculation for a given number
'''
def calculate_fizzbuzz(number):
'''
Given a number return the fizzbuzz value
'''
value = ''
if number % 3 == 0:
value += 'fizz'
if number % 5 == 0:
value += 'buzz'
if number == 0 or value == '':
... | true |
a634d5115d38cded8cd44161584cba5da09afea1 | satsumas/Euler | /prob1.py | 496 | 4.46875 | 4 | #!/usr/bin/python
"""
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.
"""
def mult_sum(n):
for a in range(n):
if a % 3 == 0 or a % 5 == 0:
multiples.appen... | true |
f11319854a0e56d9b0d4ffd9db5373859c4e7ecb | hello7s/IE709 | /Decorators.py | 2,058 | 4.1875 | 4 | @decorator
def functions(arg):
return "value"
def function(arg):
return "value"
function = decorator(function) # this passes the function to the decorator, and reassigns it to the functions
def repeater(old_function):
def new_function(*args, **kwds): # See learnpython.org/page/Multiple%20Function... | true |
f6ff640aec343ca10723dcda4ff37b914087d27e | dlz215/hello_sqlite_python | /sqlite/db_context_manager_error_handling.py | 1,454 | 4.15625 | 4 | """ sqlite3 context manager and try-except error handling """
import sqlite3
database = 'phone_db.sqlite'
def create_table():
try:
with sqlite3.connect(database) as conn:
conn.execute('create table phones (brand text, version int)')
except sqlite3.Error as e:
print(f'error creatin... | true |
e48faa8f890e34de1462546f50729912bb1a9cc0 | dlz215/hello_sqlite_python | /sqlite/insert_with_param.py | 791 | 4.34375 | 4 | import sqlite3
conn = sqlite3.connect('my_first_db.db') # Creates or opens database file
# Create a table if not exists...
conn.execute('create table if not exists phones (brand text, version int)')
# Ask user for information for a new phone
brand = input('Enter brand of phone: ')
version = int(input('Enter version... | true |
bcab1c739b480880f508e207ca50983f08c74b6d | dlz215/hello_sqlite_python | /sqlite/hello_db.py | 691 | 4.40625 | 4 | import sqlite3
# Creates or opens connection to db file
conn = sqlite3.connect('first_db.sqlite')
# Create a table
conn.execute('create table if not exists phones (brand text, version integer)')
# Add some data
conn.execute('insert into phones values ("Android", 5)')
conn.execute('insert into phones values ("iPhone"... | true |
a582580bf78ae9efebdc7f4c86e73938e8559680 | TaurusCanis/ace_it | /ace_it_test_prep/static/scripts/test_question_scripts/math_questions/Test_1/math_2/math_T1_S2_Q9.py | 1,909 | 4.21875 | 4 | import random
trap_mass = random.randint(125,175)
mouse_mass = random.randint(3,6)
answer = trap_mass - (mouse_mass * 28) - 1
question = f"<p>The mass required to set off a mouse trap is {trap_mass} grams. Of the following, what is the largest mass of cheese, in grams, that a {mouse_mass}-ounce mouse could carry and... | true |
0b13510b0931f0394fb0d33d71d723586000ffa5 | Tang8560/Geeks | /Algorithms/1.Searching and Sorting/01.Linear_Search/Linear_Search.py | 1,563 | 4.3125 | 4 | # Linear Search
# Difficulty Level : Basic
# Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
"""
Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6
Input : ar... | true |
0d195d9d4ca4abadd5b2f8439cc068c8f4e78693 | Zaneta6/Module_04 | /Calculator.py | 1,002 | 4.25 | 4 | # Calculation() function provides a simple tool for basic calculation.
# Operator allows to choose a requested operation - additing, subtracting, multiplying and dividing - based on selected index (1-4).
# The "a" and "b" parameters indicate the subjects of the operation (integers).
import sys
import logging
logging.... | true |
0fe189615a931bd51482951a95364926b28e5c0c | apapadoi/Numerical-Analysis-Projects | /Second Project/Exercise6/trapezoid.py | 1,626 | 4.25 | 4 | def trapezoid_integrate(f, a, b, N, points):
"""
Computes the integral value from a to b for function f using Trapezoid method.
Parameters
----------
f : callable
The integrating function
a,b : float
The min and max value of the integrating interval
... | true |
af59a08e7396e851052c2a8dcaf31d7d6140b463 | ParthShirolawala/PythonAssignments | /Assignment2/Question-5.py | 274 | 4.25 | 4 | #multiplying everything by 3 and output the result
import copy
numbers = [1,2,4,6,7,8]
def multiplyNumbers():
number = copy.deepcopy(numbers)
newnumber = []
for i in number:
newnumber.append(i*5)
print newnumber
print numbers
multiplyNumbers() | true |
4b88b2949f0f8f734de81d4fcdbb9b02672623c5 | xiaonanln/myleetcode-python | /src/380. Insert Delete GetRandom O(1).py | 1,165 | 4.21875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.index = {}
self.vals = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
... | true |
f646e518f6d81da0b4f32e60c78dd60f335fae71 | claudiadadamo/random | /phone_number.py | 1,653 | 4.40625 | 4 | #!/usr/bin/env python2.7
import random
from data_structures import queue
"""
Silly command line thing that will randomly generate phone numbers that the
user must confirm if correct or not. This implementation uses a queue to append
a random number and basically shift the numbers over by one. For example:
Origina... | true |
508c924c5fcbcb0963ecfae832b97f8a58853fde | adarrohn/codeeval | /tests/tests_easy/test_easy_oneeleven.py | 1,133 | 4.125 | 4 | import unittest
from easy.challenge_num_oneeleven import return_longest_word
class LongestWordTest(unittest.TestCase):
"""
Return the longest word in the line, if multiple return the first
"""
def setUp(self):
pass
def test_case_all_different(self):
"""
All words are of dif... | true |
808efddb964ada8296c4c344f11d32477de7a82e | benbendaisy/CommunicationCodes | /python_module/examples/411_Minimum_Unique_Word_Abbreviation.py | 2,619 | 4.65625 | 5 | import re
from collections import defaultdict
from typing import List
class Solution:
"""
A string can be abbreviated by replacing any number of non-adjacent substrings with their lengths. For example, a string such as "substitution" could be abbreviated as (but not limited to):
"s10n" ("s ubstit... | true |
ee46ae946c592b5718e7141fd43e9b53cbcf94ec | benbendaisy/CommunicationCodes | /python_module/examples/424_Longest_Repeating_Character_Replacement.py | 1,751 | 4.125 | 4 | class Solution:
"""
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after p... | true |
cfca2d38b44ddbe3a3dd21628e15ead6b3105c88 | benbendaisy/CommunicationCodes | /python_module/examples/413_Arithmetic_Slices.py | 1,800 | 4.1875 | 4 | from typing import List
class Solution:
"""
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
Given an inte... | true |
679df26783c30db12885101108dc85339dcb61d6 | benbendaisy/CommunicationCodes | /python_module/examples/1091_Shortest_Path_in_Binary_Matrix.py | 2,133 | 4.15625 | 4 | import collections
from typing import List
class Solution:
"""
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right c... | true |
7b8398dffd2a2ac986a8eb9f09f318ba08657414 | benbendaisy/CommunicationCodes | /python_module/examples/1239_Maximum Length_of_a_Concatenated _tring_with_Unique_Characters.py | 1,519 | 4.1875 | 4 | from typing import List
class Solution:
"""
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by de... | true |
cf08e3d07b4aeaf92e4470f32906e91c56506c4d | benbendaisy/CommunicationCodes | /python_module/examples/2390_Removing_Stars_From_a_String.py | 1,590 | 4.21875 | 4 | class Solution:
"""
You are given a string s, which contains stars *.
In one operation, you can:
Choose a star in s.
Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
... | true |
c12c818bb35748151dd939cb6f975981dda7a348 | benbendaisy/CommunicationCodes | /python_module/examples/1423_Maximum_Points_You_Can_Obtain_from_Cards.py | 2,257 | 4.59375 | 5 | from functools import lru_cache
from typing import List
class Solution:
"""
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of t... | true |
250f9690338895ac21907a38523cc8c7e2b8179d | benbendaisy/CommunicationCodes | /python_module/examples/475_Heaters.py | 2,637 | 4.3125 | 4 | import bisect
from typing import List
class Solution:
"""
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given t... | true |
aa410dcae529074f87749f5a8f6c313506d3d2e6 | benbendaisy/CommunicationCodes | /python_module/examples/491_Increasing_Subsequences.py | 1,263 | 4.1875 | 4 | from typing import List
class Solution:
"""
Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.
The given array may contain duplicates, and two equal integers should also be c... | true |
567876c5243f5f52f7e02363df445243354d4a64 | benbendaisy/CommunicationCodes | /python_module/examples/1768_Merge_Strings_Alternately.py | 1,194 | 4.40625 | 4 | class Solution:
"""
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
Example 1:
Input: word1 = ... | true |
ad61e5d8cab369e0380d12fac551e8654b671a95 | benbendaisy/CommunicationCodes | /python_module/examples/299_Bulls_and_Cows.py | 2,291 | 4.125 | 4 | from collections import defaultdict, Counter
class Solution:
"""
You are playing the Bulls and Cows game with your friend.
You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
The numbe... | true |
34e1c7dff02018790eecce9c15fdb490639d32fd | benbendaisy/CommunicationCodes | /python_module/examples/1372_Longest_ZigZag_Path_in_a_Binary_Tree.py | 2,152 | 4.5 | 4 | # Definition for a binary tree node.
from functools import lru_cache
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
You are given the root of a binary tree.
A ... | true |
12ed712982b2ea97b9c1317a4d894b84f0cf2508 | benbendaisy/CommunicationCodes | /python_module/examples/43_Multiply_Strings.py | 782 | 4.25 | 4 | class Solution:
"""
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
... | true |
fcf5e146bed08d8823483651f8efbbea438623ce | benbendaisy/CommunicationCodes | /python_module/examples/222_Count_Complete_Tree_Nodes.py | 1,389 | 4.15625 | 4 | # Definition for a binary tree node.
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Given the root of a complete binary tree, return the number of the nodes in ... | true |
54abc6283cbf41b32ee1debe709699b3c6c14ca3 | benbendaisy/CommunicationCodes | /python_module/examples/2244_Minimum_Rounds_to_Complete_All_Tasks.py | 1,692 | 4.3125 | 4 | from collections import defaultdict
from typing import List
class Solution:
"""
You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds requ... | true |
cdf7ca9c6839c2e8678911188e0d52960f9eebfd | benbendaisy/CommunicationCodes | /python_module/examples/662_Maximum_Width_of_Binary_Tree.py | 2,797 | 4.25 | 4 | # Definition for a binary tree node.
import math
from collections import deque, defaultdict
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Given the root of a b... | true |
20813878fb7e6346fb1ab86e8a77a79fb1264b5b | benbendaisy/CommunicationCodes | /python_module/examples/430_Flatten_a_Multilevel_Doubly_Linked_List.py | 2,896 | 4.28125 | 4 | """
# Definition for a Node.
"""
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
class Solution:
"""
You are given a doubly linked list, which contains nodes that have a next pointer, a previous ... | true |
8b1309373057fbd98411e5a0d78b9e699c7c501c | benbendaisy/CommunicationCodes | /python_module/examples/124_Binary_Tree_Maximum_Path_Sum.py | 2,063 | 4.25 | 4 | # Definition for a binary tree node.
import math
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
A path in a binary tree is a sequence of nodes where each pair o... | true |
6816960be9c3f6fe0505263a03cffb74c2679b61 | benbendaisy/CommunicationCodes | /python_module/examples/1035_Uncrossed_Lines.py | 2,147 | 4.46875 | 4 | from functools import lru_cache
from typing import List
class Solution:
"""
You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers nums1... | true |
8ed81cbef9e9fcc50d26491c5d209b1db7fafaac | DivyaReddyNaredla/python_classes | /abstract_classes.py | 1,211 | 4.25 | 4 | """import keyword
#print(keyword.kwlist)
print(type(1))
print(type([]))
print(type({}))
print(type(()))
print(type(""))
print(type(keyword)) #module is class"""
#Extending properties of super calss into sub class is called as inheritance
#Forcing to use same function which is defined in super class
# @ is... | true |
3b1c946c1bfcfe07ea57a9f9b1cdb2cac975c708 | Hghar929/random-forest-temperature-forecast | /main.py | 1,871 | 4.46875 | 4 | # Tutorial from https://towardsdatascience.com/random-forest-in-python-24d0893d51c0
# features: variables
# labels: y value
# Pandas is used for data manipulation
import pandas as pd
# Use numpy to convert to arrays
import numpy as np
# Using Skicit-learn to split data into training and testing sets
from sklearn.model... | true |
dbf13f1d29bc55694a92a15db4a47dea189b1c40 | rathoddilip/BasicPythonPractice | /prime_number.py | 235 | 4.125 | 4 | number = int(input("Enter number"))
prime = True
for i in range(2, number):
if number % i == 0:
prime = False
break
if prime:
print(f"{number} number is prime")
else:
print(f"{number} number is not prime")
| true |
176a3f93d8a950342dd7bbf34bed0ade9c356dd2 | ozenerdem/HackerRank | /PYTHON/Easy/sWAP cASE.py | 704 | 4.375 | 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
Sample Input 0
HackerRank.com presents "Pythonist 2".
Sample Output 0
hACKERrANK.COM PRESENTS ... | true |
881f8f061c4dc2919631e7f21746a84b88bc3ea2 | ryan-berkowitz/python | /Python Projects/Python Session 072821/Random_Number.py | 897 | 4.1875 | 4 | import random
x = random.randint(1,9)
i = 0
while True:
user = input("Enter a guess between 1 and 9: ")
if user == "exit":
break
try:
y = int(user)
except:
print("Guess is not an integer. Please input another guess.")
continue
if y > 9:
print("Gue... | true |
1abed244f1fdc0538c9a98dc6c249854f199b638 | sanupanji/python | /function_exercises/function7.py | 342 | 4.1875 | 4 | # write a function that counts the number of times a given pattern appears in a string, including overlap
# "hah", "hahahaha" --> 3
def pattern_count(ptn, strg):
count = 0
while strg.find(ptn) != -1:
i = strg.find(ptn)
strg = strg[i+1:]
count += 1
return count
print(pattern_cou... | true |
04d0b861335d0af305ef6c59a3fa4aed75a20a47 | sanupanji/python | /practice_w3resource/19_string_man_1.py | 349 | 4.15625 | 4 | '''
Write a Python program to get a new string
from a given string where "Is" has been added to the front.
If the given string already begins with "Is" then return the string unchanged.
'''
def string_man_1(st):
if st[:2].lower() == "is":
return st
return "Is" + st
print(string_man_1(inp... | true |
9575350130c5b3ab537803d810c046b1476ce15a | sanupanji/python | /practice_w3resource/17_range_1.py | 321 | 4.125 | 4 | '''
Write a Python program to test whether a number is within 100 of 1000 or 2000.
'''
def range_100(i):
if abs(2000-i) <=100 or abs(1000-i) <=100:
return f"{i} is within 100 of 1000 or 2000"
return f"{i} is not within 100 of 1000 or 2000"
print(range_100(int(input("enter the number: "))))
... | true |
7a69dca389f3c11d5510094853957c57c87015ef | mafarah1/Debt-Visualizer | /Back-End.py | 1,230 | 4.21875 | 4 | import numpy as np #not used yet
from matplotlib import pyplot as plt #plot the histogram
#get more accurate salaries for better output
major_dic= {"Communication": 45,
"Business": 50, "STEM": 65,
"Education ": 45, "MD":250,
"MBA": 100, "Liberal Arts": 40,
"Law" : 95} #... | true |
97a431a9e9982489b04893a0881b834aa021027a | miiaramo/IntroductionToDataScience | /week2/exercise2.py | 2,378 | 4.15625 | 4 | import pandas as pd
data = pd.read_csv('cleaned_data.csv')
# First consider each feature variable in turn. For categorical variables,
# find out the most frequent value, i.e., the mode. For numerical variables,
# calculate the median value.
mode_survived = data['Survived'].mode()
print(mode_survived)
mode_pclass = ... | true |
9fedea164774065621c6b012c482e9951671ad0e | josephmorrisiii/pythonProject | /homework_two/lab_eight_one_zero.py | 405 | 4.125 | 4 | #Joseph Morris
#1840300
def is_string_a_palindrome(user_string):
new_string = user_string.replace(" ", "")
if new_string == new_string[::-1]:
print(user_string, "is a palindrome")
else:
print(user_string, "is not a palindrome")
# Press the green button in the gutter to run the script.
if ... | true |
ba4f1ce84993f2bb924fbfe2fd450da1508e7104 | AvanindraC/Python | /conditionals 4.py | 436 | 4.5 | 4 | # Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged
def string_conditional(string):
if string.startswith('is'):
print(string)
else:
# return 'Is' + string
... | true |
696e979eadffb26bac50a562fd62c0dc6de655b4 | AvanindraC/Python | /histogram.py | 332 | 4.15625 | 4 | # Write a Python program to create a histogram from a given list of integers
def histogram(data):
for item in data:
print('.' * item)
data = []
num_data = int(input("Enter number of entries: "))
for item in range(0, num_data):
user_input = int(input())
data.append(user_input)
res = histogram(data... | true |
8b0c933fc0179f1a072ff79403e64ad979e69ca0 | AvanindraC/Python | /reverse.py | 262 | 4.28125 | 4 | # Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them
first = str(input("Enter first name: "))
last = str(input("Enter last name: "))
result = first[::-1] + " " + last[::-1]
print(result) | true |
02bd5ed48d7d512b30aa1b0938c87ef26629351d | JeganKunniya/practice-python-exercises | /16-PasswordGenerator.py | 1,094 | 4.125 | 4 | # Exercise 16 - Password Generator
import random
import string
STRONG = 1
MEDIUM = 2
WEAK = 3
def generate_password(password_complexity):
"""
Generates the password based on the complexity requested by the user.
:param password_complexity: could be Strong, Medium, Weak
:return: generated password b... | true |
dd75bef404b684e89eea27671c8e5adb78a35ab8 | dannyjew/Data22 | /HangMan/main.py | 2,460 | 4.28125 | 4 | word_to_guess = input("Please pick a word to guess...") # user inputs a word to guess
max_lives = 5 # max lives that the guesser has
wrong_counter = 1 # tracks the number of times the guesser guesses wrong
underscores = "________________________________________________________________________" # this is used to... | true |
94c4e796a3ab358f9c73df69be968aedcb7182e4 | EWilcox811/UdemyPython | /LambdaMap.py | 988 | 4.125 | 4 | def square(num):
return num**2
my_nums = [1,2,3,4,5]
for item in map(square, my_nums):
print(item)
list(map(square,my_nums))
def splicer(mystring):
if len(mystring)%2 == 0:
return 'EVEN'
else:
return mystring[0]
name = ['Andy','Eve','Sally']
list(map(splicer,name))
# When using the map... | true |
89fd8e1721a761ac8db70bd29590bc7d1b1ae6d3 | lingxueli/CodingBook | /Python/decorator/decorator.py | 1,223 | 4.28125 | 4 | def hello():
print('helloooooo')
greet = hello()
print(greet) # hello
greet = hello
print(greet) # function object
del hello
# hello is the pointer to the function
# this deletes the pointer not the function itself
greet() # still executed
# @decorator
# def hello():
# pass
# decorator add extra features t... | true |
fd4dfabeda6c4267eb8b57cd33c0aa95be45701d | lingxueli/CodingBook | /Python/Basics/range.py | 283 | 4.125 | 4 | # range creates an object that you can iterate over
print(range(0,100))
# obj: range(0,100)
for number in range(0,100):
print(number)
# when you don't need the variable
# send emails 100 times
for _ in range(0,100):
print('email email list')
print(_) # print 1,2,...
| true |
ef4fcfc933daf2bd296b07ec620f32af92ccd248 | lingxueli/CodingBook | /Python/Error handling/errorhandling4.py | 537 | 4.1875 | 4 | # stop the program from an error: raise
while True:
try:
age = int(input('what s your age? '))
10/age
# this stops the program
raise ValueError('hey cut it out')
# alternative: stop from any type of error
raise Exception('hey cut it out')
# remove the except part
... | true |
c25a1bb60e229ce1e9041427dadb3addc4429d56 | haodayitoutou/Algorithms | /LC50/lc24.py | 1,239 | 4.125 | 4 | """
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
"""
from util import ListNode, create_node_li... | true |
926fd5942e965801e9a0483c7ad67d0bfb33e77c | Bushraafsar/Alien-Dictionary | /alien.py | 2,532 | 4.40625 | 4 | # PYTHON ASSIGNMENT:
#ALIEN TASK:
# Python Program that display meaning of word said by alien in English Language:
# Python Program that display meaning of word said by human in alien language:
import json
print("==================== ENGLISH / ALIEN TRANSLATOR=========================")
while True:
print... | true |
4558a55e7d002e971aa7472aba0983160b90926e | ZanyeEast/ISAT252 | /lec9.py | 615 | 4.4375 | 4 | """
Lecture 9 Classes
Self method should be the first argument
"""
class car: # car is the class name
maker = 'toyota' #attribute
def __init__(self,input_model):
self.model = input_model
def report(self):
#return the attribute of the instance
return self.maker,sel... | true |
17bb66f503fee20354db38815f5ec7e094c3059c | ZanyeEast/ISAT252 | /lec8.py | 1,220 | 4.46875 | 4 | """
Lecture 8 Functions
return function should always be the last command in function
"""
#positional argument
def my_function(a, b):
result = a + b
print('a is',a)
print('b is',b)
return result
print(my_function(2, 1))
def my_function(a, b=0):
result = a + b
print('a is',a)
print('b is'... | true |
dc8df2ff35639fe143f5173aae56413e33ab125b | karinasamohvalova/OneMonth_python | /tip.py | 551 | 4.15625 | 4 | # We ask client's name and his bill
name = input("What is your name? ")
original_bill = int(input("What is your bill? "))
# We count three types if tips
tip_one = original_bill * 0.15
tip_two = original_bill * 0.18
tip_three = original_bill * 0.20
# We make an offer to the person. It includes 3 choices.
pri... | true |
2a45b8f146c70af9967b203c4cc587a0bdc801a2 | nakayamaqs/PythonModule | /Learning/func_return.py | 1,354 | 4.3125 | 4 | # from :http://docs.python.org/3.3/faq/programming.html#what-is-the-difference-between-arguments-and-parameters
# By returning a tuple of the results:
def func2(a, b):
a = 'new-value' # a and b are local names
b = b + 1 # assigned to new objects
return a, b # return new value... | true |
0b4b0a0299125f12419c24828b4e3699b8708226 | nakayamaqs/PythonModule | /Learning/find.py | 1,670 | 4.125 | 4 | #!/usr/bin/env python
# encoding: utf-8 #
# Simple imitation of the Unix find command, which search sub-tree
# for a named file, both of which are specified as arguments.
# Because python is a scripting language, and because python
# offers such fantastic support for file system navigation and
# regular expressions, py... | true |
9b16cc21ec0857141c7c359bf9a9ed5d8f72868a | ravgeetdhillon/hackerrank-algo-ds | /Extract_Number.py | 341 | 4.375 | 4 | numbers=['0','1','2','3','4','5','6','7','8','9']
print('***PROGRAM : To extract the valid phone number from the string***')
a=str(input('Input your string : '))
p=''
for char in a:
if char in numbers:
p=p+char
if len(p)==10:
print('The phone number is',p)
else:
print("Your input doesn't contain a v... | true |
75febbcc0d60df375dd9990b256fb1f35f330aa1 | balaprasanna/Trie-DataStructure | /trie.py | 2,254 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class trieNode:
""" leaf to indicates end of string """
def __init__(self):
self.next = {}
self.leaf = False
"""function to add a string to trie"""
def add_item(self, item):
i = 0
while i < len(item):
k = item[i]... | true |
7c19c4a9425947694aa49fcdd30ff905e044df7d | soumyax1das/soumyax1das | /simpleWhile.py | 320 | 4.15625 | 4 | """
This is a simple program to demonstarte the while loop in Python
"""
def create_pyramid(height):
i=1
while(i<=height):
i=i+1
print('i is',i)
if i == 4:
#continue
pass
print('+'*i)
print('*'*i)
if __name__ == '__main__':
create_pyramid(5)
| true |
8e2059b1be305f600cf4f0c1db5addd0da218cbe | yang-official/LC | /Python/4_Trees_and_Graphs/2_Graph_Traversal/207_course_schedule.py | 2,170 | 4.125 | 4 | # https://leetcode.com/problems/course-schedule/
# 207. Course Schedule
# There are a total of n courses you have to take, labeled from 0 to n-1.
# Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
# Given the total number of courses a... | true |
7e83e498e6841fa9db31c32c9591dfe5da8112ad | theknewkid/knewkidcalculator | /backend-code/calculations.py | 1,206 | 4.46875 | 4 | #Let's set up functions for the different calculations here. We'll create a float from the user's input.
hey = "Welcome to my very elementary calculator!"
print(hey)
def addition():
'''This is a function for adding.'''
a = float(input("Enter a number. "))
b = float(input("Enter another number. "))
pr... | true |
f1d80ec4d8de02adbb016bbf7a094ed24d1b9fbe | swathiswaminathan/guessing-game | /game.py | 1,640 | 4.21875 | 4 | """A number-guessing game."""
# Put your code here
import random
print "Welcome to the game!"
name = raw_input("What's your name? ")
print"Choose a random number, %s" % (name)
# secret_num = random.randint(1, 100)
#print " the secret number is %d" % (secret_num)
# guess = None
# too_high = 100
# too_low = 0
# coun... | true |
b0d5c7e842af58cd8d159e137f94a6eab79e5428 | sfGit2Hub/PythonLearn | /PythonDemo/static/max_cost_assignment.py | 1,058 | 4.40625 | 4 | import dlib
# So in this example, let's imagine we have 3 people and 3 jobs. We represent
# the amount of money each person will produce at each job with a cost matrix.
# Each row corresponds to a person and each column corresponds to a job. So for
# example, below we are saying that person 0 will make $1 at job 0, $2... | true |
3a167a50a74c630eaa197f4188b3baffb20eeced | ua114/py4e | /week1.py | 1,221 | 4.1875 | 4 | # Using strong functions
# fruit = 'banana'
# print(len(fruit)) #Lengh of the string
# fruit = 'mango'
# count = 0
# while count < len(fruit):
# print(count, fruit[count])
# count = count +1
# print('Done')
#
# for letter in 'banana':
# print(letter)
# word = 'abrasion'
# count = 0
# a_count = 0
#
# for ... | true |
f940e67265df7b83165a5aed6a153bd311b2d35a | yufang2802/CS1010E | /checkOrder.py | 338 | 4.375 | 4 | integer = input("Enter positive integer ")
def check_order(integer):
previous = 0
while (integer > 0 and integer > previous):
previous = integer
integer = int(input("Enter positive integer "))
if integer == 0:
print("Data are in increasing order.")
else:
print("Data are not in increasing order.")
check_o... | true |
4e6e1082fa4cd3c3b102eec8cdbc7de38673004e | TutorialDoctor/Scripts-for-Kids | /Python/math_basic.py | 661 | 4.1875 | 4 | # Get the sum of two numbers a and b
def sum(a,b):
return a+b
# Get the difference of two numbers a and b
def difference(a,b):
return a-b
# Get the quotient of two numbers a and b where b cannot equal 0
# You have to use a float somewhere in your dividion so that the answer comes out as a float
# A float is a num... | true |
732cb6de8566d69a84813850a25d426d862944f8 | Shailendre/simplilearn-python-training | /section1 - basic python/lesson6.5.py | 1,233 | 4.28125 | 4 | # tuple and list
# tuple: immutable
# sicnce tuple is immutable its fast in traversal and other operations
def example():
# this is called sequence packing
return 13,13
# this is sequence unpacking
a,b = example()
print(a)
# list
ll = [2,4,1,7,3,9,3,8,6,4,0]
# list size
print ("original length:", len(ll))
#... | true |
da06aa6567f4495284792a7196f01af46ecacb19 | zahranorozzadeh/tamarin4 | /tamrin4-3.py | 255 | 4.5 | 4 | # Python Program to print table
# of a number upto 10
def table(n):
for i in range (1, 11):
# multiples from 1 to 10
print (n, i, n * i)
# number for which table is evaluated
n = 5
table(n)
# This article is contributed by Shubham Rana
| true |
f1938f6cdb52543c85729a355584a25fd52ab9c4 | smspillaz/fair-technical-interview-questions | /python/default.py | 303 | 4.28125 | 4 | #!/usr/bin/env python
#
# This code *should* print [1], [2] but does something different. Can
# you explain why and how you would fix the problem?
def append(element, array=[]):
"""Return element as appended to array."""
array.append(element)
return array
print(append(1))
print(append(2)) | true |
fad067e667888ea23e5903f5b76eab36192ca521 | ZeyadAl/small-python-programs | /balance.py | 473 | 4.375 | 4 | '''
we are given 3 variablees
1) balance
2) annual interest rate
3) monthly min rate
first calculate monthly interest rate
'''
balance= float(input('Balance '))
annual= float(input('Annual interest rate '))
minrate= float(input('monthly Min rate '))
paid=0
mint= annual/12
for i in range(12):
balance= balance*(mi... | true |
ac86491af11e13ad77e3f266aba3e241a72f6476 | deesaw/PythonD-03 | /Databases/sqlite3Ex/selectTable.py | 618 | 4.25 | 4 | import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
sql = "SELECT * FROM cars"
print ("listing of all the records in the table:")
for row in cursor.execute(sql):
print (row)
print ("Results...")
cursor.execute(sql)
print(len(cursor.fetchmany(3)))
for id,carname,price in cursor.fetchal... | true |
768615562d1ba0d17b4e7a473ee8819bfd02da13 | deesaw/PythonD-03 | /Data Structures/7_dictionary.py | 750 | 4.28125 | 4 | #dictionary
marks={'Maths':97,'Science':98,'History':78}
print(marks)
print(type(marks))
print(len(marks))
print(sum(marks.values()))
print(max(marks.values()))
print(min(marks.values()))
print(marks.keys()) #prints keys from the dictionary
print(marks.valu... | true |
b5017c4fce9992d652e6cbd57056ab8ab36e3c5c | kingkongmok/kingkongmok.github.com | /bin/test/python/ex42.py | 1,852 | 4.40625 | 4 | #!/usr/bin/python
# http://learnpythonthehardway.org/book/ex42.html
# Is-A, Has-A, Objects, and Classes
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
pass
## Dog is-a Animal, has a function named __init__ that taks self, name parameters.
class Dog(Animal):
def ... | true |
0d55bfc50430c186b8c46fa816a23b27838f2aab | thuaung23/elementary-sortings | /main.py | 2,511 | 4.125 | 4 | # This program uses elementary sorts, such as selection, insertion and bubble.
# This program is written in object oriented programming.
# Written by: Thu Aung
# Written on: Oct 11,2020
"""
These elementary sorting algorithms are good for only smaller input sizes
because the time complexity of them is quadratic, O(N^2... | true |
52fed17125980a152cc0c90ef0a0cd21fa87c10b | caffwin/rev-string | /reverse-string.py | 2,816 | 4.375 | 4 | from pprint import pprint
# Reverse a string in place
# Input: string
# Output: string
# Strings are immutable in python, so use a list
# "hello" > "olleh"
# h e l l o
# 0 1 2 3 4
# 0 <-> 4
# or.. 0 <-> -1
# 1 <-> 3
# or.. 1 <-> -2
# 2 stays in place (no work done)
# h e l l o o
# 0 1 2 3 4 5
# ^ ^
# 0 ... | true |
2c655db1e97429eeb8bc525cbc9d5408f6edeaf9 | appleboy919/python_DS_ALG | /ch4_Queue/myQueue.py | 1,147 | 4.25 | 4 | # application:
# CPU scheduling
# asynchronous data between two processes
# graph traversal algorithm
# transport, operations management
# file servers, IO buffers, printer queues
# phone calls to customer service hotlines
# !! resource is shared among multiple consumers !!
# head <-> rear (tail)
# FIFO
# head: remove ... | true |
0c9f99988ba5ce914094e28cccf2c85a008ee8b6 | GintautasButkus/20210810_Coin-Flip-Streaks | /Coin Flips.py | 2,384 | 4.34375 | 4 | # Coin Flip Streaks
# For this exercise, we’ll try doing an experiment. If you flip a coin 100 times
# and write down an “H” for each heads and “T” for each tails, you’ll create
# a list that looks like “T T T T H H H H T T.” If you ask a human to make
# up 100 random coin flips, you’ll probably end up with alternatin... | true |
791fe6d02d0a5a85f62db34d82a35e07aa72aeb7 | greenca/exercism-python | /wordy/wordy.py | 945 | 4.15625 | 4 | operators = {'plus':'+', 'minus':'-', 'multiplied':'*', 'divided':'/'}
def calculate(question):
question_words = question.split(' ')
if question_words[:2] == ['What', 'is']:
question_words = question_words[2:]
num1 = question_words.pop(0)
op = question_words.pop(0)
num2 = questi... | true |
9c895d9990c777c0ecd1310d316ad10ca69b7cf8 | vdpham326/python-data-structures | /dictionary/find_anagrams.py | 892 | 4.28125 | 4 | words = ['gallery', 'recasts', 'casters', 'marine', 'bird', 'largely', 'actress', 'remain', 'allergy']
def find_anagrams(list):
new = {}
#key should store strings from input list with letters sorted alphabetically
for word in list:
key = ''.join(sorted(word))
if key not in new:
... | true |
59aa697109d141faa171bfb00ddee85cac9e153f | vdpham326/python-data-structures | /tuple/get_values.py | 608 | 4.3125 | 4 | '''
Create a function named get_min_max_mean(numbers) that accepts a list of integer values and returns the smallest element,
the largest element, and the average value respectively – all of them in the form of a tuple.
'''
def get_min_max_mean(numbers):
smallest, largest, total = numbers[0], numbers[0], 0
for ... | true |
bca033e9e874316c0386fc7efc55cc3e4034ff4c | dignakr/sample_digna | /python-IDLE/item_menu_ass1.py | 1,892 | 4.25 | 4 | class ItemList:
def __init__(self, itemname, itemcode):
self.itemname = itemname
self.itemcode = itemcode
def display(self):
print '[itemname :',self.itemname,',itemcode :',self.itemcode,']'
if __name__=="__main... | true |
d76e737379f2afd92f4dce9f74ac73593d674980 | John-Ming-Ngo/Assorted-Code | /PureWeb_Submission/Shuffle.py | 2,853 | 4.4375 | 4 | import random as rand
import copy
'''
This function, given an input value N, produces a randomized list
with each value from 1 to N. Naively, this can be done by actually
simulating a real shuffle, as I did in a prior assignment, but since
we want to optimize for speed, we're going to have to be more
creative. The fir... | true |
47ddd4ebe7f26b2f3a48439ac77110a69df333e6 | NotQuiteHeroes/HackerRank | /Python/Math/Triangle_Quest_2.py | 929 | 4.15625 | 4 | '''
You are given a positive integer N.
Your task is to print a palindromic triangle of size N.
For example, a palindromic triangle of size 5 is:
1
121
12321
1234321
123454321
You can't take more than two lines. The first line (a for-statement) is already written for you.
You have to complete the code using exactly o... | true |
8f76164190b01039565d41b9c735c5dba85304dc | NotQuiteHeroes/HackerRank | /Python/Sets/Captains_Room.py | 1,359 | 4.125 | 4 | '''
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was given a separa... | true |
ddf276c6fd4b62db64141085002cc4b246e61de1 | NotQuiteHeroes/HackerRank | /Python/Basic_Data_Types/List_Comprehensions.py | 873 | 4.28125 | 4 | '''
Let's learn about list comprehensions! You are given three integers x, y, and z representing the dimensions of a cuboid along with an integer n. You have to print a list of all possible coordinates given by (i, j, k) on a 3D grid where the sum of i + j + k is not equal to n. Here, 0 <= i <= x, 0 <= j <= y, 0 <= k <... | true |
37da311250659eff59593188f0c3a40423d93f77 | bensontjohn/pands-problem-set | /squareroot.py | 600 | 4.15625 | 4 | # Benson Thomas John, 2019
# Program that takes a positive floating point number as input and outputs an approximation of its square root.
# import the math module
import math
# Take user input and convert to float type
user_num = float(input("Please enter a positive number: "))
# Referenced : https://docs.pyt... | true |
4bee2818070b5910cd395c0c88e7df7657672819 | jerryperez25/ArtificialIntelligence-CS4341 | /Homework 1/CS4341_HW1_PerezJerry/PerezJerry/ex2.py | 773 | 4.125 | 4 | def isreverse(s1, s2):
# Your code here
if (len(s1) == 0 and len(s2) == 0): # if both lengths are 0 then they are both equal: only thing thats 0 is empty
return True;
if len(s1) != len(s2): # if the lengths of 2 words are not equal then there is no way they can be reversals
return False;... | true |
faea3e3b47ef0a20cb862df7f8090c336e8f5fda | jerry1210/HWs | /HW5/3.py | 642 | 4.15625 | 4 | '''
Write a decorator called accepts that checks if a function was called with correct argument types. Usage example:
# make sure function can only be called with a float and an int
@accepts(float, int)
def pow(base, exp):
pass
# raise AssertionError
pow('x', 10)
'''
def accepts(*types):
def decorator(func):
... | true |
0d8252d254e300ae9c60ce0ed0f9db19f6242b43 | omshivpuje/Python_Basics_to_Advance | /Python primery data structures.py | 1,104 | 4.25 | 4 | """
Primary Data structures:
1. List
2. Tuple
3. Dictionary
4. Sets
"""
# List
# Lists are mutable and ordered. Also can have different, duplicate members. can be declared in [].
ranks = [1, 2, 3, 4, 5]
fruits = ["Orange", "Mango", "Pineapple", "Strawberry"]
print("ranks: {0}, fruits: {1}".format(ranks... | true |
860936a58673a46d8ee2733dc2ced12968e74976 | gauravk268/Competitive_Coding | /Python Competitive Program/LIST.py | 1,928 | 4.34375 | 4 | Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> ## LISTS IN PYTHON
>>>
>>> list1 = [10,20,30,"hello",2.4]
>>> list1
[10, 20, 30, 'hello', 2.4]
>>> list1[1]
20
>>> list1[-4]
20
>>> ## Accessing th... | true |
b9d676a541b0c0a52e62c39eb8b665e81f8b8c2e | gauravk268/Competitive_Coding | /Python Competitive Program/gretest element in right.py | 1,087 | 4.5625 | 5 | # Python Program to replace every element with the
# greatest element on right side
# Function to replace every element with the next greatest
# element
def nextGreatest(arr):
size = len(arr)
# Initialize the next greatest element
max_from_right = arr[size-1]
# The next greatest ele... | true |
a2f503fe913e6103377a6aabca170c035b60896d | group6BCS1/BCS-2021 | /src/chapter5/excercise1.py | 485 | 4.21875 | 4 | try:
total = 0
count = 0
# the user will be able to input numbers repeatedly
while True:
x = input('enter a number')
# when done is entered, the loop will be broken
if x == 'done':
break
x = int(x)
# we are finding the total, count and average of the numbers entered
... | true |
6495d47e7d6695d6c4851252bfa5c0080aef1296 | yufanglin/Basic-Python | /List.py | 2,474 | 4.46875 | 4 | '''
List practice in Python 3
'''
############################## LISTS ##############################
courses = ['History', 'Math', 'Physics', 'CompSci']
# Print the list
print(courses)
# length of the list
print(len(courses))
# Get specific values in list
print(courses[0])
# Get last value in list
print(co... | true |
c603b386c71d984b3a4771028d7a960c1957dbe7 | colinbazzano/recursive-sorting-examples | /src/lecture.py | 1,492 | 4.1875 | 4 | # *********************************************
# NEVER DO THIS, BUT... it is recursion
# def my_recursion(n):
# print(n)
# my_recursion(n+1)
# my_recursion(1)
# *********************************************
# we have now added a base case to prevent infinite recursion
def my_recursion(n):
print(n)
... | true |
baa425cca4e36d27b14c71569660ea92e6e47815 | kishorchouhan/Udacity-Intro_to_CS | /Better splitting.py | 1,370 | 4.34375 | 4 | def split_string(source,splitlist):
word_list = ['']
at_split = False
for char in source:
if char in splitlist:
at_split = True
else:
if at_split:
# We've now reached the start of the word, time to make a new element in the list
word_li... | true |
ecd06a64bd206784e741f086a8bc6f0453716786 | vimalkkumar/Basics-of-Python | /Factorial.py | 280 | 4.1875 | 4 | def main():
def factorial_number(num):
result = 1
for i in range(1, num+1):
result = i*result
print("factorial of {} is {}".format(num, result))
factorial_number(int(input("Enter a number : ")))
if __name__ == "__main__":
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.