blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b14bab37f60ba19116cf36475643ac4e7e4a1cd6 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch2_lists_and_pointer_structures/lists_and_pointers.py | 2,302 | 4.34375 | 4 | """
Pointers
--------
Ex:
a house that you want to sell;
a few Python functions that work with images, so you pass high-resolution image data between your functions.
Those large image files remain in one single place in memory. What you do is create variables that hold the locations
of those images in memory. The... | true |
28920f935d378841ec8750148075236777dfe2b1 | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch2_lists_and_pointer_structures/circular_lists.py | 2,502 | 4.15625 | 4 | """
Circular lists
---------------
- a special case of a linked list
- It is a list where the endpoints are connected: the last node in the list points back to the first node
- Circular lists can be based on both singly and doubly linked lists
- In the case of a doubly linked circular list, the first node also needs to... | true |
0ffa31e363ce141ddc7d5a7f5526aadd74046f7d | gabrielavirna/python_data_structures_and_algorithms | /my_work/ch10_design_techniques_&_strategies/coin_counting_greedy.py | 2,416 | 4.46875 | 4 | """
Greedy algorithms
- make decisions that yield the largest benefit in the interim.
- Aim: that by making these high yielding benefit choices, the total path will lead to an overall good solution or end.
Coin-counting problem
---------------------
In some arbitrary country, we have the denominations 1 GHC, 5 GHC, an... | true |
912d8a64e49846144609746390f49caba462873c | zhangler1/leetcodepractice | /树与图/Trie Tree/Implement Trie (Prefix Tree)208.py | 1,552 | 4.125 | 4 | class TrieNode:
def __init__(self):
"""
Initialize your Node data structure here.
"""
self.children=[None]*26
self.endcount=0
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head=TrieNode()
def inser... | true |
55d07ac39edf980053d80525264424d8eaf416fc | mokrunka/Classes-and-Objects | /countcapitalconsonants.py | 992 | 4.375 | 4 | #Write a function called count_capital_consonants. This
#function should take as input a string, and return as output
#a single integer. The number the function returns should be
#the count of characters from the string that were capital
#consonants. For this problem, consider Y a consonant.
#
#For example:
#
# count_c... | true |
de8d4a940fb3c2098f2e4b6ff689f5a1a69e749f | mushamajay/PythonAssignments | /question8.py | 345 | 4.21875 | 4 | def maximum(numOne, numTwo):
if numOne>numTwo:
return numOne;
else:
return numTwo;
numOne = float(input("Enter your first number: "))
numTwo = float(input("Enter your second number: "))
print("You entered: {} {} " .format(numOne,numTwo))
print("The larger of the two numbers is: {} " .format(... | true |
7924ab943291d81d40280a3e46e35b0fbcaffda3 | anayatzirojas/lesson6python | /lesson6/problem3/problem3.py | 483 | 4.15625 | 4 | name = input ('What is your name?')
print ('Hi' + name + ','' ' 'my name is Girlfriend Bot!''<3')
mood = input ('How was your day, Lover?')
print ('Hmm I am looking up the meaning of' + mood +' ' 'just one minute.')
press= input ('I have a surprise for you. Click the screen and type okay.')
print ('HACKED! VIRUSES IS I... | true |
32ff4110bcd5bc8c2d1bb1455216581a0e68bc1b | oshrishaul/lesson1 | /Lesson2/Assignment_Class2/Extra2.py | 700 | 4.21875 | 4 | # # Create a nested for loop to create X shape (width is 7, length is 7):
# i=0
# j=4
# for row in range(5):
# for col in range(5):
# if row==i and col==j:
# print("*",end="")
# i=i+1
# j=j-1
# elif row==col:
# print("*",end="")
# else:
# ... | true |
69e4baa9758d9808ac6f72cfe90059b76b874da8 | standrewscollege2018/2020-year-12-python-code-JustineLeeNZ | /credit_manager.py | 2,896 | 4.40625 | 4 | """ Manage student info about L1 NCEA credits - Ms Lee. """
def display_all_students():
""" Display all students in a list. """
print("\nLIST OF STUDENTS")
for index in range(0, len(students)):
print("{}. {} Credits: {}".format(index+1, students[index][0], students[index][1] ))
# stores init... | true |
88627a52218cf3c4fff7d39f34f565f9f39990ee | AssafR/sandbox | /generators.py | 2,172 | 4.375 | 4 | def with_index(itr):
"""This is the same as builtin function enumerate. Don't use this except as an exercise.
I changed the name, because I don't like overriding builtin names.
Produces an iterable which returns pairs (i,x) where x is the value of the original,
and i is its index i... | true |
18f595f69bafa2de6f12e3e22e85efc24ab91d82 | knowledgeforall/Big_Data | /Big Data/arrays.py | 935 | 4.125 | 4 |
#create empty array
A = []
print("Array A: ", A)
#create a "populated" array
B = [12, 23, 56, 17, 23]
print("Array B: ", B)
#Add an element to an array
print("Before adding to A: ", A)
A.append(90)
print("After adding to A: ", A)
#access the 2nd element in array B
print("The second element in Array B is: ", B[1]... | true |
ae879397835b9f1a95459a6bdc70d12252a3754a | baraluga/programming_sandbox | /python/miscellaneous/binary_tree_optimizer.py | 2,117 | 4.34375 | 4 | '''
Recall that a full binary tree is one in which each node is either a leaf
node, or has two children. Given a binary tree, convert it to a full one by
removing nodes with only one child.
For example, given the following tree:
0
/ \
1 2
/ \
3 4
\ / ... | true |
bce7773067afd0c81466166e792751c5be04d7ec | chenlifeng283/learning_python | /7-handling conditions/code_challenge_and_solution.py | 529 | 4.40625 | 4 | # Fix the mistakes in this code and test based on the description below
# if I enter 2.00 I should see the message "The tax rate is: 0.07"
# if I enter 1.00 I should see the message "The tax rate is :0.07"
# if I enter 0.5 I should see the message "The tax rate is: 0"
price = input('How much did you pay?')
price = flo... | true |
0e123b02dca275d099869084f1ed52a9a18d571c | chenlifeng283/learning_python | /1-print/ask_for_input.py | 244 | 4.28125 | 4 | #The input function allows you to prompy the user for a value
#You need to declare a variable to hold the value entered by the user
name=input("What's your name?") #if string has single quotes,it must be enclosed in double quotes.
print(name)
| true |
84594d387e3c44e7e3cd50cf6e33b210e27a865a | BenDataAnalyst/Practice-Coding-Questions | /leetcode/67-Easy-Add-Binary/answer.py | 618 | 4.21875 | 4 | #!/usr/bin/env python
#-------------------------------------------------------------------------------
# Cheaty Python way :)
# Other way would be to add each digit bit by bit, and having a carry bit when > 1
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:... | true |
615668717c061bcdcfcc4c3f7dbe4130aeb6401b | JHHXYZ/DSCS2020 | /Assignments/Assignment 2/part3.py | 2,574 | 4.5625 | 5 | # building a ml model with sklearn
import numpy as np
import pandas as pd
"""
1. Load your data from part 2
Create two lists. One should contain the name of the features (i.e. the input
variables) you want to use to train your model, the other should contain the
column name of the labels
"""
# your code
"""
2. Div... | true |
0bb19fcdb98d6c46c174347921246fe25cf69777 | BillyRockz/Magic-8-Ball | /main.py | 1,215 | 4.125 | 4 | '''This is a game of 8-Ball where you can ask Yes/No Questions and get answers'''
alpha = True
while alpha == True:
name = input("What is your name?: ")
if name.isalpha() and name.strip():
alpha = False
beta = True
while beta == True:
question = input("Ask a (Yes/No) question: ")
beta = False
else:
pr... | true |
0e89f43161009efc79d682584518c8cce89196d6 | ngovanuc/UDA_NMLT_Python_chapter06 | /page_203_project_03.py | 925 | 4.3125 | 4 | """
author : Ngô Văn Úc
date: 30/08/2021
program: 3. Elena complains that the recursive newton function in Project 2 includes an extra
argument for the estimate. The function’s users should not have to provide this
value, which is always the same, when they call this function. Modify the definition
of the functio... | true |
0c99a8c25c99644fbaddb94b22a7146aad09b854 | ngovanuc/UDA_NMLT_Python_chapter06 | /page_199_exercise_03.py | 477 | 4.3125 | 4 | """
author : Ngô Văn Úc
date: 30/08/2021
program: 2. Write the code for a filtering that generates a list of the positive numbers in a list
named numbers. You should use a lambda to create the auxiliary function.
solution:
- sử dụng bộ loc filter
"""
word = ["a", "hello", "Uc", "handsome", "b", "c", "d"]
... | true |
cb9ad2b4f192f67206af6f565a7cb50a36b13f40 | jjena560/Data-Structures | /strings/strings.py | 656 | 4.15625 | 4 | def createStack():
stack = []
return stack
def push(stack, item):
stack.append(item)
def pop(stack):
return stack.pop()
def reverse(string):
n = len(string)
try:
stack = createStack()
for i in range(n):
push(stack, string[i])
string = ""
... | true |
61813e43dbfb6c4be84104f9e042207ef3beeb2e | sohitmiglani/Applications-in-Python | /Max Heaps.py | 931 | 4.125 | 4 | # This is the algorithm for building and working with heaps, which is a tree-based data structure.
# It allows us to build a heap from a given list, extract certain element, add and remove them.
def max_heapify(A, i):
left = 2 * i + 1
right = 2 * i + 2
largest = i
if left < len(A) and A[left] > A[la... | true |
a1e1308263ba36420c3b7095ae682addf3898b33 | sohitmiglani/Applications-in-Python | /Hash Tables.py | 1,391 | 4.40625 | 4 | # This is an algorithm to produce hash tables and implement hashing functions for efficient data storage and retrieval.
# It also has 4 examples of hashing functions that can be used to store strings.
import random
import string
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in ra... | true |
fab8ea8638fbb524c1b423a6aac64cca4e692cbd | nzrfrz/praxis-academy | /novice/01-02/list_comprehension.py | 1,529 | 4.28125 | 4 | from math import pi
print("using math lib to calculate pi: ")
print(
[str(round(pi, i)) for i in range(1, 6)]
)
print("")
# Create a list of squares
squares = []
for x in range(10):
squares.append(x ** 2)
# Creates or overwrite 'x' after loop
squares = list(map(lambda x: x ** 2, range(10)))
# Simple version ... | true |
23083506114f10882ec02b046f74a4fe502d042f | Devanshiq/Python-Programs | /car.py | 2,450 | 4.125 | 4 | # class car:
# pass
#
# ford=car()
# honda=car()
# audi=car()
# ford.speed=200
# honda.speed=400
# audi.speed=100
# ford.color='black'
# honda.color='blue'
# audi.colour='maroon'
# print(ford.speed)
# print(audi.colour)
# print(honda.color)
# class car():
# def __init__(self,speed,color):
#... | true |
75df350c68c6ff04cf879d80be5d97f2a75f48f0 | byn3/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 575 | 4.21875 | 4 | #!/usr/bin/python3
""" this is my add_integer module """
def add_integer(a, b=98):
"""Function that returns the addition of a + b
Args:
a: should be an int. if not throw error
b: second int. if not throw error. default val is 98.
Returns:
The addition of a + b or a raised TypeErr... | true |
0e6ca5815e21b5a3d5225dc2934d1ba0f390708e | ag-ds-bubble/projEuler | /solutions/solution6.py | 821 | 4.125 | 4 | """
Author : Achintya Gupta
Date Created : 22-09-2020
"""
"""
Problem Statement
------------------------------------------------
Q) The sum of the squares of the first ten natural numbers is, 385
The square of the sum of the first ten natural numbers is, 3025
Hence the difference between the sum of the square... | true |
e81ed59d35f3094800cf2c92ad860dfa50fd3dbd | ag-ds-bubble/projEuler | /solutions/solution4.py | 924 | 4.1875 | 4 | """
Author : Achintya Gupta
Date Created : 22-09-2020
"""
"""
Problem Statement
------------------------------------------------
Q) A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the produc... | true |
99a4a4fd4f46f677d72f1a41c11fa89d404f9497 | arkaris/gb_python_basic | /lesson1/task1.py | 368 | 4.1875 | 4 | user_input = input('Введите 3-значное число: ')
numbers = map(int, user_input)
numbers_sum = 0;
for number in numbers:
numbers_sum += number
print("Сумма цифр:", numbers_sum)
numbers_mul = 1;
for number in numbers:
numbers_mul *= number
print("Произведение цифр:", numbers_mul)
input('Работа завершена.') | true |
d607dcb8b0da5dcbf7e7cded267b4c58ff70cb7e | coder562/python | /83-exercise 18.py | 271 | 4.1875 | 4 | # define a function that takes a number(n)
# return a dictionary containing cube of numbers from 1 to n
# example
# cube_finder(3)
# {1:1,2:8,3:27}
def cube_finder(n):
cubes={}
for i in range(1,n+1):
cubes[i]=i**3
return cubes
print(cube_finder(10)) | true |
fef7dce0af13470cf2e11f12163e5d14624a5f1a | coder562/python | /74-more about tuples.py | 827 | 4.5 | 4 | #looping in tuple
# tuple with one element
# tuple without parenthesis
# tuple unpacking
# list inside tuple
# some functions that you can use with tuples
mixed=(1,2,3,4.5)
# for loop and tuple
# for i in mixed:
# print(i)
#we can use while loop too
# tuple with one element
nums=(1,) #, is important as python de... | true |
b61f899f7e22db47f9793d4f8e4d2f4750f6e729 | coder562/python | /65-more about lists.py | 547 | 4.21875 | 4 | #generate lists with range function
# something more about pop method
# index method
# pass list to a function
# numbers = list(range(1,10))
numbers=[1,2,3,4,5,6,7,8,9,10,1]
# print(numbers)
# print(numbers.pop()) #pop returns the value popped
# print(numbers)
# print(numbers.index(1)) #by defalut search from 0th p... | true |
d75bc9a6e32a78551ff8eae7e4bb75adb2226659 | coder562/python | /88-list comprehenstion.py | 734 | 4.21875 | 4 | #list compreshension
# with the help of list comprehension we can create of list in one line
#create a list of squares from 1 to 10
# squares=[]
# for i in range(1,11):
# squares.append(i**2)
# print(squares)
#by using list comprehension
# square2=[i**2 for i in range(1,11)]
# print(square2)
# cretate list of n... | true |
42e3bb8b71a449580d8b7699b45b76965e89dc41 | coder562/python | /52-variable scope.py | 390 | 4.125 | 4 | x=5 #global variable which is defined outside the function
def func():
global x #to change the value of global variable we use term global
x=7 #the variable defined inside the function are called local variables
return x #x has only scope upto func() not in func2() x cant be used outside func() function
pri... | true |
ed20bbc58702b64ae4b1724646dd431d41f2fcaa | coder562/python | /68-exercise 14.py | 343 | 4.5625 | 5 | # define a function that take list of words as argument and
# return list with reverse of every element in that list
# example
# ['abc','tuv','xyz']--->['cba','vut','zyx']
def reverse_elements(l):
elements = []
for i in l:
elements.append(i[::-1])
return elements
words=['abc','tuv','xyz']
print(re... | true |
b6dbcf61531c5ec98deaac7f4c4a5b405316acc3 | coder562/python | /46-function practice.py | 951 | 4.125 | 4 | # def last_char(name):
# return name[-1]
# print(last_char("vaishali"))
# last_char(9) #error
# define function and check number is even or odd
# def odd_even(num):
# if num%2==0: #% is used to check reminder
# return "even"
# else:
# return "odd"
# print(odd_even(10))
#another method
# d... | true |
45c4c66ff2ccb6042a070256a5056ba573708575 | nkhanhng/namkhanh-fundamental-c4e15 | /session4/homework/turtle_excersise/ex2.py | 344 | 4.15625 | 4 | from turtle import *
def draw_rectangle(m,n):
for i in range(2):
forward(m)
left(90)
forward(n)
left(90)
shape("turtle")
speed(1)
colors = ['red', 'blue', 'brown', 'yellow', 'grey']
for j in colors:
color(str(j))
begin_fill()
draw_rectangle(50,100)
forward(50)
... | true |
7c207be73a0defe569ec799b188b5b3544bec62b | RavinderSinghPB/data-structure-and-algorithm | /array/Find the number of sub-arrays having even sum.py | 1,132 | 4.15625 | 4 | def countEvenSum(arr, n):
# A temporary array of size 2. temp[0] is
# going to store count of even subarrays
# and temp[1] count of odd.
# temp[0] is initialized as 1 because there
# a single even element is also counted as
# a subarray
temp = [1, 0]
# Initialize count. sum is sum of el... | true |
7c54a34f8b6476b7ebef606d1416b911b525a135 | devodev/cracking_the_coding_interview_practice | /8.recursion/8.4.py | 957 | 4.3125 | 4 |
def get_subsets(s):
if not s:
return None
return _get_subsets(s, 0)
def _get_subsets(s, n):
all_subsets = None
if len(s) == n:
all_subsets = []
all_subsets.append(set())
else:
all_subsets = _get_subsets(s, n+1)
item = s[n]
more_subsets = []
... | true |
7228c8f644f982b022646dff0c24af3ba0b031c1 | Suka91/RS | /CodeArena/CodeArena/Resources/Leap_Year/version3/Leap_Year.py | 440 | 4.34375 | 4 | def leap_year(year):
if(...)==0:
if(...)== 0:
if(...) == 0:
print("{0} is a leap year".format(year))
return 1
else:
print("{0} is not a leap year".format(year))
return -1
else:
print("{0} is a leap y... | true |
1c3ed6a743b865524ff8f21fd85105f92996407f | AntonioRafaelGarcia/LPtheHW | /ex20/ex20.py | 1,581 | 4.375 | 4 | # makes argv available in this script
from sys import argv
# uses argv to assign user input when calling script
script, input_file = argv
# defines function to read and print input variable file
def print_all(f):
print(f.read())
# defines function to go to very first line of inputted variable file
def rewind(f):... | true |
63dbc6ca29923a63a42477c45d138a7c29d7c26e | AntonioRafaelGarcia/LPtheHW | /ex12.py | 312 | 4.28125 | 4 | # string prompts and directly assigns to three separate variables
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh? ")
# f prints a string statement seeded with those prompted variables
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
| true |
b56b81731cb6a6cacbbdaf7d45d645ea040a10ef | mkwak73/probability | /chapter 1/exercises/exercise1.py | 1,183 | 4.4375 | 4 | # Chapter 1 - Exercise 1
# Author: Michael Kwak
# Date: December 26 2016
#######################################################
#
# random () - return the next random floating point number in the range [0.0, 1.0)
#
import random
#
# get input for number of tosses for this simulation
#
n = int(input("Enter the val... | true |
a7a9e67983effa2597e33420b34085c55e0ed2b7 | mkwak73/probability | /chapter 1/exercises/exercise9.py | 2,743 | 4.125 | 4 | # Chapter 1 - Exercise 9 - Labouchere system
# Author: Michael Kwak
# Date: January 4 2016
#######################################################################################
#
# random () - return the next random floating point
# number in the range [0.0, 1.0)
#
import random
from math import floor
#
# defin... | true |
ea6b1b325303699febde9050a58e031f18651475 | NaregAmirianMegan/Hailstone-Problem | /hailstone_interactive.py | 558 | 4.125 | 4 | def isEven(num):
if(num%2 == 0):
return True
else:
return False
def applyOdd(num):
return 3*num + 1
def applyEven(num):
return num/2
def analyze(num, count):
if(isEven(num)):
num = applyEven(num)
else:
num = applyOdd(num)
if(num == 1):
print("Value:... | true |
da94819416e7a4a1d0afb66a2fba50469e51a458 | edawson42/pythonPortfolio | /listEvens.py | 277 | 4.125 | 4 | #make new list of even numbers only from given list
#
# Copyright 2018, Eric Dawson, All rights reserved.
def listEvens(list):
""" (list) -> list
Returns list of even numbers from given list
"""
evenList = [num for num in list if num % 2 == 0]
return evenList
| true |
27f36689b14dc824d0bd455fbbacf925ace550d0 | karkyra/Starting_out_with_python3 | /edabit/Last_Digit_Ultimate.py | 323 | 4.15625 | 4 | # Your job is to create a function, that takes 3 numbers: a, b, c and returns
# True if the last digit of a * b = the last digit of c. Check the examples below for an explanation.
def last_dig(a, b, c):
total = a * b
return str(total)[-1] == str(c)[-1]
print(last_dig(25, 21, 125))
print(last_dig(12, 215, 2142... | true |
c9b0fd090d633c3dee917dd6847f79dfc91371ff | karkyra/Starting_out_with_python3 | /edabit/Find_the_Highest_Integer.py | 420 | 4.125 | 4 | # Create a function that finds the highest integer in the list using recursion.
# Please use the recursion to solve this (not the max() method).
def find_highest(lst):
# return sorted(lst)[-1]
if len(lst) == 1:
return lst[0]
else:
current = find_highest(lst[1:])
return current if c... | true |
bc28cd89b6ee3a1faad2a948204c04010cafbc77 | karkyra/Starting_out_with_python3 | /edabit/Enharmonic_Equivalents.py | 420 | 4.125 | 4 | # Given a musical note, create a function that returns its enharmonic equivalent.
# The examples below should make this clear.
def get_equivalent(note):
d = {"Db": "C#", "Eb":"D#", "Gb":"F#", "Ab":"G#", "Bb":"A#"}
for k,v in d.items():
if note == k:
return v
elif note == v:
... | true |
f6bb7f7fcf292f512e9984696dc8151773259a30 | karkyra/Starting_out_with_python3 | /edabit/Buggy_Uppercase_Counting.py | 451 | 4.28125 | 4 | # In the Code tab is a function which is meant to return how many uppercase letters
# there are in a list of various words. Fix the list comprehension so that the code functions normally!
def count_uppercase(lst):
return sum([letter.isupper() for word in lst for letter in word])
print(count_uppercase(["SOLO", "he... | true |
10052b78817f1280becd708cc2aa42a383ffc763 | karkyra/Starting_out_with_python3 | /edabit/Characters_and_ASCII_Code_Dictionary.py | 427 | 4.1875 | 4 | # Write a function that transforms a list of characters into a list of dictionaries, where:
#
# The keys are the characters themselves.
# The values are the ASCII codes of those characters.
# example to_dict(["a", "b", "c"]) ➞ [{"a": 97}, {"b": 98}, {"c": 99}]
def to_dict(lst):
return [{i: ord(i)} for i ... | true |
fa34f7934c15719235a12fd701d0ccac2d1284bc | karkyra/Starting_out_with_python3 | /edabit/Stupid_Addition.py | 718 | 4.375 | 4 | # Create a function that takes two parameters and, if both parameters are strings,
# add them as if they were integers or if the two parameters are integers, concatenate them.
# If the two parameters are different data types, return None.
# All parameters will either be strings or integers.
def stupid_addition... | true |
846061fdcbea83a17bc21cf23cd36455acf13814 | karkyra/Starting_out_with_python3 | /edabit/International_Greetings.py | 856 | 4.375 | 4 | # Suppose you have a guest list of students and the country they are from, stored as key-value pairs in a dictionary.
# # GUEST_LIST = {
# "Randy": "Germany",
# "Karla": "France",
# "Wendy": "Japan",
# "Norman": "England",
# "Sam": "Argentina"
# }
#
# Write a function that takes in a name and returns a name tag, that s... | true |
93b9229c6f5016ba015902dc03b3ae266fc315f1 | JackCaff/WeeklyTask2-BMI- | /BMICalculation.py | 511 | 4.34375 | 4 | # Program will allow user to enter height in (CM) and weight in (KG) and calculate their BMI.
Weight = float(input("Enter your Weight in Kg: ")) #Allows user to enter Weight
Height = float(input("Enter your Height in Cm: ")) #Allows user to enter Height
Meters_squared = ((Height * Height) / 100) #Converts height en... | true |
5604489e590bc0224b0bb9aa5db23293d9a89ea2 | umairgillani93/data-structures-algorithms | /coding_problems/sort_arr.py | 357 | 4.1875 | 4 | def sort(arr: list) -> list:
'''
Sorts the given arraay in ascending order
'''
while True:
corrected = False
for i in range(len(arr) -1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
corrected = True
if not corrected:
return arr
if __name__ == '__main... | true |
f2378203319ab0d84940ac254ab24b7d047e0eae | schopr9/python-lone | /second_larjest.py | 519 | 4.28125 | 4 |
def second_largest(input_array):
"""
To find the largest second number in the array
"""
max_1 = input_array[0]
max_2 = input_array[1]
for i in range(1, len(input_array)):
if input_array[i] > max_1:
max_2 = max_1
max_1 = input_array[i]
elif input_array[i... | true |
411c840c3eed902311543ed9aa459e952b6a7802 | oleksandr-nikitenko/python-course | /Lesson_26/task3.py | 817 | 4.15625 | 4 | """
# Extend the Stack to include a method called get_from_stack that searches and returns an element e
# from a stack. Any other element must remain on the stack respecting their order.
# Consider the case in which the element is not found - raise ValueError with proper info Message
# Extend the Queue to include a me... | true |
e0a2336680d8b24bc1de0cabcb4aab1dd7135a3b | oleksandr-nikitenko/python-course | /Lesson_11/task1.py | 696 | 4.21875 | 4 | """Make a class called Person. Make the __init__() method take firstname, lastname, and age as parameters and add them
as attributes. Make another method called talk() which makes prints a greeting from the person containing, for example
like this: “Hello, my name is Carl Johnson and I’m 26 years old”."""
class Perso... | true |
5b3a41f5937f89cad7b16f7de0fa65b23bce89c1 | oleksandr-nikitenko/python-course | /Lesson_8/task3.py | 996 | 4.5625 | 5 | """
Create a function called make_operation, which takes in a simple arithmetic operator as a first parameter
(to keep things simple let it only be ‘+’, ‘-’ or ‘*’) and an arbitrary number of arguments (only numbers) as the
second parameter. Then return the sum or product of all the numbers in the arbitrary parameter. ... | true |
4df63417fc4ed7d520b59f1fdcb72fe2100c2d17 | oleksandr-nikitenko/python-course | /Lesson_15/task3.py | 1,266 | 4.21875 | 4 | """
Write a decorator `arg_rules` that validates arguments passed to the function.
A decorator should take 3 arguments:
max_length: 15
type_: str
contains: [] - list of symbols that an argument should contain
If some of the rules' checks returns False, the function should return False and print the reason it failed; ot... | true |
5095d554baf1909bb9731bda65af7e04d25b3809 | kikijtl/coding | /Candice_coding/Leetcode/Permutations.py | 778 | 4.15625 | 4 | '''Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].'''
from copy import deepcopy
def permute(num):
n = len(num)
#count = [1] * n
cur_result = []
results = []
... | true |
6eba1e86149ce3c05dcd297215f5371e400d8d92 | kikijtl/coding | /Candice_coding/Leetcode/Closest_Binary_Search_Tree_Value.py | 1,333 | 4.15625 | 4 | # Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
#
# Note:
# Given target value is a floating point.
# You are guaranteed to have only one unique value in the BST that is closest to the target.
# Definition for a binary tree node.
class TreeN... | true |
fe7e219419804dcdb343c62dd89d3601d9802266 | Rafaellinos/learning_python | /structures_algorithms/recursion/recursion3.py | 282 | 4.3125 | 4 | """
reverse string by using
"""
def reverse_str(string):
return string[::-1]
def reverse(string):
print(string)
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
# print(reverse_str('hello'))
print(reverse('hello'))
| true |
ec6c262f7c755bc2b30890ffff5b7da629e9b44d | Rafaellinos/learning_python | /OOP/objects.py | 1,177 | 4.125 | 4 | #OOP
class PlayerCharcter:
"""
self represents the instance of the class.
With this keyword, its possible to access atributes and methods of the class.
When objects are instantiated, the object itself is passed into the self parameter.
"""
membership = True # class object attribute... | true |
13a9e0c4334f1bbe6d0b89c69fe71a90d2b074f9 | Rafaellinos/learning_python | /basics/learning_lists.py | 1,694 | 4.125 | 4 | lista = [1,2,3,4]
lista.append(5)
lista2 = lista
print(lista2)
# If I try to copy the last on that way (lista2 = lista),
# any changes that I made on lista2 goes to lista aswell, because
# they are pointing to the same place in memory.
# the right way to copy a list, is lista2 = lista[:], or lista2 = lista.copy()
list... | true |
6d8cb09b90c7c9a7386e1210905b3005c51109bc | Rafaellinos/learning_python | /OOP/polymorphism.py | 688 | 4.1875 | 4 | """
Polymorphism:
Poly means many and morphism means forms, many form in other words.
In python means that objects can share the same names but work in diferent ways.
"""
class User:
def attack(self):
return "do nothing"
class Archer(User):
def __init__(self, name, arrows):
self.n... | true |
adbe2258d207f05702157e8fa1e1182a32ad35d0 | Rafaellinos/learning_python | /functional_programming/reduce.py | 661 | 4.125 | 4 | from functools import reduce
my_list = [1,2,3]
def multiply_by2(item):
return item*2
def accumulator(acc, item):
print(acc, item)
return acc+item
# func item, acc
print(reduce(accumulator, my_list, 0)) # default = 0
# output
# 0 1
# 1 2
# 3 3
# 6
sum_total = reduce((lambda x,y: x+y... | true |
3d6a633b77b2305a9f2bd3111645311ec6649881 | Rafaellinos/learning_python | /basics/learning_tuples.py | 600 | 4.40625 | 4 | """
Tuples are immutables, so you can't update, sort, add item etc
Usually more faster than lists.
Tuple only has two methods: count and index, but it works with len
"""
tuple2 = (1,2,3,4)
print(3 in tuple2)
new_tuple = tuple2[1:4]
print(new_tuple)
a, b, *other = tuple2 #unpacking tuple
print(other)
print... | true |
10b9250387e95708aab6cda408133fa0b157c3b2 | Rafaellinos/learning_python | /structures_algorithms/algorithms/leet_code_1528.py | 986 | 4.125 | 4 | """
Given a string s and an integer array indices of the same length.
The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
Return the shuffled string.
Example 1:
Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
Output: "leetcode"
Explanation: As sho... | true |
55abcf3f6a0916eeb2da275f5464c602c6a3a9b0 | Erick-INCS/FSDI_114_Algorithms_and_DataStructures | /linked_list/linked_list.py | 1,570 | 4.1875 | 4 | #!/usr/bin/env python3
""" linked list implementation """
class Node:
""" One directional node """
def __init__(self, val):
self.val = val
self.next = None
def __str__(self):
return str(self.val)
class LinkedList:
""" Data structure """
def __init__(self, val):
... | true |
c3491d075ad662a00b7c0683d4192835c9aae475 | agarw184/Data-Science | /PA04_final/problem2.py | 2,102 | 4.15625 | 4 | #perform a stencil using the filter f with width w on list data
#output the resulting list
#note that if len(data) = k, len(output) = k - width + 1
#f will accept as input a list of size width and return a single number
def stencil(data, f, width) :
#Fill in
#Initialising Variables
k = len(data)
w = wi... | true |
567ec46c085595c66571a67b0f6c7311a3d693e2 | SaraAnttila/day2-bestpractices-1 | /1a_e/animals/birds.py | 365 | 4.15625 | 4 | """
Package with types of birds
"""
class Birds:
def __init__(self):
"""
Construct this class by creating member animals
"""
self.members = ['Sparrow', 'Robin', 'Duck']
def printMembers(self):
print('Printing members of the Birds class')
for member in self.membe... | true |
fcc9afc659b9b41084eef7c08d3da756e6f4fc33 | SRashmip/FST-M1 | /Python/Activities/Activity3.py | 787 | 4.15625 | 4 | user1 = input("What is player 1 name:")
user2 = input("What is player2 name:")
user1_answer = input(user1+ "Do you want to choose rock,paper or scissor" )
user2_answer = input(user2+"Do you want to choose rock,paper or scissor")
if user1_answer==user2_answer:
print("its tie")
elif user1_answer=='rock':
... | true |
d89c05ca8e67c947a11fca49a107b4f2dd34843b | RKKgithub/databyte_inductions | /CountryCodes_task.py | 606 | 4.375 | 4 | import csv
#take country codes as input
code1, code2 = input().split()
flag = False
#empty list to store country names
data = []
#open csv file and store data in a dictionary
with open(r"CSV_FILE_PATH_GOES_IN_HERE") as file:
reader = csv.DictReader(file)
#add country names in between the two country ... | true |
720d1526b00a45fbbcc8e76855b2514400954e31 | Hussein-Mansour/ICS3UR-Assignment-6B-python | /volume_of_rectangle.py | 1,166 | 4.15625 | 4 | #!/usr/bin/env python3
# Created by: Hussein Mansour
# Created on: Fri/May28/2021
# This program calculates the volume of rectangular prism
def volume_rectangular(length_int, width_int, height_int):
# this function calculates the volume of rectangular prism using return
# process
volume = length_int * wi... | true |
803b0a3be00d0659b0451d4c211a962f4491cd4c | x223/cs11-student-work-genesishiciano | /Word_Count.py | 866 | 4.3125 | 4 | text_input= raw_input("Write your text here") # The text that you are going to use
user_choice= raw_input("what word do you want to find? ") # the word that the person is looking for
text_input=text_input.lower()# change all of the inputs into lower case
text_input=text_input.replace(".", " ")# changes all of the '.' i... | true |
71c7612841b4e6c0fe29bee99d5d73cbbe027fe4 | krewper/Python_Commits | /misc_ops.py | 1,204 | 4.125 | 4 | #swapping variables in-place
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#Reversing a string
a = "Kongsberg Digital India"
print("Reverse is", a[::-1])
#Creating a single string from all the elements in a list
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
#chaining of comparision operators
n = 10
result = ... | true |
8af810deab946e1010252e63292d9653ba6b6b50 | Dream-Team-Pro/python-udacity-lab2 | /TASK-3.py | 694 | 4.46875 | 4 | # Task 3:
# You are required to complete the function maximum(x). where "x" is a list of numbers. the function is expected to return the highest number in that list.
# Example:
# input : [5,20,12,6]
# output: 20
# you can change the numbers in the list no_list but you are not allowed to change the variable names or edi... | true |
2ce2e3f08b62ff843373991517e1af4cc2f230a7 | SaiNikhilD/Dogiparty_SaiNikhil_Spring2017 | /Assignment3/Question2_Part1.py | 1,030 | 4.21875 | 4 |
# coding: utf-8
# # Question2_Part1
# •Use 'employee_compensation' data set.
# •Find out the highest paid departments in each organization group by calculating mean of total compensation for every department.
# •Output should contain the organization group and the departments in each organization group with the tot... | true |
e4a51691d1de70e5b932773a7f34f9e7531449d7 | njberejan/Palindrome | /palindrome_advanced.py | 818 | 4.28125 | 4 | import re
# def reversed_string(sentence):
# #recursive function to reverse string
# if len(sentence) == 0:
# return ''
# else:
# return reversed_string(sentence[1:]) + sentence[0]
def is_palindrome(sentence):
#uses iterative to solve, above function not called so commented out.
sentence =... | true |
8e95b399682602881a79f1f0dc5cdc0688a74efe | sarahmbaka/Bootcamp_19 | /Day_4/MissingNumber/missing_number.py | 340 | 4.21875 | 4 | def find_missing(list1, list2):
"""Function that returns the difference between two lists"""
if not list1 and list2: # checks if list is empty
return 0
diff = list(set(list1) ^ set(list2)) # diff is the difference between the lists
if not diff:
return 0
return diff[0] #retrieve fir... | true |
b61106c9d0e72482f7320c6ae12374e98c989d66 | Riya258/PythonProblemSolvingCodeSubmission | /ps1b.py | 1,233 | 4.25 | 4 | # Name: Riya
# REG. NO.: BS19BTCS005
# Time spend: 2:30 hours
#Problem 2
#2.Paying Debt Off In a Year
"""
Write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months.
We will not be dealing with a minimum monthly payment rate.
"""
outsta... | true |
55ee6660ae1b673ef68b2e225012cc1de26e68c3 | NimalGv/Python-Programs | /MYSLATE/A2-Programs/Day-1/4.number_a_sum_of_two_primes.py | 770 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
1.Any even number greater than or equal to 4 can always be written as sum of two primes
even : even+even and odd+odd;
2.The odd number can be written as sum of two primes if the number-2 is a prime number, because
odd : odd+even and even+odd;
so, IsPrim... | true |
a1eb915db6312fe768536d0af922d02e569f476b | muhammadalie/python-think | /factorial.py | 251 | 4.21875 | 4 | def fact(n):
if type(n)==int:
print 'n is not integer'
return None
elif 0<=n<=2:return n
elif n<0:
print 'not defined,number is negative'
return None
return n*fact(n-1)
n=input('type your number: ')
print 'the factorial is ',fact(n)
| true |
82801a8c565f7c058270124cb270dd09b0213136 | felix1429/project_euler | /euler04.py | 1,058 | 4.21875 | 4 | # Largest palindrome from multiplying two three digit numbers
# 998001 is 999 * 999
# start at 998001 and iterate down until first palindrome
# then divide that palindrome by 999, 999 - 1, 999 - 2 etc until it
# divides evenly or runs out of numbers, in which case the next palindrome
# is moved to
def is_palindrome(n... | true |
bb974d1a1a6dd9b6653db0ebfb6f883d5bd6f4d6 | rajesh1994/lphw_challenges | /python_excercise/ex05.01.py | 779 | 4.125 | 4 | one_centimeter_equal_to = 0.393701 # Inches
# Getting the centimeter value from the user
centimeter = float(raw_input("Enter the centimeter value:"))
# Calculating the equalent inches by using centimeter value
inches_calculation = one_centimeter_equal_to * centimeter
# Printing the converted value in inches
print "T... | true |
83de7ca67fdb04a015d4f0ee0dad0424a1a66e0f | nileshpandit009/practice | /BE/Part-I/Python/BE_A_55/assignment1_1.py | 245 | 4.125 | 4 | my_list = input("Enter numbers separated by spaces").split(" ");
total = 0;
for num in my_list:
try:
total += int(num)
except ValueError:
print("List contains non-numeric values\n")
exit(-1)
print(total)
| true |
c98bf8c90d9ac104f2cabc8669c7888ea8fa5fbe | bunnymonster/personal-code-bits | /python/learningExercises/ListBasics.py | 760 | 4.46875 | 4 | #This file demonstrates the basics of lists.
animals = ["rabbit","fox","wolf","snail"]
#prints the list
print(animals)
#lists are indexed like strings. slicing works on lists.
print(animals[0])
print(animals[1:2])
#all slices return a new list containing the requested items.
#lists support concatenation
animals + ... | true |
9bd76cf27d41a1e017011e2409c6ae68ffd41058 | bunnymonster/personal-code-bits | /python/learningExercises/ErrorsAndExceptions.py | 2,115 | 4.25 | 4 | import sys
#
#Errors and Exceptiosn
#
#Error handled with basic try except
try:
print(x)
except:
print('Error! x not defined.')
#multiple Exceptions may be handled by a single except
#by being listed in a tuple.
try:
print(x)
except (RuntimeError, TypeError, NameError):
print('Error!')
#a class C in... | true |
e196c243910c0b42dcee2195675ef2c7e393c703 | rupol/cs-module-project-algorithms | /sliding_window_max/sliding_window_max.py | 883 | 4.28125 | 4 | '''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
# return an array with the max value of each window (i to i + k)
def sliding_window_max(nums, k):
# create an array to save the max values in
result = [0] * (len(nums) - (k - 1))... | true |
f14f5b7612a5ac16d08ac92b6766ea08659e8c92 | inickt/advent-of-code-2019 | /aoc/day01.py | 1,329 | 4.375 | 4 | """Day 1: The Tyranny of the Rocket Equation"""
from math import floor
def fuel_required(mass: float) -> float:
"""Find fuel required to launch a given module by its mass.
Take mass, divide by three, round down, and subtract 2.
Examples:
>>> fuel_required(12)
2
>>> fuel_required(14)
2
... | true |
8a007237f7cc4430ab0a1e10793e03f78fa19335 | Stubbycat85/csf-1 | /Hw-1/hw1_test.py | 1,615 | 4.3125 | 4 | # Name: ...
# Evergreen Login: ...
# Computer Science Foundations
# Programming as a Way of Life
# Homework 1
# You may do your work by editing this file, or by typing code at the
# command line and copying it into the appropriate part of this file when
# you are done. When you are done, running this file should comp... | true |
36444a7d22f2f3bae8a8bc1bec97a6772b45e713 | GhostGuy9/Python-Programs | /madlibs/Catcher/questions.py | 1,808 | 4.125 | 4 | import os
#Configure this Section
questions = [
"Type a Adverb",
"Type a Verb",
"Type a Verb in Past Tense",
"Type a Adjective",
"Type a Plural Noun",
"Fictional Character Name",
"Type a undesirable Noun",
"Type a Verb",
"Type a Noun",
"Type a Verb in Past Tense ending in \"S\"",... | true |
c7466693f23dcb10b71277637b895e78f6c1a668 | neelamy/Algorithm | /DP/Way_to_represent_n_as_sum_of_int.py | 975 | 4.125 | 4 | # Source : http://www.geeksforgeeks.org/number-different-ways-n-can-written-sum-two-positive-integers/
# Algo/DS : DP
# Complexity : O(n ^2)
# Program to find the number of ways, n can be
# written as sum of two or more positive integers.
# Returns number of ways to write n as sum of
# two or more positive integers... | true |
ec8410a8e32b0f3ecd96490b352611b9e9a6dfe0 | cspfander/Module_6 | /more_functions/validate_input_in_functions.py | 1,260 | 4.5625 | 5 | """
Program: validate_input_in_functions.py
Author: Colten Pfander
Last date modified: 9/30/2019
The purpose of this program is to write a function score_input() that takes a test_name, test_score, and
invalid_message that validates the test_score, asking the user for a valid test score until it is in the range,
then ... | true |
556d13ca018fe2391fa65925fa52905ea2710219 | gandhalik/PythonCA2020-Assignments | /Task 3/7.py | 254 | 4.40625 | 4 | #7. Write a program to replace the last element in a list with another list.
# Sample data: [[1,3,5,7,9,10],[2,4,6,8]]
# Expected output: [1,3,5,7,9,2,4,6,8]
list1 = [1,3,5,7,9,10]
list2 = [2,4,6,8]
list1[-1:]=list2
print(list1)
| true |
c309e2fdf79e7ff8f27aa7c01ac4fe94d15fda8c | gandhalik/PythonCA2020-Assignments | /Task 4/3.py | 509 | 4.65625 | 5 | # Write a program to Python find out the character in a string which is uppercase using list comprehension.
# Using list comprehension + isupper()
# initializing string
test_str = input("The sentence is: ")
# printing original string
print("The original string is : " + str(test_str))
# Extract Upper Case ... | true |
44ed2cbea71e26cf87bebedb491deb1ea1e00574 | DRay22/COOP2018 | /Chapter08/U08_Ex06_PrimeLessEqual.py | 1,489 | 4.3125 | 4 | # U08_Ex06_PrimeLessEqual.py
#
# Author:
# Course: Coding for OOP
# Section: A2
# Date: 21 Mar 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: Name and Number
# Source: Python Programming
# Chapter: #
#
# Program Description
# This program will find prime numbers less or equal to n, a user input... | true |
61d62433a082758c56de60870e8b63ec97f2c397 | DRay22/COOP2018 | /Chapter04/U04_Ex07_CircleGraphics.py | 2,381 | 4.46875 | 4 | # U04_Ex07_CircleGraphics.py
#
# Author: Donovan Ray
# Course: Coding for OOP
# Section: A2
# Date: 29 Oct 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: Circle Graphics Ex07
# Source: Python Programming
# Chapter: #04
#
# Program Description
# This program will make a circle with a user specif... | true |
dabc27a62b7c1b993cece699ae98f7cfe8b1d8a1 | DRay22/COOP2018 | /Chapter06/U06_Ex06_Area_of_Tri_Modular.py | 1,361 | 4.4375 | 4 | # U06_Ex06_Area_of_Tri_Modular.py
#
# Author: Donovan Ray
# Course: Coding for OOP
# Section: A2
# Date: 17 Jan 2019
# IDE: PyCharm
#
# Assignment Info
# Exercise: Area of Triangle 06
# Source: Python Programming
# Chapter: #06
#
# Program Description
# This program will find the area of a triangle th... | true |
6429e95316a74a6e65933c62d121395da234e974 | DRay22/COOP2018 | /Chapter04/U04_Ex09_CustomRectangle.py | 1,814 | 4.25 | 4 | # U04_Ex09_CustomRectangle.py
#
# Author: Donovan Ray
# Course: Coding for OOP
# Section: A2
# Date: 29 Oct 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: Custom Rectangle Ex09
# Source: Python Programming
# Chapter: #04
#
# Program Description
# This program will draw a rectangle based off of ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.