blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
377c78d18db40dd93bd16b65a9a1a4547c508216 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/16 Databases/databases.py | 896 | 4.3125 | 4 | #!/usr/bin/python3
# Databases in python
# Database used here is SQLite 3
# row factory in sqlite3
import sqlite3
def main():
# Connects to database and creates the actual db file if not exits already
db = sqlite3.connect('test.db')
# Interact with the database
db.execute('drop table if exi... | true |
33d9a7cc53d070f8575fa5b3b044edd4eb5e9fe4 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/12 Classes/generator.py | 1,218 | 4.46875 | 4 | #!/usr/bin/python3
# A generator object is an object that can be used in the context of an iterable
# like in for loop
# Create own range object with inclusive range
class inclusive_range:
def __init__(self, *args):
numargs = len(args)
if numargs < 1 :
raise TypeError('Requries at lea... | true |
d2d7d34fa745243c91ab891f0fdd3e28ba8b16d0 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/14 Containers/dictionary.py | 1,397 | 4.28125 | 4 | #!/usr/bin/python3
# Organizing data with dictionaries
def main():
d1 = {'one' : 1, 'two' : 2, 'three' : 3}
print(d1, type(d1))
# dictionary using dict constructor
d2 = dict(one = 1, two = 2, three = 3)
print(d2, type(d2))
d3 = dict(four = 4, five = 5, six = 6)
print(d3, type(d3... | true |
f33362d646b39360d8bdc20d346a369fdf7d6a19 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/05 Variables/Finding_type_identity.py | 1,300 | 4.3125 | 4 | #!/bin/python3
# Finding the type and identity of a variable
# Everything is object and each object has an ID which is unique
def main():
print("Main Starts !")
x = 42
print("x:",x)
print("id of x:",id(x))
print("id of 42:",id(42))
print("type of x:", type(x))
print("type of 42:", type(4... | true |
a9a1e6045d4a0ba4ff26f662bfc670c4ae007693 | alvintangz/pi-python-curriculum | /adventuregame.py | 745 | 4.34375 | 4 | # Simple adventure game for day 3.
hero = input("Name your hero. ")
print("\n" + hero + " has to save their friend from the shark infested waters.")
print("What do they do?")
print("A. Throw a bag of salt and pepper in the water?")
print("B. Drink up the whole ocean?")
print("C. Do nothing.\n")
option = input("What do ... | true |
8ca0ed2176a8dac59fd50ae330c278b1cf649ac1 | jzaunegger/PSU-Courses | /Spring-2021/CSE-597/MarkovChains.py | 1,804 | 4.3125 | 4 | '''
This application is about using Markov Chains to generate text using
N grams. A markov chain is essentially, a series of states, where each state
relates to one another in a logical fashion. In the case of text generation,
a noun phrase is always followed by a verb phrase.
Lets say we ha... | true |
28bf44989f72a0a9c14d5a34bb1068437800c72a | mustail/Election_analysis | /practice/python_practice2.py | 1,711 | 4.46875 | 4 | # python practice continued
print("Hello world.")
print("Arapahoe and Denver are not in the list of counties.")
# printing with f string
my_votes = int(input("How many votes did you get in the election?"))
total_votes = int(input("What is the total number of votes in the election?"))
percentage_votes = (my_votes/t... | true |
6873b522169569c7e04a6e39c065fdab343f6405 | Sabdix/Python-Tutorials | /Dictionaries.py | 465 | 4.25 | 4 | # A dictionary is a collection which is unordered, changeable and indexed.
thisDict = {
"apple": "green",
"bannana": "yellow",
"cherry": "red"
}
print(thisDict)
#Changing elements
thisDict["apple"] = "red"
print(thisDict)
#Create dictionary with method
thisdict = dict(apple="green", bannana="yellow", che... | true |
abbc2b40c22b26f2c2305a5b69b91cb8ccb63b9a | Sabdix/Python-Tutorials | /Json.py | 1,302 | 4.4375 | 4 | # importing JSON
import json
# If you have a JSON string, you can parse it to convert it in to a dictionary
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
#If you have a Python object, you can convert it into a JSON... | true |
bbfa000ad67f734df09ed03e70d85119123cfef0 | sangeetjena/datascience-python | /Dtastructure&Algo/algo/water_supply.py | 826 | 4.1875 | 4 | """Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.
The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which mea... | true |
00503cb30615d01facc609ef894f0ee570717a96 | kajaltingare/Python | /Basics/verbing_op.py | 328 | 4.4375 | 4 | # Write a program to accept a string from user & perform verbing operation.
inp_stmt=input("Enter the statement: ")
if(len(inp_stmt)>=3):
if(inp_stmt.endswith("ing")):
print(inp_stmt[:-3]+'ly')
else:print(inp_stmt+'ing')
else:
print('Please enter verb atleast 3 or more number of characters in... | true |
58b6f4caa8b080662653399a75cff2afc9ff6691 | kajaltingare/Python | /Basics/Patterns/pattern6_LL.py | 334 | 4.125 | 4 | # Write a program to print LowerLeft side pattern of stars.
def Pattern6(n):
for i in range(1,n+1):
for _ in range(0,n-i+1):
print('*',end='')
print()
def main():
n = eval(input('Enter the no of rows want to print pattern: '))
Pattern6(n)
if __name__ == '__main__':... | true |
c0af2569858fa4b0d2e8d8c2246d7948a8d97841 | kajaltingare/Python | /Basics/UsingFunc/fibboSeriesWithUpperLimit.py | 433 | 4.21875 | 4 | # Write a program to print fibonacci series with given upper limit, starting from 1.
def fiboSeries(upperLmt):
a,b=1,1
print(a,b,end='')
#for i in range(1,upperLmt):
while((a+b)<=upperLmt):
c=a+b
print(' %d'%c,end='')
a=b
b=c
def main():
upperLmt = eval(i... | true |
9b4de2ccf3539b1f714c3855bff8989f19f433fa | kajaltingare/Python | /Basics/min_of_3.py | 260 | 4.21875 | 4 | # Write a program to accept three numbers from user & find minimum of them.
n1,n2,n3=eval(input("Enter the 3 no.s: "))
if(n1<n2 and n1<n3):print("{0} is minimum".format(n1))
elif(n2<n1 and n2<n3):print('%d is minimum.'%n2)
else:print('%d is minimum.'%n3)
| true |
831023701ff1b841124a34e1eebb20f05489cc6a | kajaltingare/Python | /Basics/UsingFunc/isDivisibleByEight.py | 481 | 4.34375 | 4 | # Write a program to accept a no from user & check if it is divisible by 8 without using arithmatic operators.
def isDivisibleByEight(num):
if(num&7==0):
return True
else:
return False
def main():
num = eval(input('Enter the number: '))
result = isDivisibleByEight(num)
i... | true |
a8c06bb0934f021d06a854bba1861b83d31bd4e1 | kajaltingare/Python | /Basics/basic_str_indexing.py | 676 | 4.65625 | 5 | #String-Immutable container=>some basics about string.
name="kajal tingre"
print("you entered name as: ",name)
#'kajal tingre'
print("Accessing 3rd char in the string(name[2]): ",name[2])
print("2nd including to 5th excluding sub-string(name[2:5]): ",name[2:5])
print("Printing alternate char from 1st position(nam... | true |
094559f9145b0d98920ed6960f275c0de68f0d48 | Ahed-bahri/Python | /squares.py | 250 | 4.25 | 4 | #print out the squares of the numbers 1-10.
numbers=[1,2,3,4,5,6,7,8,9,10]
for i in numbers:
print("the square of each number is : ", i**2)
#mattan strategy
for i in range(1,11):
print("the square of each number is : ", i**2)
| true |
da3e46522a54ff4971dda36cb3a0ad19de85e874 | donchanee/python_trick | /Chaining_Comparison.py | 502 | 4.25 | 4 | # Chaining comparison operators:
>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True
'''
In case you're thinking it's doing 1 < x, which comes out as True, and then comparing True < 10,
which is also True, then no, that's really not what happens... | true |
ed37d9243eda6d10b8f2cb0e8c3c55791ed99e38 | KlimDos/exercism_traning | /python/yacht/yacht.py | 2,457 | 4.1875 | 4 | """
This exercise stub and the test suite contain several enumerated constants.
Since Python 2 does not have the enum module, the idiomatic way to write
enumerated constants has traditionally been a NAME assigned to an arbitrary,
but unique value. An integer is traditionally used because it’s memory
efficient.
It is a... | true |
c2bccd3dc5edb3734482d4540c954292ae6bc85f | shun-lin/Shun-LeetCode-OJ-solutions | /Algorithm/ImplmentingQueueUsingStacks.py | 1,718 | 4.40625 | 4 | class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
# stack is first in last out so in python we can use append to add and
# pop front
# we want to implement a queue which is first in first out
self.stacks = [[], []]
... | true |
e064c21b78829ef1a99ce2e205c7298cca798afc | gmaher/flask-react-be | /src/crypto/password.py | 938 | 4.3125 | 4 | import bcrypt
def hash_password(pw, rounds=10):
"""
Uses the bcrypt algorithm to generate a salt and hash a password
NOTE: ONLY PASSWORDS < 72 CHARACTERS LONG!!!!
:param pw: (required) password to hash
:param rounds: number of rounds the bcrypt algorithm will run for
"""
if not type(pw) ==... | true |
3207b1deeb5506e7d1346291901a759cc2549fca | TianfangLan/LetsGoProgram | /Python/week_notes/week2_QueueADT_v1.py | 1,718 | 4.34375 | 4 | class EmptyQueueException(Exception):
pass
class Queue():
''' this class defines a Queueu ADT and raises an exception in case the queue is empty and dequeue() or front() is requested'''
def __init__(self):
'''(Queue) -> Nonetype
creates an empty queue'''
# representation invariant
... | true |
54492efbf4c23f590bef414dcfc611dc28dde4a0 | mrklyndndcst/100-Days-of-Code-The-Complete-Python-Pro-Bootcamp-for-2022 | /Beginner/D004_Randomisation_and_Python_Lists/ProjectD4_Rock_Paper_Scissors.py | 1,551 | 4.15625 | 4 | import random
rock = "👊"
paper = "✋"
scissors = "✌️"
choices = [rock, paper, scissors]
player = int(input(f"What do you choose? type 1 for {rock}, 2 for {paper} or 3 for {scissors}\n"))
print("You choose")
if player < 1 or player > 3:
print("Invalid")
ai = random.randint(1 , 3)
print("Artificial Intell... | true |
e999d005eff83eca21ec9e1f4acb28cc96ba4d0b | zhanglulu15/python-learning | /python学习基础及简单实列/basic learing 6.py | 246 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 10:41:55 2018
@author: lulu
"""
count = 3
while count <= 5:
print("the count less than 5",count)
count = count + 1
else:
print("the count greater than 5",count) | true |
52c689ac08f7020700ec0ede437162eb1c0e7f81 | Valuoch/pythonClass | /pythonoperators.py | 1,375 | 4.53125 | 5 | #OPERATORS
#special symbols in python to carry out arithmetic and logical computations
#They include;
#1.arithmetic- simple math operations eg addition, sustraction, multiplication(*), division(/), modulas(%), floor(//),exponent(**)etc
#x=10
#y=23
#print(x+y)
#print(x-y)
#print(x/y)
#print(x*y)
#print(x%y)
#print(x//y)... | true |
ccb56373dde67a27e4c4bfabd234b6d0a310cf86 | alexthomas2020/Banking | /test_Account.py | 2,028 | 4.3125 | 4 | # Banking Application
# Author: Alex Thomas
# Updated: 11/10/2020
import unittest
from Account import get_account, get_accounts, Account
"""
Banking Application - Unit tests for Account class.
Run this program to view results of the tests.
"""
class TestAccount(unittest.TestCase):
def test_get_account(self):
... | true |
6966ec8f669922fa1a78661630eb6732ba5b549a | matthew02/project-euler | /p005.py | 820 | 4.1875 | 4 | #!/usr/bin/env python3
"""Project Euler Problem 5: Smallest multiple
Find the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20.
https://projecteuler.net/problem=5
Usage:
python3 p0005.py [number]
"""
import sys
from math import gcd
from typing import List
def smallest_multi... | true |
3d8813c43d8f57d133fb2f487cd15f65b9a59106 | gabrielbessler/ProgrammingCompetition | /AI18/AI18_1.py | 1,422 | 4.65625 | 5 | #!/bin/python3
import sys
'''
Problem Statement
You have been given an integer which represents
the length of one of cathetus of a right-angle triangle.
You need to find the lengths of the remaining sides.
There may be multiple possible answers; any one will be accepted.
'''
def pythagorean_triple(side... | true |
85f848d0e6e073ec282e96cb98481eda112c43e4 | dstamp1/FF-BoA-2020 | /day01/day01c-ForLoops.py | 2,787 | 4.6875 | 5 | ### For Loops ###
# Computers are really good at repeating the same task over and over again without making any mistakes/typos
# Let's imagine we were having a competition to see who could type out "print('hello')" as many times as we could without using copy and paste.
# We might type out
print('hello')
print('hello'... | true |
8c997e49168c94f312993b43f08b26c857579ba6 | vijaysharma1996/Python-LIst-Basic-Programmes | /list find the sum of element in list.py | 232 | 4.25 | 4 | # Python program to find sum of elements in list
# creating a list
list1 = [11, 5, 17, 18, 23]
# using sum() function
total = sum(list1)
# printing total value
print("Sum of all elements in given list: ", total)
| true |
b489616b270128b30f5f06ad34c2e4f613cdf575 | imnikkiz/Conditionals-and-Variables | /guessinggame.py | 2,344 | 4.15625 | 4 | import random
def check_guess(guess, correct):
""" Compare guess to correct answer.
Return False once guess is correct.
"""
if guess == correct:
return False
elif guess < 1 or guess > 100:
print "Your guess is out of the range 1-100, try again."
elif guess > correct:
p... | true |
6166a4a86a3a486745dee02399b400820ba446d9 | raresrosca/CtCI | /Chapter 1 Arrays and Strings/9_stringRotation.py | 847 | 4.125 | 4 | import unittest
def is_rotation(s1, s2):
"""Return True if s2 is a rotation of s1, False otherwise"""
for i, c in enumerate(s2):
if c == s1[0]:
if s2[i:]+s2[:i] == s1:
return True
return False
def is_rotation_2(s1, s2):
"""Return True if s2 is a rotation of s1, Fals... | true |
55885f48b318943495a44ff4454b5c21ca1f3f45 | sirajmuneer123/anand_python_problems | /3_chapter/extcount.py | 533 | 4.125 | 4 | #Problem 2: Write a program extcount.py to count number of files for each extension in the given directory. The program should take a directory name as argument and print count and extension for each available file extension.
import os
import sys
cwd=os.getcwd()
def count(cwd):
list1=os.listdir(cwd)
newlist=[]
frequ... | true |
9fdf38d1a2c8bf2460625ff16b4ebc6692936cfc | sirajmuneer123/anand_python_problems | /2_chapter/factorial.py | 412 | 4.1875 | 4 | #Problem 5: Write a function factorial to compute factorial of a number. Can you use the product function defined in the previous example to compute factorial?
array=[]
def factorial(number):
while number!=0:
array.append(number)
number=number-1
return array
def product(num):
mul=1
a=len(num)
while a!=0:
m... | true |
38171858be0fc89461f6e38bb85d7585c18525c1 | LTTTDH/dataScienceHelpers | /NaNer.py | 477 | 4.125 | 4 | # This function was created to deal with numerical columns that contain some unexpected string values.
# NaNer converts all string values into np.nans
def NaNer(x):
"""Takes a value and converts it into a float.
If ValueError: returns np.nan
Originally designed to use with pandas DataFrames.
... | true |
ee9d018f5a7fd7e23e66f972c0ab3aa8f8d19e27 | PingryPython-2017/black_team_palindrome | /palindrome.py | 823 | 4.28125 | 4 | def is_palindrome(word):
''' Takes in an str, checks to see if palindrome, returns bool '''
# Makes sure that the word/phrase is only lowercase
word = word.lower()
# Terminating cases are if there is no characters or one character in the word
if len(word) == 0:
return True
if len(word) == 1:
return Tru... | true |
be832202e22425289126c594a6c5649cff49d533 | dan76296/stopwatch | /stopwatch.py | 1,495 | 4.25 | 4 | import time
class StopWatch:
def __init__(self):
''' Initialises a StopWatch object'''
self.start_time = None
self.end_time = None
def __repr__(self):
'''Represents the object in a readable format'''
return 'Time Elapsed: %r' % ':'.join((self.convertSeconds(self.resul... | true |
aa08a6475f125520389646b0551301a54dafcf89 | GitFiras/CodingNomads-Python | /03_more_datatypes/3_tuples/03_16_pairing_tuples.py | 992 | 4.4375 | 4 | '''
Write a script that takes in a list of numbers and:
- sorts the numbers
- stores the numbers in tuples of two in a list
- prints each tuple
Notes:
If the user enters an odd numbered list, add the last item
to a tuple with the number 0.
'''
# sort numbers
numbers_ = [ 1, 5, 4, 67, 88, 99, 3, 2, 12]
num... | true |
be616a73c1e05410a1461277824f37d45e8a3d24 | GitFiras/CodingNomads-Python | /13_aggregate_functions/13_03_my_enumerate.py | 693 | 4.3125 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
def my_enumerate():
index = 0
value_list = ['apple', 'banana', 'pineapple', 'orange', 'grape'] # list
for value in value_list: ... | true |
64c9d551092b05a7d1fc1b4919403731cb2aa07d | GitFiras/CodingNomads-Python | /04_conditionals_loops/04_01_divisible.py | 473 | 4.40625 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
num = int(input('Please provide a number between 1 and 1,000,000,000: '))
if num % 3 == 0: # if output is 0, the numb... | true |
48550e1cb00bf023ec1394a0d0c8116fa0c8c456 | GitFiras/CodingNomads-Python | /06_functions/06_01_tasks.py | 2,146 | 4.25 | 4 | '''
Write a script that completes the following tasks.
'''
# define a function that determines whether the number is divisible by 4 or 7 and returns a boolean
print("Assignment 1 - Method 1:")
def div_by_4_or_7(x):
if x % 4 == 0:
print(f"{x} is divisible by 4: ",True) # boolean True if func... | true |
3ad789eadbc061a3dafa8af235e28282e659ad63 | GitFiras/CodingNomads-Python | /09_exceptions/09_05_check_for_ints.py | 669 | 4.625 | 5 | '''
Create a script that asks a user to input an integer, checks for the
validity of the input type, and displays a message depending on whether
the input was an integer or not.
The script should keep prompting the user until they enter an integer.
'''
while True:
try:
user_input = input("Please provide ... | true |
c43746c218b0df727e187614f7859b0146575356 | GitFiras/CodingNomads-Python | /03_more_datatypes/4_dictionaries/03_20_dict_tuples.py | 506 | 4.3125 | 4 | '''
Write a script that sorts a dictionary into a list of tuples based on values. For example:
input_dict = {"item1": 5, "item2": 6, "item3": 1}
result_list = [("item3", 1), ("item1", 5), ("item2", 6)]
'''
input_dict = {"item1": 5, "item2": 6, "item3": 1}
list_ = []
# Iteration from dict to list with tuples
for i i... | true |
20acb5c9c5b63cfb04b70a82a815027e856fb517 | GitFiras/CodingNomads-Python | /Inheritance - Course Example Code.py | 1,361 | 4.46875 | 4 | class Ingredient:
"""Models an Ingredient."""
def __init__(self, name, amount):
self.name = name
self.amount = amount
def expire(self):
"""Expires the ingredient item."""
print(f"whoops, these {self.name} went bad...")
self.name = "expired " + self.name
def __str__(self):
return f"You h... | true |
f39fadba2f9d57dd9c9f59c827619f891d579fa4 | SnehaMercyS/python-30-days-internship-tasks | /Day 7 task.py | 1,734 | 4.125 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #1) create a python module with list and import the module in anoother .py file and change the value in list
>>> list=[1,2,3,4,5,6]
>>> import m... | true |
81af9ef448d9228b34e6c8017b034ccd6405d9ea | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Arrays/2dArrays.py | 1,025 | 4.125 | 4 | import os
# Create a 2D array and print some of their elements.
studentGrades = [[72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60]]
print(studentGrades[1])
print(studentGrades[0])
print(studentGrades[2])
print(studentGrades[3][4])
# Traverse the array.
for st... | true |
ba5b7564b61ea7d0bacdfcb2ac19024a39f163ae | clopez5313/Python | /1. Become a Python Developer/4. Programming Foundations - Data Structures/Stacks and Queues/sortingQueues.py | 730 | 4.15625 | 4 | import queue
# Create the object and add some elements to it.
myQueue = queue.Queue()
myQueue.put(14)
myQueue.put(27)
myQueue.put(11)
myQueue.put(4)
myQueue.put(1)
# Sort with Bubble Sort algorithm.
size = myQueue.qsize()
for i in range(size):
# Remove the element.
item = myQueue.get()
#Remove the next... | true |
ec94e882ff4f039bad9c0785c6d615c445cb706b | shyboynccu/checkio | /old_library/prime_palindrome.py | 1,877 | 4.28125 | 4 | #!/usr/local/bin/python3
# An integer is said to be a palindrome if it is equal to its reverse in a string form. For example, 79197 and 324423 are palindromes. In this task you will be given an integer N. You must find the smallest integer M >= N such that M is a prime number and M is a palindrome.
# Input: An integer... | true |
48798e1b51baefc7c23b92cf86b34eef35313cee | emilnorman/euler | /problem007.py | 493 | 4.15625 | 4 | # !/usr/bin/python
# -*- coding: utf-8 -*-
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
#
# What is the 10 001st prime number?
def next_prime(p):
temp = p + 2
for i in xrange(3, temp, 2):
if ((temp % i) == 0):
return next_prime(t... | true |
05bd5cba24b50221d83ae84bee8958dff9b2c7ae | rsoemardja/Python | /PythonAndPygameArcade/Chapter 3 Quiz Games and If Statements/3.2/PythonOrder/PythonOrder/test.py | 996 | 4.3125 | 4 | # we are going to be taking a look at logic with if Statements
# Their is actually a hidden error
# The error is that computer looks at each statement
# and is 120 > 90. It is indeed and the else would execute but the else DID not excute hence the logic error
temperature=input("What is the temperature in Fahrenheit? ")... | true |
313c45fa97a1c12eee440966216c3904f549cd07 | KDRGibby/learning | /nthprime.py | 781 | 4.46875 | 4 | def optimusPrime():
my_list = [1,2]
my_primes = []
prime_count = 0
# this is supposed to add numbers to my_list until the prime count reaches x numbers.
while prime_count < 10:
last_num = my_list[-1]
my_list.append(last_num + 1)
#here we check to see if a number in my_list is a prime
for i in my_list:
... | true |
e170befde825656d17d5b17b81cd51d3c0f09c55 | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/P/P-1.36.py | 294 | 4.125 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python program that inputs a list of words, separated by whitespace,
and outputs how many times each word appears in the list. You
need not worry about efficiency at this point, however, as this topic is
something that will be addressed later in this book
""" | true |
fbef3fb244b0ecb1c97a293c1f9e029fe3273f6f | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 2/R/R-2.4.py | 426 | 4.3125 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number
of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your c... | true |
3d1efee5bd503d5503ecafc36e40b60ef833fb7c | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/R/R-1.1.py | 590 | 4.40625 | 4 | #-*-coding: utf-8 -*-
"""
Write a short Python function, is_multiple(n, m), that takes two integer
values and returns True if n is a multiple of m, that is, n = mi for some
integer i, and False otherwise
"""
def is_multiple(n, m):
n = int(n)
m = int(m)
if n % m == 0 and n != 0:
return True
els... | true |
092eca02e6e2d164b20444d05b2c328e0b548cb6 | allenxzy/Data-and-Structures-and-Alogrithms | /python_data/Chapter 1/P/P-1.32.py | 395 | 4.21875 | 4 | #-*-coding: utf-8 -*-
"""
Write a Python program that can simulate a simple calculator, using the
console as the exclusive input and output device. That is, each input to the
calculator, be it a number, like 12.34 or 1034, or an operator, like + or =,
can be done on a separate line. After each such input, you should o... | true |
88f2f7683025b2fcbcc0006b279bce698743d10b | himanshu2801/leetcode_codes | /sort colors.py | 912 | 4.15625 | 4 | """
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Follow up:
Could you solve thi... | true |
96ffd6f2d96e810840f4e8aab3bd3d5968f600ba | bitomann/classes | /pizza_joint.py | 1,322 | 4.625 | 5 | # 1. Create a Pizza type for representing pizzas in Python. Think about some basic
# properties that would define a pizza's values; things like size, crust type, and
# toppings would help. Define those in the __init__ method so each instance can
# have its own specific values for those properties.
class Pizza:
d... | true |
c05f369e874662f1f383cd25148e99c980f37d49 | Vohsty/password-locker | /user.py | 1,472 | 4.21875 | 4 | class User:
"""
Class to generate new instances of users
"""
user_list= [] # Empty user list
def __init__(self, f_name, l_name, username, password):
'''
To take user input to create a new user
'''
self.f_name = f_name
self.l_name = l_name
self.usernam... | true |
3f6e66a5e45651ee7fe6dd0454f771b6343edc29 | davidjbrossard/python | /hello.py | 669 | 4.3125 | 4 | import math as m
"""
This method takes in a string and returns another string. It encrypts the content of the string by using the Caesar cipher.
"""
def encrypt(message, offset):
encryptedString = "";
for a in message:
encryptedString+=chr(ord(a)+offset);
return encryptedString;
"""
This method ta... | true |
9473f6456519749d1b687bc83cf290e9d31316cf | KoushikRaghav/commandLineArguments | /stringop.py | 1,399 | 4.125 | 4 | import argparse
def fileData(fileName,stringListReplace):
with open(fileName,'w') as f:
f.write(str(stringListReplace))
print stringListReplace
def replaceString(replace,stringList,fileName,word):
rep = replace.upper()
stringListReplace = ' '
for w in stringList:
stringListReplace = w.replace(word, re... | true |
5ce58dda0c9928a43e3463e7447ce63f404c5e51 | brickfaced/data-structures-and-algorithms | /challenges/multi-bracket-validation/multi_bracket_validation.py | 2,197 | 4.34375 | 4 | class Node:
"""
Create a Node to be inserted into our linked list
"""
def __init__(self, val, next=None):
"""
Initializes our node
"""
self.val = val
self.next = next
def __repr__(self, val):
"""
Displays the value of the node
"""
... | true |
d1f9324a011cbbe33a65a2005115e06ab86f74d1 | brickfaced/data-structures-and-algorithms | /data-structures/binary_search_tree/fizzbuzztree.py | 602 | 4.5625 | 5 | def fizzbuzztree(node):
"""
Goes through each node in a binary search tree and sets node values to
either Fizz, Buzz, FizzBuzz or skips through them depending if they're
divisible by 3, 5 or both. The best way to use this function is to
apply it to a traversal method. For example: BST.in_order(fizzb... | true |
0a748373a51802c7500f8b6bd72cbd44d3f467d9 | brickfaced/data-structures-and-algorithms | /data-structures/hash_table/repeated_word.py | 857 | 4.125 | 4 | """Whiteboard Challenge 31: Repeated Word"""
from hash_table import HashTable
def repeated_word(text):
"""
Function returns the first repeated word.
First thing it does is splits the inputted string
into a list and for each word in that list it checks
if that word is already in the hash table, if ... | true |
b26893e0db5a57db2eed7de038eedc67337aecbf | abhaysingh00/PYTHON | /even odd sum of 3 digit num.py | 307 | 4.21875 | 4 | n= int(input("enter a three digit number: "))
i=n
sm=0
count=0
while(i>0):
count=count+1
sm=i%10+sm
i=i//10
if(count==3):
print(sm)
if(sm%2==0):
print("the sum is even")
else:
print("the sum is odd")
else:
print("the number entered is not of 3 digits")
| true |
7bd2f2e61e7a2728c265e2606e06fc8e95e6d7e3 | aman1698/Semester-5 | /SEE/1/1a.py | 728 | 4.125 | 4 | def insert():
l=[]
while(True):
print("1-insert an element\n2-exit")
n=int(input())
if(n==1):
print("Enter the element")
n1=int(input())
l.append(n1)
else:
return l
l1=insert()
#l1=input().split()
print("Original List: ",l1)
l1.sort()
l2=len(l1)
print("Maximum Element ",l1[l2-1])
print("Minimum ... | true |
8b83fbcfd31ba3cc1676ee16906a6bbd2935af98 | sanketsoni/6.00.1x | /longest_substring.py | 796 | 4.375 | 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 |
72f2fa7a7980edb279f23269173545890ebd360b | mohor23/code_everyday | /binary_search(recursive).py | 701 | 4.125 | 4 | //binary search using recursion in python
def binary_search(arr,l,h,number):
if l<=h:
mid=(l+h)//2
if(arr[mid]==number):
return mid
elif(number<arr[mid]):
binary_search(arr,l,mid-1,number)
else:
binary_search(arr,mid+1,h,number)
else:
r... | true |
8b6df693a8931d87148817973e68ef401f524d73 | xuefengCrown/Learning-Python | /Beginning Python/database.py | 2,953 | 4.15625 | 4 | # Listing 10-8. A Simple Database Application
# database.py
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
pid = raw_input('Enter unique ID number: ')
person = {}
person['name'] = raw_input('Enter name: ')
person['age'] = raw_input('Enter age: ')
pe... | true |
fafaffc7c97297e40be44fb5b0bd2b77b6bfb4e2 | InfinityTeq/Introduction-to-Python3 | /module05/m5-practice/data-comparison.py | 902 | 4.15625 | 4 | # for this module's practice:
# we will use sets to compare data
# created by : C0SM0
# sets of animals that can live on land and sea [respectively]
can_live_on_land = {"Wolves", "Alligator", "Deer"}
can_live_in_sea = {"Fish", "Dolphin", "Alligator"}
# create terrestial specific sets for the creature types
land_crea... | true |
534f12658f7dffa0efca11c00226adb79df46c76 | InfinityTeq/Introduction-to-Python3 | /module03/m3-practice/multiplication-tables.py | 682 | 4.4375 | 4 | # for this module's practice:
# we will make a program that will generate multiplication tables
# created by : C0SM0
# variables
range_limit = range(1, 13)
# iterate through each table
for table_number in range_limit:
# banner
print(f"\nMultiplication Table for {table_number}:")
# iterate through each ... | true |
8219a19e2e78f610f4acdff4d3139c5b65d36642 | mhamzawey/DataStructuresAlgorithms | /InsertionSort.py | 665 | 4.28125 | 4 | from BinarySearch import binarySearch
def insertionSort(arr):
"""
Insertion sort is a simple sorting algorithm
that works the way we sort playing cards in our hands.
:param arr:
:return: arr
Complexity O(n^2
"""
for i in range(len(arr)):
current = arr[i]
j ... | true |
af531dfc2e22c0b2ef6500bb74b484331f2c6ac7 | chokkalingamk/python | /Bitwise_operators.py | 588 | 4.28125 | 4 | #This is the Bitwise program to check
print ("Welcome to Addition Calculator")
print ("Enter the value A")
a = int(input())
print ("Enter the value B")
b = int(input())
and_val = (a & b)
or_val = (a | b)
xor_val = (a ^ b)
#not_val = (a ~ b)
left_val = (a << b)
right_val = (a >> b)
print ("The value of A is ", a )
print... | true |
955ba7fa1d1b396827c775318180d15ccf0b0ffe | ambateman/TechAcademy | /Python/PyDrill_Datetime_27_idle.py | 732 | 4.125 | 4 | #Python 2.7
#Branches open test
#Drill for Item 62 of Python Course
#
#The only quantity that should matter here is the hour. If the hour is between 9 and 21
#for that office, then that office is open.
import datetime
portlandTime = datetime.datetime.now().hour
nyTime = (portlandTime + 3)%24 #NYC is three hou... | true |
dc46be41cfc4becb94a1eeaec36fc098942b9fd7 | devyanshi-t/Contibution | /Codes/case.py | 493 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 10:25:35 2020
@author: devyanshitiwari
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.
"""
def swap_case(s):
x=""
for i in s:
if i.islower... | true |
71e368e81fee53211cfecaed497d06a3b385f703 | eventuallyrises/CS61A | /hw1_q4.py | 624 | 4.125 | 4 | """Hailstone Sequence problem"""
def hailstone(n):
"""Print the hailstone sequence starting at n and return its length.
>>> a = hailstone(10) # Seven elements are 10, 5, 16, 8, 4, 2, 1
10
5
16
8
4
2
1
>>> a
7
"""
assert n > 0, 'Seed number %d is not greater than 0'... | true |
b457618da678f79c59ceb9b6e191e5c6a18df933 | Vivekyadv/InterviewBit | /Tree Data Structure/2 trees/1. merge two binary tree.py | 2,064 | 4.15625 | 4 | # Given two binary tree A and B. merge them in single binary tree
# The merge rule is that if two nodes overlap, then sum of node values is the new value
# of the merged node. Otherwise, the non-null node will be used as the node of new tree.
# Tree 1 Tree 2 Merged Tree
# 2 3 ... | true |
edcd7c026b3fd1a6122be4e78f13a77516a9c9e2 | Vivekyadv/InterviewBit | /String/String math/4. power of 2.py | 1,531 | 4.25 | 4 | # Find if Given number is power of 2 or not.
# More specifically, find if given num can be expressed as 2^k where k >= 1.
# Method 1: using log func
# 2 ^ k = num
# k*log(2) = log(num)
# k = log(num,2)
# if ceil value of k is equal to k then it can be expressed
num1 = "1024"
num2 = "1023"
from math import log, ceil
... | true |
cb1225395f4f4787d998a299bfa40e077da4421c | hualili/opencv | /deep-learning-2020S/20-2021S-0-2slicing-2021-2-24.py | 2,631 | 4.21875 | 4 | """
Program: 2slicing.py
Coded by: HL
Date: Feb. 2019
Status: Debug
Version: 1.0
Note: NP slicing
Slicing arrays, e.g., taking elements from one given index to another given index.
(1) pass slice instead of index as: [start:end].
(2) define the step like: [start:end:step].
(3) if we don't pass start its considered 0, ... | true |
894e677b208321a842d980a623f9a00bdee2ecea | gan3i/CTCI-Python | /Revision/LinkedList/remove_duplicates_2.1_.py | 2,738 | 4.15625 | 4 |
#ask questions
# 1. is it a doubly linked list or singly linked list
# 2. what type of data are we storing, integer? float? string? can there be negatives,
class Node():
def __init__(self,data):
self.data = data
self.next = None
# in interview do not write the linked list class assume that it's g... | true |
6169a5437d4ea11923d0857763dbc8c26ab8fc10 | lonely7yk/LeetCode_py | /LeetCode484FindPermutation.py | 2,821 | 4.21875 | 4 | """
By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a
decreasing relationship between two numbers, 'I' represents an increasing relationship between
two numbers. And our secret signature was constructed by a special integer array, which contains
uniquely all the different... | true |
1ffd9e7ad58b95c2cc0ea50932209de8ce1218c2 | lonely7yk/LeetCode_py | /LeetCode425WordSquares.py | 2,901 | 4.15625 | 4 | """
Given a set of words (without duplicates), find all word squares you can build from them.
A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns).
For example, the word sequence ["ball","area","lead","lady"] forms a word square bec... | true |
b336e49c34dff2b02b7fd80f3f1ef8ab12513ec5 | lonely7yk/LeetCode_py | /LeetCode401BinaryWatch.py | 2,155 | 4.1875 | 4 | """
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom
represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads "3:25".
Given a non-negative integer n which represents the... | true |
8c36c1856f7a002736f85d36d5b6af586b613faf | lonely7yk/LeetCode_py | /LeetCode1000/LeetCode1363LargestMultipleofThree.py | 2,572 | 4.25 | 4 | """
Given an integer array of digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order.
Since the answer may not fit in an integer data type, return the answer as a string.
If there is no answer return an empty string.
Example 1:
Input: digits = [8,1,9]
... | true |
07f16a7a3c94ffb901cfa58800c1ea6d43c01ba2 | lonely7yk/LeetCode_py | /LeetCode080RemoveDuplicatesfromSortedArrayII.py | 2,097 | 4.125 | 4 | """
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most
twice and return the new length.
Do not allocate extra space for another array; you must do this by modifying the input array
in-place with O(1) extra memory.
Clarification:
Confused why the returned value is an int... | true |
2ad306d0b108ae285a558caf7a29d762f3a2caee | devendrapansare21/Python-with-Lets-Upgrage | /Assignment_Day-4.py | 693 | 4.1875 | 4 | '''Program to find number of 'we' in given string and their positions in string '''
str1="what we think we become ; we are Python pragrammers"
print("Total number of 'we' in given string are ", str1.count("we"))
print("position of first 'we'--> ",str1.find("we"))
print("position of last 'we'--> ",str1.rfind("we... | true |
48021044a11b7c223777765d4586f343212bc0ac | dasszer/sudoki | /sudoki.py | 2,445 | 4.15625 | 4 | import pprint
# sudoki.py : solves a sudoku board by a backtracking method
def solve(board):
"""
Solves a sudoku board using backtracking
:param board: 2d list of ints
:return: solution
"""
find = find_empty(board)
if find:
row, col = find
else:
return True
for i i... | true |
a1f9631072c3e8da6a46de97db2cb0a3b9bcdb99 | priyatharshini23/2 | /power.py | 217 | 4.4375 | 4 | # 2
num=int(input("Enter the positive integer:"))
exponent=int(input("Enter exponent value:"))
power=1
i=1
while(i<=exponent):
power=power*num
i=i+1
print("The Result of{0}power{1}={2}".format(num,exponent,power)
| true |
6730b03c1a640ce24dcca9a2a335906295209339 | rajasekaran36/GE8151-PSPP-2020-Examples | /unit2/practice-newton-squareroot.py | 362 | 4.3125 | 4 | print("Newton Method to find sq_root")
num = int(input("Enter number: "))
guess = 1
while(True):
x = guess
f_x = (x**2) - num
f_d_x = 2*x
actual = x - (f_x/f_d_x)
actual = round(actual,6)
if(guess == actual):
break
else:
print("guess=",guess,"actual=",actual)
guess = ... | true |
70d0f8c4cc2fc8bb64513fa5b4350501a0812ad7 | Aamir-Meman/BoringStuffWithPython | /sequences/reduce-transforming-list.py | 646 | 4.15625 | 4 | """
The reduce function is the one iterative function which can be use
to implement all of the other iterative functions.
The basic idea of reduce is that it reduces the list to a single value.
The single value could be sum as shown below, or any kind of object including a new list
"""
from _functools import reduce... | true |
067c7fea36ae0de1ac94277db2f3215270a1040d | Tiger-a11y/PythonProjects | /dict Exercise.py | 479 | 4.21875 | 4 | # Apni Dictionary
dict = { "Set" : "Sets are used to store multiple items in a single variable.",
"Tuples" : "Tuples are used to store multiple items in a single variable.",
"List" : "Lists are used to store multiple items in a single variable.",
"String" : "Strings in python are surrounded b... | true |
0d19edda62a7a9a5d74f0cd59405eb82cbaa924f | sankalpg10/GAN_Even_Num_Generator | /dataset.py | 1,240 | 4.125 | 4 | import math
import numpy as np
def int_to_bin(number: int) -> int:
# if number is negative or not an integer raise an error
if number < 0 or type(number) is not int:
raise ValueError("only positive integers are allowed")
# converts binary number into a list and returns it
return [... | true |
75764f96681592643f63082b017aa4c1a64d5e56 | justawho/Python | /TablePrinter.py | 620 | 4.25 | 4 | ## A function named printTable() that rakes a list of lists of strings and
## displays it in a well-organized table
def printTable(someTable):
colWidths = [0] * len(someTable)
for j in range (len(someTable[0])):
for i in range(len(someTable)):
colWidths[i] = len(max(someTable[i], key=len))
... | true |
92f7400e1ffa24879e1626c42e1e5c21c2e4eda8 | eshthakkar/coding_challenges | /bit_manipulation.py | 1,108 | 4.125 | 4 | # O(n^2 + T) runtime where n is the total number of words and T is the total number of letters.
def max_product(words):
"""Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters.
You may assume that each word will contain only l... | true |
3e6f61f56ba8f3973be04896b5827c9bf99f664b | eshthakkar/coding_challenges | /rectangle_overlap.py | 1,895 | 4.1875 | 4 | # Overlapping rectangle problem, O(1) space and time complexity
def find_rectangular_overlap(rect1, rect2):
""" Find and return the overlapping rectangle between given 2 rectangles"""
x_overlap_start_pt , overlap_width = find_range_overlap(rect1["x_left"], rect1["width"], rect2["x_left"], rect2["width"])
y... | true |
49421b3c6d6cd17108c8a9ef1c58130c2c531d3e | eshthakkar/coding_challenges | /kth_largest_from_sorted_subarrays.py | 676 | 4.125 | 4 | # O(k) time complexity and O(1) space complexity
def kth_largest(list1,list2,k):
""" Find the kth largest element from 2 sorted subarrays
>>> print kth_largest([2, 5, 7, 8], [3, 5, 5, 6], 3)
6
"""
i = len(list1) - 1
j = len(list2) - 1
count = 0
while count < k:
if list1... | true |
2dfff17f70a01dcaf4d742352055b160fbc06669 | jimibarra/cn_python_programming | /miniprojects/trip_cost_calculator.py | 396 | 4.375 | 4 | print("This script will calculate the cost of a trip")
distance = int(input("Please type the distance to drive in kilometers: "))
usage = float(input("Please type the fuel usage of your car in liters/kilometer: "))
cost_per_liter = float(input("Please type the cost of a liter of fuel: "))
total_cost = cost_per_liter *... | true |
a9cfee9934cc75445451574cfc4878cb11d39f4d | jimibarra/cn_python_programming | /07_classes_objects_methods/07_02_shapes.py | 1,539 | 4.625 | 5 | '''
Create two classes that model a rectangle and a circle. The rectangle class should
be constructed by length and width while the circle class should be constructed by
radius.
Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle),
perimeter (of the rectangle) and cir... | true |
b1b191321e4f71bf57f4052aaa91cb01c8d60501 | jimibarra/cn_python_programming | /07_classes_objects_methods/07_01_car.py | 1,075 | 4.53125 | 5 | '''
Write a class to model a car. The class should:
1. Set the attributes model, year, and max_speed in the __init__() method.
2. Have a method that increases the max_speed of the car by 5 when called.
3. Have a method that prints the details of the car.
Create at least two different objects of this Car class and dem... | true |
8c1053a3d6092c244c89f36e11d60cc63b1d9090 | jimibarra/cn_python_programming | /03_more_datatypes/2_lists/03_11_split.py | 540 | 4.40625 | 4 | '''
Write a script that takes in a string from the user. Using the split() method,
create a list of all the words in the string and print the word with the most
occurrences.
'''
user_string = input("Please enter a string: ")
my_list = user_string.split(" ")
print(my_list)
my_dict = {}
my_set = set(my_list)
for item ... | true |
900c1185f0af45dd797ce33c0e0ce11fb759a449 | jimibarra/cn_python_programming | /02_basic_datatypes/2_strings/02_09_vowel.py | 991 | 4.4375 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
#Total Vowel Count
vowel = ['a', 'e', 'i', 'o', 'u']
stri... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.