blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ee4770920fb96f25fea3462b58418c4919891758 | tberhanu/elts-of-coding | /Sorting/sort_linked_list.py | 844 | 4.1875 | 4 | def sort_linked_list(ll):
"""
Strategy:
1. Loop through the linked list and append each Node to the ARRAY, O(N), since looping through N
number of Nodes, and APPENDING to Array takes only O(1), unlike INSERTING w/c takes O(N).
2. Sort the array in REVERSE OREDER i.e. a... | true |
f46cec3b67374f498a85f493aa0e90b10a4094fe | tberhanu/elts-of-coding | /GreedyAlgorithms/two_sum.py | 1,386 | 4.125 | 4 | def two_sum(arr, target):
"""
Given a sorted array of integers, and a target value, get two numbers that adds up to the TARGET.
Strategy 1: Brute-force: Double for loop checking each and every pair: O(N * N)
Strategy 2: HashTable: Putting the arr in HashTable or SET, and check if (Target - e) found in H... | true |
b49ddda99c07271539c9bfd92ea9b63d8d1dfc34 | tberhanu/elts-of-coding | /Searching/search_sorted_matrix.py | 1,862 | 4.21875 | 4 | def search_sorted_matrix(matrix, num):
"""
Question: Given a sorted 2D array, matrix, search for NUM
SORTED MATRIX: means each ROW is increasing, and each COL is increasing
Solution:
Brute-force approach of looping thru the double array takes O(N * N)
Smart approach is:
1. Gr... | true |
f6ca9a0bd17be2e8f4547a2f65b94b546e33a3e9 | tberhanu/elts-of-coding | /GreedyAlgorithms/optimum_task_assignment.py | 1,076 | 4.3125 | 4 | def optimum_task_assignment(task_durations):
"""
Consider assigning tasks to workers where each worker must be assigned exactly TWO TASKS, and each task has a
fixed amount of time it takes.
Design an algorithm that takes as input a set of tasks and returns an optimum assignment.
Note: Simply enumer... | true |
45677c2998c579fefea3630fde8fc71beb5c5f37 | tberhanu/elts-of-coding | /Arrays/even_odd.py | 863 | 4.28125 | 4 | def even_odd(arr):
"""
Page 37.
Rearranging evens first and odds later.
Time Complexity: O(N)
Space Complexity: O(1)
arr = [2, 3, 4, 5, 6, 7, 8, 3, 0, 2, 4, 5]
:returns: [2, 4, 6, 8, 0, 2, 4, 3, 5, 7, 5, 5]
"""
i, j = 0, 0
while j < len(arr) - 1:
if arr[i] % 2 == 0:
... | false |
caccbb5a383caf682478494c3288e2f45424e298 | jimmy1087/codeKatas | /sorting/bubbleSort.py | 836 | 4.21875 | 4 | '''
o(n^2) 5 * 5 = 25 steps to sort an array of 5 elements that were in desc order.
'''
def bubbleSort(array):
steps = 0
outerLoop = 1
sorted = False
sortedElements = 0
while not sorted:
steps += 1
print('[[loop]]', outerLoop)
outerLoop += 1
sorted = True
for... | true |
6e131e58dba3ebaa6ffb342e6ab3d7f0023d646a | eriksLapins/datu_analize_kursi | /Day7_Dicts_files/day7_uzd1.py | 1,289 | 4.1875 | 4 | #%% my version
# uztaisīt tā, lai lietotājs ievada informāciju par studentu, jāsagatavo vārdnīca un jāizvada informācija
# visa ievade un izvade notiek main funckijā, bet visa loģika - vārdnīcas sagatavošana un atgriešana notiek citā failā
from day7_uzd1_logic import create_dict_student
def create_student():
... | false |
9e5e40c15f41762cf4fcc76c484260d6bcebb9f1 | bradg4508/self_taught_challenges | /chp_4.py | 1,479 | 4.4375 | 4 | #1
def square(x):
"""
Returns x^2.
:param x: int.
:return: int x raised to the second power.
"""
return x**2
print(square(2))
#2
def print_string(word):
"""
Prints a string passed in by user.
:param word: str.
"""
print(word)
print_string("This is a sent... | true |
924f623d0dae965902aba3b2c4d2abc9e14d3e4e | marcovnyc/penguin-code | /1000_exercises/1000_exercises_02.py | 563 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 3 22:59:33 2021
@author: Marco M
"""
print("Let's calculate the area of a rectangle")
print("Formula: A = w * l")
print("Enter width and height")
width_value = int(input("enter width -> "))
height_value = int(input("enter height -> "))
area = wi... | true |
cc2b260b8fe52136b91c440c2b264dd1ef93e126 | marcovnyc/penguin-code | /Impractical-Python-Projects/chapter_8_9/syllable_counter.py | 2,095 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 17 16:29:46 2019
@author: toddbilsborough
Project 15 - Counting Syllables from Impractical Python Projects
Objective
- Write a Python program that counts the number of syllables in an
English word or phrase
Notes
- First experience with natural l... | true |
91e78752c499744a110c0dc947a52cfbf60a0594 | utep-cs-systems-courses/python-intro-ecrubio | /wordCount.py | 2,127 | 4.125 | 4 | import sys # command line arguments
import re # regular expression tools
import os # checking if file exists
#Checking that the correct format is used when running the program.
#When running the file it should also have the input and output files in the argument
def argumentCheck():
if len(... | true |
d4cded95c436c9973d914324a537690e1e2b0060 | MohamedGassem/ai_for_tetris | /src/AI/metrics.py | 2,554 | 4.125 | 4 | import numpy as np
def compute_holes(board):
"""
Compute the number of holes in the board
Note: a hole is defined as an empty cell with a block one or more
blocks above
Parameters
----------
board: 2d array_like
The tetris board
... | true |
c10bacef9eab1132af932f4aeae83d954093cc7f | burnacct36/lpthw | /ex29.py | 756 | 4.3125 | 4 | # An if-statement creates what is called
# a "branch" in the code. The if-statement
# tells your script, "If this boolean expression
# is True, then run the code under it, otherwise skip it."
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "No... | true |
0540e9ef0c4fd0a078d4c36d7e52f87996b171e6 | Davie704/My-Beginner-Python-Journey | /IfStatementsBasic.py | 1,048 | 4.21875 | 4 | # If statement basics
# Ex 1
salary = 8000
if salary > 5000:
print("My salary is too low!")
else:
print("My salary is above average, its okay right now.")
# Ex 2
age = 55
if age > 50:
print("You're a senior Developer, for sure!")
elif age > 40:
print("You're more than 40 years old.")
el... | true |
71a34df3b3807a67a682d0ff908b5d4c3cdf07c8 | Davie704/My-Beginner-Python-Journey | /Variables.py | 1,241 | 4.5 | 4 | # My Learning Python Journey
# A simple string example
short_string_example = "Have a great week, Ninjas!"
print(short_string_example)
# Print the first letter of a string variable, index 9
first_letter_variable = "New York City"[9]
print(first_letter_variable)
# Mixed upper and lowercase variable
mixed_l... | true |
7b2270e4177a957ff674f6a17a22041910889efa | FarazMannan/Magic-8-Ball | /Magic8Ball.py | 2,755 | 4.1875 | 4 | import random
count = 0
# count = count + 1
print("Welcome to Faraz's Magic 8 Ball")
# Faraz, wrap the code below in a loop so the user can
# keep asking the magic 8 ball questions... Go!
# Challenge number 2 before we call it a day...
# create a variable to keep track of whether we should keep running
# the magi... | true |
66cfcfab59440263d4a5d8c583dacb8c00f0ef15 | PAPION93/python-playground | /01_python_basic/07-2-Inheritance.py | 1,473 | 4.5 | 4 | # 파이썬 클래스
# 상속, 다중상속
class Car:
"""Parent Class"""
def __init__(self, type, color):
self.type = type
self.color = color
def show(self):
return 'Car Class show()'
class BmwCar(Car):
"""Sub Class"""
def __init__(self, car_name, type, color):
super().__init__(type, co... | false |
562aab1605b9c5e77f75b11d9a3b74552ca2c5da | ProdigyX6217/interview_prep | /char_count.py | 251 | 4.4375 | 4 | user_str = input("Please enter a string: ")
# This variable will be used to hold the number of characters in the string.
count = 0
# This for loop adds 1 to count for each character in user_str.
for char in user_str:
count += 1
print(count) | true |
8851c47cc61d585a02bbe8ab035c3248afd5e3a6 | ProdigyX6217/interview_prep | /convert_degrees.py | 720 | 4.5 | 4 | celsius = int(input("Please enter an integer value for degrees celsius: "))
def fahrenheit(cel):
# To avoid the approximation error that would occur if the float 1.8 was used in the calculation, 1.8 * 10 is used
# instead, resulting in the integer 18. To balance this out, 32 is also multiplied by 10 to get... | true |
b679551cca213b2b705d70eff7e45b61c2b3f010 | karaspd/leetcode-problem | /python/6/ZigzagConversion.py | 1,477 | 4.15625 | 4 | """
6. ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a st... | true |
ada4a46a88954707cb958f23a0b13332d4ed37eb | shavvo/Projects | /Projects/PtHW_Ex/ex15_open_files.py | 668 | 4.25 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
# 'open' is a command that reads the files
# ( as long as you put the name of the file in
# the command line when you run the script)
print "Here is your file %r:" % filename
print txt.read()
# txt is the variable of object and the . (dot)
# is to add... | true |
b0ff17bb9b8e449491605256305d1873e21c322d | RedPython20/New-Project | /weight_conv.py | 460 | 4.3125 | 4 | #Weight Converter app
#Convert your weight to either pounds or kilos.
#This section gets the user's data
weight = input("How much do you weigh? ")
unit = input("(L)bs or (K)gs? ")
#Pounds to kilos
if unit == "L":
new_weight = int(weight) // 2.205
print("Your weight in kilos is : ", str(new_wei... | true |
54de09d1bfb95805012c167e2dfbe9dbe9fc3751 | MarkBenjaminKatamba/python_sandbox | /python_sandbox_starter/conditionals.py | 1,704 | 4.46875 | 4 | # If/ Else conditions are used to decide to do something based on something being true or false
c = 16
d = 16.4
# Comparison Operators (==, !=, >, <, >=, <=) - Used to compare values
# Simple if
# if c > d:
# print(f'{c} is greater than {d}')
# If/else
# if c > d:
# print(f'{c} is greater than {d}')
# else:
... | true |
a0261cafabef291f465553216412ee185a0a84ca | flash-drive/Python-First-Go | /Homework 2 Fall Time.py | 759 | 4.15625 | 4 | # Homework 2 Fall time
# Mark Tenorio 5/10/2018
# Write a program that determines the time it takes for an object
# to hit the ground from a given height
# Recall the kinematics equation:
# distance = velocity(initial) * t + (1/2)*acceleration*time^2
# Assume that velocity(initial) is zero m/s.
# Assume that... | true |
d9e16a8ffdcbac930cb679cce804e6d2478ddedc | flash-drive/Python-First-Go | /Homework 3 Weather Stats.py | 976 | 4.28125 | 4 | # Homework 3 Weather Stats
# Mark Tenorio 5/13/2018
# Write a program that takes in a list
# comprised of a vector and a string. Output the maximum and average
# of the vector and output the string.
# Import modules
from statistics import mean
import ast
# Function to output max, average, and string from ... | true |
c68142b091a3f615de97fc4aeb5a46cfac02f508 | flash-drive/Python-First-Go | /Classes.py | 1,440 | 4.46875 | 4 | #### Class ####
# Classes are blueprints where you can make objects
# Objects contain different variables and methods (function)
# Differences between a class and an object is that the values that belong
# to the variables are not defined. It will not refer to a specific object.
# class Robot:
# def intro... | true |
c974d7b78b2410ef05689f39ebe0ff1e277f44fc | RashiKndy2896/Guvi | /Dec19_hw31strong.py | 561 | 4.28125 | 4 | maximum = int(input(" Please Enter the Maximum Value: "))
def factorial(number):
fact = 1
if number == 0 or number == 1 :
return fact
for i in range(2, number + 1) :
fact *= i
return fact
for Number in range(1, maximum):
Temp = Number
... | true |
06ea689737eb486f770bec009b657f706d863656 | euphoria-paradox/py_practice | /2_helloworld_unicode.py | 289 | 4.25 | 4 | # This program displays the unicode encoding for 'Hello World!'
# Intro greeting
print('The Unicode encoding for \'Hello World!\' is: ')
# Output results.
print(ord('H'), ord('e'), ord('l'), ord('l'), ord('o'), ord(' '),
ord('W'), ord('o'), ord('r'), ord('l'), ord('d'), ord('!'))
| false |
75d9e3de14c2f7e2fda2de6f6be687625176f389 | euphoria-paradox/py_practice | /p_d_3/3_fruit_display.py | 346 | 4.34375 | 4 | # P1 3
# Program to display respective fruit name for
# the user input of Alphabets(A,B or C)
alphabet = input('Enter the character(A or B or C): ')
# checking for condition
if alphabet == 'A':
print('Apple')
elif alphabet == 'B':
print('Banana')
elif alphabet == 'C':
print('Coconut')
else:
... | true |
266cc73a414731724b29a33a8bf3aaba718ca3a4 | euphoria-paradox/py_practice | /p_d_3/monthly_mortgage.py | 1,647 | 4.46875 | 4 | # Home Loan Amortization
# This program calculates the monthly mortgage payments for a given loan amount
# term and range of interests from 3 to 18%
# the formula for determinig the mortgage is A/D
# A - original loan amount
# D - discount factor given by D = ((1+r)^n -1)/r(1+r)^n
# n- number of payments, r-inter... | true |
3341c9c72a7ed6f6233ca4eca015aa38020106ed | euphoria-paradox/py_practice | /p_d_3/3.3.1_sum_even.py | 274 | 4.1875 | 4 | # Addition of even numbers between 100 and 200
# Init
num = 100
sum_of_even = 0
# summing of even numbers using a while loop
while num <= 200:
sum_of_even += num
num += 2
# Display of result of addition
print('Sum of even numbers between 100 & 200:', sum_of_even) | true |
6b4ea4370106b2820c50f7d8f62f10498a1fbef7 | euphoria-paradox/py_practice | /p_d_3/lif_signs.py | 1,440 | 4.375 | 4 | # Life Signs
# This is a test program to that determines number of breaths
# and the number of heartbeats the person had in their life
# based on their age.
# The average respiration rate of people changes during different
# stages of development.
# the breath rates used are :
# Infant - 30-60 breaths per min
... | true |
a65ddcbd2e1e57a05a1e7573e821a4bec1418062 | CampbellD84/Sprint-Challenge--Data-Structures-Python | /reverse/reverse.py | 1,885 | 4.125 | 4 | class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.nex... | true |
bd92d14b3a8498cf4aadb39a31a3071d33c4d7c0 | AlexanderPoleshchuk/Docker-sort | /sorting.py | 381 | 4.125 | 4 | def bubble_sort(my_list):
last_index = len(my_list) - 1
for i in range(0, last_index):
for j in range(0, last_index - i):
if my_list[j] > my_list[j + 1]:
my_list[j], my_list[j + 1] = my_list[j + 1], my_list[j]
return my_list
if __name__ == '__main__':
example_list =... | false |
08a06f8bf0c3c4084f4e361c6294225f7f9f091f | damiati-a/CURSO-DE-PYTHON | /Mundo 1/aula 6.py | 976 | 4.21875 | 4 | # CONDIÇÕES
"""
if e else (se e senão)
se carro.esquerda()
bloco_v_
senão
bloco_f_
correto
if carro.esquerda():
bloco True
else:
bloco False
"""
"""
tempo = int(input('Quantos anos tem seu carro? '))
if tempo <=3:
print('carro novo')
else:
print('carro velho')
print('--FIM--')
... | false |
47e774c6d56bac7a2e0bb9e249e70a95c1b79542 | damiati-a/CURSO-DE-PYTHON | /Mundo 1/ex018.py | 514 | 4.125 | 4 | # Seno, Cosseno e Tangente
import math
an = float(input('Digite o angulo que deseja? '))
sen = math.sin(math.radians(an))
print('O angulo de {} tem o seno de {:.2f}'.format(an, sen))
cos = math.cos(math.radians(an))
print('O angulo de {} tem o cosseno de {:.2f}'.format(an, cos))
tan = math.tan(math.radians(an)... | false |
33ef25bcd74c64f23733386d5c48ebea36968d89 | rjdoubleu/GSU | /Design and Analysis of Algortithms/Python/Depth_First_Search.py | 1,943 | 4.15625 | 4 | # Python program to print DFS traversal from a given given graph
# Visits all verticies and computes their mean and variance
from collections import defaultdict
#from random import randint
# This class represents a directed graph using adjacency list representation
class Graph:
# Constructor
def __init... | true |
5a5a1b03c9b6fb68c07014256b34cf9e7af6d7e0 | vijaybnath/python | /vijay16.py | 464 | 4.21875 | 4 | energy = int(input('enter the number you want to convert '))
units = input('which type of convertion you want to do only (kw)kilowatts to watts , (kv) kilovolt to volt or (v)olt to watt ')
if (units == "kw"):
converted = energy * 1000
print(f"the converted energy = {converted} watt")
elif(units == "kv"):
co... | true |
1aa3363b36796f3672ff6db15c6771b93839c360 | RNTejas/programming | /Python_Flow_Control/Python Flow Control/8.For loop.py | 304 | 4.375 | 4 | print("Welcome to the For Loop")
"""
The computer can perform the repeated tasks very quickly or earlier like,
For Loop
While Loop
List Comprehension and Generators
it executes the block of code for each iterable
"""
parrot = "Norwegian Blue"
for character in parrot:
print(character)
| true |
e5d92fbeff64e9a91d4a94b2329a840970f77372 | RNTejas/programming | /Python_Flow_Control/Python Flow Control/1.if Statements.py | 742 | 4.25 | 4 | # the input function will returns the value as a string
# name = input("Please enter your name: ")
# age =int(input(f"How old are you, {name}?"))
# print(age) # this will print out the age but we can't add the string to this number
# print(f"{name}, is {age} Years old")
# age = int(age)
# print(2 + age * 10)
# ... | true |
a4a88d8eb3ab92368571017794feb22f99a1893d | byui-cse/cse210-student-solo-checkpoints-complete | /06-nim/nim/game/board.py | 2,039 | 4.3125 | 4 | import random
class Board:
"""A designated playing surface. The responsibility of Board is to keep track of the pieces in play.
Stereotype:
Information Holder
Attributes:
_piles (list): The number of piles of stones.
"""
def __init__(self):
"""The class constructor.
... | true |
7493c538d11bf91f27a028d505b5f3e98cf7f61e | UtsavRaychaudhuri/Learn-Python3-the-Hard-Way | /ex9.py | 446 | 4.125 | 4 | # assigning the variable
days="Mon Tue Wed Thu Fri Sat Sun"
# assigning to a variable but with new line inbuilt into the string
months="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
# printing
print("Here are the days:",days)
# printing
print("Here are the months:",months)
# Multiline string
print("""
There's something ... | true |
8857381167f42e0a633e6d27d17f1b3e70ecc8c9 | bergolho/curso_python_ufsj | /codes/grambery/sample_4/numpy_array_copy.py | 710 | 4.15625 | 4 | import numpy as np
def copy_by_reference ():
# Criando um array x
x = np.array([ 1., 2., 3.5 ])
# Agora o ponteiro 'a' aponta para o array 'x'
a = x
print("a")
print(a)
print("x")
print(x)
# Alterando o ultimo elemento de 'a'
a[-1] = 3
print("a")
print(a)
print("x")
print(x)
def copy_by_value ():
... | false |
79d97d8382aaf7b9993e108b7a2fa0580b6cf53b | Aaryan1734/RPS | /RPS.py | 1,758 | 4.21875 | 4 | # ROCK PAPER SCISSORS GAME
# Remember the rules:
# rock beats scissors
# scissors beats paper
# paper beats rock
import getpass
print("""Let's play a game of rock paper scissors!!
You'll need a partner to play this game.
To End the Game input any response other than rock, paper or scissors.""")
print(... | true |
bbced53efb44e572f6c919da5a7bd7b2dc510c8e | porregu/unit5 | /claswork8.py | 306 | 4.15625 | 4 | user_number = int(input("what number do you want to put?"))
while user_number!=1:
print(user_number)
if user_number%2==0:
user_number/=2
print("new number = ",user_number)# print the new number
else:
user_number=user_number*3+1
print("new number = ",user_number) | true |
1320d84cad763e584256cd1f8be502618534221b | Zchap1/Old_Python | /guess my number game.py | 645 | 4.125 | 4 | print ("\tWelcome to 'guess my numer'!")
print ("\n I'm thinking of a number between 1 and 1000.")
print ("Try to guess it in as few attempts as possible.\n")
# set the initial values
import random
the_number = random.randint(1, 1000)
#guess = int(input("take a guess: "))
guess = 0
tries = 0
#guessing loops5
while gue... | true |
b21dc12fd76fb85352c1ea0a9ebbed5ec9e730f1 | Jean13/convenience | /unscramble.py | 1,470 | 4.15625 | 4 | # Template for unscrambling words
# Compares a scrambled wordlist with original wordlist and unscrambles
unscrambled = []
def main():
readFiles()
# Read the original wordlist and the txt file with the scrambled words
def readFiles():
# Makes the words from the files available to the whole program
glob... | true |
4fcad62bea4bb3df5080548ab6e1ed117d7c747b | VolanNnanpalle/Python-Projects | /rock_paper_scissors.py | 1,650 | 4.46875 | 4 | # -*- coding: UTF-8 -*-
"""
Rock, Paper, Scissors Game
Make a rock-paper-scissors game where it is the player vs the computer. The computer’s answer will be randomly generated, while the program will ask the user for their input.
"""
from random import randint
#rock beats scissors
#paper beats rock
#scissors beats... | true |
dc7fd3fa3c12fc96a59261296a9d8b0bd097153b | yuvaraj950/pythonprogram | /averageof list.py | 247 | 4.15625 | 4 | #Take a list
list1 = [5,6,8,9,7,5]
#Average of number = sum of numbers in list /total members in list
length = len(list1)
print(length)
sum_list1 = sum(list1)
print(sum_list1)
#output
average_list1 = (sum_list1 / length)
print(average_list1) | true |
9d3f29045a19aaa700f9c4d46780013ca88eb829 | SameerShiekh77/Python-Tutorial | /tut11.py | 742 | 4.3125 | 4 | print("CALCULATOR DEVELOP BY IT EDUCATION\n\n\n\n")
num1 = int(input("Enter your first number: "))
num2 = int(input("Enter your second number: "))
op = input("Select your operator\n\t+\t-\t*\t/\t%\n")
if op == '+':
{
print("The sum of num1 and num2 is: ", num1 + num2)
}
elif op == '-':
... | false |
365898eb7874e64e2dcd5a04e21eb28b667ad119 | miguelhasbun/Proyecto-1_SI | /main.py | 871 | 4.15625 | 4 | from trie import *
from levenshtein import *
WORD_TARGET = sys.argv[1]
for word in WORDS:
trie.insert(word)
l = levenshtein()
if WORD_TARGET=="grep" or WORD_TARGET=="ping" or WORD_TARGET=="ls":
result = WORD_TARGET
else:
print ("Did you meant to say:",l.search(WORD_TARGET))
result = l.search(WORD_TA... | true |
7037a8f4a82695fdbc29207f80336fed27d15ec1 | alexander-mcdowell/Algorithms | /python/InsertionSort.py | 1,131 | 4.4375 | 4 | # Insertion Sort: Simple sorting algorithm that works relatively well for small lists.
# Worst-case performance: O(n^2) where n is the length of the array.
# Average-case performance: O(n^2)
# Best-case performance: O(n)
# Worst-case space complexity: O(1)
# Method:
# 1. Loop through the array. If array[i + 1] < ar... | true |
1781d10e402e177dec64720c36b491c8167acbdd | alexander-mcdowell/Algorithms | /python/ShellSort.py | 1,847 | 4.3125 | 4 | import math
# Shell sort: a variant of isertion sort that sorts via the use of "gaps."
# Worst-case complexity: O(n log n) where n is the length of the array.
# Average-case complexity: O(n^4/3)
# Best-case complexity: O(n^3/2)
# Worst-case space complexity: O(1)
# Method:
# 1. Initialize the gap values.
# 2. ... | true |
29a4361f03d95b3e5ace4e4b90c3d870a88e4794 | alexander-mcdowell/Algorithms | /python/ExponentiationSqr.py | 1,445 | 4.28125 | 4 | import math
# There are two algorithms here: Exponentiation by Squaring and Modulo of Exponentiation by Squaring.
# Both algorithms use O(log n) squarings and O(log n) multiplications.
# Exponentiation by Squaring: Quickly computes the value n^k by using properties of squaring.
# This method works because of the prop... | true |
ba99261bb0e910510ca11ab149de4e417a60495f | gauravdn47/SyllabusHandsOn | /chapter3_Python Operators and Expressions.py | 962 | 4.125 | 4 | # Expressions vs Statements
# Expression
4 + 5
4 * 9
True
False
# Statements
# If Condition
# Converting int to str and vice-versa
x = 5
type_of_x = type(x)
print(type_of_x)
y = str(x)
type_of_y = type(y)
print(type_of_y)
a = '5'
type_of_a = type(a)
print(type_of_a)
b = int(a)
type_of_b = typ... | false |
b89316b96fe7dfd9153ad9e474f2f9b9e6362f2d | imeixi/python_fishc_test | /020/closure.py | 881 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 如果在一个内部函数里,对在外部作用域的变量进行了引用,那么这个内部函数就被称为闭包。
def fun_x(x):
"""返回一个函数名,不加()"""
def fun_y(y):
return x * y
return fun_y #
# fun_y就是一个闭包
# 调用1,先返回一个函数
f = fun_x(8)
print(f)
result = f(5)
print(result)
# 调用2
print(fun_x(8)(10))
def fun1():
"""no... | false |
677b93fab786b8e3997ab0b8c42db26093ff6b20 | gaomigithub/Leetcode | /GraphValidTree.py | 1,696 | 4.25 | 4 | # Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
# For example:
# Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
# Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3],... | true |
5157bf522b57563d8d340a3c06e15863c5c43f7c | YooMo/PythonLearn | /python基础操作/LEARN2 字符串类型.py | 848 | 4.28125 | 4 | # PYTHON的数据类型
# 常见的数据类型
# 1.字符串类型
love = "i love u"
like = "你真棒"
helloworld = "你好 世界!"
print(love, helloworld, like)
# 大字符串可以换行,也很帅,也是str类型
# 大字符串还可以当注释使用(当你没有把此字符串赋值给某一变量时)
s = '''
这是一个大字符串
我用s来接收了
绿色的好看是这样的
'''
print(s, type(s))
# 在python中,type()用于返回数据类型
# <class 'str'>字符串类型
print(love, type(love))
# # 单双引号可以互相嵌套
#... | false |
b13d1b40e5fe1b97f94bc9a2380542cba9640364 | viniciuszambotti/statistics | /Binomial_Distribution/code.py | 584 | 4.1875 | 4 | '''
Task
The ratio of boys to girls for babies born in Russia is 1.09: 1 .
If there is 1 child born per birth, what proportion of Russian families with exactly 6 children will have at least 3 boys?
Write a program to compute the answer using the above parameters. Then print your result, rounded to a scale of 3 decimal ... | true |
8b012009d004b277dcd911213be55ad4e62b12f1 | qbarefoot/python_basics_refreshers | /pbrf1.8_sorting_lists.py | 1,076 | 4.59375 | 5 | #we can use the ".sort()" statement to put a list in alphabetical order.
horses = [ "appalose", "fresian", "mustang", "clydesdale", "arabian" ]
horses.sort()
print(horses)
#we can also arrange our list in alphabetical order backwards with the ".sort(reverse=True)".
horses = [ "appalose", "fresian", "mustang", "clydesd... | true |
090041cd7dc95f2a3176b13985a691c289379037 | smh82/Python_Assignments | /Vowels.py | 335 | 4.34375 | 4 | # Write a Python program to test whether a passed letter is a vowel or not
letter = input ("enter the letter to be checked : ")
v = "AEIOU"
for i in v:
if i.upper() == letter.upper():
print("the letter {t} is a vowel".format(t=letter))
break
else :
print( "the letter {t} is not a vowel ".for... | true |
06881534aeb302011ff5229bbb4feae0047d4e3f | smh82/Python_Assignments | /Area_of_Circle.py | 214 | 4.4375 | 4 | # Python program which accepts the radius of a circle from the user and compute the area
import math
radius = float(input ("Enter Area of Cirle "))
print("Area of Circle is : " + str( math.pi*radius**2 ))
| true |
7e431309e3ea62fc8f056f7ea302c05281cc6a13 | mulongxinag/xuexi | /L10数据库基础和sqlite/2sqlite示例1.py | 1,775 | 4.1875 | 4 | # (重点)sqlite示例
import sqlite3
connect = sqlite3.connect("testsqlite.db")
cursor = connect.cursor()
# cursor.execute("""CREATE TABLE student(
# id INT PRIMARY KEY ,
# name VARCHAR(10)
# );""")
cursor.execute("""
INSERT INTO student(id,name)VALUES (2,"小明");
""")
cu... | false |
fb303846e73f0a2ab5be9110c2c45c4b23681aa5 | ParkerCS/ch15-searches-bernhardtjj | /ch15Lab.py | 1,452 | 4.15625 | 4 | """
Complete the chapter lab at http://programarcadegames.com/index.php?chapter=lab_spell_check
"""
import re
# This function takes in a file of text and returns
# a list of words in the file.
def split_file(file):
return [x for line in file for x in re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line.strip())]
dict_... | false |
9d7e5b798dac265dbd23c4c5f8bca62db8cad843 | projectinnovatenewark/student_repository | /todos/3_classes_and_beyond/17_classestodo.py | 1,656 | 4.53125 | 5 | """
Creating classes for your classmates
"""
# TODO: Create a class for an Employee, and include basic data
# TODO: like hours worked, salary, first name, last name, age, and title
# TODO: Create a function inside the class and print out a formatted
# TODO: set of strings explaining the details from the employee. Us... | true |
493f8f4a9e1529d7275944c2f094f4c71829c3a9 | ambosing/PlayGround | /Python/Problem Solving/BOJ/boj10768.py | 239 | 4.125 | 4 | mon = int(input())
day = int(input())
if mon > 2:
print("After")
if mon == 2:
if day == 18:
print("Special")
if day > 18:
print("After")
if day < 18:
print("Before")
if mon < 2:
print("Before")
| false |
7d66b8782ac7e066a550125483791c7ec6c8beaf | alive-web/paterns | /src/strategy/second.py | 1,920 | 4.125 | 4 | __author__ = 'plevytskyi'
class PrimeFinder(object):
def __init__(self, algorithm):
"""
Constructor, takes a callable object called algorithm.
algorithm should take a limit argument and return an iterable of prime
numbers below that limit.
"""
self.algorithm = algo... | true |
098f4f60e0a9eafe5e039ff135354b073b1b1016 | andizzle/flipping-game | /board.py | 1,188 | 4.125 | 4 | from Move import move
class Board:
size = 0
moves = 0
def __init__(self, board_size):
"""
Construct a board grid like
"""
x = 0
self.grid = []
self.size = board_size
while(x < board_size):
row = [1 for size in range(board_size)]
... | true |
41ca379a56bc9ec574862380c660d00ef6948eb7 | MMelendez526/Comp_Hmwk | /Melendez_hw3_p3.py | 1,356 | 4.1875 | 4 | #Computational Homework #3, Problem #3
#Calculate the heat capacity of a solid
import math
import matplotlib.pyplot as plt
import numpy as np
V = 0.001 #in m^3
p = 6.022e28 #in m^-3
theta = 428 #in K
k = 1.38e-23
T = float(input('Please enter the desired temperature: '))
CV = (9*V*p*k)*((T/theta)**3)
def C(x)... | false |
429c33062fd855385134e8294ad03cb3fd7d1a43 | Thatguy027/Learning | /Learning_python/ex3.py | 923 | 4.34375 | 4 | # print text in quotes
print "I will now count my chickens:"
# calculates 25 + (30/6)
print "Hens", 25 + 30 / 6
# % or modulus gives you the remainder of 75/4 = 3
print 75 % 4
# 100 - (25*3)%4
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 5 % 2
print 1 - 1/4 + 6
# calculates everyth... | true |
c9f9b5ddce63734ae225e8f899707b6db253945e | melardev/PythonAlgorithmSnippets | /sort_nested_iterable_by_index.py | 420 | 4.375 | 4 | """
We will sort a list of tuples based on the index of a tuple that is contained in the list
This would also work for list of lists (shown in other demo)
"""
def sort_callback(value):
return value[1]
my_list_of_tuples = [(1, 2), (2, 3), (3, 4), (2, 2), (2, 1)]
my_list_of_tuples.sort(key=sort_callback)
print(m... | true |
d192f485a91461f5cffadb07c247d22f9335578c | sharepusher/leetcode-lintcode | /data_structures/tree/trie/implement_trie.py | 2,514 | 4.125 | 4 | ## Reference
# http://www.lintcode.com/en/problem/implement-trie/
# 208 https://leetcode.com/problems/implement-trie-prefix-tree/#/description
## Tags - Medium; Blue
# Trie; Facebook; Uber; Google
## Description
# Implement a trie with insert, search, and startsWith methods.
# NOTE:
# You may assume that all inputs a... | true |
cab50d418dfc432d379e5754a0367d499ae620e2 | sharepusher/leetcode-lintcode | /data_structures/hashtable/hash_function.py | 1,688 | 4.25 | 4 | ## Reference
# http://www.lintcode.com/en/problem/hash-function/
## Tags - Easy
# Hash Table
## Description
# In data structure hash, hash function is used to convert a string (or any other type)
# into an integer smaller than hash size and bigger or equal to zero.
# The objective of designing a hash function is to "... | true |
0eb832f03503b99fbca623515c4230512846cb9b | superstones/LearnPython | /Part1/week1/Chapter6/directory_exercise/directory_table_6.3&6.4.py | 758 | 4.28125 | 4 | # 6.3词汇表
directory = {
'print': 'Output statement',
'min': 'Find the smallest number in the list',
'max': 'Find the largest number in the list',
'sum': 'Sum the list',
'pop': 'Delete the list of element',
'for': 'Repeat statement',
'+': 'Add two objects',
'-': 'Get a negative number or s... | true |
d1373ab395a8a6200cf0193c02d52e74ef112a17 | superstones/LearnPython | /Part1/week1/Chapter4/Exercise/cut_4.10.py | 301 | 4.5 | 4 | #4.10切片
items = ['beautiful', 'handsome', 'brilliant', 'nice', 'prefect', 'regret', 'forgive']
print("The first three items in the list are:")
print(items[:3])
print("Three items from the middle of the list are:")
print(items[2:5])
print("The last three items in the list are:")
print(items[-3:])
| true |
7394d5ab482418b278d95c53be799cbe3c47bf8a | nchen0/Data-Structures-Algorithms | /Data Structures/Queues & Stacks/Intro - Queue.py | 1,085 | 4.15625 | 4 | # Queues follow a FIFO (First in first out) approach.
# It's tempting to use a similar approach as stack for implementing the queue, with an array, but it becomes tragically inefficient. When pop is called on a list with a non-default index, a loop is executed to shift all elements beyond the specified index to the lef... | true |
85d196557625563dfc6d3cee88445d373d18529c | nchen0/Data-Structures-Algorithms | /Data Structures/Queues & Stacks/Circular LinkedList as Queue.py | 1,204 | 4.28125 | 4 | class CircularQueue:
"""Queue implementation using circular linked list for storage"""
def __init__(self):
self.tail = None
self.size = 0
def isEmpty(self):
return self.size == 0
def first(self):
if self.isEmpty():
return "List is empty"
head = self... | true |
00d1bbd2552698704a794b6881a07bd33f750db8 | jnajman/hackaton | /03_recursion/03_draw_01_nautilus.py | 1,350 | 4.3125 | 4 | '''
In this exercise, you'll understand the concepts of recursion using selected programs - Fibonacci sequence, Factorial and others. We will also use Turtle graphics to simulate recursion in graphics.
Factorial
Fibonacci
Greatest common divisor
Once we understand the principles of recursion, we can do fun stuff with... | true |
8e065ebbc6e027da7d048c8678bb8efd0922c4cd | MaxBabii/home_work_python_starter | /home_work_3(1).py | 1,369 | 4.34375 | 4 | #Напшите программу калькулятор в которой пользователь сможет выбрать операцию,
#ввести необходимые числа и получить результат.
#Операции, которые необходимо реализовать: сложение, вычитание, умножение, деление, возведение в степень, синус, косинус и тангенс числа
import math
operation = input("""
+
-
*
/
**
sin
cos... | false |
b08d237c10a08e9e5de0e43cc1cd2905b693e209 | CharlotteKings/Data14Python | /introduction/Advanced_FizzBuzz.py | 962 | 4.40625 | 4 | # Function to check if inputted values are integers
def check(val):
while not val.isnumeric():
val = input("Please type a valid number? \n")
if val.isnumeric:
return int(val)
# Assign
counter = check(input("What number do you want to start from? \n"))
limit = check(input("What number do you wan... | true |
3a3845be749058ed1c1c4141bcd36584ca49da17 | any027/PyTest_Examples | /pytest_venv/calculator/calculator.py | 856 | 4.21875 | 4 | class CalculatorError(Exception):
""" An exception class for Calculator """
class Calculator():
""" Example Calculator """
def add(self, a, b):
self.check_operands(a)
self.check_operands(b)
return a + b
def subtract(self, a, b):
self.check_operands(a)
self.che... | true |
f63cfe08575a4b76beb41bfe211128f4bf5766df | tomasdecamino/CS_TOLIS | /PressButton/PressButton.pyde | 900 | 4.1875 | 4 | # Tomas de Camino Beck
#CS course with Pyhton
# Simple press button code
# button list
# list is organized [x,y,size, True/False]
buttons = [
[10,10,50,True],
[60,10,50, False],
[110,10,50, False],
[160,10,50, False]
]
pressButton = False
def setup():
size... | true |
9cbc49a3f4fd7034880f2b2afae37ba371ace4a5 | rmanovv/python | /task23/overlap_files.py | 950 | 4.1875 | 4 | '''
Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of all
prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000.
(If you forgot, prime numbers are numbers that can’t be divided by any other number. And yes,... | true |
9a3a63ab84c5b99872331e30e1ac230d76e04982 | rmanovv/python | /checkIO/electronic_station/Clock Angle.py | 1,342 | 4.34375 | 4 | # You are given a time in 24-hour format and you should calculate a lesser angle between the hour and minute hands in degrees.
# Don't forget that clock has numbers from 1 to 12, so 23 == 11. The time is given as a string with the follow format "HH:MM",
# where HH is hours and MM is minutes. Hours and minutes are g... | true |
609940a97b34d5dc2553c55e3b706366d537c647 | brockco1/E01a-Control-Structues | /main10.py | 2,198 | 4.40625 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # displays the text Greetings! when you run the p... | true |
6bfc6fc9b3e30c9ace200101ca2897a3bae19f2a | doulgeo/project-euler-python | /divisable.py | 872 | 4.25 | 4 | """
The general idea is that each of the numbers that
have to divide the answer, can be assigned to a list of
bools. So if your test number is 2520, then if 11 divides it
then you have a true value appended in a list. If all 8 booleans
in this list are true then that means that every number divides the test.
"""
... | true |
51613767a95f88083e372dd54761467f91241a2b | amresh1495/LPTHW-examples-Python-2.X | /ex19.py | 1,065 | 4.28125 | 4 | # Function to show that variables in a function are not connected to the variables in script.
# We can pass any variable as an arguement of the function just by using "=" sign.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses." % cheese_count
print "You have %d boxes of crack... | true |
a00c1c4a2319b4d9564eac7519a93d2fa866c0c4 | gistable/gistable | /all-gists/5653532/snippet.py | 975 | 4.125 | 4 | # coding=UTF-8
"""
Faça um Programa que leia um número inteiro menor que 1000
e imprima a quantidade de centenas, dezenas e unidades do mesmo.
Observando os termos no plural a colocação do "e", da vírgula entre outros.
Exemplo:
326 = 3 centenas, 2 dezenas e 6 unidades
"""
number = int(raw_input("Digite um numero: ... | false |
b6fa8168713b014478c8057a2ccefa4069d2c998 | gistable/gistable | /dockerized-gists/76d774879245b355e8bff95f9172f9f8/snippet.py | 488 | 4.375 | 4 | # Example of using callbacks with Python
#
# To run this code
# 1. Copy the content into a file called `callback.py`
# 2. Open Terminal and type: `python /path/to/callback.py`
# 3. Enter
def add(numbers, callback):
results = []
for i in numbers:
results.append(callback(i))
return results
def... | true |
bf74fdd5ad7fd81c5f2990d51c114d2347a3c460 | gistable/gistable | /all-gists/1867612/snippet.py | 2,481 | 4.28125 | 4 | class Kalman:
"""
USAGE:
# e.g., tracking an (x,y) point over time
k = Kalman(state_dim = 6, obs_dim = 2)
# when you get a new observation —
someNewPoint = np.r_[1,2]
k.update(someNewPoint)
# and when you want to make a new prediction
predicted_location = k.predict()
NOTE:
Setting state_dim to 3*... | true |
11cab5af1cd5e36fba209f005e2353c71b8a7729 | gistable/gistable | /all-gists/2438498/snippet.py | 1,686 | 4.125 | 4 | #! /usr/bin/python
#
# Church numerals in Python.
# See http://en.wikipedia.org/wiki/Church_encoding
#
# Vivek Haldar <vh@vivekhaldar.com>
#
# https://gist.github.com/2438498
zero = lambda f: lambda x: x
# Compute the successor of a Church numeral, n.
# Apply function one more time.
succ = (lambda n: lambda f: lambda... | false |
ca98687acf174fa07c31df1305ce8eb81c26b4a9 | gistable/gistable | /all-gists/9231107/snippet.py | 1,103 | 4.3125 | 4 | #!/usr/bin/env python2
# Functional Python: reduce, map, filter, lambda, *unpacking
# REDUCE EXAMPLE
add = lambda *nums: reduce(lambda x, y: x + y, nums)
def also_add(*nums):
'''Does the same thing as the lambda expression above.'''
def add_two_numbers(x, y):
return x + y
return reduce(add_two_nu... | true |
7a106333ddb52a4ea723a68648b65d201a072591 | gistable/gistable | /all-gists/91c49ddaceb38c0a6b241df6831a141b/snippet.py | 2,995 | 4.125 | 4 | import random, math
#Ignore def monte_carlo(): ...im just defining a function
def monte_carlo():
#At the end sums will add up all the f(n)
sums = 0
#just creating a dictionary, ignore this, not too important
functions = {'1': 'x', '2': 'x^2', '3': 'sin', '4': 'cos', '5': 'exp'}
print("Choose your... | true |
523f130fc786632ba04c2fa319472d483395c2f0 | gistable/gistable | /all-gists/1546736/snippet.py | 2,317 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
"""
String to Brainfuck.
Converts a string to a brainfuck code that prints that string.
Author: j0hn <j0hn.com.ar@gmail.com>
"""
import sys
def char2bf(char):
"""Convert a char to brainfuck code that prints that char."""
result_code = ""
ascii_value = ord(char)
... | true |
4953f3f11c03077361bea42f30ecc6f2fb1fb7e3 | gistable/gistable | /dockerized-gists/1253276/snippet.py | 1,145 | 4.21875 | 4 | import datetime
class Timer(object):
"""A simple timer class"""
def __init__(self):
pass
def start(self):
"""Starts the timer"""
self.start = datetime.datetime.now()
return self.start
def stop(self, message="Total: "):
"""Stops the timer. Returns ... | true |
ae23d72d889981dc4790a74d30d43148053e1f87 | gistable/gistable | /dockerized-gists/986af2a657d331a848d5/snippet.py | 1,348 | 4.125 | 4 | # -*- coding: utf-8 -*-
def calcular_dv(numero):
"""
Función para el cálculo de el dígito de verificación utilizado en el NIT y
CC por la DIAN Colombia.
>>> calcular_dv(811026552)
9
>>> calcular_dv(890925108)
6
>>> calcular_dv(800197384)
0
>>> calcular_dv(899999034)
1
>>... | false |
79e24593006755464c5495cdab9b72ddad11df1d | gistable/gistable | /all-gists/e515a92542fc41ea5911/snippet.py | 400 | 4.15625 | 4 | import math
def stringNorm(s):
norm = 0
for c in s:
if not c==" ":
norm+=math.pow(ord(c),2)
return math.sqrt(norm)
def anagram_detection(s1,s2):
return stringNorm(s1)==stringNorm(s2)
s1 = input("Please enter first string: ").lower()
s2 = input("Please enter second string: ").lowe... | false |
3cc4c5610432cf98e385c8fe476e9554c6f52ab7 | gistable/gistable | /dockerized-gists/2004597/snippet.py | 2,504 | 4.40625 | 4 | # This function prints out all of the values and sub-values in any variable, including
# lists, tuples and classes. It's not very efficient, so use it for testing/debugging
# purposes only. Examples are below:
#-------------------------------------------------------------------------------------
# ShowData(range(10)... | true |
6636fb368009ddcb070c71b5c9900d8856c28501 | chanshik/codewars | /sum_digits.py | 627 | 4.25 | 4 | """
Write a function named sumDigits which takes a number as input
and returns the sum of the absolute value of each of the number's decimal digits.
For example:
sumDigits(10) # Returns 1
sumDigits(99) # Returns 18
sumDigits(-32) # Returns 5
Let's assume that all numbers in the input will be integer values.
... | true |
420879938f42c8d3c2fa6b472f35cb3f1d7f6fad | chanshik/codewars | /triangle_type.py | 1,507 | 4.4375 | 4 | # coding=utf-8
"""
In this kata, you should calculate type of triangle with three given sides a, b and c.
If all angles are less than 90°, this triangle is acute and function should return 1.
If one angle is strictly 90°, this triangle is right and function should return 2.
If one angle more than 90°, this triangle ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.