blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d7de4f27b05171c1a29e6fd4f1b0fab5e872dbaf | AnshumanSinghh/DSA | /Sorting/selection_sort.py | 864 | 4.28125 | 4 | def selection_sort(arr, n):
for i in range(n):
min_id = i
for j in range(i + 1, n):
if arr[min_id] > arr[j]:
min_id = j
arr[min_id], arr[i] = arr[i], arr[min_id]
return arr
# Driver Code Starts
if __name__ == "__main__":
arr = list(map(int, input... | true |
d124e426fc4a6f6f42c2942a8ce753e31c07ba56 | AnniePawl/Tweet-Gen | /class_files/Code/Stretch_Challenges/reverse.py | 1,036 | 4.28125 | 4 | import sys
def reverse_sentence(input_sentence):
"""Returns sentence in reverse order"""
reversed_sentence = input_sentence[::-1]
return reversed_sentence
def reverse_word(input_word):
"""Returns word in reverse order"""
reversed_word = input_word[::-1]
return reversed_word
def reverse_rev... | true |
5428b2f9dce1f91420c57963dcd1e80275e3c6cb | AnniePawl/Tweet-Gen | /class_files/Code/rearrange.py | 864 | 4.125 | 4 | import sys
import random
def rearrange_words(input_words):
"""Randomly rearranges a set of words provided as commandline arguments"""
# Initiate new list to hold rearranged words
rearranged_words = []
# Randomly place input words in rearranged_words list until all input words are used
while len(re... | true |
f76a969859f8cdbfedb6a147d505ae1fc788dc19 | Chris-Valenzuela/Notes_IntermediatePyLessons | /4_Filter.py | 664 | 4.28125 | 4 | # Filter Function #4
# Filter and map are usually used together. The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.
# filter(function, iterable) - takes in the same arguements as map
def add7(x):
return x+7
def isOdd(x):
return x ... | true |
df1920f69ffd2cab63280aa8140c7cade46d6289 | bhavyanshu/PythonCodeSnippets | /src/input.py | 1,297 | 4.59375 | 5 | # Now let us look at examples on how to ask the end user for inputs.
print "How many cats were there?",
numberofcats = int(raw_input())
print numberofcats
# Now basically what we have here is that we take user input as a string and not as a proper integer value as
# it is supposed to be. So this is a major problem be... | true |
c0c986476ddb5849c3eb093487047acb2a8cadec | jlassi1/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 413 | 4.34375 | 4 | #!/usr/bin/python3
"""module"""
def append_write(filename="", text=""):
"""function that appends a string at the end of a text file (UTF8)
and returns the number of characters added:"""
with open(filename, mode="a", encoding="UTF8") as myfile:
myfile.write(text)
num_char = 0
for w... | true |
8583fccda88b05dd25b0822e1e403de2ad64af11 | Sisyphus235/tech_lab | /algorithm/tree/lc110_balanced_binary_tree.py | 2,283 | 4.40625 | 4 | # -*- coding: utf8 -*-
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/... | true |
3c7c978a4d753e09e2b12245b559960347972b37 | Sisyphus235/tech_lab | /algorithm/tree/lc572_subtree_of_another_tree.py | 1,623 | 4.3125 | 4 | # -*- coding: utf8 -*-
"""
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure
and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
Example 1:
Give... | true |
1651e397c9fb56f6c6b56933babc60f97e830aac | Sisyphus235/tech_lab | /algorithm/array/find_number_occuring_odd_times.py | 1,177 | 4.25 | 4 | # -*- coding: utf8 -*-
"""
Given an array of positive integers.
All numbers occur even number of times except one number which occurs odd number of times.
Find the number in O(n) time & constant space.
Examples :
Input : arr = {1, 2, 3, 2, 3, 1, 3}
Output : 3
Input : arr = {5, 7, 2, 7, 5, 2, 5}
Output : 5
"""
def... | true |
3cc965eda451b01a9c0f8eee2f80f64ea1d902a3 | Sisyphus235/tech_lab | /algorithm/tree/lc145_post_order_traversal.py | 1,363 | 4.15625 | 4 | # -*- coding: utf8 -*-
"""
Given a binary tree, return the postorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""
from typing import List
class TreeNode:
def __init__(self, ... | true |
d7eda822fb84cd5abd4e7a66fa76eec506b09599 | omarfq/CSGDSA | /Chapter14/Exercise2.py | 960 | 4.25 | 4 | # Add a method to the DoublyLinkedList class that prints all the elements in reverse order
class Node:
def __init__(self, data):
self.data = data
self.next_element = None
self.previous_element = None
class DoublyLinkedList:
def __init__(self, head_node, last_node):
self.head_n... | true |
3f13fa57a9d0e51fd4702c7c7814e0e277cb8f36 | omarfq/CSGDSA | /Chapter13/Exercise2.py | 277 | 4.125 | 4 | # Write a function that returns the missing number from an array of integers.
def find_number(array):
array.sort()
for i in range(len(array)):
if i not in array:
return i
return None
arr = [7, 1, 3, 4, 5, 8, 6, 9, 0]
print(find_number(arr))
| true |
63226638939260126c5d1ee013b0f76e9d5f5812 | Temujin18/trader_code_test | /programming_test1/solution_to_C.py | 506 | 4.3125 | 4 | """
C. Write a rotate(A, k) function which returns a rotated array A, k times; that is, each
element of A will be shifted to the right k times
○
rotate([3, 8, 9, 7, 6], 3) returns [9, 7, 6, 3, 8]
○
rotate([0, 0, 0], 1) returns [0, 0, 0]
○
rotate([1, 2, 3, 4], 4) returns [1, 2, 3, 4]
"""
from typing import List
def ... | true |
ea13ba0ca0babd500a0b701db9693587830a4546 | cryoMike90s/Daily_warm_up | /Basic_Part_I/ex_21_even_or_odd.py | 380 | 4.28125 | 4 | """Write a Python program to find whether a given number (accept from the user) is even or odd,
print out an appropriate message to the user."""
def even_or_odd(number):
if (number % 2 == 0) and (number > 0):
print("The number is even")
elif number == 0:
print("This is zero")
else:
... | true |
4bb88de5f9de506d24fe0ff4acf2c43bb4bc7bca | momentum-team-3/examples | /python/oo-examples/color.py | 1,888 | 4.3125 | 4 | def avg(a, b):
""" This simple helper gets the average of two numbers.
It will be used when adding two Colors.
"""
return (a + b) // 2 # // will divide and round all in one.
def favg(a, b):
""" This simple helper gets the average of two numbers.
It will be used when adding two Colors.... | true |
c20d16b102e1e408648cf055eb2b37a6d5198987 | VSpasojevic/PA | /vezba05/stablo/stablo/stablo.py | 2,136 | 4.21875 | 4 | class Node:
"""
Tree node: left child, right child and data
"""
def __init__(self, p = None, l = None, r = None, d = None):
"""
Node constructor
@param A node data object
"""
self.parent = p
self.left = l
self.right = r
self.data = d
clas... | false |
26f77ff9d2e26fe9e711f5b72a4d09aed7f45b16 | gaoshang1999/Python | /leetcod/dp/p121.py | 1,421 | 4.125 | 4 | # 121. Best Time to Buy and Sell Stock
# DescriptionHintsSubmissionsDiscussSolution
# Discuss Pick One
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design ... | true |
fe82dce52d79df152dc57e93ae6e97e9efa722e5 | keerthiballa/PyPart4 | /fibonacci_linear.py | 856 | 4.3125 | 4 | """
Exercise 3
Create a program called fibonacci_linear.py
Requirements
Given a term (n), determine the value of x(n).
In the fibonacci_linear.py program, create a function called fibonnaci. The function should take in an integer and return the value of x(n).
This problem must be solved WITHOUT the use of recursion.... | true |
38367ab9a4c7cc52c393e9c22b1752dd27e0f0f4 | eugenejazz/python2 | /task02-2.py | 625 | 4.25 | 4 | # coding: utf-8
# 2. Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
def checkeven(x):
if (int(x) % 2) == 0:
return 1
else:
return 0
def checkodd(x):
if (int(x) % 2) == 0:
return 0
else:
retu... | false |
4e480a91ec51f5a2b8bf4802c3bd40d134cac839 | eugenejazz/python2 | /task02-3.py | 412 | 4.4375 | 4 | # coding: utf-8
# 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
# Например, если введено число 3486, то надо вывести число 6843.
def reversestring(x):
return(print(x[::-1]))
a = str(input("Введите число: "))
reversestring(a) | false |
fcfcbf9381003708979b90a0ca204fe54fe747cc | amit-shahani/Distance-Unit-Conversion | /main.py | 1,193 | 4.25 | 4 | def add_unit(list_of_units, arr):
unit = str(input('Enter the new unit: ').lower())
conversion_ratio = float(
input('Enter the conversion ration from metres: '))
list_of_units.update({unit: conversion_ratio})
# arr.append(unit)
return list_of_units, arr
def conversion(list_of_units, arr):
... | true |
a5f7e54bd93e3445690ab874805e4e57005cecde | galhyt/python_excercises | /roads.py | 2,852 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'numberOfWays' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY roads as parameter.
#
# returns the number of ways to put 3 hotels in three different cities while the dis... | true |
1bd458f150f97dd84780f65da401e59ec7fbfd5a | pkiop/Timechecker_web | /TimeChecker_web/backend/server/templates/python_class_example.py | 260 | 4.25 | 4 | #python_class_example.py
class MyClass:
"""A simple example class이건 독 스트링"""
i = 12345
def f(self):
return 'hello world'
def __init__(self, a):
self.i = a
# def __init__(self):
# self.i = 22222
x = MyClass(3)
print(x.i)
print(x.f()) | false |
5c23070568b655b41f55e81f65a2d5840bd9b9c8 | WesRoach/coursera | /specialization-data-structures-algorithms/algorithmic-toolbox/week3/solutions/7_maximum_salary/python/largest_number.py | 979 | 4.3125 | 4 | from typing import List
from functools import cmp_to_key
def compare(s1: str, s2: str) -> int:
"""Returns orientation of strings producing a smaller integer.
Args:
s1 (str): first string
s2 (str): second string
Returns:
int: one of: (-1, 0, 1)
-1: s1 first produces sm... | true |
9901dd9ebb20c27db8e1519bcd71db450b7a7b2e | baxter-t/Practice | /codingProblems/productFib.py | 399 | 4.25 | 4 | '''
Find the product of nth fibonacci numbers
'''
def nthFib(n):
if n == 0 or n == 1:
return n
return nthFib(n-1) + nthFib(n-2)
def prodFib(prod):
n = 2
product = nthFib(n) * nthFib(n - 1)
while product <= prod:
if product == prod:
return True
n += 1
... | false |
0b52e4ad1eef997e3a8346eb6f7ea30c4a591bb9 | JankaGramofonomanka/alien_invasion | /menu.py | 1,794 | 4.21875 | 4 | from button import Button
class Menu():
"""A class to represent a menu."""
def __init__(self, screen, space=10):
"""Initialize a list of buttons."""
self.buttons = []
self.space = space
self.height = 0
self.screen = screen
self.screen_rect = screen.get_rect()
#Number of selected button.
self.select... | true |
ee19f685bf59a801596b6f4635944680ada27bc9 | MateuszSacha/Iteration | /development exercise 1.py | 317 | 4.3125 | 4 | # Mateusz Sacha
# 05-11-2014
# Iteration Development exercise 1
number = 0
largest = 0
while not number == -1:
number = int(input("Enter a number:"))
if number > largest:
largest = number
if number == -1:
print("The largest number you've entered is {0}".format(largest))
... | true |
8995e16a70f94eddc5e26b98d51b1e03799ef774 | MateuszSacha/Iteration | /half term homework RE3.py | 302 | 4.1875 | 4 | # Mateusz Sacha
# Revision exercise 3
total = 0
nofnumbers = int(input("How many number do you want to calculate the average from?:"))
for count in range (0,nofnumbers):
total = total + int(input("Enter a number:"))
average = total / nofnumbers
print("The average is {0}".format(average))
| true |
5cbed6cdc2549ec225e478fb061deeff30cf5666 | lleonova/jobeasy-algorithms-course | /4 lesson/Longest_word.py | 305 | 4.34375 | 4 | # Enter a string of words separated by spaces.
# Find the longest word.
def longest_word(string):
array = string.split(' ')
result = array[0]
for item in array:
if len(item) > len(result):
result = item
return result
print(longest_word('vb mama nvbghn bnb hjnuiytrc')) | true |
8a69feedb8da68729ee69fd193a3db2d8c59dc88 | lleonova/jobeasy-algorithms-course | /2 lesson/Fibonacci.py | 1,251 | 4.28125 | 4 | # The equation for the Fibonacci sequence:
# φ0 = 0, φ1 = 1, φn = φn−1 + φn−2.
#
# The task is to display all the numbers from start to n of the Fibonacci sequence φn
# Equation:
# F0 = 0
# F1 = 1
# F2 = 1
# Fn = Fn-1 + Fn-2
def fibonacci(n):
fibonacci_1 = 1
fibonacci_2 = 1
if n == 0:
print(0)... | false |
04e373740e134f7b71f655c44b76bba0c51bd6a1 | lleonova/jobeasy-algorithms-course | /3 lesson/Count_substring_in_the_string.py | 720 | 4.28125 | 4 | # Write a Python function, which will count how many times a character (substring)
# is included in a string. DON’T USE METHOD COUNT
def substring_in_the_string(string, substring):
index = 0
count = 0
if len(substring) > len(string):
return 0
elif len(substring) == 0 or len(string) == 0:
... | true |
66db39164628280219e3849c8cddeed370915ccb | pragatirahul123/practice_folder | /codeshef1.py | 206 | 4.1875 | 4 | # Write a program to print the numbers from 1 to 20 in reverse order.
# Output: 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
var=20
while var>=1:
print(var," ",end="")
var=var-1
| true |
3f69d6abcca9971f266402b6eda42e62a399aab2 | OdayaGU/TestProject | /TestProject/src/homework_1.py | 373 | 4.15625 | 4 | import pandas as pd
print ("welcome to your first HW: FILTER BY. So yallaa...")
df = pd.DataFrame({"ID":[703,783,788,780,790],"NAME":["John","James","Marry","Gil","Roy"], "LEVEL":[5,5,4,5,4],"GRADE":[87,88,90,65,100]})
print (df)
print ("--------------")
print ("Your task: given the dataframe above print on ... | false |
3491a2c56d9e5761996237f2be8060de2a8a6e4b | BDDM98/Evaluador-Posfijo | /compilador.py | 2,100 | 4.1875 | 4 | # -*- coding: utf-8 -*-
class Pila:
""" Representa una pila con operaciones de apilar, desapilar y
verificar si está vacía. """
def __init__(self):
""" Crea una pila vacía. """
# La pila vacía se representa con una lista vacía
self.items=[]
def apilar(self, x):
... | false |
a1acd77a9c1adbe44056a532909bc9378681122a | OnoKishio/Applied-Computational-Thinking-with-Python | /Chapter15/ch15_storyTime.py | 781 | 4.1875 | 4 | print('Help me write a story by answering some questions. ')
name = input('What name would you like to be known by? ')
location = input('What is your favorite city, real or imaginary? ')
time = input('Is this happening in the morning or afternoon? ')
color = input('What is your favorite color? ')
town_spot = input('Are... | true |
3cca295b200f107f100923509c3a31077be52995 | akashbaran/PyTest | /github/q6.py | 635 | 4.25 | 4 | """Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma ... | true |
b0b2d09c383a9d1354caf54eedc9d0df4a0e9d6a | akashbaran/PyTest | /github/q21.py | 1,077 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 30 15:34:34 2018
@author: eakabar
A robot moves in a plane starting from the original point (0,0).
The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps.
The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after t... | true |
c6e7af5146e9bcacd925ea9579dd15a8f571bfed | akashbaran/PyTest | /github/re_username1.py | 405 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 31 12:25:27 2018
@author: eakabar
Assuming that we have some email addresses in the "username@companyname.com" format,
please write program to print the user name of a given email address.
Both user names and company names are composed of letters only.
"""
import re
ema... | true |
b761d29007cc6ccf91f4c838e7fb2f4ebc972e8f | JimNastic316/TestRepository | /DictAndSet/challenge_simple_deep_copy.py | 1,020 | 4.375 | 4 | # write a function that takes a dictionary as an argument
# and returns a deep copy of the dictionary without using
# the 'copy' module
from contents import recipes
def my_deepcopy(dictionary: dict) -> dict:
"""
Copy a dictionary, creating copies of the 'list' or 'dict' values
:param dictionary: ... | true |
42455a07e117cf79b631630e7fe65f6cceaf5911 | micmoyles/hackerrank | /alternatingCharacters.py | 880 | 4.15625 | 4 | #!/usr/bin/python
'''
https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings
You are given a string containing characters and only. Your task is to change it into a string such that there are no matching adjacent cha... | true |
3a53c4f41bf1a8604ea073a17762e2dcfc39c8d8 | jbsec/pythonmessagebox | /Message_box.py | 598 | 4.21875 | 4 | #messagebox with tkinter in python
from tkinter import *
from tkinter import messagebox
win = Tk()
result1 = messagebox.askokcancel("Title1 ", "Do you really?")
print(result1) # yes = true no = false
result2 = messagebox.askyesno("Title2", "Do you really?")
print(result2) # yes = true no = false
result... | true |
a993b0b69e113eefbf033a5a6c4bbebd432ad5e9 | cs-fullstack-2019-fall/codeassessment2-insideoutzombie | /q3.py | 1,017 | 4.40625 | 4 | # ### Problem 3
# Given 2 lists of claim numbers, write the code to merge the 2
# lists provided to produce a new list by alternating values between the 2 lists.
# Once the merge has been completed, print the new list of claim numbers
# (DO NOT just print the array variable!)
# ```
# # Start with these lists
# list_of_... | true |
dfccab9f95be2b883dddb721f22ddf50bf5b2166 | roconthebeatz/python_201907 | /day_02/dictionary_02.py | 1,141 | 4.1875 | 4 | # -*- coding: utf-8 -*-
# 딕셔너리 내부에 저장된 데이터 추출 방법
# - 키 값을 활용
numbers = { "ONE" : 1, "TWO" : 2, "THREE" : 3 }
# [] 를 사용하여 값을 추출
print(f"ONE -> {numbers['ONE']}")
print(f"TWO -> {numbers['TWO']}")
print(f"THREE -> {numbers['THREE']}")
# [] 를 사용하여 값을 추출하는 경우
# 존재하지 않는 키값을 사용하면 에러가 발생됩니다.
print(f"FIVE -> {n... | false |
ec2279635d73dfabdce13ef10a7922ad697939a2 | roconthebeatz/python_201907 | /day_02/list_03.py | 484 | 4.25 | 4 | # -*- coding: utf-8 -*-
# 리스트 내부 요소의 값 수정
# 문자열 데이터와 같은 경우 배열(리스트)의 형태로 저장되며
# 값의 수정이 허용되지 않는 데이터 타입입니다.
msg = "Hello Python~!"
msg[0] = 'h'
# 반면, 일반적인 리스트 변수는 내부 요소의 값을
# 수정할 수 있습니다.
numbers = [1,2,3,4,5]
print(f"before : {numbers}")
numbers[2] = 3.3
print(f"after : {numbers}")
... | false |
4d820a5480f429613b8f09ca50cacae0d2d5d377 | roconthebeatz/python_201907 | /day_03/while_02.py | 603 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# 제어문의 중첩된 사용
# 제어문들은 서로 다른 제어문에 포함될 수 있음
# 1 ~ 100 까지의 정수를 출력하세요.
# (홀수만 출력하세요...)
step = 1
while step < 101 :
if step % 2 == 1 :
# 제어문 내부에 위한 또다른 제어문의
# 실행 코드는 해당 제어문의 영역에
# 포함되기 위해서
# 추가적으로 들여쓰기를 작성해야 합니다.
print(f"step => {step:... | false |
f8cee34470276d3eb0f8e127d6698c39990a68c2 | yuto-te/my-python-library | /src/factrize_divisionize.py | 730 | 4.21875 | 4 | """
素因数分解
約数列挙
"""
"""
e.g. 2**2 * 3**2 * 5**2 = [(2, 2), (3, 2), (5, 2)]
"""
def factorize(n):
fct = [] # prime factor
b, e = 2, 0 # base, exponent
while b * b <= n:
while n % b == 0:
n = n // b
e = e + 1
if e > 0:
fct.append((b, e))
b, e = b ... | false |
67eda0475ddaca871d0c092032a458f994e94a0d | dvbckle/RoboGarden-Bootcamp | /Create edit and Delete files.py | 1,515 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 2 14:48:35 2019
@author: dvbckle
"""
# code snips to create, edit and delete files
def main():
_file = 'my_create_and_delete_file.txt'
_CreateFile(_file)
_WriteToFile(_file)
_ReadandPrintFromFile(_file)
_AppendToFile(_file)
_ReadandPrintFromFile(... | false |
af3dd2583562a8fa5f2a45dacb6eea900f1409f5 | JiungChoi/PythonTutorial | /Boolean.py | 402 | 4.125 | 4 | print(2 > 1) #1
print(2 < 1) #0
print(2 >= 1) #1
print(2 <= 2) #1
print(2 == 1) #0
print(2 != 1) #1
print( 2 > 1 and "Hello" == "Hello") # 1 & 1
print(not True) #0
print(not not True) #1
#True == 1
print(f"True is {int(True)}")
x = 3
print(x > 4 or not (x < 2 or x == 3))
print(type(3))
print(type(True))
print(type(... | true |
7a93dfe5082ef046d45f4526081c317063641b66 | rafal1996/CodeWars | /Remove exclamation marks.py | 434 | 4.3125 | 4 | #Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
def remove_exclamation_marks(s):
count=s.count("!")
s = s.replace('!','',count)
return s
print(remove_exclamation_marks("Hello World!"))
print(remove_exclamation_marks("Hello World!!!"))
print(remove_e... | true |
4d32c35fbc001223bf7def3087a5e0f02aef8f09 | rafal1996/CodeWars | /Merge two sorted arrays into one.py | 597 | 4.3125 | 4 | # You are given two sorted arrays that both only contain integers.
# Your task is to find a way to merge them into a single one, sorted in asc order.
# Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays.
#
# You don't need to worry about validation, since arr1 and arr2... | true |
9998009659bc70720c63ab399c45fb8adafe5e2b | sam-calvert/mit600 | /problem_set_1/ps1b.py | 1,827 | 4.5 | 4 | #!/bin/python3
"""
Paying Debt Off In a Year
Problem 2
Now 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.
Take as raw_input() the following floating point numbers:
1. ... | true |
c806a5d9275a6026fb58cc261b8bfd95c1d66b90 | keshavkummari/python-nit-7am | /Operators/bitwise.py | 1,535 | 4.71875 | 5 | '''--------------------------------------------------------------'''
# 5. Bitwise Operators :
'''--------------------------------------------------------------'''
"""
Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60; and b = 13;
Now in binary format they will be as follows :
a = 0011... | true |
910fe52e3d7eafcec15c6d5e31cc8d33bd087942 | keshavkummari/python-nit-7am | /DataTypes/Strings/unicodes.py | 2,461 | 4.1875 | 4 | Converting to Bytes. The opposite method of bytes.decode() is str.encode(),
which returns a bytes representation of the Unicode string,
encoded in the requested encoding.
The errors parameter is the same as the parameter of the
decode() method but supports a few more possible handlers.
UTF-8 is one such ... | true |
f5c67e47e4140b3d92226fe3df69055c3a0c3d85 | keshavkummari/python-nit-7am | /Operators/arithmetic.py | 709 | 4.53125 | 5 | '''--------------------------------------------------------------'''
# 1. Arithmetic Operators:
'''--------------------------------------------------------------'''
"""
1. + = Addition
2. - = Subtraction
3. * = Multiplication
4. / = Division
5. % = Modulus
6. ** = Exponent
7. // = Floor Division
"""
# Ex... | false |
c81ca7b213c5b8f442f5a1169be00a72874ecd7a | mirajbasit/dice | /dice project.py | 1,152 | 4.125 | 4 | import random
# do this cuz u have to
def main():
# .lower makes everything inputted lowercase
roll_dice = input("Would you like to roll a dice, yes or no? ").lower()
# add the name of what is being defined each time
if roll_dice == "no" or roll_dice == "n":
print("Ok, see you later ")
... | true |
53d5d64be2ba5861b854bd279f366e54f681235e | OscaRoa/intro-python | /mi_primer_script.py | 749 | 4.125 | 4 | # Primera sección de la clase
# Intro a scripts
"""
Primera sección de la clase
Intro a scripts
"""
# Segunda sección
# Estructuras de control
if 3 > 5 and 3 > 2:
print("Tres es mayor que cinco y que dos")
# edad = 18
# if edad > 18:
# print("Loteria!")
# elif edad == 18:
# print("Apenitas loteria!")
# e... | false |
f58b89d169650839c43e0b716b877f6661245f48 | vnBB/python_basic_par1_exersises | /exercise_5.py | 283 | 4.375 | 4 | # Write a Python program which accepts the user's first and last name and print them in
# reverse order with a space between them.
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
print("Your name is: " + lastname + " " + firstname) | true |
4f1db5440a48a15f126f4f97439ef197c0c380ab | mynameischokan/python | /Strings and Text/1_4.py | 1,915 | 4.375 | 4 | """
************************************************************
**** 1.4. Matching and Searching for Text Patterns
************************************************************
#########
# Problem
#########
# We want to match or search text for a specific pattern.
#########
# Solution
#########
# If the text you’re... | true |
2005dfcd3969edb4c38aba4b66cbb9a5eaa2e0f2 | mynameischokan/python | /Data Structures and Algorithms/1_3.py | 1,459 | 4.15625 | 4 | '''
*************************************************
**** Keeping the Last N Items
*************************************************
#########
# Problem
#########
# You want to keep a limited history of the last few items seen during iteration
# or during some other kind of processing.
#########
# Solution
#######... | true |
383dbeb58575c030f659e21cfe9db4de0f3b4043 | mynameischokan/python | /Files and I:O/1_3.py | 917 | 4.34375 | 4 | """
*************************************************************
**** 5.3. Printing with a Different Separator or Line Ending
*************************************************************
#########
# Problem
#########
- You want to output data using print(),
but you also want to change the separator charact... | true |
6dfbf466e6a2697a3c650dd7963e8b446c3ebbdd | paulprigoda/blackjackpython | /button.py | 2,305 | 4.25 | 4 | # button.py
# for lab 8 on writing classes
from graphics import *
from random import randrange
class Button:
"""A button is a labeled rectangle in a window.
It is enabled or disabled with the activate()
and deactivate() methods. The clicked(pt) method
returns True if and only if the button is enabled ... | true |
bf694c58e1e2f543f3c84c41e32faa3301654c6e | akshat-52/FallSem2 | /act1.19/1e.py | 266 | 4.34375 | 4 | country_list=["India","Austria","Canada","Italy","Japan","France","Germany","Switerland","Sweden","Denmark"]
print(country_list)
if "India" in country_list:
print("Yes, India is present in the list.")
else:
print("No, India is not present in the list.") | true |
f04933dd4fa2167d54d9be84cf03fa7f9916664c | akshat-52/FallSem2 | /act1.25/3.py | 730 | 4.125 | 4 | def addition(a,b):
n=a+b
print("Sum : ",n)
def subtraction(a,b):
n=a-b
print("Diffrence : ",n)
def multiplication(a,b):
n=a*b
print("Product : ",n)
def division(a,b):
n=a/b
print("Quotient : ",n)
num1=int(input("Enter the first number : "))
num2=int(input("Enter the second n... | true |
bda09e5ff5b572b11fb889b929daddb9f4e53bb9 | rhps/py-learn | /Tut1-Intro-HelloWorld-BasicIO/py-greeting.py | 318 | 4.25 | 4 | #Let's import the sys module which will provide us with a way to read lines from STDIN
import sys
print "Hi, what's your name?" #Ask the user what's his/her name
#name = sys.stdin.readline() #Read a line from STDIN
name = raw_input()
print "Hello " + name.rstrip() #Strip the new line off from the end of the string
| true |
795d075e858e3f3913f9fc1fd0cb424dcaafe504 | rhps/py-learn | /Tut4-DataStructStrListTuples/py-lists.py | 1,813 | 4.625 | 5 | # Demonstrating Lists in Python
# Lists are dynamically sized arrays. They are fairly general and can contain any linear sequence of Python objects: functions, strings, integers, floats, objects and also, other lists. It is not necessary that all objects in the list need to be of the same type. You can have a list wit... | true |
dbd856336c8f7e2e724e9b50c81494b3ca3a7771 | tmjnow/Go-Python-data-structures-and-sorting | /Datastructures/queue/queue.py | 1,054 | 4.28125 | 4 | '''
Implementation of queue using list in python.
Operations are O(1)
`python queue.py`
'''
class Queue():
def __init__(self):
self.items = []
def is_empty(self):
return self._is_empty()
def enqueue(self, item):
self._enqueue(item)
def dequeue(self):
return self._d... | false |
ec823610ba821cd62f067b8540e733f46946de34 | thaycacac/kids-dev | /PYTHON/lv2/lesson1/exercise2.py | 463 | 4.15625 | 4 | import random
number_random = random.randrange(1, 100)
numer_guess = 0
count = 0
print('Input you guess: ')
while number_random != numer_guess:
numer_guess = (int)(input())
if number_random > numer_guess:
print('The number you guess is smaller')
count += 1
elif number_random < numer_guess:
print('The... | true |
011d9ac704c3705fd7b6025c3e38d440a30bf59a | Saskia-vB/Eng_57_2 | /Python/exercises/108_bizzuuu_exercise.py | 1,540 | 4.15625 | 4 | # Write a bizz and zzuu game ##project
user_number= (int(input("please enter a number")))
for i in range(1, user_number + 1):
print(i)
while True:
user_number
play = input('Do you want to play BIZZZUUUU?\n')
if play == 'yes':
user_input = int(input('what number would you like to play to?\n'))
for num ... | true |
b572d0bda55a6a4b9a3bbf26b609a0edc026c0a3 | Saskia-vB/Eng_57_2 | /Python/dictionaries.py | 1,648 | 4.65625 | 5 | # Dictionaries
# Definition and syntax
# a dictionary is a data structure, like a list, but organized with keys and not index.
# They are organized with 'key' : 'value' pairs
# for example 'zebra' : 'an African wild animal that looks like a horse but has black and white or brown and white lines on its body'
# This mean... | true |
793e45264df9239562ea359d2b1f704643e7c9e2 | alveraboquet/Class_Runtime_Terrors | /Students/andrew/lab1/lab1_converter.py | 1,903 | 4.4375 | 4 | def feet_to_meters():
measurment = { 'ft':0.03048}
distance = input("Enter a distance in feet: ")
meters = float(distance) * measurment['ft']
print(f'{distance} ft is {meters}m ')
def unit_to_meters():
measurment = {'ft':0.03048, 'km':1000, 'mi':1609.34}
distance = input("Enter a distance in meters: ... | false |
d0625cb91921c28816cd5ab06a100cb3ae9e4bbb | alveraboquet/Class_Runtime_Terrors | /Students/cleon/Lab_6_password_generator_v2/password_generator_v2.py | 1,206 | 4.1875 | 4 | # Cleon
import string
import random
speChar = string.hexdigits + string.punctuation # special characters
print(" Welcome to my first password generator \n") # Welcome message
lower_case_length = int(input("Please use the number pad to enter how many lowercase letters : "))
upper_case_length = int(input("How many... | true |
5a89444d7b72175ba533b87139a5a611a11a89a7 | alveraboquet/Class_Runtime_Terrors | /Students/Jordyn/Python/Fundamentals1/problem1.py | 224 | 4.3125 | 4 | def is_even(value):
value = abs(value % 2)
if value > 0:
return 'Is odd'
elif value == 0:
return 'Is even'
value = int(input('Input a whole number: '))
response = is_even(value)
print(response) | true |
59bc2af7aeef6ce948184bb1291f18f81026ed9c | alveraboquet/Class_Runtime_Terrors | /Students/Jordyn/Python/Fundamentals2/problem3.py | 296 | 4.1875 | 4 | def latest_letter(word):
length = len(word)
length -= 1
word_list = []
for char in word:
word_list += [char.lower()]
return word_list[length]
word = input("Please input a sentence: ")
letter = latest_letter(word)
print(f"The last letter in the sentence is: {letter}") | true |
627275ef1f88b1c633f0114347570dc62a16f175 | alveraboquet/Class_Runtime_Terrors | /Students/cadillacjack/Python/lab15/lab15.py | 1,306 | 4.1875 | 4 | from string import punctuation as punct
# Import ascii punctuation as "punct".
# "punct" is a list of strings
with open ('monte_cristo.txt', 'r') as document:
document_content = document.read(500)
doc_cont = document_content.replace('\n',' ')
# Open designated file as "file". "file" is a string
for punc in punct:... | true |
0c31b359da41c800121e7560fceac30836e2daec | alveraboquet/Class_Runtime_Terrors | /Students/tom/Lab 11/Lab 11, make change, ver 1.py | 1,903 | 4.15625 | 4 | # program to make change
# 10/16/2020
# Tom Schroeder
play_again = True
while play_again:
money_amount = input ('Enter the amount amount of money to convert to change: \n')
float_convert = False
while float_convert == False:
try:
money_amount = float(money_amount)
... | true |
8a8ce83b77498d38089aea25b1edd589330d8f0b | alveraboquet/Class_Runtime_Terrors | /Students/cadillacjack/Python/oop/volume.py | 1,152 | 4.25 | 4 | class Volume:
def __init__(self, length, width, height):
self.length = int(length)
self.width = int(width)
self.height = int(height)
def perimeter(self):
per = 2 * (self.length * self.width)
return per
def area(self):
area = self.length * self.width
re... | false |
bd89d612e7e9d15153ad804f85dfe64245c365a6 | DanielY1783/accre_python_class | /bin/06/line_counter.py | 1,440 | 4.71875 | 5 | # Author: Daniel Yan
# Email: daniel.yan@vanderbilt.edu
# Date: 2018-07-25
#
# Description: My solution to the below exercise posed by Eric Appelt
#
# Exercise: Write a command line utility in python that counts the number
# of lines in a file and prints them. to standard output.
#
# The utility should take the name of... | true |
b4d3854aea11e1cac0cece0b4dbd708b6d95d184 | DanielY1783/accre_python_class | /bin/01/fib.py | 1,338 | 4.53125 | 5 | # Author: Daniel Yan
# Email: daniel.yan@vanderbilt.edu
# Date: 2018-06-07
#
# Description: My solution to the below exercise posed by Eric Appelt
#
# Exercise: Write a program to take an integer that the user inputs and print
# the corresponding Fibonacci Number. The Fibonacci sequence begins 1, 1, 2, 3,
# 5, 8, 13, s... | true |
1db59dcb55f8b898d4d57ad244edc677b590941b | rshin808/quickPython | /Classes/EXoverriding.py | 1,387 | 4.34375 | 4 | class Animal:
def __init__(self, name):
self._name = str(name)
def __str__(self):
return "I am an Animal with name " + self._name
def get_name(self):
return self._name
def make_sound(self):
raise NotImplementedError("Subclass must implement abstract method")
... | false |
64739565dd86b5b36fdbe203c3f6beeb2c78b847 | anthony-marino/ramapo | /source/courses/cmps130/exercises/pe01/pe1.py | 651 | 4.5625 | 5 | #############################################
# Programming Excercise 1
#
# Write a program that asks the user
# for 3 integers and prints the
# largest odd number. If none of the
# three numbers were odd, print a message
# indicating so.
#############################################
x = int(input("Enter x: "))
y =... | true |
9dbffbb4195dfe02d90e4f2bd2813cc2a7d993a6 | anthony-marino/ramapo | /source/courses/cmps130/exercises/pe10/pe10-enumeration.py | 1,047 | 4.40625 | 4 | ##############################################################################
# Programming Excercise 10
#
# Find the square root of X using exhaustive enumeration
#############################################################################
# epsilon represents our error tolerance. We'll
# accept any answer Y where... | true |
f279a594a986076b96993995f5072bcc383244d6 | singh-vijay/PythonPrograms | /PyLevel3/Py19_Sets.py | 288 | 4.15625 | 4 | '''
Sets is collection of items with no duplicates
'''
groceries = {'serial', 'milk', 'beans', 'butter', 'bananas', 'milk'}
''' Ignore items which are given twice'''
print(groceries)
if 'pizza' in groceries:
print("you already have pizza!")
else:
print("You need to add pizza!") | true |
96ee1777becc904a39b140c901522881b2942cee | WavingColor/LeetCode | /LeetCode:judge_route.py | 1,034 | 4.125 | 4 | # Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
# The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (d... | true |
f084aa9b24edc8fe1b0d87cd20beee21288946ad | mattandersoninf/AlgorithmDesignStructures | /Points/Python/Point.py | 1,083 | 4.15625 | 4 | # python impolementation of a point
# a point in 2-D Euclidean space which should contain the following
# - x-coordinate
# - y-coordinate
# - moveTo(new_x,new_y): changes the coordinates to be equal to the new coordinates
# - distanceTo(x_val,y_val): this function returns the distance from the current point to some oth... | true |
91eb26b11d3a5839b3906211e3e10a636ac0277b | Exia01/Python | /Self-Learning/testing_and_TDD/basics/assertions.py | 649 | 4.28125 | 4 | # Example1
def add_positive_numbers(x, y):
# first assert, then expression, message is optional
assert x > 0 and y > 0, "Both numbers must be positive! -> {}, {}".format(
x, y)
return x + y
# test cases
print(add_positive_numbers(1, 1)) # 2
add_positive_numbers(1, -1) # AssertionError: Both ... | true |
dbdf00041078931bec33a443fbd330194cf60ec0 | Exia01/Python | /Self-Learning/lists/slices.py | 361 | 4.28125 | 4 | items = [1, 2, 3, 4, 5, 6, ['Hello', 'Testing']]
print(items[1:])
print(items[-1:])
print(items[::-1])# reverses the list
print(items[-3:])
stuff = items[:] # will copy the array
print(stuff is items) # share the same memory space?
print(stuff[0:7:2])
print(stuff[7:0:-2])
stuff[:3] = ["A", "B", "C"]
print(stuf... | true |
64878d4e5e228f2c45c578ea44614fcb5dc67e1b | Exia01/Python | /Self-Learning/built-in_functions/abs_sum_round.py | 712 | 4.125 | 4 | #abs --> Returns the absolute value of a number. The argument may be an integer or a floating point number
#Example
print(abs(5)) #5
print(abs(3.5555555))
print(abs(-1324934820.39248))
import math
print(math.fabs(-3923)) #treats everything as a float
#Sum
#takes an iterable and an optional start
# returns the sum... | true |
278dd78ed805a27e0a702bdd8c9064d3976a2f78 | Exia01/Python | /Python OOP/Vehicles.py | 2,884 | 4.21875 | 4 | # file vehicles.py
class Vehicle:
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
def drive(self, miles):
self.mileage += miles
return self
... | true |
65a6a75a451031ae2ea619b3b8b2210a44859ca3 | Exia01/Python | /Self-Learning/Algorithm_challenges/three_odd_numbers.py | 1,607 | 4.1875 | 4 | # three_odd_numbers
# Write a function called three_odd_numbers, which accepts a list of numbers and returns True if any three consecutive numbers sum to an odd number.
def three_odd_numbers(nums_list, window_size=3):
n = window_size
results = []
temp_sum = 0
#test this check
if window_size > len... | true |
66ebbe4465ff1a433f5918e7b20f019c60b496ae | Exia01/Python | /Self-Learning/lambdas/basics/basics.py | 725 | 4.25 | 4 | # A regular named function
def square(num): return num * num
# An equivalent lambda, saved to a variable but has no name
square2 = lambda num: num * num
# Another lambda --> anonymous function
add = lambda a,b: a + b #automatically returns
#Executing the function
print(square(7))
# Executing the lambdas
print(square... | true |
40be281781c92fc5417724157b0eebb2aefb8160 | Exia01/Python | /Self-Learning/functions/operations.py | 1,279 | 4.21875 | 4 | # addd
def add(a, b):
return a+b
print(add(5, 6))
# divide
def divide(num1, num2): # num1 and num2 are parameters
return num1/num2
print(divide(2, 5)) # 2 and 5 are the arguments
print(divide(5, 2))
# square
def square(num): # takes in an argument
return num * num
print(square(4))
print(square(... | true |
44697f20d48ba5522c2b77358ad1816d6af2bb96 | Exia01/Python | /Self-Learning/built-in_functions/exercises/sum_floats.py | 611 | 4.3125 | 4 | #write a function called sum_floats
#This function should accept a variable number of arguments.
#Should return the sum of all the parameters that are floats.
# if the are no floats return 0
def sum_floats(*args):
if (any(type(val) == float for val in args)):
return sum((val for val in args if type(val)==f... | true |
f8b7cd07614991a3ae5580fd2bd0458c730952ee | Exia01/Python | /Self-Learning/functions/exercises/multiple_letter_count.py | 428 | 4.3125 | 4 | #Function called "multiple_letter_count"
# return dictionary with count of each letter
def multiple_letter_count(word = None):
if not word:
return None
if word:
return {letter: word.count(letter) for letter in word if letter != " "}
#Variables
test_1 = "Hello World!"
test_2 = ... | true |
7ad9a8f7530f0636495f8b65372cccd4fe050c24 | Exia01/Python | /Self-Learning/OOP/part2/exercises/multiple_inheritance.py | 784 | 4.15625 | 4 | class Aquatic:
def __init__(self, name):
self.name = name
def swim(self):
return f'{self.name} is swimming'
def greet(self):
return f'I am {self.name} of the sea!'
class Ambulatory:
def __init__(self, name):
self.name = name
def walk(self):
return f'{self.... | false |
bea429f7de9a604e1d92b4506038dd17fef4c7eb | shvnks/comp354_calculator | /src/InterpreterModule/Tokens.py | 936 | 4.28125 | 4 | """Classes of all possible types that can appear in a mathematical expression."""
from dataclasses import dataclass
from enum import Enum
class TokenType(Enum):
"""Enumeration of all possible Token Types."""
"Since they are constant, and this is an easy way to allow us to know which ones we are manipulating.... | true |
aa7556b840c4efa4983cd344c69008a0f342f528 | shvnks/comp354_calculator | /src/functionsExponentOldAndrei.py | 2,603 | 4.21875 | 4 | # make your functions here
def exponent_function(constant, base, power):
total = base
if power % 1 == 0:
if power == 0 or power == -0:
return constant * 1
if power > 0:
counter = power - 1
while counter > 0:
total *= base
co... | true |
8face047d25661db2f4a5ed4faccf7036977c899 | y0m0/MIT.6.00.1x | /Lecture5/L5_P8_isIn.py | 854 | 4.28125 | 4 | def isIn(char, aStr):
'''
char: a single character
aStr: an alphabetized string
returns: True if char is in aStr; False otherwise
'''
# Base case: If aStr is empty, we did not find the char.
if aStr == '':
return False
# Base case: if aStr is of length 1, just see if t... | true |
4a442570e403106067cd7df096500e2d34099819 | ge01/StartingOutWithPython | /Chapter_02/program_0212.py | 236 | 4.1875 | 4 | # Get the user's first name.
first_name = raw_input('Enter your first name: ')
# Get the user's last name.
last_name = raw_input('Enter your last name: ')
# Print a greeting to the user.
print('Hello ' + first_name + " " + last_name)
| true |
d38fbf3290696cc8ca9ae950fd4fe81c0253bbfd | jiresimon/csc_lab | /csc_ass_1/geometric_arithmetic/geo_arithmetic_mean.py | 1,066 | 4.25 | 4 | from math import *
print("Program to calculate the geometric/arithmetic mean of a set of positive values")
print()
print("N -- Total number of positive values given")
print()
total_num = int(input("Enter the value for 'N' in the question:\n>>> "))
print()
print("Press the ENTER KEY to save each value you enter...")
... | true |
bcb4dd22aab6768e2540ccd3394a8078b8b38490 | RazvanCimpean/Python | /BMI calculator.py | 337 | 4.25 | 4 | # Load pandas
import pandas as pd
# Read CSV file into DataFrame df
df = pd.read_csv('sample 2.csv', index_col=0)
# Show dataframe
print(df) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.