blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0d68551843d403dfe1ba8f923220c70937532eb0 | paradoxal/3.-linkedlist | /linkedlist MALLI.py | 2,810 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
:File: linkedlist.py
:Author: <Your email>
:Date: <The date>
"""
class LinkedList:
"""
A doubly linked list object class.
The implementation makes use of a `ListNode` class that is used to
store the references from each node to its predecessor and follower
... | true |
81fe36735b80677a69cd5f1b229ba777cb0dcdf9 | santosh-srm/srm-pylearn | /28_max_of_three_numbers.py | 917 | 4.40625 | 4 | """28_max_of_three_numbers.py"""
print("----Finding max of 3 numbers----")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
if (num1 > num2):
if (num1 > num3):
print(f'The max number is {num1}')
else:
pr... | true |
485638e90767c3729c2e58115078a84fba15158a | santosh-srm/srm-pylearn | /W03D01/32_multiplicationtable.py | 708 | 4.3125 | 4 | """Print a multiplication table."""
def main():
"""Printing Multiplication Table"""
print_table(2)
print_table(7)
print_table(13)
def print_table(n):
"""Print nth Multiplication Table"""
print(f"Table {n}")
for i in range(1, 11):
print(f'{n} * {i} = {n*i}')
print("\n")
main()
... | false |
8a8b90655fc27a1434364c3581fdb48792f07658 | dlenwell/interview-prep-notes | /code-samples/python/inverting_trees/invert.py | 1,913 | 4.25 | 4 | """
Tree inversion:
"""
from tree import Node, Tree
from collections import deque
class InvertTree(Tree):
"""
InvertTree Tree class extends the base Tree class and just adds the invert
functions.
This class includes a recursive and an iterative version of the function.
"""
def invert_aux(s... | true |
3110b65f4b971f4a2c2967f250e3a22afd73e8f0 | ajerit/python-projects | /sorting/binary.py | 451 | 4.15625 | 4 | #
# Adolfo Jeritson
# Binary search implementation
# 2016
#
# inputs: A: Array of elements
# x: Target element
# returns None if the element is not found
# the position in the array if the element is found
def binarySearch(A, x):
start = 0
end = len(A)
while start < end:
mid = end + (start-end) ... | true |
ea30d850e5f06ac21da9ef24a9f1e4d6cade3401 | Anupama-Regi/python_lab | /24-color1_not_in_color2.py | 235 | 4.1875 | 4 | print("Program that prints out all colors from color-list1 not contained in color-list2")
l=input("Enter list1 of colors : ")
l2=input("Enter list2 of colors : ")
a=l.split()
b=l2.split()
l3=[i for i in a if i not in b]
print(l3) | true |
674392160a40f2309d6542271f2325d25bd5abc8 | Anupama-Regi/python_lab | /28-remove_even_numbers.py | 315 | 4.21875 | 4 | print("*Program to create a list removing even numbers from a list of integers.*")
n=input("Enter the list of integers : ")
l=list(map(int,n.split()))
print("List of numbers : ",l)
#l2=[i for i in l if i%2!=0]
#print(l2)
for i in l:
if(i%2==0):
l.remove(i)
print("List after removing even numbers : ",l) | true |
7f902eb622852e3435c85d96ab00338b215a3f1e | Anupama-Regi/python_lab | /Cycle_3-python-Anupama_Regi/15-factorial_using_function.py | 209 | 4.4375 | 4 | print("Program to find factorial using function")
def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
print("Factorial is ",f)
n=int(input("Enter the number to find factorial : "))
factorial(n)
| true |
10c8ddc131128cc08d98033c80d062d4a09e1484 | inventionzhang/TensorFlowApplication | /tensorFlowApp/test/ReloadFunction2.py | 1,315 | 4.21875 | 4 | # -*- coding: utf-8 -*-
# 定义在类的内部
class time:
# 构造函数
def __init__(self, hour=0, minutes=0, seconds=0):
self.hour = hour
self.minutes = minutes
self.seconds = seconds
# 函数的第一个参数是self,如果没有第二个参数,具体就用self.hour
def printTime(self, t):
print str(t.hour) + ":" + \
... | false |
54c1bc7e8f9d226fb869cd0da58026cfb5b08d24 | Jazmany23/Codigos | /ciclos.py | 917 | 4.125 | 4 | # ciclos
class Ciclos:
def __init__(self,num1=0,num2=1):
self.numero1=num1
def usoWhile(self):
# ciclo reetitivo que se ejecuta por verdadero y sale por falso
car = input("Ingrese vocal: ")
car = car.lower()
while car not in('a','e','i','o','u'):
car = inpu... | false |
3bf050700ee59e70d6fa1b5f41b4829a1b033df9 | horia94ro/python_fdm_26februarie | /day_2_part_1.py | 1,981 | 4.25 | 4 | print(7 >= 10)
print(10 != 12)
print(15 > 10)
a = 32
if (a >= 25 and a <= 30):
print("Number in the interval")
else:
if (a < 25):
print("Number is smaller than 25")
else:
print("Number is bigger than 30")
if a >= 25 and a <= 30:
print("Number in the interval")
elif a < 25:
print... | true |
ac3ef1b204dc2e5be36f08d323737db025865c55 | Woodforfood/learn_how_to_code | /Codewars/7kyu/Find_the_capitals.py | 260 | 4.125 | 4 | # Write a function that takes a single string (word) as argument.
# The function must return an ordered list containing the indexes of all capital letters in the string.
def capitals(word):
return [i for i, letter in enumerate(word) if letter.isupper()]
| true |
7a63e23ebafcc8275fa1307cfa41aa79050538ba | aslishemesh/Exercises | /exercise1.py | 692 | 4.125 | 4 | # Exercise1 - training.
def check_div_even(num, check):
if num % check == 0:
return True
else:
return False
num = input("Please enter a number: ")
if check_div_even(num, 4):
print "The number %d can be divided by 4" % num
elif check_div_even(num, 2):
print "The number %d is an e... | true |
5db0c8336d976269440ab89746298616c314654a | DDinCA/Byte-of-Python | /ds_using_tuple.py | 973 | 4.25 | 4 | #推荐总是使用括号来指明元组的开始和结束
#尽管括号只是一个可选选项
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))
new_zoo = 'monkey', 'camel', zoo
#把zoo作为一个整体带入了new zoo,所以new zoo一共只有三个个体
print('Number of cages in the new zoo is', len(new_zoo))
#这句其实就是计算new zoo里的个体数量
print('All animals in new zoo a... | false |
9f1157b501791c4cac209b2ebacefaf0c04da0aa | benfield97/info-validator | /info_validator.py | 1,041 | 4.1875 | 4 | import pyinputplus as pyip
import datetime
import re
while True:
name = pyip.inputStr("What is your name? ")
if all(x.isalpha() or x.isspace() for x in name):
name_len = name.split()
if len(name_len) < 2:
print("Please enter both a first and last name")
continue
... | true |
7e2a2ca00bbaac892cd350564e296d9fc06b3b76 | Xuezhi94/learning-and-exercise | /.vscode/数据结构的Python实现/02.数组结构/02.09.左下三角矩阵.py | 924 | 4.125 | 4 | #设计一个Python程序,将左下三角矩阵压缩为一维数组
global arr_size #矩阵维数大小
arr_size = 5
#一维数组的数组声明
num = int(arr_size * (arr_size + 1) / 2)
b = [None] * num
def get_value(i, j):
index = int(i * (i + 1) / 2 + j)
return b[index]
#下三角矩阵的内容
a = [[76, 0, 0, 0, 0], [54, 51, 0, 0, 0], [23, 8, 26, 0, 0],
[43, 35, 28, 18, 0], [12,... | false |
a4e828ffddc57348328a53dae0208e7be7044902 | nerdycheetah/lessons | /recursion_practice.py | 339 | 4.28125 | 4 | '''
Recursion Practice 10/17/2020
Example: Let's make a function that takes in a number and recursively adds to the total until the number reaches 1
'''
def recursive_total(n:int) -> int:
if n == 1:
return n
else:
print(f'n is currently: {n}')
return recursive_total(n - 1) + n
print(r... | true |
edcab377fe47ccda40631e5c4a906446972c0ca3 | nicowjy/practice | /Leetcode/101对称二叉树.py | 753 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 对称二叉树
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
... | true |
1daf2db78044c8a1fcd44d918f5156a06ea9c75d | KartikKannapur/Algorithms | /00_Code/01_LeetCode/559_MaximumDepthofN-aryTree.py | 1,385 | 4.25 | 4 | """
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
We should return its max depth, which is 3.
"""
"""
# Definition for a Node.
class Node(object):
def __init__(se... | true |
b4f0f0a2746fe03ceebd1007794f815f4d5c36a1 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/557_ReverseWordsinaStringIII.py | 704 | 4.21875 | 4 | # #Given a string, you need to reverse the order of characters
# #in each word within a sentence while still preserving whitespace
# #and initial word order.
# #Example 1:
# #Input: "Let's take LeetCode contest"
# #Output: "s'teL ekat edoCteeL tsetnoc"
# #Note: In the string, each word is separated by single space and
... | true |
2f883b3bd4645908e4b77ed0ae0669be10e283be | KartikKannapur/Algorithms | /00_Code/01_LeetCode/876_MiddleoftheLinkedList.py | 1,440 | 4.1875 | 4 | """
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this n... | true |
e9a1f7f92c7d888ab70fe09ca91e45d4bda6d162 | KartikKannapur/Algorithms | /00_Code/02_HackerRank/Dynamic_Programming/Fibonacci_Modified.py | 507 | 4.25 | 4 | """
https://www.hackerrank.com/challenges/fibonacci-modified/problem
"""
# !/bin/python3
import sys
def fibonacciModified(t1, t2, n):
# Complete this function
memo = [0] * (n + 1)
memo[0] = t1
memo[1] = t2
for i in range(2, n + 1):
memo[i] = memo[i - 2] + (memo[i - 1] ** 2)
return ... | false |
7b60b68b7fb1f6e0f71f016fee6c1a5fa25289a3 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/239_SlidingWindowMaximum.py | 1,155 | 4.28125 | 4 | """
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Example:
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
O... | true |
cd1d5ae088fc786391b2a0ff3c27dd874420d13f | KartikKannapur/Algorithms | /00_Code/01_LeetCode/332_ReconstructItinerary.py | 1,832 | 4.5625 | 5 | """
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order. All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary th... | true |
0a1b65a184da3df85610fbe3760ae972c2834db1 | KartikKannapur/Algorithms | /00_Code/01_LeetCode/883_ProjectionAreaof3DShapes.py | 2,987 | 4.5 | 4 | """
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Now we view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3 dimen... | true |
24ea31762444a62ad6d997c484bf624da5cdd2a5 | KartikKannapur/Algorithms | /02_Coursera_Algorithmic_Toolbox/Week_01_MaximumPairwiseProduct.py | 991 | 4.1875 | 4 | # Uses python3
__author__ = "Kartik Kannapur"
# #Import Libraries
import sys
# #Algorithm:
# #Essentially we need to pick the 2 largest elements from the array
# #Method 1: Sort the array and select the two largest elements - Very expensive
# #Method 2: Scan the entire array twice by maintaining two indexes - Max1 an... | true |
950e019702f534105369ef8d70380546c910e1dc | testmywork77/WorkspaceAbhi | /Year 8/Casting.py | 812 | 4.28125 | 4 | name = "Bruce"
age = "42"
height = 1.86
highscore = 128
# For this activity you will need to use casting as appropriate.
# Using the data stored in the above variables:
# 1. Use concatenation to output the sentence - "Bruce is 1.86m tall."
print(name + " is " + str(1.86) + "m tall.")
# 2. Use concatenation to output th... | true |
bd3d80133d7780eaacc843d4f7f9a144a6a56802 | testmywork77/WorkspaceAbhi | /Year 8/Concatenation_Practice.py | 1,042 | 4.34375 | 4 | name = "Abhinav"
age = "11"
fav_sport = "Cricket"
fav_colour = "red"
fav_animal = "lion"
# Create the following sentences by using concatenation
# Example: A sentence that says who he is and how old he is
print("My name is " + name + " and I am " + age + " ,I like to play " + fav_sport)
# NOTE: Don't forget about sp... | true |
d1c7cadba59a9c79cf30df4167483821263c15e5 | krishnaja625/CSPP-1-assignments | /m6/p3/digit_product.py | 416 | 4.125 | 4 | '''
Given a number int_input, find the product of all the digits
example:
input: 123
output: 6
'''
def main():
'''
Read any number from the input, store it in variable int_input.
'''
N3 = int(input())
N2 = N3
N = abs(N3)
S = 0
K = 0
if N > 0:
S = 1
while N > 0:
N2 = N%10
S = S*N2
N = N//10... | true |
065d5fda40b2c6f28f7736e946076f3b3d709f27 | Santoshi321/PythonPractice | /ListExcercise.txt | 1,866 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 15:06:30 2019
@author: sgandham
"""
abcd = ['nintendo','Spain', 1, 2, 3]
print(abcd)
# Ex1 - Select the third element of the list and print it
abcd[2]
# Ex2 - Type a nested list with the follwing list elements inside list abcd mentioned above... | true |
9996f4b93c4f91733742a6793da400f6b3bab637 | rebecca16/CYPAbigailAD | /funcion_print_el_que_si_es_xd.py | 750 | 4.125 | 4 | # print tiene 4 formas de uso
"""
1.- con comas
2.- con signo '+'
3.- con la funcion format ()
4.- Es con una variante de format ()
"""
# Con comas
#un espacio y haciendo casting de tipo
edad = 10
nombre = "Juan"
estatura = 1.67
print (edad , estatura , nombre )
# con '+' hace lo mismo pero no realiza el casting auto... | false |
3630cc5aeda264cc010df9809a3ef48d809b9cb3 | myNameArnav/dsa-visualizer | /public/codes/que/que.py | 1,771 | 4.25 | 4 | # Python3 program for array implementation of queue
INT_MIN = -32768
# Class Queue to represent a queue
class Queue:
# __init__ function
def __init__(self, capacity):
self.front = self.size = 0
self.rear = capacity - 1
self.array = [None]*capacity
self.capacity = capacity
... | true |
ed57a1ae2c3abd176cf440c00857b411899dd32e | myNameArnav/dsa-visualizer | /public/codes/dfs/dfs.py | 1,868 | 4.28125 | 4 | # Python3 program to implement DFS
# This function adds an edge to the graph.
# It is an undirected graph. So edges
# are added for both the nodes.
def addEdge(g, u, v):
g[u].append(v)
g[v].append(u)
# This function does the Depth First Search
def DFS_Visit(g, s):
# Colour is gray as it is visited par... | true |
d78d4b827bc6013444e4db630cd1261773a0bea8 | Bcdirito/django_udemy_notes | /back_end_notes/python/level_two/object_oriented_notes/oop_part_two.py | 791 | 4.53125 | 5 | # Example
class Dog():
# Class Object Attributes
# Always go up top
species = "Mammal"
# initializing with attributes
def __init__(self, breed, name):
self.breed = breed
self.name = name
# can be done without mass assignment
my_dog = Dog("German Shepherd", "Louis")
# can be... | true |
f4ddf222cd4c3d87ffee555eb23937de49298016 | AshurMotlagh/CECS-174 | /Lab 3.13.py | 223 | 4.375 | 4 | ##
# Print the first 3 letters of a string, followed by ..., followed by the last 3 letters of a string.
##
word = input("Enter a word with longer than 8 letters: ")
print("The new word is", word[0:3], "...", word[-3:]) | true |
5b52810c905e0213d4e30a36931640fe503e8f09 | ivelinakaraivanova/SoftUniPythonFundamentals | /src/Lists_Advanced_Exercise/01_Which_Are_In.py | 265 | 4.15625 | 4 | first_list = input().split(", ")
second_list = input().split(", ")
result_list =[]
for item in first_list:
for item2 in second_list:
if item in item2:
if item not in result_list:
result_list.append(item)
print(result_list) | true |
fb2a40e552b6bcddefcd8693718848ad87407c26 | ashishihota/learning-Algorithms | /linked_list/linked_list_book.py | 1,123 | 4.15625 | 4 | class node(object):
def __init__(self, data):
self.data = data
self.next = None
def get_data(self):
return self.data
def set_next(self, next):
self.next = next
def get_next(self):
return self.next
def has_next(self):
return self.next... | false |
0b246053cbffe4fa6a52f10f5a0982052cdebf4f | azdrachak/CS212 | /212/Unit2/HW2-2.py | 1,564 | 4.125 | 4 | #------------------
# User Instructions
#
# Hopper, Kay, Liskov, Perlis, and Ritchie live on
# different floors of a five-floor apartment building.
#
# Hopper does not live on the top floor.
# Kay does not live on the bottom floor.
# Liskov does not live on either the top or the bottom floor.
# Perlis lives on a h... | true |
75fa0274e9cfd4193bb5d1730caf90b2b0c5b194 | edagotti689/PYTHON-7-REGULAR-EXPRESSIONS | /1_match.py | 508 | 4.15625 | 4 | '''
1. Match is used to find a pattern from starting position
'''
import re
name = 'sriram'
mo = re.match('sri', name)
print(mo.group())
# matching through \w pattern
name = 'sriram'
mo = re.match('\w\w\w', name)
print(mo.group())
# matching numbers through \d pattern
name = 'sriram123'
mo = re.match... | true |
a59503d23f606bad8fc8ff6c68001e6ea1783431 | Rd-Feng/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 257 | 4.125 | 4 | #!/usr/bin/python3
"""Define MyList that extends list"""
class MyList(list):
"""add print_sorted instance method that prints the list in sorted order"""
def print_sorted(self):
"""print list in sorted order"""
print(sorted(self))
| true |
62e3752738f77f5c638ecbfcc3451b901338cec3 | vesnushka-sokol/test | /03_try_except/word_count.py | 819 | 4.15625 | 4 | def count_words(filename):
"""" Подсчет приблизительного количества строк в файле """
try:
with open(filename) as f:
content = f.read()
except FileNotFoundError:
with open('missing_files.txt', 'a', encoding='utf-8') as m:
m.write(filename + '\n')
# pas... | false |
705cc760876474bc595a7244895ea27ecb875d76 | shrirangmhalgi/Python-Bootcamp | /25. Iterators Generators/iterators.py | 495 | 4.34375 | 4 | # iterator is object which can be iterated upon An object which returns data, one at a time when next() is called on it
name = "Shrirang"
iterator = iter(name)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print... | true |
2302ed436657bca98feffd12477b4294ba12313b | shrirangmhalgi/Python-Bootcamp | /8. Boolean Statements/conditional_statements.py | 789 | 4.125 | 4 | name = input("Enter a name:\n")
if name == "shrirang":
print("Hello Shrirang")
elif name == "suvarna":
print("Hello Suvarna")
elif name == "rajendra":
print("Hello Rajendra")
else:
print("Hello User")
# truthiness and falsiness
# (is) is used to evaluate truthiness and falsiness
# falsiness includes
#... | true |
d81cadb1c01234f822fab833bc67f06b8c0cfa10 | shrirangmhalgi/Python-Bootcamp | /20. Lambdas and Builtin Functions/builtin_functions.py | 1,851 | 4.125 | 4 | import sys
# 1. all() returns true if ALL elements of iteratable are truthy
print(all(list(range(10))))
print(all(list(range(1, 10))))
# 2. any() returns true if ANY of the element is truthy
print(any(list(range(10))))
print(any(list(range(1, 10))))
# 3. sys.getsizeof
print(sys.getsizeof([x % 2 == 0 for x in range(1... | true |
713b3b42119f727b8e3bc59a09a6f0f27e748339 | shrirangmhalgi/Python-Bootcamp | /12. Lists/lists.py | 1,903 | 4.53125 | 5 | # len() function can be used to find length of anything..
# lists start with [ and end with ] and are csv
task = ["task 1", "task 2", "task 3"]
print(len(task)) # prints the length of the list...
list1 = list(range(1, 10)) # another way to define a list
# accessing data in the lists
# lists are accessed like arra... | true |
4a9158546b978eb121262bb114def980bfbc2ca9 | shrirangmhalgi/Python-Bootcamp | /30. File Handling/reading_file.py | 528 | 4.1875 | 4 | file = open("story.txt")
print(file.read())
# After a file is read, the cursor is at the end...
print(file.read())
# seek is used to manipulate the position of the cursor
file.seek(0) # Move the cursor at the specific position
print(file.readline()) # reads the first line of the file
file.seek(0)
print(file.readlines... | true |
d7df6511316ed65740cca6f8570f152fad2637fe | chivitc1/python-turtle-learning | /turtle15.py | 552 | 4.15625 | 4 | """
animate1.py
Animates the turtle using the ontimer function.
"""
from turtle import *
def act():
"""Move forward and turn a bit, forever."""
left(2)
forward(2)
ontimer(act, 1)
def main():
"""Start the timer with the move function.
The user’s click exits the program."""
reset()
sha... | true |
1731be54e0a9905f6f751a97808931ce54e0bec0 | chivitc1/python-turtle-learning | /menuitem_test.py | 1,121 | 4.28125 | 4 | """
menuitem_test.py
A simple tester program for menu items.
"""
from turtle import *
from menuitem import MenuItem
from flag import Flag
INDENT = 30
START_Y = 100
ITEM_SPACE = 30
menuClick = Flag()
def changePenColor(c):
"""Changes the system turtle’s color to c."""
menuClick.value(True)
color(c)
def ... | true |
4dfa7c1f1f9f51b838fcfb7e7d6c9f5f4fad2d42 | chivitc1/python-turtle-learning | /turtle17.py | 1,508 | 4.46875 | 4 | """
testpoly.py
Illustrates the use of begin_poly, end_poly, and get_poly to
create custom turtle shapes.
"""
from turtle import *
def regularPolygon(length, numSides):
"""Draws a regular polygon.
Arguments: the length and number of sides."""
iterationAngle = 360 / numSides
for count in range(numSides... | true |
85c90222620112056beeca40bd89fa028eddaa37 | MichaelTennyson/OOP | /lab7(practice).py | 2,775 | 4.21875 | 4 | import string
# converts file into a list of strings
def create_data_list(data_file : string) -> list:
o_file = open(data_file, 'r')
data_list = []
for line_str in o_file:
data_list.append(line_str.strip().split(','))
return data_list
def monthly_averages(data_list : list) -> list:... | false |
dab151fa8d3e2045bd5fab97d96c7ed1e1e9fe7f | MichaelTennyson/OOP | /lab3(practice).py | 516 | 4.5 | 4 | # The following program scrambles a string, leaving the first and last letter be
# the user first inputs their string
# the string is then turned into a list and is split apart
# the list of characters are scrambled and concatenated
import random
print("this program wil take a word and will scramble it \n")
... | true |
415a67a9d93c18d9794baadf1c50d0eb9e51ae27 | Yvonnexx/code | /binary_search.py | 341 | 4.125 | 4 | #!/usr/bin/python
def binary_search(num, target):
length = len(num)
start = 0
end = length - 1
while start < end:
mid = start + (end-start)/2
if target > num[mid]:
start = mid + 1
else:
end = mid
return start
num = [1,2,3,4,5]
target = 3
print binary... | false |
4e44b69e698e6f9435bc9e147b473398e8c794e1 | DanielShin2/CP1404_practicals | /prac05/emails.py | 624 | 4.1875 | 4 | def name_from_email(email):
username = email.split("@")[0]
parts = username.split(".")
name = " ".join(parts).title()
return name
def main():
email_name = {}
email = input("Enter your email: ")
while email != "":
name = name_from_email(email)
correct = input("Is your name {}... | true |
7b7ae24c2bf54988394165e6c63c165a84472f0e | mrudulamucherla/Python-Class | /2nd assign/dec to binary,.py | 510 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 9 16:19:30 2020
@author: mrudula
"""
#write prgm to convert decimal to binary number sysytem using bitwise operator
binary_num=list()
decimal_num=int(input("enter number"))
for i in range(0,8):
shift=decimal_num>>i #code to check value of last bit and ... | true |
d99c43ed6e3f8ff9cbd3ee31063216578a3702f5 | mrudulamucherla/Python-Class | /While Loop,134.py | 236 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 14:13:32 2020
@author: mrudula
"""
#Print all 3 multiples from 1 to 100 using for while loop.
while True:
for i in range (1,101):
print(i*3,end=" ")
break | true |
4cf6cf7d66050a5a9a4f2ef8f7ad48b5f20d9dc3 | lilbond/bitis | /day1/exploring.py | 2,508 | 4.53125 | 5 | """
Samples below are intended to get us started with Python.
Did you notice this is a multi-line comment :-) and yes being the first
one and before code, it qualifies to be documentation as well. How Cool!!!
In order to be a docstring it had to be multi-line
"""
# print hello world :-), Hey this is a single line com... | true |
ab4ad6fb7096a9276d614b2d0b4a97276f1c2512 | cpucortexm/python_IT | /python_interacting _with_os/logfile/parse_log.py | 1,985 | 4.3125 | 4 | #!/usr/bin/env python3
import sys
import os
import re
''' The script parses the input log file and generates an output containing only
relevant logs which the user can enter on command prompt
'''
def error_search(log_file):
error = input("What is the error? ") # input the error string which you want to see in th... | true |
3802612e9ba51aaa8d3307e8ab39d413dc8b6d20 | nguyntony/class | /large_exercises/large_fundamentals/guess2.py | 1,553 | 4.21875 | 4 | import random
on = True
attempts = 5
guess = None
print("Let's play a guessing game!\nGuess a number 1 and 10.")
while on:
# correct = random.randint(1, 10)
while True:
try:
guess = int(input())
break
except ValueError:
print("Please give a number!")
... | true |
9148ba1063ba78923a760707e24d3f3e78a2fab1 | nguyntony/class | /python101/strings.py | 303 | 4.1875 | 4 | # interpolation syntax
first_name = "tony"
last_name = "nguyen"
print("hello %s %s, this is interpolation syntax" % (first_name, last_name))
# f string
print(f"Hi my name is {first_name} {last_name}")
# escape string, you use the back slash \
# \n, \t
# concatenating is joining two things together
| true |
518a262e0db8dc3b9a9645f41f331ee79794dc54 | nguyntony/class | /python102/dict/ex1_dict.py | 458 | 4.21875 | 4 | siblings = {}
# for a list you can not create a new index but in a dictionary you can create a new key with the value at any time.
siblings["name"] = "Misty"
siblings["age"] = 15
siblings["fav_colors"] = ["pink", "yellow"]
siblings["fav_colors"].append("blue")
print(siblings)
# loop
# key
for key in siblings:
... | true |
aa4105b0f27729de85e91b4a106d25509b6a991d | nguyntony/class | /python102/list/ex3_list.py | 1,185 | 4.375 | 4 | # Using the code from exercise 2, prompt the user for which item the user thinks is the most interesting. Tell the user to use numbers to pick. (IE 0-3).
# When the user has entered the value print out the selection that the user chose with some sort of pithy message associated with the choice.
things = ["water bott... | true |
b6817fa9a655b70a7a24bedcfe2ddcad19ac2b4e | Randyedu/python | /知识点/04-LiaoXueFeng-master/06-dict.py | 1,767 | 4.3125 | 4 | '''
dict
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
'''
d = {'Min':95, 'Bob':75, 'Tra':85}
print(d, type(d))
print(d['Min'])
print(d)
# 如果key不存在,dict就会报错
# 要避免key不存在的错误,有两种办法,一是通过in判断key是否存在
print('tra' in d)
print('Tra' in d)
# 二是通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
pri... | false |
280dde835bdd22c44a461955634526aa9bd57faa | cute3954/Solving-Foundations-of-Programming | /problem-solving-with-python/makeBricks.py | 1,302 | 4.3125 | 4 | # https://codingbat.com/prob/p183562
#
# We want to make a row of bricks that is goal inches long.
# We have a number of small bricks (1 inch each) and big bricks (5 inches each).
# Return true if it is possible to make the goal by choosing from the given bricks.
# This is a little harder than it looks and can be done ... | true |
9a06dd1b4a054f8202f226251f3038002c011d11 | skyaiolos/myshiyanlou | /designPattern/behavioralPattern/templateMethod.py | 1,864 | 4.15625 | 4 | __author__ = "Jianguo Jin (jinjianguosky@hotmail.com)"
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# Created by Jianguo on 2017/6/5
"""
Description:
"""
import abc
class Fishing(object):
"""
钓鱼模板基类
"""
__metaclass__ = abc.ABCMeta
def finishing(self):
"""
钓鱼方法中,确定了要... | false |
1226a6de159e071159a9aca6f00a4dd2483265ab | daveboat/interview_prep | /coding_practice/binary_tree/populating_next_right_pointers_in_each_node.py | 2,486 | 4.125 | 4 | """
LC116 - Populating Next Right Pointers in Each Node
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The
binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point... | true |
49dfa92d60ff280719607b50f9e5a6aa40f76e1e | daveboat/interview_prep | /coding_practice/general/robot_bounded_in_circle.py | 2,663 | 4.15625 | 4 | """
LC1041 - Robot bounded in circle
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.
The robot performs the instructions given in order... | true |
c38cc560308edabac42c87bec8252bc9f446e39c | momentum-cohort-2019-05/w2d2-palindrome-bhagh | /palindrome.py | 577 | 4.25 | 4 | import re
#grab user input
submission = input("Enter a word or sentence(s): ")
#function to clean up text by user
def cleantext (submission):
submission = (re.sub("[^a-zA-Z0-9]+", '', submission).replace(" ",""))
return submission
print(cleantext(submission))
#create a string that's the reverse of the text ... | true |
e74a0ce8b1b2301019f58e51ad1befacaf983a4c | sidmusale97/SE-Project | /Pricing Algorithm/linearRegression.py | 1,113 | 4.28125 | 4 | '''
------------------------------------------------------------------------------------
This function is used to compute the mean squared error of a given data set and also
to find the gradient descent of the theta values and minimize the costfunction.
------------------------------------------------------------... | true |
93226ba29c06e18e86531e1c7326ab89082d473c | SAbarber/python-exercises | /ex12.py | 611 | 4.34375 | 4 | #Write a Python class named Circle.
Use the radius as a constructor.
Create two methods which will compute the AREA and the PERIMETER of a circle.
A = π r^2 (pi * r squared)
Perimeter = 2πr
class Circle:
def area(self):
return self.pi * self.radius ** 2
def __init__(self, pi, radius):
self.pi = pi
... | true |
153844a39053bf165547a8626a89840a82274f36 | alu0100636857/Grupo1H | /src/src/InterpolacionTaylor.py | 781 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Interpolación: Taylor
# Gabriela Balcedo Acosta y Vanesa Abad Armas
# Curso: 2012/2013
from math import *
from sympy import *
A=0
B=2
def factorial(n):
if (n<2):
return 1
r=1
for i in range(2,n+1):
r*=i
return r
def deriv():
symb_x = S... | false |
1cca34bd53ba9d73f844dccf011526deb399cd18 | darkbodhi/Some-python-homeworks | /divN.py | 713 | 4.25 | 4 | minimum = int(input("Please insert the minimal number: "))
maximum = int(input("Please insert the maximal number: "))
divisor = int(input("Please insert the number on which the first one will be divided: "))
x = minimum % divisor
if divisor <= 0:
raise Exception("An error has occurred. The divisor is not a natural ... | true |
aa0c6a66944e2cef568c401bd7f55e55bca1cec6 | anilkumar-satta-au7/attainu-anilkumar-satta-au7 | /create_a_dictionary_from_a_string.py | 430 | 4.21875 | 4 | #3) Write a Python program to create a dictionary from a string.
# Note: Track the count of the letters from the string.
# Sample string : 'w3resource'
# Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
test_str = "w3resource"
all_freq = {}
for i in test_str:
... | true |
01b0cf471c7e1a3d5ea42bd4e8ce2b44eaaba293 | pyaephyokyaw15/credit-card-validation | /credit-card.py | 1,811 | 4.28125 | 4 | '''
Credit-card Validation
- This script is used to determine whether a certain credit-card is
valid or not.
- It is based on Luhn’s algorithm.
- It also determines the type of Card(eg.MASTER, VISA, AMEX)
'''
def main():
# getting number from user until it is numeric value
while True:
card = i... | true |
a36d51210c4062391cca3a8218f990388fc20cca | jenihuang/hb_challenges | /EASY/lazy-lemmings/lemmings.py | 942 | 4.21875 | 4 | """Lazy lemmings.
Find the farthest any single lemming needs to travel for food.
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
>>> furthest(7, [0, 6])
3
>>> furthest(7, [0, 6])
3
>>> furthest(3, [0, 1, 2])... | true |
de62ef9fb09f2d10b0813bf727442cb6c282b546 | jenihuang/hb_challenges | /EASY/replace-vowels/replacevowels.py | 946 | 4.34375 | 4 | """Given list of chars, return a new copy, but with vowels replaced by '*'.
For example::
>>> replace_vowels(['h', 'i'])
['h', '*']
>>> replace_vowels([])
[]
>>> replace_vowels(['o', 'o', 'o'])
['*', '*', '*']
>>> replace_vowels(['z', 'z', 'z'])
['z', 'z', 'z']
Make sure to handle ... | true |
6ce8b6c28e28ea4207d7bfbc95fb9ccc0d558602 | jenihuang/hb_challenges | /MEDIUM/balanced-brackets/balancedbrackets.py | 1,935 | 4.15625 | 4 | """Does a given string have balanced pairs of brackets?
Given a string, return True or False depending on whether the string
contains balanced (), {}, [], and/or <>.
Many of the same test cases from Balance Parens apply to the expanded
problem, with the caveat that they must check all types of brackets.
These are fi... | true |
29c4f36d8bfa47db7391311153a590deeb43216b | jenihuang/hb_challenges | /MEDIUM/maxpath/maxpath.py | 2,844 | 4.125 | 4 | """Given a triangle of values, find highest-scoring path.
For example::
2
5 4
3 4 7
1 6 9 6 = [2,4,7,9] = 22
This works:
>>> triangle = make_triangle([[2], [5, 4], [3, 4, 7], [1, 6, 9, 6]])
>>> triangle
[2, 5, 4, 3, 4, 7, 1, 6, 9, 6]
>>> maxpath(triangle)
22
"""
class Node(... | true |
9015d36d969ed1e22d46113064e94a3c26dc0043 | jenihuang/hb_challenges | /EASY/rev-string/revstring.py | 519 | 4.15625 | 4 | """Reverse a string.
For example::
>>> rev_string("")
''
>>> rev_string("a")
'a'
>>> rev_string("porcupine")
'enipucrop'
"""
def rev_string(astring):
"""Return reverse of string.
You may NOT use the reversed() function!
"""
rev_str = ''
for i in range(len(astring)-1, ... | true |
6fdb741e9ccd497a7f6a7ae00604072bbf178262 | jenihuang/hb_challenges | /EASY/missing-number/missing.py | 831 | 4.15625 | 4 | """Given a list of numbers 1...max_num, find which one is missing in a list."""
def missing_number(nums, max_num):
"""Given a list of numbers 1...max_num, find which one is missing.
*nums*: list of numbers 1..[max_num]; exactly one digit will be missing.
*max_num*: Largest potential number in list
>... | true |
de346421fd9bf36a0113d702ccf6de03620b8198 | Johan-p/learnpythonShizzle | /exercise_36_birthdayplots.py | 1,639 | 4.28125 | 4 | """
In this exercise, use the bokeh Python library to plot a histogram
of which months the scientists have birthdays in!
"""
print(__doc__)
from bokeh.plotting import figure, show, output_file
from collections import Counter
import json
def read_jsonfile():
#global birthday_dictionary
global x
global ... | true |
713ed8035bf707c380e127bab4f0c6b36f6641ce | Johan-p/learnpythonShizzle | /Madlibs.py | 1,517 | 4.46875 | 4 | """
In this project, we'll use Python to write a Mad Libs word game! Mad Libs have short stories with blank spaces that a player can fill in. The result is usually funny (or strange).
Mad Libs require:
A short story with blank spaces (asking for different types of words).
Words from the player to fill in those ... | true |
8a8d89f72edd35ccb2928af5b147ad882899c6fe | Johan-p/learnpythonShizzle | /exercise_33_birthdaydictionaries.py | 884 | 4.59375 | 5 | """
or this exercise, we will keep track of when our friends birthdays are,
and be able to find that information based on their name.
Create a dictionary (in your file) of names and birthdays.
When you run your program it should ask the user to enter a name,
and return the birthday of that person back to them. ... | true |
c816a4224eeff0e5610176feb5df8eacfe3efcfb | HarrisonWelch/MyHackerRankSolutions | /python/Nested Lists.py | 496 | 4.25 | 4 | # Nested Lists.py
# Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
marksheet = []
for _ in range(0,int(input())):
marksheet.append([raw_input(), float(raw_input())])
second_highest =... | true |
fc9d7761b45597c8d3efb6fd81f76f0c96d547b7 | Lenux56/FromZeroToHero | /text_vowelfound.py | 519 | 4.4375 | 4 | '''
Enter a string and the program counts the number of vowels in the text.
For added complexity have it report a sum of each vowel found.
'''
import re
def multi_re_find():
'''
search and count vowels
'''
phrase = input('Please, enter a phrase to find vowels and count it: ')
while not phrase:
... | true |
2cf324ff75aad67c528a30bc86c29cfa3bfb167f | kojicovski/python | /exercises/ex035.py | 233 | 4.125 | 4 | a = int(input('Value a: '))
b = int(input('Value b: '))
c = int(input('Value c: '))
if a > b-c and a < b+c and b > a-c and b < a+c and c > a-b and c < a+b:
print('You can do a triangle')
else:
print('You cant do a triangle') | false |
6fd37514ac6e3d8425ed3646191bfd539b2947b5 | nurlan5t/python-homeworks | /hw15_queue в ООП варианте.py | 551 | 4.21875 | 4 | ''' Написать queue в ООП варианте. В классе должно быть
состояние хранящее со списком и метод pop()'''
from collections import deque
class My_list():
q = deque()
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
print("\nElements dequeued ... | false |
20e59d6494ba4c87140ccf88af9e846164ce0596 | vikas-ukani/Hacktoberfest_2021 | /Rock_Paper_Scissors.py | 1,368 | 4.28125 | 4 | import random
print("Welcome to rock paper scissors game .....")
print("You have three chances greater the wins in individual game will increase your chance to win")
print("Press 0-->paper , 1-->rock , 2-->scissors")
comp = 0
player = 0
for i in range(3):
player_choice = input("Your turn")
comp_choice=random.r... | true |
3f7c545c8765583c918074b6c73f4114522a1d2b | emmanuelnaveen/decision-science | /date_format.py | 292 | 4.3125 | 4 | from datetime import date
# Read the current date
current_date = date.today()
# Print the formatted date
print("Today is :%d-%d-%d" % (current_date.day,current_date.month,current_date.year))
# Set the custom date
custom_date = date(2021, 05, 20)
print("The date is:",custom_date) | true |
49c046a92870d3f128849c8ad0452ca7c71c75f1 | SruthiM-10/5th-grade | /Programs/reverseName.py | 275 | 4.21875 | 4 | s=input("What is your first name?")
f=input("What is your middle name if you have one? If you don't have a middle name, just type no")
r=input("What is your last name?")
if f=="no":
print("Your name in reverse is",r,s)
else:
print("Your name in reverse is",r,f,s,)
| true |
8d138c56ac0215a1ea4dabd2ccf7d575b09c6d9c | VDK45/Full_stack | /Lesson_1/Lesson 1 Task 5.py | 1,288 | 4.28125 | 4 | """
5. Запросите у пользователя значения выручки и издержек фирмы.
Определите, с каким финансовым результатом работает фирма
(прибыль — выручка больше издержек, или убыток — издержки больше выручки).
Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность в... | false |
e0c98e27237e12afd4485ef4c188a6fb0bf22479 | VDK45/Full_stack | /Lesson_4/lesson4Task7.py | 1,115 | 4.21875 | 4 | """
7. Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом:
for el in fact(n). Функция отвечает за получение факториала числа,
а в цикле необходимо выводить т... | false |
513a9d0167adda155e9f267aab31db2b75f4e441 | dulalsaurab/Graph-algorithm | /plot.py | 418 | 4.1875 | 4 | ''' This file will plot 2-d and 3-d points'''
import numpy as np
import matplotlib.pyplot as plt
# drawing lines between given points iteratively
def draw_line(array):
data = array # array should be of format [(),(),(),()]
# 2D ploting using matplotlib
def plot_2D(array, size):
# array should be of format... | true |
7fd8d5fa17e95775f7fe83d7e1259259555bf4e0 | nidjaj/python-basic-codes | /noispositive.py | 503 | 4.15625 | 4 | # if function
x=int(input("enter a no."))
if x>0:
print("%d is positive"%x)
if x<0:
print("%d is negative"%x)
if x==0:
print("%d is zero"%x)
# if else function
x=int(input("enter a no."))
if x>0: #we also use paranthesis'()'
print("%d is positive"%x)
else:
print("... | false |
950fb0e048a560043577605d9642d69808f974da | Rohitha92/Python | /Sorting/BubbleSort.py | 774 | 4.1875 | 4 | #Bubble sort implementation
#multiple passes throught the list.
##Ascending order
def bubble_sort(arr):
swapped = True
while(swapped):
swapped = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1]= temp
swapped = Tr... | true |
7216c73c1532bb08e436447f01903f98e7be6660 | Rohitha92/Python | /StacksQueuesDeques/Queue.py | 578 | 4.21875 | 4 | #Implement Queue
#First in First out
#insert items at the First (zero index)
#delete from first (zero index)
class Queue(object):
def __init__(self):
self.items=[]
def enqueue(self,val): #add to the rear
self.items.insert(0,val)
def size(self):
return len(self.items)
def isempty(self):... | true |
dbab87656743bc392657697bd944b8df9e1fea4d | duarte15/exercicioProva4 | /Questão3- Letícia Duarte.py | 353 | 4.125 | 4 | #QUESTAO3
print("Funes recursivas so funes que chamam a si mesma de forma que, para resolver um problema maior, utiliza a recurso para chegar as unidades bsicas do problema em questo e ento calcular o resultado final.\n Exemplo:")
def fatorial(n):
if (n==1):
return (n)
return fatorial(n-1)*n-1
prin... | false |
2decca9c52862f63ebf355efab54d0446c2147b8 | Shubhamditya36/python-pattern-programs | /a.7.1.py | 267 | 4.40625 | 4 | # PROGRAM TO PRINT FLOYD'S TRIANGLE (PRINTING NUMBERS IN RIGHT TRIANGLE SHAPE)
# EXAMPLE :
#
# 1234
# 567
# 89
# 10
n=int(input("enter a number:"))
num=1
for row in range(n,0,-1):
for col in range(0,row-1):
print(num,end="")
num+=1
print()
| false |
7aeba56b0611f7db71a27daf3cb8f007273cdbc2 | Shubhamditya36/python-pattern-programs | /a13.py | 391 | 4.1875 | 4 | # PROGRAM TO PRINT PATTERN GIVEN BELOW.
# 1
# 2 1 2
# 3 2 1 2 3
# 4 3 2 1 2 3 4
# 5 4 3 2 1 2 3 4 5
num=int(input ("enter a number of rows:"))
for row in range(1,num+1):
for col in range(0,num-row+1):
print(end=" ")
for col in range(row,0,-1):
print(col,end=" ")
... | true |
68d99566855facd7d1fb225b65ec1a72ba804178 | Shubhamditya36/python-pattern-programs | /a22.py | 757 | 4.125 | 4 | # PROGRAM TO PRINT PATTERN GIVEN BELOW.
# 5 5 5 5 5 5 5 5 5
# 5 4 4 4 4 4 4 4 5
# 5 4 3 3 3 3 3 4 5
# 5 4 3 2 2 2 3 4 5
# 5 4 3 2 1 2 3 4 5
# 5 4 3 2 2 2 3 4 5
# 5 4 3 3 3 3 3 4 5
# 5 4 4 4 4 4 4 4 5
# 5 5 5 5 5 5 5 5 5
N=int(input(" enter a number of rows;"))
k=(2*N)-1
low=0
high=k-1
value=N
matrix=[[0 for i in ran... | false |
6539173b858b23d1e0ce6daa4431edc7c0c8761b | svigstol/100-days-of-python | /days-in-a-month.py | 1,522 | 4.21875 | 4 | # 100 Days of Python
# Day 10.2 - Days In A Month
# Enter year and month as inputs. Then, display number of days in that month
# for that year.
# Sarah Vigstol
# 5/31/21
def isLeap(year):
"""Determine whether or not a given year is a leap year."""
if year % 4 == 0:
if year % 100 == 0:
if ye... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.